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/FORMAT/SpecArrayFile.cpp | .cpp | 544 | 21 | // 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/SpecArrayFile.h>
using namespace std;
namespace OpenMS
{
SpecArrayFile::SpecArrayFile() = default;
SpecArrayFile::~SpecArrayFile() = default;
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/MSPGenericFile.cpp | .cpp | 11,368 | 320 | // 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/MSPGenericFile.h>
#include <OpenMS/CONCEPT/Constants.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/KERNEL/SpectrumHelper.h>
#include <OpenMS/METADATA/Precursor.h>
#include <OpenMS/SYSTEM/File.h>
#include <boost/regex.hpp>
#include <fstream>
#include <array>
namespace OpenMS
{
MSPGenericFile::MSPGenericFile() :
DefaultParamHandler("MSPGenericFile")
{
getDefaultParameters(defaults_);
defaultsToParam_(); // write defaults into Param object param_
}
MSPGenericFile::MSPGenericFile(const String& filename, MSExperiment& library) :
DefaultParamHandler("MSPGenericFile")
{
getDefaultParameters(defaults_);
defaultsToParam_(); // write defaults into Param object param_
load(filename, library);
}
void MSPGenericFile::getDefaultParameters(Param& params)
{
params.clear();
params.setValue("synonyms_separator", "|", "The character that will separate the synonyms in the Synon metaValue.");
}
void MSPGenericFile::updateMembers_()
{
synonyms_separator_ = param_.getValue("synonyms_separator").toString();
}
void MSPGenericFile::load(const String& filename, MSExperiment& library)
{
loaded_spectra_names_.clear();
synonyms_.clear();
std::ifstream ifs(filename, std::ifstream::in);
if (!ifs.is_open())
{
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);
}
}
const Size BUFSIZE { 65536 };
char line[BUFSIZE];
library.clear(true);
MSSpectrum spectrum;
spectrum.setMetaValue("is_valid", 0); // to avoid adding invalid spectra to the library
boost::cmatch m;
boost::regex re_name("(?:^Name|^NAME): (.+)", boost::regex::no_mod_s);
boost::regex re_retention_time("(?:^Retention Time|^RETENTIONTIME): (.+)", boost::regex::no_mod_s);
boost::regex re_synon("^synon(?:yms?)?: (.+)", boost::regex::no_mod_s | boost::regex::icase);
boost::regex re_points_line(R"(^\d)");
boost::regex re_point(R"((\d+(?:\.\d+)?)[: \t](\d+(?:\.\d+)?);? ?)");
boost::regex re_cas_nist(R"(^CAS#: ([\d-]+); NIST#: (\d+))"); // specific to NIST db
boost::regex re_precursor_mz("^PRECURSORMZ: (.+)");
boost::regex re_num_peaks("(?:^Num Peaks|^Num peaks): (\\d+)");
// regex for meta values required for MetaboliteSpectralMatcher
boost::regex re_inchi("^INCHIKEY: (.+)");
boost::regex re_smiles("^SMILES: (.+)");
boost::regex re_sum_formula("^FORMULA: (.+)");
boost::regex re_precursor_type("^PRECURSORTYPE: (.+)");
// matches everything else
boost::regex re_metadatum("^(.+): (.+)", boost::regex::no_mod_s);
OPENMS_LOG_INFO << "\nLoading spectra from .msp file. Please wait." << std::endl;
while (!ifs.eof())
{
ifs.getline(line, BUFSIZE);
// Peaks
if (boost::regex_search(line, m, re_points_line))
{
OPENMS_LOG_DEBUG << "re_points_line\n";
boost::regex_search(line, m, re_point);
do
{
OPENMS_LOG_DEBUG << "{" << m[1] << "} {" << m[2] << "}; ";
const double position { std::stod(m[1]) };
const double intensity { std::stod(m[2]) };
spectrum.push_back( Peak1D(position, intensity) );
} while ( boost::regex_search(m[0].second, m, re_point) );
}
// Synon
else if (boost::regex_search(line, m, re_synon))
{
// OPENMS_LOG_DEBUG << "Synon: " << m[1] << "\n";
synonyms_.emplace_back(m[1]);
}
// Name
else if (boost::regex_search(line, m, re_name))
{
addSpectrumToLibrary(spectrum, library);
// OPENMS_LOG_DEBUG << "\n\nName: " << m[1] << "\n";
spectrum.clear(true);
synonyms_.clear();
spectrum.setName(String(m[1]));
spectrum.setMetaValue(Constants::UserParam::MSM_METABOLITE_NAME, spectrum.getName());
spectrum.setMetaValue("is_valid", 1);
}
// Number of Peaks
else if (boost::regex_search(line, m, re_num_peaks))
{
spectrum.setMetaValue("Num Peaks", String(m[1]));
}
// Retention Time
else if (boost::regex_search(line, m, re_retention_time))
{
spectrum.setRT(std::stod(m[1]));
}
// set Precursor MZ
else if (boost::regex_search(line, m, re_precursor_mz))
{
std::vector<Precursor> precursors;
Precursor p;
p.setMZ(std::stod(m[1]));
precursors.push_back(p);
spectrum.setPrecursors(precursors);
}
//CAS# NIST#
else if (boost::regex_search(line, m, re_cas_nist))
{
// OPENMS_LOG_DEBUG << "CAS#: " << m[1] << "; NIST#: " << m[2] << "\n";
spectrum.setMetaValue(String("CAS#"), String(m[1]));
spectrum.setMetaValue(String("NIST#"), String(m[2]));
}
// Meta values for MetaboliteSpectralMatcher
else if (boost::regex_search(line, m, re_inchi))
{
spectrum.setMetaValue(Constants::UserParam::MSM_INCHI_STRING, String(m[1]));
}
else if (boost::regex_search(line, m, re_smiles))
{
spectrum.setMetaValue(Constants::UserParam::MSM_SMILES_STRING, String(m[1]));
}
else if (boost::regex_search(line, m, re_sum_formula))
{
spectrum.setMetaValue(Constants::UserParam::MSM_SUM_FORMULA, String(m[1]));
}
else if (boost::regex_search(line, m, re_precursor_type))
{
spectrum.setMetaValue(Constants::UserParam::MSM_PRECURSOR_ADDUCT, String(m[1]));
}
// Other metadata, needs to be last, matches everything
else if (boost::regex_search(line, m, re_metadatum))
{
// OPENMS_LOG_DEBUG << m[1] << m[2] << "\n";
spectrum.setMetaValue(String(m[1]), String(m[2]));
}
}
// To make sure a spectrum is added even if no empty line is present before EOF
addSpectrumToLibrary(spectrum, library);
OPENMS_LOG_INFO << "Loading spectra from .msp file completed." << std::endl;
}
void MSPGenericFile::store(const String& filename, const MSExperiment& library) const
{
std::ofstream output_file(filename.c_str());
// checking if file is writable
if (!File::writable(filename))
{
throw Exception::FileNotWritable(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename);
}
for (const auto& spectrum : library.getSpectra())
{
if (spectrum.getName().empty())
{
throw Exception::MissingInformation(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"The current spectrum misses the Name information.");
}
if (spectrum.size())// we will not store spectrum with no peaks
{
output_file << "Name: " << spectrum.getName() << '\n';
output_file << "Retention Time: " << spectrum.getRT() << '\n';
const auto& synonyms = spectrum.getMetaValue("Synon");
if (synonyms.valueType() == OpenMS::DataValue::DataType::STRING_VALUE)
{
StringList list;
synonyms.toString().split(synonyms_separator_, list);
for (const auto& syn : list)
{
output_file << "Synon: " << syn << '\n';
}
}
if (spectrum.metaValueExists("CAS#") && spectrum.metaValueExists("NIST#"))
{
output_file << "CAS#: " << spectrum.getMetaValue("CAS#") << "; NIST#: " << spectrum.getMetaValue("NIST#") << '\n';
}
// Other metadata
static const std::array<std::string, 4> ignore_metadata = {"Synon", "CAS#", "NIST#", "Num Peaks"};
std::vector<String> keys;
spectrum.getKeys(keys);
for (const auto& key : keys)
{
const auto& value = spectrum.getMetaValue(key);
if (std::find(ignore_metadata.begin(), ignore_metadata.end(), key) == ignore_metadata.end())
{
output_file << key << ": " << value << '\n';
}
}
// Peaks
output_file << "Num Peaks: " << spectrum.size() << '\n';
int peak_counter = 0;
for (const auto& peak : spectrum)
{
output_file << peak.getPos() << ":" << peak.getIntensity() << " ";
if ((++peak_counter % 5) == 0)
{
output_file << '\n';
}
}
if ((peak_counter % 5) != 0)
{
output_file << '\n';
}
// separator
output_file << '\n';
}
}
output_file.close();
}
void MSPGenericFile::addSpectrumToLibrary(
MSSpectrum& spectrum,
MSExperiment& library
)
{
if (static_cast<int>(spectrum.getMetaValue("is_valid")) == 0)
{
return;
}
// Check that required metadata (Name, Num Peaks) is present
// Num Peaks is checked later in the code (when verifying for the number of points parsed)
if (spectrum.getName().empty())
{
throw Exception::MissingInformation(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"The current spectrum misses the Name information.");
}
// Check that the spectrum is not a duplicate (i.e. already present in `library`)
const Size name_found = loaded_spectra_names_.count(spectrum.getName());
if (!name_found)
{
// Check that all expected points are parsed
if (!spectrum.metaValueExists("Num Peaks"))
{
throw Exception::MissingInformation(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"The current spectrum misses the Num Peaks information.");
}
const String& num_peaks { spectrum.getMetaValue("Num Peaks") };
if (spectrum.size() != std::stoul(num_peaks) )
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
num_peaks,
"The number of points parsed does not coincide with `Num Peaks`.");
}
if (!synonyms_.empty())
{
String synon;
for (const String& s : synonyms_)
{
synon += s + synonyms_separator_;
}
if (!synon.empty())
{
synon.pop_back();
}
spectrum.setMetaValue("Synon", synon);
}
spectrum.removeMetaValue("is_valid");
if (spectrum.getRT() < 0)
{ // set RT to spectrum index
spectrum.setRT(library.getSpectra().size());
}
library.addSpectrum(spectrum);
loaded_spectra_names_.insert(spectrum.getName());
if (loaded_spectra_names_.size() % 20000 == 0)
{
OPENMS_LOG_INFO << "Loaded " << loaded_spectra_names_.size() << " spectra..." << std::endl;
}
}
else
{
OPENMS_LOG_INFO << "DUPLICATE: " << spectrum.getName() << std::endl;
}
spectrum.setMetaValue("is_valid", 0);
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/ZlibCompression.cpp | .cpp | 5,064 | 138 | // 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, Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/FORMAT/ZlibCompression.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <array>
#include <zlib.h>
using namespace std;
namespace OpenMS
{
void ZlibCompression::compressString(std::string& str, std::string& compressed)
{
compressData(reinterpret_cast<Bytef*>(&str[0]), str.size(), compressed);
}
void ZlibCompression::compressData(const void* raw_data, const size_t in_length, std::string& compressed)
{
compressed.clear();
const unsigned long sourceLen = (unsigned long)in_length;
unsigned long compressed_length = compressBound(in_length);
compressed.resize(compressed_length); // reserve enough space -- we may not need all of it
int zlib_error = compress(reinterpret_cast<Bytef*>(&compressed[0]), &compressed_length, (Bytef*)raw_data, sourceLen);
switch (zlib_error)
{
case Z_OK: // Compression successful
break;
case Z_MEM_ERROR:
throw Exception::OutOfMemory(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, compressed_length);
case Z_BUF_ERROR:
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Destination buffer too small for compressed output",
String(compressed_length));
default:
throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Compression error!");
}
compressed.resize(compressed_length); // cut down to the actual data
}
void uncompressStringSingleShot___(const void* compressed_data, size_t nr_bytes, std::string& raw_data, size_t output_size)
{
if (nr_bytes == 0)
{
raw_data.clear();
return;
}
raw_data.resize(output_size);
uLongf uncompressedSize = output_size;
int ret = uncompress((Bytef*)raw_data.data(), &uncompressedSize, (Bytef*)compressed_data, nr_bytes);
if (ret == Z_OK)
{
if (uncompressedSize != raw_data.size())
{
OPENMS_LOG_INFO << "ZlibCompression::uncompressString: Warning: decompressed data was smaller (" << std::to_string(uncompressedSize) << ") than anticipated: " << std::to_string(output_size) << std::endl;
raw_data.resize(uncompressedSize);
}
}
else if (ret == Z_BUF_ERROR)
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Decompression failed because specified output_size was too small. Size of data after decompression is larger than anticipated: " + std::to_string(uncompressedSize), std::to_string(output_size));
}
else
{
throw Exception::InternalToolError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "zlib::inflate failed with code " + std::to_string(ret) + " .");
}
}
void uncompressStringIterative___(const void* compressed_data, size_t nr_bytes, std::string& uncompressed)
{
uncompressed.clear();
// Setup input
z_stream strm = {};
strm.next_in = (Bytef*)(compressed_data);
strm.avail_in = nr_bytes;
// Initialize zlib (use inflateInit2 for gzip or raw deflate)
int ret = inflateInit(&strm);
if (ret != Z_OK)
{
throw Exception::InternalToolError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "zlib::inflateInit failed with code " + std::to_string(ret) + " .");
}
// Decompress loop
const size_t CHUNK_SIZE = 16384;
std::array<char, CHUNK_SIZE> buffer;
do
{
strm.avail_out = CHUNK_SIZE;
strm.next_out = (Bytef*)buffer.data();
ret = inflate(&strm, Z_NO_FLUSH);
if (ret == Z_STREAM_ERROR || ret == Z_DATA_ERROR || ret == Z_MEM_ERROR || ret == Z_BUF_ERROR)
{
inflateEnd(&strm);
throw Exception::InternalToolError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "zlib::inflate failed with code " + std::to_string(ret) + " .");
}
size_t bytes_decompressed = CHUNK_SIZE - strm.avail_out;
uncompressed.insert(uncompressed.end(), buffer.begin(), buffer.begin() + bytes_decompressed);
} while (ret != Z_STREAM_END);
inflateEnd(&strm);
}
void ZlibCompression::uncompressData(const void* compressed_data, size_t nr_bytes, std::string& raw_data, size_t output_size)
{
if (output_size == 0)
{ // unknown output size - decompress chunk by chunk
uncompressStringIterative___(compressed_data, nr_bytes, raw_data);
}
else
{ // known output size - decompress into a preallocated string
uncompressStringSingleShot___(compressed_data, nr_bytes, raw_data, output_size);
}
}
void ZlibCompression::uncompressString(const String& in, std::string& out, size_t output_size)
{
uncompressData(in.data(), in.size(), out, output_size);
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/ParamXMLFile.cpp | .cpp | 12,171 | 364 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Stephan Aiche $
// --------------------------------------------------------------------------
#include <OpenMS/FORMAT/ParamXMLFile.h>
#include <OpenMS/FORMAT/HANDLERS/ParamXMLHandler.h>
#include <iostream>
#include <fstream>
#include <algorithm>
namespace OpenMS
{
String writeXMLEscape(const String& to_escape)
{
return Internal::XMLHandler::writeXMLEscape(to_escape);
}
ParamXMLFile::ParamXMLFile() :
XMLFile("/SCHEMAS/Param_1_8_0.xsd", "1.8.0")
{
}
void ParamXMLFile::store(const String& filename, const Param& param) const
{
//open file
std::ofstream os_;
std::ostream* os_ptr;
if (filename != "-")
{
os_.open(filename.c_str(), std::ofstream::out);
if (!os_)
{
throw Exception::UnableToCreateFile(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename);
}
os_ptr = &os_;
}
else
{
os_ptr = &std::cout;
}
//write to file stream
writeXMLToStream(os_ptr, param);
os_.close();
}
void ParamXMLFile::writeXMLToStream(std::ostream* os_ptr, const Param& param) const
{
// Note: For a long time the handling of 'getTrace()' was vulnerable to an unpruned tree (a path of nodes, but no entries in them), i.e.
// too many closing tags are written to the INI file, but no opening ones.
// This never mattered here, as removeAll() was fixed to prune the tree.
// TODO: Nowadays this should be fixed and removeAll() might not be necessary.
std::ostream& os = *os_ptr;
os.precision(writtenDigits<double>(0.0));
os << "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n";
os << "<PARAMETERS version=\"" << getVersion() << "\" xsi:noNamespaceSchemaLocation=\"https://raw.githubusercontent.com/OpenMS/OpenMS/develop/share/OpenMS/SCHEMAS/Param_1_8_0.xsd\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n";
String indentation = " ";
Param::ParamIterator it = param.begin();
while (it != param.end())
{
//write opened/closed nodes
const std::vector<Param::ParamIterator::TraceInfo>& trace = it.getTrace();
for (const Param::ParamIterator::TraceInfo& it2 : trace)
{
if (it2.opened) //opened node
{
String d = it2.description;
//d.substitute('"','\'');
d.substitute("\n", "#br#");
//d.substitute("<","<");
//d.substitute(">",">");
os << indentation << "<NODE name=\"" << writeXMLEscape(it2.name) << "\" description=\"" << writeXMLEscape(d) << "\">" << "\n";
indentation += " ";
}
else //closed node
{
indentation.resize(indentation.size() - 2);
os << indentation << "</NODE>" << "\n";
}
}
//write item
if (it->value.valueType() != ParamValue::EMPTY_VALUE)
{
// we create a temporary copy of the tag list, since we remove certain tags while writing,
// that will be represented differently in the xml
std::set<std::string> tag_list = it->tags;
ParamValue::ValueType value_type = it->value.valueType();
bool stringParamIsFlag = false;
//write opening tag
switch (value_type)
{
case ParamValue::INT_VALUE:
os << indentation << "<ITEM name=\"" << writeXMLEscape(it->name) << "\" value=\"" << it->value.toString() << R"(" type="int")";
break;
case ParamValue::DOUBLE_VALUE:
os << indentation << "<ITEM name=\"" << writeXMLEscape(it->name) << "\" value=\"" << it->value.toString() << R"(" type="double")";
break;
case ParamValue::STRING_VALUE:
if (tag_list.find("input file") != tag_list.end())
{
os << indentation << "<ITEM name=\"" << writeXMLEscape(it->name) << "\" value=\"" << writeXMLEscape(it->value.toString()) << R"(" type="input-file")";
tag_list.erase("input file");
}
else if (tag_list.find("output file") != tag_list.end())
{
os << indentation << "<ITEM name=\"" << writeXMLEscape(it->name) << "\" value=\"" << writeXMLEscape(it->value.toString()) << R"(" type="output-file")";
tag_list.erase("output file");
}
else if (tag_list.find("output prefix") != tag_list.end())
{
os << indentation << "<ITEM name=\"" << writeXMLEscape(it->name) << "\" value=\"" << writeXMLEscape(it->value.toString()) << R"(" type="output-prefix")";
tag_list.erase("output prefix");
}
else if (it->valid_strings.size() == 2 &&
it->valid_strings[0] == "true" && it->valid_strings[1] == "false" &&
it->value == "false")
{
stringParamIsFlag = true;
os << indentation << "<ITEM name=\"" << writeXMLEscape(it->name) << "\" value=\"" << Internal::encodeTab(writeXMLEscape(it->value.toString())) << R"(" type="bool")";
}
else
{
os << indentation << "<ITEM name=\"" << writeXMLEscape(it->name) << "\" value=\"" << Internal::encodeTab(writeXMLEscape(it->value.toString())) << R"(" type="string")";
}
break;
case ParamValue::STRING_LIST:
if (tag_list.find("input file") != tag_list.end())
{
os << indentation << "<ITEMLIST name=\"" << writeXMLEscape(it->name) << R"(" type="input-file")";
tag_list.erase("input file");
}
else if (tag_list.find("output file") != tag_list.end())
{
os << indentation << "<ITEMLIST name=\"" << writeXMLEscape(it->name) << R"(" type="output-file")";
tag_list.erase("output file");
}
else
{
os << indentation << "<ITEMLIST name=\"" << writeXMLEscape(it->name) << R"(" type="string")";
}
break;
case ParamValue::INT_LIST:
os << indentation << "<ITEMLIST name=\"" << writeXMLEscape(it->name) << R"(" type="int")";
break;
case ParamValue::DOUBLE_LIST:
os << indentation << "<ITEMLIST name=\"" << writeXMLEscape(it->name) << R"(" type="double")";
break;
default:
break;
}
//replace all critical characters in description
String d = it->description;
//d.substitute("\"","'");
d.substitute("\n", "#br#");
//d.substitute("<","<");
//d.substitute(">",">");
os << " description=\"" << writeXMLEscape(d) << "\"";
// required
if (tag_list.find("required") != tag_list.end())
{
os << " required=\"true\"";
tag_list.erase("required");
}
else
{
os << " required=\"false\"";
}
// advanced
if (tag_list.find("advanced") != tag_list.end())
{
os << " advanced=\"true\"";
tag_list.erase("advanced");
}
else
{
os << " advanced=\"false\"";
}
// tags
if (!tag_list.empty())
{
String list;
for (std::set<std::string>::const_iterator tag_it = tag_list.begin(); tag_it != tag_list.end(); ++tag_it)
{
if (!list.empty())
list += ",";
list += *tag_it;
}
os << " tags=\"" << writeXMLEscape(list) << "\"";
}
//restrictions
// for boolean Flags they are implicitly given
if (!stringParamIsFlag)
{
String restrictions = "";
switch (value_type)
{
case ParamValue::INT_VALUE:
case ParamValue::INT_LIST:
{
bool min_set = (it->min_int != -std::numeric_limits<Int>::max());
bool max_set = (it->max_int != std::numeric_limits<Int>::max());
if (max_set || min_set)
{
if (min_set)
{
restrictions += String(it->min_int);
}
restrictions += ':';
if (max_set)
{
restrictions += String(it->max_int);
}
}
}
break;
case ParamValue::DOUBLE_VALUE:
case ParamValue::DOUBLE_LIST:
{
bool min_set = (it->min_float != -std::numeric_limits<double>::max());
bool max_set = (it->max_float != std::numeric_limits<double>::max());
if (max_set || min_set)
{
if (min_set)
{
restrictions += String(it->min_float);
}
restrictions += ':';
if (max_set)
{
restrictions += String(it->max_float);
}
}
}
break;
case ParamValue::STRING_VALUE:
case ParamValue::STRING_LIST:
if (!it->valid_strings.empty())
{
restrictions.concatenate(it->valid_strings.begin(), it->valid_strings.end(), ",");
}
break;
default:
break;
}
// for files we store the restrictions as supported_formats
if (!restrictions.empty())
{
if (it->tags.find("input file") != it->tags.end()
|| it->tags.find("output file") != it->tags.end()
|| it->tags.find("output prefix") != it->tags.end())
{
os << " supported_formats=\"" << writeXMLEscape(restrictions) << "\"";
}
else
{
os << " restrictions=\"" << writeXMLEscape(restrictions) << "\"";
}
}
}
//finish opening tag
switch (value_type)
{
case ParamValue::INT_VALUE:
case ParamValue::DOUBLE_VALUE:
case ParamValue::STRING_VALUE:
os << " />" << "\n";
break;
case ParamValue::STRING_LIST:
{
os << ">" << "\n";
const std::vector<std::string>& list = it->value;
for (Size i = 0; i < list.size(); ++i)
{
os << indentation << " <LISTITEM value=\"" << Internal::encodeTab(writeXMLEscape(list[i])) << "\"/>" << "\n";
}
os << indentation << "</ITEMLIST>" << "\n";
}
break;
case ParamValue::INT_LIST:
{
os << ">" << "\n";
const IntList& list = it->value;
for (Size i = 0; i < list.size(); ++i)
{
os << indentation << " <LISTITEM value=\"" << list[i] << "\"/>" << "\n";
}
os << indentation << "</ITEMLIST>" << "\n";
}
break;
case ParamValue::DOUBLE_LIST:
{
os << ">" << "\n";
const DoubleList& list = it->value;
for (Size i = 0; i < list.size(); ++i)
{
os << indentation << " <LISTITEM value=\"" << list[i] << "\"/>" << "\n";
}
os << indentation << "</ITEMLIST>" << "\n";
}
break;
default:
break;
}
}
++it;
}
// if we had tags ...
if (param.begin() != param.end())
{
//close remaining tags
const std::vector<Param::ParamIterator::TraceInfo>& trace = it.getTrace();
for (std::vector<Param::ParamIterator::TraceInfo>::const_iterator it2 = trace.begin(); it2 != trace.end(); ++it2)
{
Size ss = indentation.size();
indentation.resize(ss - 2);
os << indentation << "</NODE>" << "\n";
}
}
os << "</PARAMETERS>" << std::endl; // forces a flush
}
void ParamXMLFile::load(const String& filename, Param& param)
{
Internal::ParamXMLHandler handler(param, filename, schema_version_);
parse_(filename, &handler);
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/TextFile.cpp | .cpp | 4,409 | 171 | // 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/FORMAT/TextFile.h>
#include <OpenMS/SYSTEM/File.h>
#include <fstream>
using namespace std;
namespace OpenMS
{
TextFile::TextFile() = default;
TextFile::~TextFile() = default;
TextFile::TextFile(const String& filename, bool trim_lines, Int first_n, bool skip_empty_lines, const String& comment_symbol)
{
load(filename, trim_lines, first_n, skip_empty_lines, comment_symbol);
}
void TextFile::load(const String& filename, bool trim_lines, Int first_n, bool skip_empty_lines, const String& comment_symbol)
{
// stream in binary mode prevents interpretation and merging of \r on Windows & MacOS
// .. so we can deal with it ourselves in a consistent way
ifstream is(filename.c_str(), ios_base::in | ios_base::binary);
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);
}
}
buffer_.clear();
String str;
bool had_enough = false;
while (getLine(is, str) && !had_enough)
{
if (trim_lines)
{
str.trim();
}
// skip? (only after trimming!)
if (skip_empty_lines && str.empty())
{
continue;
}
// skip due to comment line
if ( (!comment_symbol.empty()) && str.hasPrefix(comment_symbol))
{
continue;
}
buffer_.push_back(str);
if (first_n > -1 && static_cast<Int>(buffer_.size()) == first_n)
{
had_enough = true;
break;
}
} // while
}
void TextFile::store(const String& filename)
{
ofstream os;
// stream not opened in binary mode, thus "\n" will be evaluated platform dependent (e.g. resolve to \r\n on Windows)
os.open(filename.c_str(), ofstream::out);
if (!os)
{
throw Exception::UnableToCreateFile(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename);
}
for (const String& it : buffer_)
{
if (it.hasSuffix("\n"))
{
if (it.hasSuffix("\r\n"))
{
os << it.chop(2) << "\n";
}
else
{
os << it;
}
}
else
{
os << it << "\n";
}
}
os.close();
}
std::istream& TextFile::getLine(std::istream& is, std::string& t)
{
t.clear();
// The characters in the stream are read one-by-one using a std::streambuf.
// That is faster than reading them one-by-one using the std::istream.
// Code that uses streambuf this way must be guarded by a sentry object.
std::istream::sentry se(is, true);
if (!se)
{ // the stream has an error
return is;
}
std::streambuf* sb = is.rdbuf();
for (;;)
{
int c = sb->sbumpc(); // get and advance to next char
switch (c) {
case '\n':
return is;
case '\r': // consume next '\n' (if any) and return
if (sb->sgetc() == '\n') // peek current char
{
sb->sbumpc(); // consume it
}
return is;
case std::streambuf::traits_type::eof():
is.setstate(std::ios::eofbit); // still allows: while(is == true)
if (t.empty())
{ // only if we just started a new line, we set the is.fail() == true, ie. is == false
is.setstate(std::ios::badbit);
}
return is;
default:
t += (char)c;
}
}
}
TextFile::ConstIterator TextFile::begin() const
{
return buffer_.begin();
}
TextFile::ConstIterator TextFile::end() const
{
return buffer_.end();
}
TextFile::Iterator TextFile::begin()
{
return buffer_.begin();
}
TextFile::Iterator TextFile::end()
{
return buffer_.end();
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/SwathFile.cpp | .cpp | 15,240 | 382 | // 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/SwathFile.h>
#include <OpenMS/ANALYSIS/OPENSWATH/DATAACCESS/SpectrumAccessSqMass.h>
#include <OpenMS/OPENSWATHALGO/DATAACCESS/DataStructures.h>
#include <OpenMS/FORMAT/DATAACCESS/MSDataChainingConsumer.h>
#include <OpenMS/FORMAT/DATAACCESS/SwathFileConsumer.h>
#include <OpenMS/FORMAT/FileHandler.h>
//TODO remove MzML after we get transform support for our handlers
#include <OpenMS/FORMAT/MzMLFile.h>
#include <OpenMS/FORMAT/MzXMLFile.h>
#include <OpenMS/FORMAT/HANDLERS/MzMLSqliteHandler.h>
#include <OpenMS/FORMAT/HANDLERS/MzMLSqliteSwathHandler.h>
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/METADATA/ExperimentalSettings.h>
#include <OpenMS/SYSTEM/File.h>
#include <memory> // for make_shared
namespace OpenMS
{
using Interfaces::IMSDataConsumer;
/// Loads a Swath run from a list of split mzML files
std::vector<OpenSwath::SwathMap> SwathFile::loadSplit(StringList file_list,
const String& tmp,
std::shared_ptr<ExperimentalSettings>& exp_meta,
const String& readoptions)
{
int progress = 0;
startProgress(0, file_list.size(), "Loading data");
std::vector<OpenSwath::SwathMap> swath_maps(file_list.size());
#ifdef _OPENMP
#pragma omp parallel for
#endif
for (SignedSize i = 0; i < boost::numeric_cast<SignedSize>(file_list.size()); ++i)
{
#ifdef _OPENMP
#pragma omp critical (OPENMS_SwathFile_loadSplit)
#endif
{
std::cout << "Loading file " << i << " with name " << file_list[i] << " using readoptions " << readoptions << '\n';
}
String tmp_fname = "openswath_tmpfile_" + String(i) + ".mzML";
std::shared_ptr<PeakMap > exp(new PeakMap);
OpenSwath::SpectrumAccessPtr spectra_ptr;
// Populate meta-data
if (i == 0)
{
exp_meta = populateMetaData_(file_list[i]);
}
if (readoptions == "normal")
{
FileHandler().loadExperiment(file_list[i], *exp.get(), {FileTypes::MZML});
spectra_ptr = SimpleOpenMSSpectraFactory::getSpectrumAccessOpenMSPtr(exp);
}
else if (readoptions == "cache")
{
// Cache and load the exp (metadata only) file again
spectra_ptr = doCacheFile_(file_list[i], tmp, tmp_fname, exp);
}
else
{
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Unknown option " + readoptions);
}
OpenSwath::SwathMap swath_map;
bool ms1 = false;
double upper = -1, lower = -1, center = -1;
if (exp->empty())
{
std::cerr << "WARNING: File " << file_list[i] << "\n does not have any scans - I will skip it" << std::endl;
continue;
}
if (exp->getSpectra()[0].getPrecursors().empty())
{
std::cout << "NOTE: File " << file_list[i] << "\n does not have any precursors - I will assume it is the MS1 scan.\n";
ms1 = true;
}
else
{
// Checks that this is really a SWATH map and extracts upper/lower window
OpenSwathHelper::checkSwathMap(*exp.get(), lower, upper, center);
}
swath_map.sptr = spectra_ptr;
swath_map.lower = lower;
swath_map.upper = upper;
swath_map.center = center;
swath_map.ms1 = ms1;
#ifdef _OPENMP
#pragma omp critical (OPENMS_SwathFile_loadSplit)
#endif
{
OPENMS_LOG_DEBUG << "Adding Swath file " << file_list[i] << " with " << swath_map.lower << " to " << swath_map.upper << '\n';
swath_maps[i] = swath_map;
setProgress(progress++);
}
}
endProgress();
return swath_maps;
}
/// Loads a Swath run from a single mzML file
std::vector<OpenSwath::SwathMap> SwathFile::loadMzML(const String& file,
const String& tmp,
std::shared_ptr<ExperimentalSettings>& exp_meta,
const String& readoptions,
Interfaces::IMSDataConsumer* plugin_consumer)
{
std::cout << "Loading mzML file " << file << " using readoptions " << readoptions << '\n';
String tmp_fname = tmp.hasSuffix('/') ? File::getUniqueName() : ""; // use tmp-filename if just a directory was given
startProgress(0, 1, "Loading metadata file " + file);
std::shared_ptr<PeakMap> exp_stripped = populateMetaData_(file);
exp_meta = exp_stripped;
// First pass through the file -> get the meta data
std::cout << "Will analyze the metadata first to determine the number of SWATH windows and the window sizes.\n";
std::vector<int> swath_counter;
int nr_ms1_spectra;
std::vector<OpenSwath::SwathMap> known_window_boundaries;
countScansInSwath_(exp_stripped->getSpectra(), swath_counter, nr_ms1_spectra, known_window_boundaries);
std::cout << "Determined there to be " << swath_counter.size()
<< " SWATH windows and in total " << nr_ms1_spectra << " MS1 spectra\n";
endProgress();
std::shared_ptr<FullSwathFileConsumer> dataConsumer;
startProgress(0, 1, "Loading data file " + file);
if (readoptions == "normal")
{
dataConsumer = std::make_shared<RegularSwathFileConsumer>(known_window_boundaries);
dataConsumer->setExperimentalSettings(*exp_meta.get());
}
else if (readoptions == "cache")
{
dataConsumer = std::make_shared<CachedSwathFileConsumer>(known_window_boundaries, tmp, tmp_fname, nr_ms1_spectra, swath_counter);
dataConsumer->setExperimentalSettings(*exp_meta.get());
}
else if (readoptions == "split")
{
// WARNING: swath_maps will be empty when querying retrieveSwathMaps()
dataConsumer = std::make_shared<MzMLSwathFileConsumer>(known_window_boundaries, tmp, tmp_fname, nr_ms1_spectra, swath_counter);
dataConsumer->setExperimentalSettings(*exp_meta.get());
}
else
{
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Unknown or unsupported option " + readoptions);
}
std::vector<Interfaces::IMSDataConsumer *> consumer_list;
// only use plugin if non-empty
if (plugin_consumer)
{
exp_meta->setMetaValue("nr_ms1_spectra", nr_ms1_spectra); // required for SwathQC::getExpSettingsFunc()
plugin_consumer->setExperimentalSettings(*exp_meta.get()); // set the meta data
exp_meta->removeMetaValue("nr_ms1_spectra"); // served its need. remove
// plugin_consumer->setExpectedSize(nr_ms1_spectra + accumulate(swath_counter)); // not needed currently
consumer_list.push_back(plugin_consumer);
}
consumer_list.push_back(dataConsumer.get());
MSDataChainingConsumer chaining_consumer(consumer_list);
MzMLFile().transform(file, &chaining_consumer, false, true); // we do not need to reload metadata, it has already been loaded
OPENMS_LOG_DEBUG << "Finished parsing Swath file \n";
std::vector<OpenSwath::SwathMap> swath_maps;
dataConsumer->retrieveSwathMaps(swath_maps);
endProgress();
return swath_maps;
}
/// Loads a Swath run from a single mzXML file
std::vector<OpenSwath::SwathMap> SwathFile::loadMzXML(const String& file,
const String& tmp,
std::shared_ptr<ExperimentalSettings>& exp_meta,
const String& readoptions)
{
std::cout << "Loading mzXML file " << file << " using readoptions " << readoptions << '\n';
String tmp_fname = "openswath_tmpfile";
startProgress(0, 1, "Loading metadata file " + file);
std::shared_ptr<PeakMap > experiment_metadata(new PeakMap);
FileHandler f;
f.getOptions().setAlwaysAppendData(true);
f.getOptions().setFillData(false);
f.loadExperiment(file, *experiment_metadata, {FileTypes::MZXML});
exp_meta = experiment_metadata;
// First pass through the file -> get the meta data
std::cout << "Will analyze the metadata first to determine the number of SWATH windows and the window sizes.\n";
std::vector<int> swath_counter;
int nr_ms1_spectra;
std::vector<OpenSwath::SwathMap> known_window_boundaries;
countScansInSwath_(experiment_metadata->getSpectra(), swath_counter, nr_ms1_spectra, known_window_boundaries);
std::cout << "Determined there to be " << swath_counter.size() <<
" SWATH windows and in total " << nr_ms1_spectra << " MS1 spectra\n";
endProgress();
FullSwathFileConsumer* dataConsumer;
startProgress(0, 1, "Loading data file " + file);
if (readoptions == "normal")
{
dataConsumer = new RegularSwathFileConsumer(known_window_boundaries);
MzXMLFile().transform(file, dataConsumer);
}
else if (readoptions == "cache")
{
dataConsumer = new CachedSwathFileConsumer(known_window_boundaries, tmp, tmp_fname, nr_ms1_spectra, swath_counter);
MzXMLFile().transform(file, dataConsumer);
}
else if (readoptions == "split")
{
dataConsumer = new MzMLSwathFileConsumer(known_window_boundaries, tmp, tmp_fname, nr_ms1_spectra, swath_counter);
MzXMLFile().transform(file, dataConsumer);
}
else
{
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Unknown or unsupported option " + readoptions);
}
OPENMS_LOG_DEBUG << "Finished parsing Swath file \n";
std::vector<OpenSwath::SwathMap> swath_maps;
dataConsumer->retrieveSwathMaps(swath_maps);
delete dataConsumer;
endProgress();
return swath_maps;
}
/// Loads a Swath run from a single sqMass file
std::vector<OpenSwath::SwathMap> SwathFile::loadSqMass(const String& file, std::shared_ptr<ExperimentalSettings>& /* exp_meta */)
{
startProgress(0, 1, "Loading sqmass data file " + file);
OpenMS::Internal::MzMLSqliteSwathHandler sql_mass_reader(file);
std::vector<OpenSwath::SwathMap> swath_maps = sql_mass_reader.readSwathWindows();
for (Size k = 0; k < swath_maps.size(); k++)
{
std::vector<int> indices = sql_mass_reader.readSpectraForWindow(swath_maps[k]);
OpenMS::Internal::MzMLSqliteHandler handler(file, 0);
OpenSwath::SpectrumAccessPtr sptr(new OpenMS::SpectrumAccessSqMass(handler, indices));
swath_maps[k].sptr = sptr;
}
// also store the MS1 map
OpenSwath::SwathMap ms1_map;
std::vector<int> indices = sql_mass_reader.readMS1Spectra();
OpenMS::Internal::MzMLSqliteHandler handler(file, 0);
OpenSwath::SpectrumAccessPtr sptr(new OpenMS::SpectrumAccessSqMass(handler, indices));
ms1_map.sptr = sptr;
ms1_map.ms1 = true;
swath_maps.push_back(ms1_map);
endProgress();
std::cout << "Determined there to be " << swath_maps.size() <<
" SWATH windows and in total " << indices.size() << " MS1 spectra\n";
return swath_maps;
}
/// Cache a file to disk
OpenSwath::SpectrumAccessPtr SwathFile::doCacheFile_(const String& in, const String& tmp, const String& tmp_fname,
const std::shared_ptr<PeakMap >& experiment_metadata)
{
String cached_file = tmp + tmp_fname + ".cached";
String meta_file = tmp + tmp_fname;
// Create new consumer, transform infile, write out metadata
{
MSDataCachedConsumer cachedConsumer(cached_file, true);
MzMLFile().transform(in, &cachedConsumer, *experiment_metadata.get());
Internal::CachedMzMLHandler().writeMetadata(*experiment_metadata.get(), meta_file, true);
} // ensure that filestream gets closed
std::shared_ptr<PeakMap > exp(new PeakMap);
FileHandler().loadExperiment(meta_file, *exp.get(), {FileTypes::MZML});
return SimpleOpenMSSpectraFactory::getSpectrumAccessOpenMSPtr(exp);
}
/// Only read the meta data from a file and use it to populate exp_meta
std::shared_ptr< PeakMap > SwathFile::populateMetaData_(const String& file)
{
std::shared_ptr<PeakMap > experiment_metadata(new PeakMap);
FileHandler f;
f.getOptions().setAlwaysAppendData(true);
f.getOptions().setFillData(false);
f.loadExperiment(file, *experiment_metadata);
return experiment_metadata;
}
/// Counts the number of scans in a full Swath file (e.g. concatenated non-split file)
void SwathFile::countScansInSwath_(const std::vector<MSSpectrum>& exp,
std::vector<int>& swath_counter, int& nr_ms1_spectra,
std::vector<OpenSwath::SwathMap>& known_window_boundaries,
double TOLERANCE)
{
int ms1_counter = 0;
for (Size i = 0; i < exp.size(); i++)
{
const MSSpectrum& s = exp[i];
{
if (s.getMSLevel() == 1)
{
ms1_counter++;
}
else
{
if (s.getPrecursors().empty())
{
throw Exception::InvalidParameter(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Found SWATH scan (MS level 2 scan) without a precursor. Cannot determine SWATH window.");
}
const std::vector<Precursor> prec = s.getPrecursors();
// set ion mobility if exists, otherwise will take default value of -1
double imLower, imUpper;
if (s.metaValueExists("ion mobility lower limit"))
{
imLower = s.getMetaValue("ion mobility lower limit"); // want this to be -1 if no ion mobility
imUpper = s.getMetaValue("ion mobility upper limit");
}
else
{
imLower = -1;
imUpper = -1;
}
const OpenSwath::SwathMap boundary(prec[0].getMZ() - prec[0].getIsolationWindowLowerOffset(),
prec[0].getMZ() + prec[0].getIsolationWindowUpperOffset(),
prec[0].getMZ(),
imLower,
imUpper,
false);
bool found = false;
for (Size j = 0; j < known_window_boundaries.size(); j++)
{
// Check if the current scan is within the known window boundaries
if (known_window_boundaries[j].isEqual(boundary, TOLERANCE))
{
found = true;
swath_counter[j]++;
}
}
if (!found)
{
// we found a new SWATH scan
swath_counter.push_back(1);
known_window_boundaries.push_back(boundary);
OPENMS_LOG_DEBUG << "Adding Swath centered at " << boundary.center
<< " m/z with an isolation window of " << boundary.lower << " to " << boundary.upper
<< " m/z and IM start of " << boundary.imLower << " and IM end of " << boundary.imUpper << '\n';
}
}
}
}
nr_ms1_spectra = ms1_counter;
std::cout << "Determined there to be " << swath_counter.size() <<
" SWATH windows and in total " << nr_ms1_spectra << " MS1 spectra\n";
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/PercolatorInfile.cpp | .cpp | 23,403 | 653 | // 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, Johannes von Kleist $
// --------------------------------------------------------------------------
#include <OpenMS/FORMAT/PercolatorInfile.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/CONCEPT/Constants.h>
#include <OpenMS/METADATA/SpectrumLookup.h>
#include <OpenMS/FORMAT/CsvFile.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <regex>
#include <functional>
#include <unordered_set>
namespace OpenMS
{
using namespace std;
void PercolatorInfile::store(const String& pin_file,
const PeptideIdentificationList& peptide_ids,
const StringList& feature_set,
const std::string& enz,
int min_charge,
int max_charge)
{
TextFile txt = preparePin_(peptide_ids, feature_set, enz, min_charge, max_charge);
txt.store(pin_file);
}
// uses spectrum_reference, if empty uses spectrum_id, if also empty fall back to using index
String PercolatorInfile::getScanIdentifier(
const PeptideIdentification& pid, size_t index)
{
// MSGF+ uses this field, is empty if not specified
String scan_identifier = pid.getSpectrumReference();
if (scan_identifier.empty())
{
// XTandem uses this (integer) field
// these ids are 1-based in contrast to the index which is 0-based. This might be problematic to use for merging
if (pid.metaValueExists("spectrum_id") && !pid.getMetaValue("spectrum_id").toString().empty())
{
scan_identifier = "scan=" + pid.getMetaValue("spectrum_id").toString();
}
else
{
scan_identifier = "index=" + String(index); // fall back
OPENMS_LOG_WARN << "no known spectrum identifiers, using index [1,n] - use at own risk." << endl;
}
}
return scan_identifier.removeWhitespaces();
}
PeptideIdentificationList PercolatorInfile::load(
const String& pin_file,
bool higher_score_better,
const String& score_name,
const StringList& extra_scores,
StringList& filenames,
String decoy_prefix,
double threshold,
bool SageAnnotation)
{
CsvFile csv(pin_file, '\t');
//Sage Variables, initialized in the following block if SageAnnotation is set
map<int, vector<PeptideHit::PeakAnnotation>> anno_mapping;
CsvFile tsv;
CsvFile annos;
unordered_map<String, size_t> to_idx_t;
if (SageAnnotation) // Block for special treatment of sage
{
String tsv_file_path = pin_file.substr(0, pin_file.size()-3);
tsv_file_path = tsv_file_path + "tsv";
tsv = CsvFile(tsv_file_path,'\t');
String temp_diff = "results.sage.pin";
String anno_file_path = pin_file.substr(0, pin_file.size()-temp_diff.length());
anno_file_path = anno_file_path + "matched_fragments.sage.tsv";
annos = CsvFile(anno_file_path, '\t');
//map PSMID to vec of PeakAnnotation
StringList sage_tsv_header;
tsv.getRow(0, sage_tsv_header);
{
int idx_t{};
for (const auto& h : sage_tsv_header) { to_idx_t[h] = idx_t++; }
}
// processs annotation file
StringList sage_annotation_header;
annos.getRow(0, sage_annotation_header);
unordered_map<String, size_t> to_idx_a; // map column name to column index, for full annotation file file
{
int idx_a{};
for (const auto& h : sage_annotation_header) { to_idx_a[h] = idx_a++; }
}
// map PSMs -> PeakAnnotation vector
auto num_rows = annos.rowCount();
for (size_t i = 1; i < num_rows; ++i)
{
StringList row;
annos.getRow(i, row);
//Check if mapping already has PSM, if it does add
if (anno_mapping.find(row[to_idx_a.at("psm_id")].toInt()) == anno_mapping.end())
{
//Make a new vector of annotations
PeptideHit::PeakAnnotation peak_temp;
peak_temp.annotation = row[to_idx_a.at("fragment_type")] + row[to_idx_a.at("fragment_ordinals")];
peak_temp.charge = row[to_idx_a.at("fragment_charge")].toInt();
peak_temp.intensity = row[to_idx_a.at("fragment_intensity")].toDouble();
peak_temp.mz = row[to_idx_a.at("fragment_mz_experimental")].toDouble();
vector<PeptideHit::PeakAnnotation> temp_anno_vec;
temp_anno_vec.push_back(peak_temp);
anno_mapping[ row[to_idx_a.at("psm_id")].toInt() ] = temp_anno_vec;
}
else
{
//Add values to exisiting vector
PeptideHit::PeakAnnotation peak_temp;
peak_temp.annotation = row[to_idx_a.at("fragment_type")] + row[to_idx_a.at("fragment_ordinals")];
peak_temp.charge = row[to_idx_a.at("fragment_charge")].toInt();
peak_temp.intensity = row[to_idx_a.at("fragment_intensity")].toDouble();
peak_temp.mz = row[to_idx_a.at("fragment_mz_experimental")].toDouble();
anno_mapping[ row[to_idx_a.at("psm_id")].toInt() ].push_back(peak_temp);
}
}
}
StringList pin_header;
csv.getRow(0, pin_header);
unordered_map<String, size_t> to_idx; // map column name to column index
{
int idx{};
for (const auto& h : pin_header) { to_idx[h] = idx++; }
}
// determine file name column index in percolator in file
int file_name_column_index{-1};
if (auto it = std::find(pin_header.begin(), pin_header.end(), "FileName"); it != pin_header.end())
{
file_name_column_index = it - pin_header.begin();
}
// determine extra scores and store column indices
std::set<String> found_extra_scores; // additional (non-main) scores that should be stored in the PeptideHit, order important for comparable idXML
for (const String& s : extra_scores)
{
if (auto it = std::find(pin_header.begin(), pin_header.end(), s); it != pin_header.end())
{
found_extra_scores.insert(s);
}
else
{
OPENMS_LOG_WARN << "Extra score: " << s << " not found in Percolator input file." << endl;
}
}
// charge columns are not standardized, so we check for the format and create hash to lookup column name to charge mapping
std::regex charge_one_hot_pattern("^charge\\d+$");
std::regex sage_one_hot_pattern("^z=\\d+$");
String charge_prefix;
unordered_map<String, int> col_name_to_charge;
// Special handling for sage: sage produces an additional column for PSMs outside of the "suggested" charge search range (e.g., charge 2-5).
// The reason is that sage searches always for the charge annotated in the spectrum raw file. Only if the annotation is missing it will search
// the suggested charge range.
bool found_sage_otherz_charge_column{false};
for (const String& c : pin_header)
{
if (std::regex_match(c, charge_one_hot_pattern))
{
col_name_to_charge[c] = c.substr(6).toInt();
charge_prefix = "charge";
}
else if (std::regex_match(c, sage_one_hot_pattern))
{
col_name_to_charge[c] = c.substr(2).toInt();
charge_prefix = "z=";
}
else if (c == "z=other") // SAGE
{
found_sage_otherz_charge_column = true;
OPENMS_LOG_DEBUG << "Found SAGE charge column 'z=other'. Will extract charge from this column if charge was not set in the one-hot encoded charge columns." << endl;
}
}
auto n_rows = csv.rowCount();
PeptideIdentificationList pids;
pids.reserve(n_rows);
String spec_id;
String raw_file_name("UNKNOWN");
unordered_map<String, size_t> map_filename_to_idx; // fast lookup of filename to index in filenames vector
for (size_t i = 1; i != n_rows; ++i)
{
StringList row;
csv.getRow(i, row);
StringList t_row;
if (SageAnnotation)
{
tsv.getRow(i, t_row);
// skip if spectrum_q is above threshold
if (t_row[to_idx_t.at("spectrum_q")].toDouble() > threshold ) continue;
}
if (row.size() != pin_header.size())
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Error: line " + String(i) + " of file '" + pin_file + "' does not have the same number of columns as the pin_header!", String(i));
}
if (file_name_column_index >= 0)
{
raw_file_name = row[file_name_column_index];
if (map_filename_to_idx.find(raw_file_name) == map_filename_to_idx.end())
{
filenames.push_back(raw_file_name);
map_filename_to_idx[raw_file_name] = filenames.size() - 1;
}
}
// NOTE: In our pin files that we WRITE, SpecID will be filename + vendor spectrum native ID
// However, many search engines (e.g. Sage) choose arbitrary IDs, which is unfortunately allowed
// by this loosely defined format.
const String& sSpecId = row[to_idx.at("SpecId")];
double IM = 0.0;
if (auto it = to_idx.find("ion_mobility"); it != to_idx.end())
{
const String& sIM = row[it->second]; // read IM from e.g. Sage output
IM = sIM.toDouble();
}
// In theory, this should be an integer, but Sage currently cannot extract the number from all vendor spectrum IDs,
// so it writes the full ID as string
String sScanNr = row[to_idx.at("ScanNr")];
if (sSpecId != spec_id)
{
pids.resize(pids.size() + 1);
pids.back().setHigherScoreBetter(higher_score_better);
pids.back().setScoreType(score_name);
pids.back().setMetaValue(Constants::UserParam::ID_MERGE_INDEX, map_filename_to_idx.at(raw_file_name));
pids.back().setRT(row[to_idx.at("retentiontime")].toDouble() * 60.0); // search engines typically write minutes (e.g., sage)
pids.back().setMetaValue("PinSpecId", sSpecId);
if (IM > 0.0) // Sage might annotate 0.0 if no IM is present
{
pids.back().setMetaValue(Constants::UserParam::IM, IM);
}
// Since ScanNr is the closest to help in identifying the spectrum in the file later on,
// we use it as spectrum_reference. Since it can be integer only or the complete
// vendor ID, you will need a lookup in case of number only later!!
pids.back().setSpectrumReference(sScanNr);
}
String sPeptide = row[to_idx.at("Peptide")];
const double score = row[to_idx.at(score_name)].toDouble();
String target_decoy = row[to_idx.at("Label")].toInt() == 1 ? "target" : "decoy";
const String& sProteins = row[to_idx.at("Proteins")];
int rank = to_idx.count("rank") ? row[to_idx.at("rank")].toInt() : 1;
StringList accessions;
int charge = 0;
for (const auto& [name, z] : col_name_to_charge)
{
if (row[to_idx.at(name)] == "1")
{
charge = z;
break;
}
}
// all one-hot encoded charge columns are zero. Use value in the sage "z=other" column if it exists.
if (charge == 0 && found_sage_otherz_charge_column)
{
charge = row[to_idx.at("z=other")].toInt();
}
if (charge != 0)
{
pids.back().setMZ(row[to_idx.at("ExpMass")].toDouble() / std::fabs(charge) + Constants::PROTON_MASS_U);
}
sProteins.split(';', accessions);
// deduce decoy state from accessions if decoy_prefix is set
if (!decoy_prefix.empty())
{
bool dec = false;
bool tgt = false;
for (const auto& acc : accessions)
{
if (!(dec && tgt))
{
if (acc.hasPrefix(decoy_prefix))
{
dec = true;
}
else
{
tgt = true;
}
}
else
{
break;
}
}
if (tgt && dec)
{
target_decoy = "target+decoy";
}
else if (tgt)
{
target_decoy = "target";
}
else {
target_decoy = "decoy";
}
}
// needs to handle strings like: [+42]-MVLVQDLLHPTAASEAR, [+304.207]-ETC[+57.0215]RQLGLGTNIYNAER etc.
sPeptide.substitute("]-", "]."); // we can parse [+42].MVLVQDLLHPTAASEAR
sPeptide.substitute("-[", ".["); // we can parse MVLVQDLLHPTAASEAR.[+111]
AASequence aa_seq = AASequence::fromString(sPeptide);
PeptideHit ph(score, rank - 1, charge, std::move(aa_seq));
ph.setMetaValue("target_decoy", target_decoy);
for (const auto& name : found_extra_scores)
{
String value = row[to_idx.at(name)];
if (name == "ln(-poisson)" && value == "inf") value = "3.5"; // workaround for Sage
ph.setMetaValue(name, value);
}
// adding own meta values
if (SageAnnotation)
{
ph.setMetaValue("spectrum_q", t_row[to_idx_t.at("spectrum_q")].toDouble()); //TODO: check if column exists / SAGE specific treatment
}
ph.setMetaValue("DeltaMass", ( row[to_idx.at("ExpMass")].toDouble() - row[to_idx.at("CalcMass")].toDouble()) );
// add annotations
if (SageAnnotation)
{
if (anno_mapping.find(sSpecId.toInt()) != anno_mapping.end())
{
// copy annotations from mapping to PeptideHit
vector<PeptideHit::PeakAnnotation> pep_vec;
for (const PeptideHit::PeakAnnotation& pep : anno_mapping[sSpecId.toInt()])
{
pep_vec.push_back(pep) ;
}
ph.setPeakAnnotations(pep_vec);
}
}
// add link to protein (we only know the accession but not start/end, aa_before/after in protein at this point)
for (const String& accession : accessions)
{
ph.addPeptideEvidence(PeptideEvidence(accession));
}
pids.back().insertHit(std::move(ph));
}
return pids;
}
TextFile PercolatorInfile::preparePin_(
const PeptideIdentificationList& peptide_ids,
const StringList& feature_set,
const std::string& enz,
int min_charge,
int max_charge)
{
TextFile txt;
txt.addLine(ListUtils::concatenate(feature_set, '\t'));
if (peptide_ids.empty())
{
OPENMS_LOG_WARN << "No identifications provided. Creating empty percolator input." << endl;
return txt;
}
// extract native id (usually in spectrum_reference)
const String sid = getScanIdentifier(peptide_ids[0], 0);
// determine RegEx to extract scan/index number
boost::regex scan_regex = boost::regex(SpectrumLookup::getRegExFromNativeID(sid));
// keep track of errors
size_t missing_meta_value_count{};
set<String> missing_meta_values;
size_t index = 0;
for (const PeptideIdentification& pep_id : peptide_ids)
{
index++;
// try to make a file and scan unique identifier
String scan_identifier = getScanIdentifier(pep_id, index);
String file_identifier = pep_id.getMetaValue("file_origin", String());
file_identifier += (String)pep_id.getMetaValue("id_merge_index", String());
Int scan_number = SpectrumLookup::extractScanNumber(scan_identifier, scan_regex, true);
double exp_mass = pep_id.getMZ();
double retention_time = pep_id.getRT();
for (const PeptideHit& psm : pep_id.getHits())
{
if (psm.getPeptideEvidences().empty())
{
OPENMS_LOG_WARN << "PSM (PeptideHit) without protein reference found. "
<< "This may indicate incomplete mapping during PeptideIndexing (e.g., wrong enzyme settings)."
<< "Will skip this PSM." << endl;
continue;
}
PeptideHit hit(psm); // make a copy of the hit to store temporary features
hit.setMetaValue("SpecId", file_identifier + scan_identifier);
hit.setMetaValue("ScanNr", scan_number);
if (hit.getTargetDecoyType() == PeptideHit::TargetDecoyType::UNKNOWN)
{
OPENMS_LOG_WARN << "PSM without target/decoy information found. "
<< "This may indicate incomplete mapping during PeptideIndexing (e.g., wrong decoy prefix settings)."
<< "Will skip this PSM." << endl;
continue;
}
int label = hit.isDecoy() ? -1 : 1;
hit.setMetaValue("Label", label);
int charge = hit.getCharge();
String unmodified_sequence = hit.getSequence().toUnmodifiedString();
double calc_mass;
if (!hit.metaValueExists("CalcMass"))
{
calc_mass = hit.getSequence().getMZ(charge);
hit.setMetaValue("CalcMass", calc_mass); // Percolator calls is CalcMass instead of m/z
}
else
{
calc_mass = hit.getMetaValue("CalcMass");
}
if (hit.metaValueExists("IsotopeError")) // for backwards compatibility (generated by MSGFPlusAdaper OpenMS < 2.6)
{
float isoErr = hit.getMetaValue("IsotopeError").toString().toFloat();
exp_mass = exp_mass - (isoErr * Constants::C13C12_MASSDIFF_U) / charge;
}
else if (hit.metaValueExists(Constants::UserParam::ISOTOPE_ERROR)) // OpenMS user param name for isotope error
{
float isoErr = hit.getMetaValue(Constants::UserParam::ISOTOPE_ERROR).toString().toFloat();
exp_mass = exp_mass - (isoErr * Constants::C13C12_MASSDIFF_U) / charge;
}
hit.setMetaValue("ExpMass", exp_mass);
// needed in case "description of correct" option is used
double delta_mass = exp_mass - calc_mass;
hit.setMetaValue("deltamass", delta_mass);
hit.setMetaValue("retentiontime", retention_time);
hit.setMetaValue("mass", exp_mass);
double score = hit.getScore();
// TODO better to use log scores for E-value based scores
hit.setMetaValue("score", score);
int peptide_length = unmodified_sequence.size();
hit.setMetaValue("peplen", peptide_length);
for (int i = min_charge; i <= max_charge; ++i)
{
hit.setMetaValue("charge" + String(i), charge == i);
}
// just first peptide evidence
char aa_before = hit.getPeptideEvidences().front().getAABefore();
char aa_after = hit.getPeptideEvidences().front().getAAAfter();
bool enzN = isEnz_(aa_before, unmodified_sequence.prefix(1)[0], enz);
hit.setMetaValue("enzN", enzN);
bool enzC = isEnz_(unmodified_sequence.suffix(1)[0], aa_after, enz);
hit.setMetaValue("enzC", enzC);
int enzInt = countEnzymatic_(unmodified_sequence, enz);
hit.setMetaValue("enzInt", enzInt);
hit.setMetaValue("dm", delta_mass);
double abs_delta_mass = abs(delta_mass);
hit.setMetaValue("absdm", abs_delta_mass);
//peptide
String sequence = "";
aa_before = aa_before == '[' ? '-' : aa_before;
aa_after = aa_after == ']' ? '-' : aa_after;
sequence += aa_before;
sequence += ".";
// Percolator uses square brackets to indicate PTMs
sequence += hit.getSequence().toBracketString(false, true);
sequence += ".";
sequence += aa_after;
hit.setMetaValue("Peptide", sequence);
//proteinId1
StringList proteins;
for (const PeptideEvidence& pep : hit.getPeptideEvidences())
{
proteins.push_back(pep.getProteinAccession());
}
hit.setMetaValue("Proteins", ListUtils::concatenate(proteins, '\t'));
StringList feats;
for (const String& feat : feature_set)
{
// Some Hits have no NumMatchedMainIons, and MeanError, etc. values. Have to ignore them!
if (hit.metaValueExists(feat))
{
feats.push_back(hit.getMetaValue(feat).toString());
}
}
// here: feats (metavalues in peptide hits) and feature_set are equal if they have same size (if no metavalue is missing)
if (feats.size() == feature_set.size())
{ // only if all feats were present add
txt.addLine(ListUtils::concatenate(feats, '\t'));
}
else
{ // at least one feature is missing in the current peptide hit
missing_meta_value_count++;
for (const auto& f : feature_set)
{
if (std::find(feats.begin(), feats.end(), f) == feats.end()) missing_meta_values.insert(f);
}
}
}
}
// print warnings
if (missing_meta_value_count != 0)
{
OPENMS_LOG_WARN << "There were peptide hits with missing features/meta values. Skipped peptide hits: " << missing_meta_value_count << endl;
OPENMS_LOG_WARN << "Names of missing meta values: " << endl;
for (const auto& f : missing_meta_values)
{
OPENMS_LOG_WARN << f << endl;
}
}
return txt;
}
bool PercolatorInfile::isEnz_(const char& n, const char& c, const std::string& enz)
{
if (enz == "trypsin")
{
return ((n == 'K' || n == 'R') && c != 'P') || n == '-' || c == '-';
}
else if (enz == "trypsinp")
{
return (n == 'K' || n == 'R') || n == '-' || c == '-';
}
else if (enz == "chymotrypsin")
{
return ((n == 'F' || n == 'W' || n == 'Y' || n == 'L') && c != 'P') || n == '-' || c == '-';
}
else if (enz == "thermolysin")
{
return ((c == 'A' || c == 'F' || c == 'I' || c == 'L' || c == 'M'
|| c == 'V' || (n == 'R' && c == 'G')) && n != 'D' && n != 'E') || n == '-' || c == '-';
}
else if (enz == "proteinasek")
{
return (n == 'A' || n == 'E' || n == 'F' || n == 'I' || n == 'L'
|| n == 'T' || n == 'V' || n == 'W' || n == 'Y') || n == '-' || c == '-';
}
else if (enz == "pepsin")
{
return ((c == 'F' || c == 'L' || c == 'W' || c == 'Y' || n == 'F'
|| n == 'L' || n == 'W' || n == 'Y') && n != 'R') || n == '-' || c == '-';
}
else if (enz == "elastase")
{
return ((n == 'L' || n == 'V' || n == 'A' || n == 'G') && c != 'P')
|| n == '-' || c == '-';
}
else if (enz == "lys-n")
{
return (c == 'K')
|| n == '-' || c == '-';
}
else if (enz == "lys-c")
{
return ((n == 'K') && c != 'P')
|| n == '-' || c == '-';
}
else if (enz == "arg-c")
{
return ((n == 'R') && c != 'P')
|| n == '-' || c == '-';
}
else if (enz == "asp-n")
{
return (c == 'D')
|| n == '-' || c == '-';
}
else if (enz == "glu-c")
{
return ((n == 'E') && (c != 'P'))
|| n == '-' || c == '-';
}
else
{
return true;
}
}
// Function adapted from Enzyme.h in Percolator converter
// TODO: Use existing OpenMS functionality.
Size PercolatorInfile::countEnzymatic_(const String& peptide, const string& enz)
{
Size count = 0;
for (Size ix = 1; ix < peptide.size(); ++ix)
{
if (isEnz_(peptide[ix - 1], peptide[ix], enz))
{
++count;
}
}
return count;
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/MzTabM.cpp | .cpp | 31,386 | 745 | // 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/FORMAT/ControlledVocabulary.h>
#include <OpenMS/FORMAT/MzTabM.h>
#include <OpenMS/SYSTEM/File.h>
#include <regex>
namespace OpenMS
{
MzTabMMetaData::MzTabMMetaData()
{
mz_tab_version.fromCellString(String("2.0.0-M"));
}
const MzTabMMetaData& MzTabM::getMetaData() const
{
return m_meta_data_;
}
void MzTabM::setMetaData(const MzTabMMetaData& md)
{
m_meta_data_ = md;
}
const MzTabMSmallMoleculeSectionRows& MzTabM::getMSmallMoleculeSectionRows() const
{
return m_small_molecule_data_;
}
void MzTabM::setMSmallMoleculeSectionRows(const MzTabMSmallMoleculeSectionRows &m_smlsd)
{
m_small_molecule_data_ = m_smlsd;
}
const MzTabMSmallMoleculeFeatureSectionRows& MzTabM::getMSmallMoleculeFeatureSectionRows() const
{
return m_small_molecule_feature_data_;
}
void MzTabM::setMSmallMoleculeFeatureSectionRows(const MzTabMSmallMoleculeFeatureSectionRows &m_smfsd)
{
m_small_molecule_feature_data_ = m_smfsd;
}
const MzTabMSmallMoleculeEvidenceSectionRows& MzTabM::getMSmallMoleculeEvidenceSectionRows() const
{
return m_small_molecule_evidence_data_;
}
void MzTabM::setMSmallMoleculeEvidenceSectionRows(const MzTabMSmallMoleculeEvidenceSectionRows &m_smesd)
{
m_small_molecule_evidence_data_ = m_smesd;
}
std::vector<String> MzTabM::getMSmallMoleculeOptionalColumnNames() const
{
return getOptionalColumnNames_(m_small_molecule_data_);
}
std::vector<String> MzTabM::getMSmallMoleculeFeatureOptionalColumnNames() const
{
return getOptionalColumnNames_(m_small_molecule_feature_data_);
}
std::vector<String> MzTabM::getMSmallMoleculeEvidenceOptionalColumnNames() const
{
return getOptionalColumnNames_(m_small_molecule_evidence_data_);
}
void MzTabM::addMetaInfoToOptionalColumns(const std::set<String>& keys,
std::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);
}
}
void MzTabM::getFeatureMapMetaValues_(const FeatureMap& feature_map,
std::set<String>& feature_user_value_keys,
std::set<String>& observationmatch_user_value_keys,
std::set<String>& compound_user_value_keys)
{
for (Size i = 0; i < feature_map.size(); ++i)
{
// feature section optional columns
const Feature& f = feature_map[i];
std::vector<String> keys;
f.getKeys(keys);
// replace whitespaces with underscore
std::transform(keys.begin(), keys.end(), keys.begin(), [&](String& s) { return s.substitute(' ', '_'); });
feature_user_value_keys.insert(keys.begin(), keys.end());
auto match_refs = f.getIDMatches();
for (const IdentificationDataInternal::ObservationMatchRef& match_ref : match_refs)
{
// feature section optional columns
std::vector<String> obsm_keys;
match_ref->getKeys(obsm_keys);
// replace whitespaces with underscore
std::transform(obsm_keys.begin(), obsm_keys.end(), obsm_keys.begin(), [&](String& s) { return s.substitute(' ', '_'); });
// remove "IDConverter_trace" metadata from the ObservationMatch
// introduced by the IdentificationDataConverter
// since it leads to convolution of IDConverter_trace_* optional columns
for (const auto& key : obsm_keys)
{
if (!key.hasSubstring("IDConverter_trace"))
{
observationmatch_user_value_keys.insert(key);
}
}
// evidence section optional columns
IdentificationData::IdentifiedMolecule molecule = match_ref->identified_molecule_var;
IdentificationData::IdentifiedCompoundRef compound_ref = molecule.getIdentifiedCompoundRef();
std::vector<String> compound_keys;
compound_ref->getKeys(compound_keys);
// replace whitespaces with underscore
std::transform(compound_keys.begin(), compound_keys.end(), compound_keys.begin(), [&](String& s) { return s.substitute(' ', '_'); });
compound_user_value_keys.insert(compound_keys.begin(), compound_keys.end());
}
}
}
// FeatureMap with associated identification data
MzTabM MzTabM::exportFeatureMapToMzTabM(const FeatureMap& feature_map)
{
MzTabM mztabm;
MzTabMMetaData m_meta_data;
// extract identification data from FeatureMap
const IdentificationData& id_data = feature_map.getIdentificationData();
OPENMS_PRECONDITION(!id_data.empty(),
"The FeatureMap has to have a non empty IdentificationData object attached!")
// extract MetaValues from FeatureMap
std::set<String> feature_user_value_keys;
std::set<String> observationmatch_user_value_keys;
std::set<String> compound_user_value_keys;
MzTabM::getFeatureMapMetaValues_(feature_map, feature_user_value_keys, observationmatch_user_value_keys, compound_user_value_keys);
// ####################################################
// MzTabMetaData
// ####################################################
std::regex reg_backslash{R"(\\)"};
UInt64 local_id = feature_map.getUniqueId();
// mz_tab_id (mandatory)
m_meta_data.mz_tab_id.set("local_id: " + String(local_id));
// title (not mandatory)
// description (not mandatory)
// sample_processing (not mandatory)
// instrument-name (not mandatory)
// instrument-source (not mandatory)
// instrument-analyzer (not mandatory)
// instrument-detector (not mandatory)
// meta_software.setting[0] (not mandatory)
MzTabSoftwareMetaData meta_software;
ControlledVocabulary cv;
MzTabString reliability = MzTabString("2"); // initialize at 2 (should be valid for all tools - putatively annotated compound)
cv.loadFromOBO("PSI-MS", File::find("/CV/psi-ms.obo"));
for (const auto& software : id_data.getProcessingSoftwares())
{
if (software.metaValueExists("reliability"))
{
reliability = MzTabString(std::string(software.getMetaValue("reliability")));
}
MzTabParameter p_software;
ControlledVocabulary::CVTerm cvterm;
// add TOPP - all OpenMS Tools have TOPP attached in the PSI-OBO
std::string topp_tool = "TOPP " + software.getName();
if (cv.hasTermWithName(topp_tool)) // asses CV-term based on tool name
{
cvterm = cv.getTermByName(topp_tool);
}
else
{
// use "analysis software" instead
OPENMS_LOG_WARN << "The tool: " << topp_tool << " is currently not registered in the PSI-OBO.\n";
OPENMS_LOG_WARN << "'The general term 'analysis software' will be used instead.\n";
OPENMS_LOG_WARN << "Please register the tool as soon as possible in the psi-ms.obo (https://github.com/HUPO-PSI/psi-ms-CV)" << std::endl;
cvterm = cv.getTermByName("analysis software");
}
p_software.fromCellString("[MS, " + cvterm.id + ", " + cvterm.name + ", " + software.getVersion() + "]");
meta_software.software = p_software;
m_meta_data.software[m_meta_data.software.size() + 1] = meta_software; // starts at 1
}
// publication (not mandatory)
// contact name (not mandatory)
// contact aff (not mandatory)
// contact mail (not mandatory)
// uri (not mandatory)
// ext. study uri (not mandatory)
// quantification_method (mandatory)
MzTabParameter quantification_method;
quantification_method.setNull(true);
std::map<String, std::vector<String>> action_software_name;
for (const auto& step : id_data.getProcessingSteps())
{
IdentificationDataInternal::ProcessingSoftwareRef s_ref = step.software_ref;
for (const auto& action : step.actions)
{
action_software_name[action].emplace_back(s_ref->getName());
}
};
// set quantification method based on OpenMS Tool(s)
// current only FeatureFinderMetabo is used
for (const auto& quantification_software : action_software_name[DataProcessing::QUANTITATION])
{
if (quantification_software == "FeatureFinderMetabo")
{
ControlledVocabulary::CVTerm cvterm;
cvterm = cv.getTermByName("LC-MS label-free quantitation analysis");
quantification_method.fromCellString("[MS, " + cvterm.id + ", " + cvterm.name + ", ]");
}
}
if (quantification_method.isNull())
{
OPENMS_LOG_WARN << "If the quantification of your computational analysis is not 'LC-MS label-free quantitation analysis'.\n"
<< "Please contact a OpenMS Developer to add the appropriate tool and description to MzTab-M." << std::endl;
ControlledVocabulary::CVTerm cvterm = cv.getTermByName("LC-MS label-free quantitation analysis");
quantification_method.fromCellString("[MS, " + cvterm.id + ", " + cvterm.name + ", ]");
}
m_meta_data.quantification_method = quantification_method;
// sample[1-n] (not mandatory)
// sample[1-n]-species[1-n] (not mandatory)
// sample[1-n]-tissue[1-n] (not mandatory)
// sample[1-n]-cell_type[1-n] (not mandatory)
// sample[1-n]-disease[1-n] (not mandatory)
// sample[1-n]-description (not mandatory)
// sample[1-n]-custom[1-n] (not mandatory)
MzTabMMSRunMetaData meta_ms_run;
std::string input_file_name;
auto input_files = id_data.getInputFiles();
for (const auto& input_file : input_files) // should only be one in featureXML
{
input_file_name = input_file.name;
input_file_name = String(std::regex_replace(input_file_name, reg_backslash, "/"));
if (!String(input_file_name).hasPrefix("file://")) input_file_name = "file://" + input_file_name;
meta_ms_run.location.set(input_file_name);
}
// meta_ms_run.location.set(input_files[0].name);
// ms_run[1-n]-instrument_ref (not mandatory)
// ms_run[1-n]-format (not mandatory)
// ms_run[1-n]-id_format (not mandatory)
// ms_run[1-n]-fragmentation_method[1-n] (not mandatory)
// ms_run[1-n]-scan_polarity[1-n] (mandatory)
// assess scan polarity based on the first adduct
auto adducts = id_data.getAdducts();
if (!adducts.empty())
{
std::string_view first_adduct;
for (const auto& adduct : adducts)
{
first_adduct = adduct.getName();
break;
}
if (first_adduct.at(first_adduct.size() - 1) == '+')
{
ControlledVocabulary::CVTerm cvterm;
cvterm = cv.getTermByName("positive scan");
MzTabParameter spol;
spol.fromCellString("[MS, " + cvterm.id + ", " + cvterm.name + ", ]");
meta_ms_run.scan_polarity[1] = spol;
}
else
{
ControlledVocabulary::CVTerm cvterm;
cvterm = cv.getTermByName("negative scan");
MzTabParameter spol;
spol.fromCellString("[MS, " + cvterm.id + ", " + cvterm.name + ", ]");
meta_ms_run.scan_polarity[1] = spol;
}
}
else
{
// if no adduct information is available warn, but assume positive mode.
OPENMS_LOG_WARN << "No adduct information available: scan polarity will be assumed to be positive." << std::endl;
ControlledVocabulary::CVTerm cvterm;
cvterm = cv.getTermByName("positive scan");
MzTabParameter spol;
spol.fromCellString("[MS, " + cvterm.id + ", " + cvterm.name + ", ]");
meta_ms_run.scan_polarity[1] = spol;
}
// ms_run[1-n]-hash (not mandatory)
// ms_run[1-n]-hash_method (not mandatory)
MzTabMAssayMetaData meta_ms_assay;
// assay[1-n] (mandatory)
meta_ms_assay.name = MzTabString("assay_" + File::basename(input_file_name).prefix('.').trim());
// assay[1-n]-custom[1-n] (not mandatory)
// assay[1-n]-external_uri (not mandatory)
// assay[1-n]-sample_ref (not mandatory)
// assay[1-n]-ms_run_ref (mandatory)
MzTabInteger ms_run_ref(1);
meta_ms_assay.ms_run_ref = ms_run_ref;
MzTabMStudyVariableMetaData meta_ms_study_variable;
// study_variable[1-n] (mandatory)
meta_ms_study_variable.name = MzTabString("study_variable_" + File::basename(input_file_name).prefix('.').trim());
// study_variable[1-n]-assay_refs (mandatory)
std::vector<int> assay_refs;
assay_refs.emplace_back(1);
meta_ms_study_variable.assay_refs = assay_refs;
// study_variable[1-n]-average_function (not mandatory)
// study_variable[1-n]-variation_function (not mandatory)
// study_variable[1-n]-description (mandatory)
meta_ms_study_variable.description = MzTabString("study_variable_" + File::basename(input_file_name).prefix('.').trim());
// study_variable[1-n]-factors (not mandatory)
// custom[1-n] (not mandatory)
MzTabCVMetaData meta_cv;
// cv[1-n]-label (mandatory)
meta_cv.label = MzTabString(cv.name());
// cv[1-n]-full_name (mandatory)
meta_cv.full_name = MzTabString(cv.label());
// cv[1-n]-version (mandatory)
meta_cv.version = MzTabString(cv.version());
// cv[1-n]-uri (mandatory)
meta_cv.url = MzTabString(cv.url());
m_meta_data.cv[1] = meta_cv;
// these have to be added to the identification data
// in the actual tool writes the mztam-m
MzTabMDatabaseMetaData meta_db;
meta_db.prefix.setNull(true);
meta_db.version = MzTabString("Unknown");
meta_db.database.fromCellString("[,, no database , null]");
meta_db.uri = MzTabString("https://hmdb.ca/"); // default if not set
for (const auto& db : id_data.getDBSearchParams())
{
if (db.database.find("custom") != std::string::npos) // custom database
{
meta_db.prefix.setNull(true);
meta_db.version = MzTabString(db.database_version);
meta_db.database.fromCellString("[,, " + db.database + ", ]");
}
else // assumption that prefix is the same as database name
{
meta_db.prefix = MzTabString(db.database);
meta_db.version = MzTabString(db.database_version);
meta_db.database.fromCellString("[,," + db.database + ", ]");
}
if (db.metaValueExists("database_location"))
{
std::vector<std::string> db_loc = ListUtils::create<std::string>(db.getMetaValue("database_location"), '|');
for (auto& loc : db_loc)
{
loc = String(std::regex_replace(loc, reg_backslash, "/"));
if (!String(loc).hasPrefix("file://")) loc = "file://" + loc;
}
String db_location_uri = ListUtils::concatenate(db_loc, '|');
meta_db.uri = MzTabString(db_location_uri);
}
// else: keep the default URI (https://hmdb.ca/) set at initialization
m_meta_data.database[m_meta_data.database.size() + 1] = meta_db; // starts at 1
}
// derivatization_agent[1-n] (not mandatory)
MzTabParameter quantification_unit;
quantification_unit.setNull(true);
for (const auto& software : id_data.getProcessingSoftwares())
{
if (software.getName() == "FeatureFinderMetabo")
{
if (software.metaValueExists("parameter: algorithm:mtd:quant_method"))
{
String quant_method = software.getMetaValue("parameter: algorithm:mtd:quant_method");
if (quant_method == "area")
{
ControlledVocabulary::CVTerm cvterm;
cvterm = cv.getTermByName("MS1 feature area");
quantification_unit.fromCellString("[MS, " + cvterm.id + ", " + cvterm.name + ", ]");
}
else if (quant_method == "median")
{
ControlledVocabulary::CVTerm cvterm;
cvterm = cv.getTermByName("median");
quantification_unit.fromCellString("[MS, " + cvterm.id + ", " + cvterm.name + ", ]");
}
else // max_height
{
ControlledVocabulary::CVTerm cvterm;
cvterm = cv.getTermByName("MS1 feature maximum intensity");
quantification_unit.fromCellString("[MS, " + cvterm.id + ", " + cvterm.name + ", ]");
}
}
}
}
if (quantification_unit.isNull())
{
OPENMS_LOG_WARN << "It was not possible to assess the quantification_unit - MS1 feature area - will be used as default." << std::endl;
ControlledVocabulary::CVTerm cvterm;
cvterm = cv.getTermByName("MS1 feature area");
quantification_unit.fromCellString("[MS, " + cvterm.id + ", " + cvterm.name + ", ]");
}
// small_molecule-quantification_unit (mandatory)
// small_molecule_feature-quantification_unit (mandatory)
m_meta_data.small_molecule_quantification_unit = quantification_unit;
m_meta_data.small_molecule_feature_quantification_unit = quantification_unit;
// small_molecule-identification_reliability (mandatory)
MzTabParameter rel;
ControlledVocabulary::CVTerm cvterm_rel = cv.getTermByName("compound identification confidence level");
rel.fromCellString("[MS, " + cvterm_rel.id + ", " + cvterm_rel.name + ", ]");
m_meta_data.small_molecule_identification_reliability = rel;
int software_score_counter = 0;
std::vector<String> identification_tools = action_software_name[DataProcessing::IDENTIFICATION];
std::vector<IdentificationDataInternal::ScoreTypeRef> id_score_refs;
for (const IdentificationDataInternal::ProcessingSoftware& software : id_data.getProcessingSoftwares())
{
// check if in "Identification Vector"
if (std::find(identification_tools.begin(), identification_tools.end(), software.getName()) != identification_tools.end())
{
for (const IdentificationDataInternal::ScoreTypeRef& score_type_ref : software.assigned_scores)
{
++software_score_counter;
m_meta_data.id_confidence_measure[software_score_counter].fromCellString("[,, " + score_type_ref->cv_term.getName() + ", ]");
id_score_refs.emplace_back(score_type_ref);
}
}
}
// colunit-small_molecule (not mandatory)
// colunit-small_molecule_feature (not mandatory)
// colunit-small_molecule_evidence (not mandatory)
m_meta_data.ms_run[1] = meta_ms_run;
m_meta_data.assay[1] = meta_ms_assay;
m_meta_data.study_variable[1] = meta_ms_study_variable;
// iterate over features and construct the feature, summary and evidence section
MzTabMSmallMoleculeSectionRows smls;
MzTabMSmallMoleculeFeatureSectionRows smfs;
MzTabMSmallMoleculeEvidenceSectionRows smes;
// set identification method based on OpenMS Tool(s)
// usually only one identification_method in one featureXML
MzTabParameter identification_method;
identification_method.fromCellString("[, , OpenMS TOPP, ]");
MzTabParameter ms_level;
ms_level.setNull(true);
for (const auto& identification_software : action_software_name[DataProcessing::IDENTIFICATION])
{
int id_mslevel = 1;
ControlledVocabulary::CVTerm cvterm;
if (identification_software == "AccurateMassSearch")
{
cvterm = cv.getTermByName("accurate mass");
identification_method.fromCellString("[MS, " + cvterm.id + ", " + cvterm.name + ", ]");
id_mslevel = 1;
}
else if (identification_software == "SiriusAdapter")
{
cvterm = cv.getTermByName("de novo search");
identification_method.fromCellString("[MS, " + cvterm.id + ", " + cvterm.name + ", ]");
id_mslevel = 2;
}
else if (identification_software == "MetaboliteSpectralMatcher")
{
cvterm = cv.getTermByName("TOPP SpecLibSearcher");
identification_method.fromCellString("[MS, " + cvterm.id + ", " + cvterm.name + ", ]");
id_mslevel = 2;
}
else
{ // default for unknown
id_mslevel = 1;
}
ControlledVocabulary::CVTerm cvterm_level = cv.getTermByName("ms level");
ms_level.fromCellString("[MS, " + cvterm_level.id + ", " + cvterm_level.name + ", " + String(id_mslevel) + "]");
}
// Set default values if not set by the loop above
if (ms_level.isNull())
{
// Default to MS level 1 if not specified
ControlledVocabulary::CVTerm cvterm_level = cv.getTermByName("ms level");
ms_level.fromCellString("[MS, " + cvterm_level.id + ", " + cvterm_level.name + ", 1]");
}
// Check if identification_method has a valid CV term (not the placeholder with empty CV label/accession)
// The placeholder is "[, , OpenMS TOPP, ]" which has empty CV_label_ and accession_
if (identification_method.getCVLabel().empty() && identification_method.getAccession().empty())
{
OPENMS_LOG_WARN << "The identification method of your computational analysis cannot be assessed.\n"
<< "Using 'data processing action' as default identification method.\n"
<< "Please check if the ProcessingActions are set correctly!" << std::endl;
// Use a generic CV term for data processing
ControlledVocabulary::CVTerm cvterm = cv.getTermByName("data processing action");
identification_method.fromCellString("[MS, " + cvterm.id + ", " + cvterm.name + ", ]");
}
// ####################################################
//
// ####################################################
int feature_section_entry_counter = 1;
int evidence_section_entry_counter = 1;
for (auto& f : feature_map) // iterate over features and fill all sections
{
auto match_refs = f.getIDMatches();
if (match_refs.empty()) // features without identification
{
MzTabMSmallMoleculeFeatureSectionRow smf;
smf.smf_identifier = MzTabString(feature_section_entry_counter);
std::vector<MzTabString> corresponding_evidences;
smf.sme_id_refs.setNull(true);
if (f.metaValueExists("adducts"))
{
StringList adducts = f.getMetaValue("adducts");
smf.adduct = MzTabString(ListUtils::concatenate(adducts,'|'));
}
else
{
smf.adduct.setNull(true);
}
smf.sme_id_ref_ambiguity_code.setNull(true);
smf.isotopomer.setNull(true);
smf.exp_mass_to_charge = MzTabDouble(f.getMZ());
smf.charge = MzTabInteger(f.getCharge());
smf.retention_time = MzTabDouble(f.getRT());
smf.rt_start.setNull(true);
smf.rt_end.setNull(true);
smf.small_molecule_feature_abundance_assay[1] = MzTabDouble(f.getIntensity()); // only one map in featureXML
addMetaInfoToOptionalColumns(feature_user_value_keys, smf.opt_, String("global"), f);
smfs.emplace_back(smf);
++feature_section_entry_counter;
}
else
{
// feature row based on number of individual identifications and adducts!
std::map<String, std::vector<int>> evidence_id_ref_per_adduct;
// TODO: Remove copy operation (operator< IDData Ref)
std::set<IdentificationDataInternal::ObservationMatchRef, CompareMzTabMMatchRef> sorted_match_refs(match_refs.begin(), match_refs.end());
for (const auto& ref : sorted_match_refs) // iterate over all identifications of a feature
{
// evidence section
MzTabMSmallMoleculeEvidenceSectionRow sme;
// IdentifiedCompound
IdentificationData::IdentifiedMolecule molecule = ref->identified_molecule_var;
IdentificationData::IdentifiedCompoundRef compound_ref = molecule.getIdentifiedCompoundRef();
sme.sme_identifier = MzTabString(evidence_section_entry_counter);
sme.evidence_input_id = MzTabString("mass=" + String(f.getMZ()) + ",rt=" + String(f.getRT()));
sme.database_identifier = MzTabString(compound_ref->identifier);
sme.chemical_formula = MzTabString(compound_ref->formula.toString());
sme.smiles = MzTabString(compound_ref->smile);
sme.inchi = MzTabString(compound_ref->inchi);
sme.chemical_name = MzTabString(compound_ref->name);
sme.uri.setNull(true);
sme.derivatized_form.setNull(true);
String adduct = getAdductString_(ref);
sme.adduct = MzTabString(adduct);
sme.exp_mass_to_charge = MzTabDouble(f.getMZ());
sme.charge = MzTabInteger(f.getCharge());
sme.calc_mass_to_charge = MzTabDouble(compound_ref->formula.getMonoWeight());
// For e.g. SIRIUS using multiple MS2 spectra for one identification
// use the with pipe concatenated native_ids as spectra ref
// this should also be available match_ref
MzTabSpectraRef sp_ref;
sp_ref.setMSFile(1);
sp_ref.setSpecRef(ref->observation_ref->data_id);
sme.spectra_ref = sp_ref;
sme.identification_method = identification_method; // based on tool used for identification (CV-Term)
sme.ms_level = ms_level;
int score_counter = 0;
for (const auto& id_score_ref : id_score_refs) // vector of references based on the ProcessingStep
{
++score_counter; //starts at 1 anyway
sme.id_confidence_measure[score_counter] = MzTabDouble(ref->getScore(id_score_ref).first);
}
sme.rank = MzTabInteger(1); // defaults to 1 if no rank system is used
addMetaInfoToOptionalColumns(observationmatch_user_value_keys, sme.opt_, String("global"), *ref);
addMetaInfoToOptionalColumns(compound_user_value_keys, sme.opt_, String("global"), *compound_ref);
evidence_id_ref_per_adduct[adduct].emplace_back(evidence_section_entry_counter);
evidence_section_entry_counter += 1;
smes.emplace_back(sme);
}
// feature section
// one feature entry per adduct - iterate evidences_per_adduct
for (const auto& epa : evidence_id_ref_per_adduct)
{
MzTabMSmallMoleculeFeatureSectionRow smf;
smf.smf_identifier = MzTabString(feature_section_entry_counter);
std::vector<MzTabString> corresponding_evidences;
for (const auto& evidence : epa.second)
{
corresponding_evidences.emplace_back(evidence);
}
smf.sme_id_refs.set(corresponding_evidences);
smf.adduct = MzTabString(epa.first);
if (epa.second.size() <= 1)
{
smf.sme_id_ref_ambiguity_code.setNull(true);
}
else
{
smf.sme_id_ref_ambiguity_code = MzTabInteger(1);
}
smf.isotopomer.setNull(true);
smf.exp_mass_to_charge = MzTabDouble(f.getMZ());
smf.charge = MzTabInteger(f.getCharge());
smf.retention_time = MzTabDouble(f.getRT());
smf.rt_start.setNull(true);
smf.rt_end.setNull(true);
smf.small_molecule_feature_abundance_assay[1] = MzTabDouble(f.getIntensity()); // only one map in featureXML
addMetaInfoToOptionalColumns(feature_user_value_keys, smf.opt_, String("global"), f);
smfs.emplace_back(smf);
++feature_section_entry_counter;
}
}
}
// based summary on available features and evidences
// OpenMS does currently not aggregate the information of two features with corresponding adducts
// e.g. F1 mz = 181.0712 rt = 10, [M+H]1+; F2 mz = 203.0532, rt = 10 [M+Na]1+ (neutral mass for both: 180.0634)
// features will be represented individually here.
for (const auto& smf : smfs)
{
MzTabMSmallMoleculeSectionRow sml;
sml.sml_identifier = smf.smf_identifier;
sml.smf_id_refs.set({smf.smf_identifier});
std::vector<MzTabString> database_identifier;
std::vector<MzTabString> chemical_formula;
std::vector<MzTabString> smiles;
std::vector<MzTabString> inchi;
std::vector<MzTabString> chemical_name;
std::vector<MzTabString> uri;
std::vector<MzTabDouble> theoretical_neutral_mass;
std::vector<MzTabString> adducts;
for (const MzTabString & evidence : smf.sme_id_refs.get())
{
const auto& current_row_it = std::find_if(smes.begin(), smes.end(), [&evidence] (const MzTabMSmallMoleculeEvidenceSectionRow& sme) { return sme.sme_identifier.get() == evidence.get(); });
database_identifier.emplace_back(current_row_it->database_identifier);
chemical_formula.emplace_back(current_row_it->chemical_formula);
smiles.emplace_back(current_row_it->smiles);
inchi.emplace_back(current_row_it->inchi);
chemical_name.emplace_back(current_row_it->chemical_name);
uri.emplace_back(current_row_it->uri);
MzTabString cm = current_row_it->chemical_formula;
if (cm.toCellString() != "" && cm.toCellString() != "null" )
{
theoretical_neutral_mass.emplace_back(EmpiricalFormula(cm.toCellString()).getMonoWeight());
}
else
{
MzTabDouble dnull;
dnull.setNull(true);
theoretical_neutral_mass.emplace_back(dnull);
}
adducts.emplace_back(current_row_it->adduct);
}
sml.database_identifier.set(database_identifier);
sml.chemical_formula.set(chemical_formula);
sml.smiles.set(smiles);
sml.inchi.set(inchi);
sml.chemical_name.set(chemical_name);
sml.uri.set(uri);
sml.theoretical_neutral_mass.set(theoretical_neutral_mass);
sml.adducts.set(adducts);
sml.reliability = reliability;
sml.best_id_confidence_measure.setNull(true);
sml.best_id_confidence_value.setNull(true);
sml.small_molecule_abundance_assay = smf.small_molecule_feature_abundance_assay;
sml.small_molecule_abundance_study_variable[1].setNull(true);
sml.small_molecule_abundance_variation_study_variable[1].setNull(true);
smls.emplace_back(sml);
}
mztabm.setMetaData(m_meta_data);
mztabm.setMSmallMoleculeEvidenceSectionRows(smes);
mztabm.setMSmallMoleculeFeatureSectionRows(smfs);
mztabm.setMSmallMoleculeSectionRows(smls);
return mztabm;
}
String MzTabM::getAdductString_(const IdentificationDataInternal::ObservationMatchRef& match_ref)
{
String adduct_name;
if (match_ref->adduct_opt)
{
adduct_name = (*match_ref->adduct_opt)->getName();
// M+H;1+ -> [M+H]1+
if (adduct_name.find(';') != std::string::npos) // wrong format -> reformat
{
String prefix = adduct_name.substr(0, adduct_name.find(';'));
String suffix = adduct_name.substr(adduct_name.find(';') + 1, adduct_name.size());
adduct_name = "[" + prefix + "]" + suffix;
}
}
else
{
adduct_name = "null";
}
return adduct_name;
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/IndexedMzMLFileLoader.cpp | .cpp | 2,102 | 70 | // 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/IndexedMzMLFileLoader.h>
#include <OpenMS/FORMAT/MzMLFile.h>
#include <OpenMS/KERNEL/OnDiscMSExperiment.h>
#include <OpenMS/FORMAT/DATAACCESS/MSDataWritingConsumer.h>
namespace OpenMS
{
IndexedMzMLFileLoader::IndexedMzMLFileLoader() = default;
IndexedMzMLFileLoader::~IndexedMzMLFileLoader() = default;
PeakFileOptions & IndexedMzMLFileLoader::getOptions()
{
return options_;
}
const PeakFileOptions & IndexedMzMLFileLoader::getOptions() const
{
return options_;
}
void IndexedMzMLFileLoader::setOptions(const PeakFileOptions & options)
{
options_ = options;
}
bool IndexedMzMLFileLoader::load(const String& filename, OnDiscPeakMap& exp)
{
return exp.openFile(filename);
}
void IndexedMzMLFileLoader::store(const String& filename, OnDiscPeakMap& exp)
{
// Create a writing data consumer which consumes the experiment (writes it to disk)
PlainMSDataWritingConsumer consumer(filename);
consumer.setExpectedSize(exp.getNrSpectra(), exp.getNrChromatograms());
consumer.setExperimentalSettings(*exp.getExperimentalSettings().get());
options_.setWriteIndex(true); // ensure that we write the index
consumer.setOptions(options_);
for (Size i = 0; i < exp.getNrSpectra(); i++)
{
MSSpectrum s = exp.getSpectrum(i);
consumer.consumeSpectrum(s);
}
for (Size i = 0; i < exp.getNrChromatograms(); i++)
{
MSChromatogram c = exp.getChromatogram(i);
consumer.consumeChromatogram(c);
}
}
void IndexedMzMLFileLoader::store(const String& filename, PeakMap& exp)
{
MzMLFile f;
options_.setWriteIndex(true); // ensure that we write the index
f.setOptions(options_);
f.store(filename, exp);
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/GzipIfstream.cpp | .cpp | 7,694 | 201 | // 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 <iostream>
#include <OpenMS/FORMAT/GzipIfstream.h>
#include <OpenMS/CONCEPT/Exception.h>
#include <OpenMS/SYSTEM/File.h>
#include <cstdlib>
using namespace std;
namespace OpenMS
{
GzipIfstream::GzipIfstream(const char * filename) :
gzfile_(nullptr), n_buffer_(0), stream_at_end_(false)
{
open(filename);
}
GzipIfstream::GzipIfstream() :
gzfile_(nullptr), n_buffer_(0), gzerror_(0), stream_at_end_(true)
{
}
GzipIfstream::~GzipIfstream()
{
close();
}
size_t GzipIfstream::read(char * s, size_t n)
{
if (gzfile_ != nullptr)
{
n_buffer_ = gzread(gzfile_, s, (unsigned int) n /* size of buf */);
if (gzeof(gzfile_) == 1)
{
close();
stream_at_end_ = true;
}
if (n_buffer_ < 0)
{
close();
const char* err_string = gzerror(gzfile_, &gzerror_);
std::string error_message = err_string ? err_string : "unknown error (code: " + std::to_string(gzerror_) + ")";
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "error reading from gzip file", error_message);
}
return n_buffer_;
}
else
{
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "no file for decompression initialized");
}
}
void GzipIfstream::open(const char * filename)
{
if (gzfile_ != nullptr)
{
close();
}
gzfile_ = gzopen(filename, "rb"); // read binary: always open in binary mode because windows and mac open in text mode
gzbuffer(gzfile_, 524288); // set buffer size to 512kb to improve read performance (about 7% for mzML files incl. parsing)
//aborting, ahhh!
if (gzfile_ == nullptr)
{
close();
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);
}
}
else
{
stream_at_end_ = false;
/* crc = crc32(0L, Z_NULL, 0);
FILE* file = fopen(filename,"rb");
fseek(file,8,SEEK_END);
char crc_[4];
fgets(crc_,5,file);
original_crc = 0;
original_crc |= crc_[0];
original_crc = original_crc << 8;
original_crc |= crc_[1];
original_crc = original_crc << 8;
original_crc |= crc_[2];
original_crc = original_crc << 8;
original_crc |= crc_[3];
original_crc = original_crc << 8;
cout<<hex<<crc_[0]<<hex<<crc_[1]<<hex<<crc_[2]<<hex<<crc_[3];
cout<<dec<<"ORIGINAL"<<original_crc<<endl;
const int CRC_BUFFER_SIZE = 8192;
unsigned char buf[CRC_BUFFER_SIZE];
size_t bufLen;
FILE* file2 = fopen(filename,"rb");
** accumulate crc32 from file **
crc = 0;
while (1)
{
bufLen = fread( buf, 1, CRC_BUFFER_SIZE, file2 );
if (bufLen == 0) {
if (ferror(file2)) {
fprintf( stderr, "error reading file\n" );
return;
}
break;
}
crc = crc32( crc, buf, bufLen );
}
cout<<"CRC" <<crc<<endl;
*/
}
}
void GzipIfstream::close()
{
if (gzfile_ != nullptr)
{
gzclose(gzfile_);
}
gzfile_ = nullptr;
stream_at_end_ = true;
}
/*
void GzipIfstream::updateCRC32(const char* s, const size_t n)
{
const Bytef * sb = reinterpret_cast<const Bytef *>(s);
crc = crc32(crc, sb, n);
}
unsigned long GzipIfstream::Crc32_ComputeBuf( unsigned long inCrc32, const void *buf,
size_t bufLen )
{
static const unsigned long crcTable[256] = {
0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,
0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,
0xE7B82D07,0x90BF1D91,0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,
0x6DDDE4EB,0xF4D4B551,0x83D385C7,0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,
0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5,0x3B6E20C8,0x4C69105E,0xD56041E4,
0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,0x35B5A8FA,0x42B2986C,
0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59,0x26D930AC,
0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F,
0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB,
0xB6662D3D,0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,
0x9FBFE4A5,0xE8B8D433,0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,
0x086D3D2D,0x91646C97,0xE6635C01,0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,
0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,0x65B0D9C6,0x12B7E950,0x8BBEB8EA,
0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65,0x4DB26158,0x3AB551CE,
0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB,0x4369E96A,
0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9,
0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,
0xCE61E49F,0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,
0xB7BD5C3B,0xC0BA6CAD,0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739,
0x9DD277AF,0x04DB2615,0x73DC1683,0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8,
0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,0xF00F9344,0x8708A3D2,0x1E01F268,
0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,0xFED41B76,0x89D32BE0,
0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5,0xD6D6A3E8,
0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,
0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF,
0x4669BE79,0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703,
0x220216B9,0x5505262F,0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7,
0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,
0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,0x95BF4A82,0xE2B87A14,0x7BB12BAE,
0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21,0x86D3D2D4,0xF1D4E242,
0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,0x88085AE6,
0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45,
0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,
0x3E6E77DB,0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,
0x47B2CF7F,0x30B5FFE9,0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,
0xCDD70693,0x54DE5729,0x23D967BF,0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,
0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D };
unsigned long crc32;
unsigned char *byteBuf;
size_t i;
** accumulate crc32 for buffer **
crc32 = inCrc32 ^ 0xFFFFFFFF;
byteBuf = (unsigned char*) buf;
for (i=0; i < bufLen; i++) {
crc32 = (crc32 >> 8) ^ crcTable[ (crc32 ^ byteBuf[i]) & 0xFF ];
}
return( crc32 ^ 0xFFFFFFFF );
}*/
} //namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/FLASHDeconvFeatureFile.cpp | .cpp | 9,224 | 204 | // 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/FLASHDeconvFeatureFile.h>
namespace OpenMS
{
/**
@brief FLASHDeconv Spectrum level output *.tsv, *.msalign (for TopPIC) file formats
@ingroup FileIO
**/
void FLASHDeconvFeatureFile::writeHeader(std::ostream& os, bool report_decoy)
{
os << "FeatureIndex\tFileName\tMSLevel";
if (report_decoy) os << "\tIsDecoy";
os << "\tMonoisotopicMass\tAverageMass\tMassCount\tStartRetentionTime"
"\tEndRetentionTime\tRetentionTimeDuration\tApexRetentionTime"
"\tSumIntensity\tMaxIntensity\tFeatureQuantity\tMinCharge\tMaxCharge\tChargeCount\tIsotopeCosineScore\tQscore2D\tPerChargeIntensity\tPerIsotopeIntensity"
"\n";
}
void FLASHDeconvFeatureFile::writeTopFDFeatureHeader(std::ostream& os, uint ms_level)
{
// //File_name Fraction_ID Spectrum_ID Scans MS_one_ID MS_one_scans Fraction_feature_ID Fraction_feature_intensity
// Fraction_feature_score Fraction_feature_min_time Fraction_feature_max_time
// Fraction_feature_apex_time Precursor_monoisotopic_mz Precursor_average_mz Precursor_charge Precursor_intensity
if (ms_level == 1)
{
os << "File_name\tFraction_ID\tFeature_ID\tMass\tIntensity\tMin_time\tMax_time\tMin_scan\tMax_scan\tMin_charge\tMax_charge\tApex_time\tApex_scan\tApex_intensity\tRep_charge\tRep_average_mz\tEnvelope_num\tEC_score\n";
}
else
{
os << "File_name\tFraction_ID\tSpectrum_ID\tScans\tMS_one_ID\tMS_one_scans\tFraction_feature_ID\tFraction_feature_intensity\tFraction_feature_score\tFraction_feature_min_time\tFraction_feature_max_time\tFraction_feature_apex_time\tPrecursor_monoisotopic_mz\tPrecursor_average_mz\tPrecursor_charge\tPrecursor_intensity\n";
}
os.flush();
}
void FLASHDeconvFeatureFile::writeFeatures(const std::vector<FLASHHelperClasses::MassFeature>& mass_features, const String& file_name, std::ostream& os, bool report_decoy)
{
std::stringstream ss;
for (auto& mass_feature : mass_features)
{
const auto& mt = mass_feature.mt;
double mass = mt.getCentroidMZ() + mass_feature.iso_offset * Constants::ISOTOPE_MASSDIFF_55K_U;
double avg_mass = mass_feature.avg_mass;
double sum_intensity = .0;
for (auto& p : mt)
{
sum_intensity += p.getIntensity();
}
ss << mass_feature.index << "\t" << file_name << "\t" << mass_feature.ms_level;
if (report_decoy)
{ ss << "\t" << (mass_feature.is_decoy? 1 : 0);
}
ss << "\t" << std::to_string(mass) << "\t" << std::to_string(avg_mass) << "\t" // massdiff
<< mt.getSize() << "\t" << mt.begin()->getRT()/60.0 << "\t" << mt.rbegin()->getRT()/60.0 << "\t" << mt.getTraceLength() << "\t" << mt[mt.findMaxByIntPeak()].getRT()/60.0 << "\t" << sum_intensity << "\t"
<< mt.getMaxIntensity(false) << "\t" << mt.computePeakArea() << "\t" << mass_feature.min_charge << "\t" << mass_feature.max_charge << "\t" << mass_feature.charge_count << "\t"
<< mass_feature.isotope_score << "\t" << std::setprecision (15) << (mass_feature.qscore) << std::setprecision (-1) << "\t";
for (int i = mass_feature.min_charge; i <= mass_feature.max_charge; i++)
{
ss << mass_feature.per_charge_intensity[abs(i)];
if (i < mass_feature.max_charge)
{ ss << ";";
}
}
ss << "\t";
int iso_end_index = 0;
for (Size i = 0; i < mass_feature.per_isotope_intensity.size(); i++)
{
if (mass_feature.per_isotope_intensity[i] == 0)
{
continue;
}
iso_end_index = (int)i;
}
for (int i = 0; i <= iso_end_index; i++)
{
ss << mass_feature.per_isotope_intensity[i];
if (i < iso_end_index)
{ ss << ";";
}
}
ss << "\n";
}
os << ss.str();
}
void FLASHDeconvFeatureFile::writeTopFDFeatures(std::vector<DeconvolvedSpectrum>& deconvolved_spectra, const std::vector<FLASHHelperClasses::MassFeature>& mass_features,
const std::map<int, double>& scan_rt_map, const String& file_name, std::ostream& os, uint ms_level)
{
std::stringstream ss;
if (ms_level == 1)
{
uint max_feature_index = 0;
for (const auto& mass_feature : mass_features)
{
if (mass_feature.ms_level != 1 || mass_feature.is_decoy) continue;
double sum_intensity = .0;
for (const auto& m : mass_feature.mt)
{
sum_intensity += m.getIntensity();
}
const auto& apex = mass_feature.mt[mass_feature.mt.findMaxByIntPeak()];
ss << file_name << "\t0\t" << mass_feature.index << "\t" << std::to_string(mass_feature.mt.getCentroidMZ()) << "\t" << std::to_string(sum_intensity) << "\t" << std::to_string(mass_feature.mt.begin()->getRT()/60.0)
<< "\t" << std::to_string(mass_feature.mt.rbegin()->getRT()/60.0) << "\t" << mass_feature.min_scan_number << "\t" << mass_feature.max_scan_number << "\t"
<< mass_feature.min_charge << "\t" << mass_feature.max_charge << "\t" << std::to_string(apex.getRT()/60.0) << "\t" << mass_feature.scan_number << "\t"
<< std::to_string(apex.getIntensity()) << "\t" << mass_feature.rep_charge << "\t" << mass_feature.rep_mz << "\t0\t0\n";
max_feature_index = std::max(max_feature_index, mass_feature.index);
}
for (auto& dspec : deconvolved_spectra)
{
if (dspec.getOriginalSpectrum().getMSLevel() == 1 || dspec.getPrecursorPeakGroup().empty()) continue;
if (dspec.getPrecursorPeakGroup().getFeatureIndex() != 0) continue;
auto pg = dspec.getPrecursorPeakGroup();
double rt = scan_rt_map.at(pg.getScanNumber())/60.0;
const auto& [z, Z] = pg.getAbsChargeRange();
pg.setFeatureIndex(++max_feature_index);
dspec.setPrecursorPeakGroup(pg);
double rep_mz = 0;
double p_int = 0;
for (const auto& p : pg)
{
if (p.abs_charge != pg.getRepAbsCharge()) continue;
if (p.intensity < p_int) continue;
p_int = p.intensity;
rep_mz = p.mz;
}
ss << file_name << "\t0\t" << max_feature_index << "\t" << std::to_string(pg.getMonoMass()) << "\t" << std::to_string(pg.getIntensity()) << "\t" << std::to_string(rt)
<< "\t" << std::to_string(rt) << "\t" << pg.getScanNumber() << "\t" << pg.getScanNumber() << "\t"
<< z << "\t" << Z << "\t" << std::to_string(rt) << "\t" << pg.getScanNumber() << "\t"
<< std::to_string(pg.getIntensity()) << "\t" << pg.getRepAbsCharge() << "\t" << std::to_string(rep_mz) << "\t0\t0\n";
}
}
if (ms_level == 2)
{
for (auto& dspec : deconvolved_spectra)
{
if (dspec.getOriginalSpectrum().getMSLevel() == 1 || dspec.getPrecursorPeakGroup().empty()) continue;
if (dspec.getPrecursorPeakGroup().getFeatureIndex() == 0) continue;
auto pg = dspec.getPrecursorPeakGroup();
int ms2_scan_number = dspec.getScanNumber();
ss << file_name << "\t0\t" << ms2_scan_number - 1 << "\t" << ms2_scan_number << "\t" << pg.getScanNumber() - 1 << "\t" << pg.getScanNumber() << "\t" << pg.getFeatureIndex() << "\t";
if (pg.getFeatureIndex() < mass_features.size() + 1)
{
const auto& mass_feature = mass_features[pg.getFeatureIndex() - 1];
const auto& apex = mass_feature.mt[mass_feature.mt.findMaxByIntPeak()];
double sum_intensity = .0;
for (const auto& m : mass_feature.mt)
{
sum_intensity += m.getIntensity();
}
ss << std::to_string(sum_intensity) << "\t0\t" << std::to_string(mass_feature.mt.begin()->getRT()/60.0)
<< "\t" << std::to_string(mass_feature.mt.rbegin()->getRT()/60.0) << "\t" << std::to_string(apex.getRT()/60.0) << "\t" << std::to_string(mass_feature.mt.getCentroidMZ())
<< "\t" << std::to_string(mass_feature.rep_mz) << "\t" << mass_feature.rep_charge << "\t" << std::to_string(dspec.getPrecursor().getIntensity()) << "\n";
}
else
{
double rt = scan_rt_map.at(pg.getScanNumber()) / 60.0;
double rep_mz = 0;
double p_int = 0;
for (const auto& p : pg)
{
if (p.abs_charge != pg.getRepAbsCharge()) continue;
if (p.intensity < p_int) continue;
p_int = p.intensity;
rep_mz = p.mz;
}
ss << std::to_string(pg.getIntensity()) << "\t0\t" << std::to_string(rt)
<< "\t" << std::to_string(rt) << "\t" << std::to_string(rt) << "\t" << std::to_string(pg.getMonoMass())
<< "\t" << std::to_string(rep_mz) << "\t" << pg.getRepAbsCharge() << "\t" << std::to_string(dspec.getPrecursor().getIntensity()) << "\n";
}
}
}
os << ss.str();
}
} // namespace OpenMS | C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/PercolatorOutfile.cpp | .cpp | 12,162 | 337 | // 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/PercolatorOutfile.h>
#include <OpenMS/CHEMISTRY/ModificationDefinitionsSet.h>
#include <OpenMS/CHEMISTRY/ModificationsDB.h>
#include <OpenMS/FORMAT/CsvFile.h>
namespace OpenMS
{
using namespace std;
// initialize static variable:
const std::string PercolatorOutfile::score_type_names[] =
{"qvalue", "PEP", "score"};
PercolatorOutfile::PercolatorOutfile() = default;
PercolatorOutfile::ScoreType PercolatorOutfile::getScoreType(
String score_type_name)
{
score_type_name.toLower();
if ((score_type_name == "q-value") || (score_type_name == "qvalue") ||
(score_type_name == "q value"))
{
return ScoreType::QVALUE;
}
if ((score_type_name == "pep") ||
(score_type_name == "posterior error probability"))
{
return ScoreType::POSTERRPROB;
}
if (score_type_name == "score")
{
return ScoreType::SCORE;
}
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Not a valid Percolator score type",
score_type_name);
}
void PercolatorOutfile::resolveMisassignedNTermMods_(String& peptide) const
{
boost::regex re(R"(^[A-Z]\[(?<MOD1>-?\d+(\.\d+)?)\](\[(?<MOD2>-?\d+(\.\d+)?)\])?)");
boost::smatch match;
bool found = boost::regex_search(peptide, match, re);
if (found && match["MOD1"].matched)
{
const ResidueModification* null = nullptr;
vector<const ResidueModification*> maybe_nterm(2, null);
String residue = peptide[0];
String mod1 = match["MOD1"].str();
double mass1 = mod1.toDouble();
maybe_nterm[0] = ModificationsDB::getInstance()->
getBestModificationByDiffMonoMass(mass1, 0.01, residue,
ResidueModification::N_TERM);
if (maybe_nterm[0] && !match["MOD2"].matched &&
((maybe_nterm[0]->getId() != "Carbamidomethyl") || (residue != "C")))
{ // only 1 mod, may be terminal -> assume terminal (unless it's CAM!):
String replacement = ".(" + maybe_nterm[0]->getId() + ")" + residue;
peptide = boost::regex_replace(peptide, re, replacement);
}
// only 1 mod, may not be terminal -> nothing to do
else if (match["MOD2"].matched) // two mods
{
String mod2 = match["MOD2"].str();
double mass2 = mod2.toDouble();
maybe_nterm[1] = ModificationsDB::getInstance()->
getBestModificationByDiffMonoMass(mass2, 0.01, residue,
ResidueModification::N_TERM);
if (maybe_nterm[0] && !maybe_nterm[1])
{ // first mod is terminal:
String replacement = "(" + maybe_nterm[0]->getId() + ")" + residue +
"[" + mod2 + "]";
peptide = boost::regex_replace(peptide, re, replacement);
}
else if (maybe_nterm[1] && !maybe_nterm[0])
{ // second mod is terminal:
String replacement = "(" + maybe_nterm[1]->getId() + ")" + residue +
"[" + mod1 + "]";
peptide = boost::regex_replace(peptide, re, replacement);
}
else // ambiguous cases
{
vector<const ResidueModification*> maybe_residue(2, null);
maybe_residue[0] = ModificationsDB::getInstance()->
getBestModificationByDiffMonoMass(mass1, 0.01, residue,
ResidueModification::ANYWHERE);
maybe_residue[1] = ModificationsDB::getInstance()->
getBestModificationByDiffMonoMass(mass2, 0.01, residue,
ResidueModification::ANYWHERE);
if (maybe_nterm[0] && maybe_nterm[1]) // both mods may be terminal
{
if (maybe_residue[0] && !maybe_residue[1])
{ // first mod must be non-terminal -> second mod is terminal:
String replacement = "(" + maybe_nterm[1]->getId() + ")" +
residue + "[" + mod1 + "]";
peptide = boost::regex_replace(peptide, re, replacement);
}
else if (maybe_residue[1] && !maybe_residue[0])
{ // second mod must be non-terminal -> first mod is terminal:
String replacement = "(" + maybe_nterm[0]->getId() + ")" +
residue + "[" + mod2 + "]";
peptide = boost::regex_replace(peptide, re, replacement);
}
else // both mods may be terminal or non-terminal :-(
{ // arbitrarily assume first mod is terminal
String replacement = "(" + maybe_nterm[0]->getId() + ")" +
residue + "[" + mod2 + "]";
peptide = boost::regex_replace(peptide, re, replacement);
}
}
// if neither mod can be terminal, something is wrong -> let
// AASequence deal with it
}
}
}
}
void PercolatorOutfile::getPeptideSequence_(String peptide, AASequence& seq)
const
{
// 'peptide' includes neighboring amino acids, e.g.: K.AAAR.A
// but unclear to which protein neighboring AAs belong, so we ignore them:
size_t len = peptide.size(), start = 0, count = std::string::npos;
if (peptide[1] == '.')
{
start = 2;
}
if (peptide[len - 2] == '.')
{
count = len - start - 2;
}
peptide = peptide.substr(start, count);
// re-format modifications:
String unknown_mod = "[unknown]";
if (peptide.hasSubstring(unknown_mod))
{
OPENMS_LOG_WARN << "Removing unknown modification(s) from peptide '" << peptide
<< "'" << endl;
peptide.substitute(unknown_mod, "");
}
boost::regex re(R"(\[UNIMOD:(\d+)\])");
std::string replacement = "(UniMod:$1)";
peptide = boost::regex_replace(peptide, re, replacement);
// search results from X! Tandem:
// N-terminal mods may be wrongly assigned to the first residue; there may
// be up to two mass shifts (one terminal, one residue) in random order!
resolveMisassignedNTermMods_(peptide);
// positive mass shifts are missing the "+":
re.assign("\\[(\\d)");
replacement = "[+$1";
peptide = boost::regex_replace(peptide, re, replacement);
seq = AASequence::fromString(peptide);
}
void PercolatorOutfile::load(const String& filename,
ProteinIdentification& proteins,
PeptideIdentificationList& peptides,
SpectrumMetaDataLookup& lookup,
ScoreType output_score)
{
SpectrumMetaDataLookup::MetaDataFlags lookup_flags =
(SpectrumMetaDataLookup::MDF_RT |
SpectrumMetaDataLookup::MDF_PRECURSORMZ |
SpectrumMetaDataLookup::MDF_PRECURSORCHARGE);
if (lookup.reference_formats.empty())
{
// MS-GF+ Percolator (mzid?) format:
lookup.addReferenceFormat(R"(_SII_(?<INDEX1>\d+)_\d+_\d+_(?<CHARGE>\d+)_\d+)");
// Mascot Percolator format (RT may be missing, e.g. for searches via
// ProteomeDiscoverer):
lookup.addReferenceFormat(R"(spectrum:[^;]+[(scans:)(scan=)(spectrum=)](?<INDEX0>\d+)[^;]+;rt:(?<RT>\d*(\.\d+)?);mz:(?<MZ>\d+(\.\d+)?);charge:(?<CHARGE>-?\d+))");
// X! Tandem Percolator format:
lookup.addReferenceFormat(R"(_(?<INDEX0>\d+)_(?<CHARGE>\d+)_\d+$)");
}
vector<String> items;
CsvFile source(filename, '\t');
source.getRow(0, items);
String header = ListUtils::concatenate<String>(items, '\t');
if (header !=
"PSMId\tscore\tq-value\tposterior_error_prob\tpeptide\tproteinIds")
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
header, "Not a valid header for Percolator (PSM level) output");
}
set<String> accessions;
Size no_charge = 0, no_rt = 0, no_mz = 0; // counters for missing data
peptides.clear();
for (Size row = 1; row < source.rowCount(); ++row)
{
source.getRow(row, items);
SpectrumMetaDataLookup::SpectrumMetaData meta_data;
try
{
lookup.getSpectrumMetaData(items[0], meta_data, lookup_flags);
}
catch (...)
{
String msg = "Error: Could not extract data for spectrum reference '" +
items[0] + "' from row " + String(row);
OPENMS_LOG_ERROR << msg << endl;
}
PeptideHit hit;
if (meta_data.precursor_charge != 0)
{
hit.setCharge(meta_data.precursor_charge);
}
else
{
++no_charge; // maybe TODO: calculate charge from m/z and peptide mass?
}
PeptideIdentification peptide;
peptide.setIdentifier("id");
if (!std::isnan(meta_data.rt))
{
peptide.setRT(meta_data.rt);
}
else
{
++no_rt;
}
if (!std::isnan(meta_data.precursor_mz))
{
peptide.setMZ(meta_data.precursor_mz);
}
else
{
++no_mz;
}
double score = items[1].toDouble();
double qvalue = items[2].toDouble();
double posterrprob = items[3].toDouble();
hit.setMetaValue("Percolator_score", score);
hit.setMetaValue("Percolator_qvalue", qvalue);
hit.setMetaValue("Percolator_PEP", posterrprob);
switch (output_score)
{
case ScoreType::SCORE:
hit.setScore(score);
peptide.setScoreType("Percolator_score");
peptide.setHigherScoreBetter(true);
break;
case ScoreType::QVALUE:
hit.setScore(qvalue);
peptide.setScoreType("q-value");
peptide.setHigherScoreBetter(false);
break;
case ScoreType::POSTERRPROB:
hit.setScore(posterrprob);
peptide.setScoreType("Posterior Error Probability");
peptide.setHigherScoreBetter(false);
break;
case ScoreType::SIZE_OF_SCORETYPE:
throw Exception::InvalidParameter(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "'output_score' must not be 'SIZE_OF_SCORETYPE'!");
}
AASequence seq;
getPeptideSequence_(items[4], seq);
hit.setSequence(seq);
for (Size pos = 5; pos < items.size(); ++pos)
{
accessions.insert(items[pos]);
PeptideEvidence evidence;
evidence.setProteinAccession(items[pos]);
hit.addPeptideEvidence(evidence);
}
peptide.insertHit(hit);
peptides.push_back(peptide);
}
proteins = ProteinIdentification();
proteins.setIdentifier("id");
proteins.setDateTime(DateTime::now());
proteins.setSearchEngine("Percolator");
for (set<String>::const_iterator it = accessions.begin();
it != accessions.end(); ++it)
{
ProteinHit hit;
hit.setAccession(*it);
proteins.insertHit(hit);
}
// add info about allowed modifications:
ModificationDefinitionsSet mod_defs;
mod_defs.inferFromPeptides(peptides);
ProteinIdentification::SearchParameters params;
mod_defs.getModificationNames(params.fixed_modifications,
params.variable_modifications);
proteins.setSearchParameters(params);
OPENMS_LOG_INFO << "Created " << proteins.getHits().size() << " protein hits.\n"
<< "Created " << peptides.size() << " peptide hits (PSMs)."
<< endl;
if (no_charge > 0)
{
OPENMS_LOG_WARN << no_charge << " peptide hits without charge state information."
<< endl;
}
if (no_rt > 0)
{
OPENMS_LOG_WARN << no_rt << " peptide hits without retention time information."
<< endl;
}
if (no_mz > 0)
{
OPENMS_LOG_WARN << no_mz << " peptide hits without mass-to-charge information."
<< endl;
}
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/MascotXMLFile.cpp | .cpp | 5,353 | 146 | // 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/MascotXMLFile.h>
using namespace xercesc;
using namespace std;
namespace OpenMS
{
MascotXMLFile::MascotXMLFile() :
Internal::XMLFile()
{
}
void MascotXMLFile::load(const String& filename,
ProteinIdentification& protein_identification,
PeptideIdentificationList& id_data,
const SpectrumMetaDataLookup& lookup)
{
map<String, vector<AASequence> > peptides;
load(filename, protein_identification, id_data, peptides, lookup);
}
void MascotXMLFile::load(const String& filename,
ProteinIdentification& protein_identification,
PeptideIdentificationList& id_data,
map<String, vector<AASequence> >& peptides,
const SpectrumMetaDataLookup& lookup)
{
//clear
protein_identification = ProteinIdentification();
id_data.clear();
Internal::MascotXMLHandler handler(protein_identification, id_data,
filename, peptides, lookup);
parse_(filename, &handler);
// since the Mascot XML can contain "peptides" without sequences,
// the identifications without any real peptide hit are removed
PeptideIdentificationList filtered_hits;
filtered_hits.reserve(id_data.size());
Size missing_sequence = 0; // counter
for (PeptideIdentification& id_it : id_data)
{
const vector<PeptideHit>& peptide_hits = id_it.getHits();
if (!peptide_hits.empty() &&
(peptide_hits.size() > 1 || !peptide_hits[0].getSequence().empty()))
{
filtered_hits.push_back(id_it);
}
else if (!id_it.empty()) ++missing_sequence;
}
if (missing_sequence)
{
OPENMS_LOG_WARN << "Warning: Removed " << missing_sequence
<< " peptide identifications without sequence." << endl;
}
id_data.swap(filtered_hits);
// check if we have (some) RT information:
Size no_rt_count = 0;
for (PeptideIdentification& id_it : id_data)
{
if (!id_it.hasRT())
{
++no_rt_count;
}
}
if (no_rt_count)
{
OPENMS_LOG_WARN << "Warning: " << no_rt_count << " (of " << id_data.size()
<< ") peptide identifications have no retention time value."
<< endl;
}
// if we have a mapping, but couldn't find any RT values, that's an error:
if (!lookup.empty() && (no_rt_count == id_data.size()))
{
throw Exception::MissingInformation(
__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"No retention time information for peptide identifications found");
}
// argh! Mascot 2.2 tends to repeat the first hit (yes it appears twice),
// so we delete one of them
for (PeptideIdentification& pip : id_data)
{
vector<PeptideHit> peptide_hits = pip.getHits();
// check if equal, except for rank
if (peptide_hits.size() > 1 &&
peptide_hits[0].getScore() == peptide_hits[1].getScore() &&
peptide_hits[0].getSequence() == peptide_hits[1].getSequence() &&
peptide_hits[0].getCharge() == peptide_hits[1].getCharge())
{
// erase first hit
peptide_hits.erase(peptide_hits.begin() + 1);
pip.setHits(peptide_hits);
}
}
}
void MascotXMLFile::initializeLookup(SpectrumMetaDataLookup& lookup, const PeakMap& exp, const String& scan_regex)
{
// load spectra and extract scan numbers from the native IDs
// (expected format: "... scan=#"):
lookup.readSpectra(exp.getSpectra());
if (scan_regex.empty()) // use default formats
{
if (!lookup.empty()) // raw data given -> spectrum look-up possible
{
// possible formats and resulting scan numbers:
// - Mascot 2.3 (?):
// <pep_scan_title>scan=818</pep_scan_title> -> 818
// - ProteomeDiscoverer/Mascot 2.3 or 2.4:
// <pep_scan_title>Spectrum136 scans:712,</pep_scan_title> -> 712
// - other variants:
// <pep_scan_title>Spectrum3411 scans: 2975,</pep_scan_title> -> 2975
// <...>File773 Spectrum198145 scans: 6094</...> -> 6094
// <...>6860: Scan 10668 (rt=5380.57)</...> -> 10668
// <pep_scan_title>Scan Number: 1460</pep_scan_title> -> 1460
lookup.addReferenceFormat("[Ss]can( [Nn]umber)?s?[=:]? *(?<SCAN>\\d+)");
// - with .dta input to Mascot:
// <...>/path/to/FTAC05_13.673.673.2.dta</...> -> 673
lookup.addReferenceFormat(R"(\.(?<SCAN>\d+)\.\d+\.(?<CHARGE>\d+)(\.dta)?)");
}
// title containing RT and MZ instead of scan number:
// <...>575.848571777344_5018.0811_controllerType=0 controllerNumber=1 scan=11515_EcoliMS2small</...>
lookup.addReferenceFormat(R"(^(?<MZ>\d+(\.\d+)?)_(?<RT>\d+(\.\d+)?))");
}
else // use only user-defined format
{
lookup.addReferenceFormat(scan_regex);
}
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/MS2File.cpp | .cpp | 525 | 24 | // 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/MS2File.h>
using namespace std;
namespace OpenMS
{
MS2File::MS2File() :
ProgressLogger()
{
}
MS2File::~MS2File() = default;
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/MzTabBase.cpp | .cpp | 16,702 | 888 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Oliver Alka $
// $Authors: Timo Sachsenberg, Oliver Alka $
// --------------------------------------------------------------------------
#include <OpenMS/FORMAT/MzTabBase.h>
#include <OpenMS/DATASTRUCTURES/ListUtils.h>
#include <cassert>
namespace OpenMS
{
bool MzTabParameterList::isNull() const
{
return parameters_.empty();
}
void MzTabParameterList::setNull(bool b)
{
if (b) { parameters_.clear(); }
}
String MzTabParameterList::toCellString() const
{
if (isNull())
{
return "null";
}
else
{
String ret;
for (std::vector<MzTabParameter>::const_iterator it = parameters_.begin(); it != parameters_.end(); ++it)
{
if (it != parameters_.begin())
{
ret += "|";
}
ret += it->toCellString();
}
return ret;
}
}
void MzTabParameterList::fromCellString(const String& s)
{
String lower = s;
lower.toLower().trim();
if (lower == "null")
{
setNull(true);
}
else
{
std::vector<String> fields;
s.split("|", fields);
for (Size i = 0; i != fields.size(); ++i)
{
MzTabParameter p;
lower = fields[i];
lower.toLower().trim();
if (lower == "null")
{
throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String("MzTabParameter in MzTabParameterList must not be null '") + s);
}
p.fromCellString(fields[i]);
parameters_.push_back(p);
}
}
}
std::vector<MzTabParameter> MzTabParameterList::get() const
{
return parameters_;
}
void MzTabParameterList::set(const std::vector<MzTabParameter>& parameters)
{
parameters_ = parameters;
}
MzTabStringList::MzTabStringList() :
sep_('|')
{
}
void MzTabStringList::setSeparator(char sep)
{
sep_ = sep;
}
bool MzTabStringList::isNull() const
{
return entries_.empty();
}
void MzTabStringList::setNull(bool b)
{
if (b)
{
entries_.clear();
}
}
String MzTabStringList::toCellString() const
{
if (isNull())
{
return "null";
}
else
{
String ret;
for (std::vector<MzTabString>::const_iterator it = entries_.begin(); it != entries_.end(); ++it)
{
if (it != entries_.begin())
{
ret += sep_;
}
ret += it->toCellString();
}
return ret;
}
}
void MzTabStringList::fromCellString(const String& s)
{
String lower = s;
lower.toLower().trim();
if (lower == "null")
{
setNull(true);
}
else
{
std::vector<String> fields;
s.split(sep_, fields);
for (Size i = 0; i != fields.size(); ++i)
{
MzTabString ts;
ts.fromCellString(fields[i]);
entries_.push_back(ts);
}
}
}
std::vector<MzTabString> MzTabStringList::get() const
{
return entries_;
}
void MzTabStringList::set(const std::vector<MzTabString>& entries)
{
entries_ = entries;
}
MzTabSpectraRef::MzTabSpectraRef() :
ms_run_(0)
{
}
bool MzTabSpectraRef::isNull() const
{
return (ms_run_ < 1) || (spec_ref_.empty());
}
void MzTabSpectraRef::setNull(bool b)
{
if (b)
{
ms_run_ = 0;
spec_ref_.clear();
}
}
void MzTabSpectraRef::setMSFile(Size index)
{
assert(index >= 1);
if (index >= 1)
{
ms_run_ = index;
}
}
void MzTabSpectraRef::setSpecRef(const String& spec_ref)
{
assert(!spec_ref.empty());
if (!spec_ref.empty())
{
spec_ref_ = spec_ref;
}
else
{
OPENMS_LOG_WARN << "Spectrum reference not set." << std::endl;
}
}
String MzTabSpectraRef::getSpecRef() const
{
assert(!isNull());
return spec_ref_;
}
Size MzTabSpectraRef::getMSFile() const
{
assert(!isNull());
return ms_run_;
}
void MzTabSpectraRef::setSpecRefFile(const String& spec_ref)
{
assert(!spec_ref.empty());
if (!spec_ref.empty())
{
spec_ref_ = spec_ref;
}
}
String MzTabSpectraRef::toCellString() const
{
if (isNull())
{
return "null";
}
else
{
return String("ms_run[") + String(ms_run_) + "]:" + spec_ref_;
}
}
void MzTabSpectraRef::fromCellString(const String& s)
{
String lower = s;
lower.toLower().trim();
if (lower == "null")
{
setNull(true);
}
else
{
std::vector<String> fields;
s.split(":", fields);
if (fields.size() != 2)
{
throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String("Can not convert to MzTabSpectraRef from '") + s + "'");
}
spec_ref_ = fields[1];
ms_run_ = (Size)(fields[0].substitute("ms_run[", "").remove(']').toInt());
}
}
MzTabParameter::MzTabParameter()
: CV_label_(""),
accession_(""),
name_(""),
value_("")
{
}
bool MzTabParameter::isNull() const
{
return CV_label_.empty() && accession_.empty() && name_.empty() && value_.empty();
}
void MzTabParameter::setNull(bool b)
{
if (b)
{
CV_label_.clear();
accession_.clear();
name_.clear();
value_.clear();
}
}
void MzTabParameter::setCVLabel(const String& CV_label)
{
CV_label_ = CV_label;
}
void MzTabParameter::setAccession(const String& accession)
{
accession_ = accession;
}
void MzTabParameter::setName(const String& name)
{
name_ = name;
}
void MzTabParameter::setValue(const String& value)
{
value_ = value;
}
String MzTabParameter::getCVLabel() const
{
assert(!isNull());
return CV_label_;
}
String MzTabParameter::getAccession() const
{
assert(!isNull());
return accession_;
}
String MzTabParameter::getName() const
{
assert(!isNull());
return name_;
}
String MzTabParameter::getValue() const
{
assert(!isNull());
return value_;
}
String MzTabParameter::toCellString() const
{
if (isNull())
{
return "null";
}
else
{
String ret = "[";
ret += CV_label_ + ", ";
ret += accession_ + ", ";
if (name_.hasSubstring(", "))
{
ret += String("\"") + name_ + String("\""); // quote name if it contains a ","
}
else
{
ret += name_;
}
ret += String(", ");
if (value_.hasSubstring(", "))
{
ret += String("\"") + value_ + String("\""); // quote value if it contains a ","
}
else
{
ret += value_;
}
ret += "]";
return ret;
}
}
void MzTabParameter::fromCellString(const String& s)
{
String lower = s;
lower.toLower().trim();
if (lower == "null")
{
setNull(true);
}
else
{
StringList fields;
String field;
bool in_quotes = false;
for (String::const_iterator sit = s.begin(); sit != s.end(); ++sit)
{
if (*sit == '\"') // start or end of quotes
{
in_quotes = !in_quotes;
}
else if (*sit == ',') // , encountered
{
if (in_quotes) // case 1: , in quote
{
field += ','; // add , (no split)
}
else // split at , if not in quotes
{
fields.push_back(field.trim());
field.clear();
}
}
else if (*sit != '[' && *sit != ']')
{
// skip leading ws
if (*sit == ' ' && field.empty())
{
continue;
}
field += *sit;
}
}
fields.push_back(field.trim());
if (fields.size() != 4)
{
throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String("Could not convert String '") + s + "' to MzTabParameter");
}
CV_label_ = fields[0];
accession_ = fields[1];
name_ = fields[2];
value_ = fields[3];
}
}
MzTabString::MzTabString(const String& s)
{
set(s);
}
void MzTabString::set(const String& value)
{
String lower = value;
lower.toLower().trim();
if (lower == "null")
{
setNull(true);
}
else
{
value_ = value;
value_.trim();
}
}
String MzTabString::get() const
{
return value_;
}
bool MzTabString::isNull() const
{
return value_.empty();
}
void MzTabString::setNull(bool b)
{
if (b)
{
value_.clear();
}
}
MzTabString::MzTabString()
: value_()
{
}
String MzTabString::toCellString() const
{
if (isNull())
{
return "null";
}
else
{
return value_;
}
}
void MzTabString::fromCellString(const String& s)
{
set(s);
}
MzTabBoolean::MzTabBoolean(bool v)
{
set((int)v);
}
MzTabBoolean::MzTabBoolean()
: value_(-1)
{
}
void MzTabBoolean::set(const bool& value)
{
value_ = (int)value;
}
Int MzTabBoolean::get() const
{
return value_;
}
bool MzTabBoolean::isNull() const
{
return value_ < 0;
}
void MzTabBoolean::setNull(bool b)
{
if (!b)
value_ = -1;
else
value_ = 0;
}
String MzTabBoolean::toCellString() const
{
if (isNull())
{
return "null";
}
else
{
if (value_)
{
return "1";
}
else
{
return "0";
}
}
}
void MzTabBoolean::fromCellString(const String& s)
{
String lower = s;
lower.toLower().trim();
if (lower == "null")
{
setNull(true);
}
else
{
if (s == "0")
{
set(false);
}
else if (s == "1")
{
set(true);
}
else
{
throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String("Could not convert String '") + s + "' to MzTabBoolean");
}
}
}
bool MzTabIntegerList::isNull() const
{
return entries_.empty();
}
void MzTabIntegerList::setNull(bool b)
{
if (b)
{
entries_.clear();
}
}
String MzTabIntegerList::toCellString() const
{
if (isNull())
{
return "null";
}
else
{
String ret;
for (std::vector<MzTabInteger>::const_iterator it = entries_.begin(); it != entries_.end(); ++it)
{
if (it != entries_.begin())
{
ret += ",";
}
ret += it->toCellString();
}
return ret;
}
}
void MzTabIntegerList::fromCellString(const String& s)
{
String lower = s;
lower.toLower().trim();
if (lower == "null")
{
setNull(true);
}
else
{
std::vector<String> fields;
s.split(",", fields);
for (Size i = 0; i != fields.size(); ++i)
{
MzTabInteger ds;
ds.fromCellString(fields[i]);
entries_.push_back(ds);
}
}
}
std::vector<MzTabInteger> MzTabIntegerList::get() const
{
return entries_;
}
void MzTabIntegerList::set(const std::vector<MzTabInteger>& entries)
{
entries_ = entries;
}
MzTabInteger::MzTabInteger(const int v)
{
set(v);
}
MzTabInteger::MzTabInteger()
: value_(0), state_(MZTAB_CELLSTATE_NULL)
{
}
void MzTabInteger::set(const Int& value)
{
state_ = MZTAB_CELLSTATE_DEFAULT;
value_ = value;
}
Int MzTabInteger::get() const
{
if (state_ == MZTAB_CELLSTATE_DEFAULT)
{
return value_;
}
else
{
throw Exception::ElementNotFound(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String("Trying to extract MzTab Integer value from non-integer valued cell. Did you check the cell state before querying the value?"));
}
}
String MzTabInteger::toCellString() const
{
switch (state_)
{
case MZTAB_CELLSTATE_NULL:
return "null";
case MZTAB_CELLSTATE_NAN:
return "NaN";
case MZTAB_CELLSTATE_INF:
return "Inf";
case MZTAB_CELLSTATE_DEFAULT:
default:
return String(value_);
}
}
void MzTabInteger::fromCellString(const String& s)
{
String lower = s;
lower.toLower().trim();
if (lower == "null") { setNull(true); }
else if (lower == "nan") { setNaN(); }
else if (lower == "inf") { setInf(); }
else // default case
{
// some mzTab files from external sources contain floating point numbers in integer columns
auto val = lower.toDouble();
if (val != (Int)val) // check if the value is actually an integer (e.g. 4.0)
{
throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String("Could not convert String '") + s + "' to MzTabInteger");
}
set((Int)val);
}
}
bool MzTabInteger::isNull() const
{
return state_ == MZTAB_CELLSTATE_NULL;
}
void MzTabInteger::setNull(bool b)
{
state_ = b ? MZTAB_CELLSTATE_NULL : MZTAB_CELLSTATE_DEFAULT;
}
bool MzTabInteger::isNaN() const
{
return state_ == MZTAB_CELLSTATE_NAN;
}
void MzTabInteger::setNaN()
{
state_ = MZTAB_CELLSTATE_NAN;
}
bool MzTabInteger::isInf() const
{
return state_ == MZTAB_CELLSTATE_INF;
}
void MzTabInteger::setInf()
{
state_ = MZTAB_CELLSTATE_INF;
}
bool MzTabDouble::isNull() const
{
return state_ == MZTAB_CELLSTATE_NULL;
}
void MzTabDouble::setNull(bool b)
{
state_ = b ? MZTAB_CELLSTATE_NULL : MZTAB_CELLSTATE_DEFAULT;
}
bool MzTabDouble::isNaN() const
{
return state_ == MZTAB_CELLSTATE_NAN;
}
void MzTabDouble::setNaN()
{
state_ = MZTAB_CELLSTATE_NAN;
}
bool MzTabDouble::isInf() const
{
return state_ == MZTAB_CELLSTATE_INF;
}
void MzTabDouble::setInf()
{
state_ = MZTAB_CELLSTATE_INF;
}
MzTabDouble::MzTabDouble()
: value_(0.0), state_(MZTAB_CELLSTATE_NULL)
{
}
MzTabDouble::MzTabDouble(const double v)
{
set(v);
}
void MzTabDouble::set(const double& value)
{
state_ = MZTAB_CELLSTATE_DEFAULT;
value_ = value;
}
double MzTabDouble::get() const
{
if (state_ != MZTAB_CELLSTATE_DEFAULT)
{
throw Exception::ElementNotFound(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String("Trying to extract MzTab Double value from non-double valued cell. Did you check the cell state before querying the value?"));
}
return value_;
}
String MzTabDouble::toCellString() const
{
switch (state_)
{
case MZTAB_CELLSTATE_NULL:
return "null";
case MZTAB_CELLSTATE_NAN:
return "NaN";
case MZTAB_CELLSTATE_INF:
return "Inf";
case MZTAB_CELLSTATE_DEFAULT:
default:
return String(value_);
}
}
void MzTabDouble::fromCellString(const String& s)
{
String lower = s;
lower.toLower().trim();
if (lower == "null")
{
setNull(true);
}
else if (lower == "nan")
{
setNaN();
}
else if (lower == "inf")
{
setInf();
}
else // default case
{
set(lower.toDouble());
}
}
bool MzTabDouble::operator<(const MzTabDouble& rhs) const
{
return this->value_ < rhs.value_;
}
bool MzTabDouble::operator==(const MzTabDouble& rhs) const
{
return this->value_ == rhs.value_;
}
bool MzTabDoubleList::isNull() const
{
return entries_.empty();
}
void MzTabDoubleList::setNull(bool b)
{
if (b)
{
entries_.clear();
}
}
String MzTabDoubleList::toCellString() const
{
if (isNull())
{
return "null";
}
else
{
String ret;
for (std::vector<MzTabDouble>::const_iterator it = entries_.begin(); it != entries_.end(); ++it)
{
if (it != entries_.begin())
{
ret += "|";
}
ret += it->toCellString();
}
return ret;
}
}
void MzTabDoubleList::fromCellString(const String& s)
{
String lower = s;
lower.toLower().trim();
if (lower == "null")
{
setNull(true);
}
else
{
std::vector<String> fields;
s.split("|", fields);
for (Size i = 0; i != fields.size(); ++i)
{
MzTabDouble ds;
ds.fromCellString(fields[i]);
entries_.push_back(ds);
}
}
}
std::vector<MzTabDouble> MzTabDoubleList::get() const
{
return entries_;
}
void MzTabDoubleList::set(const std::vector<MzTabDouble>& entries)
{
entries_ = entries;
}
} // namespace OpenMS | C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/MSstatsFile.cpp | .cpp | 31,372 | 749 | // 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/MSstatsFile.h>
#include <OpenMS/SYSTEM/File.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <tuple>
using namespace std;
using namespace OpenMS;
const String MSstatsFile::na_string_ = "NA";
void MSstatsFile::checkConditionLFQ_(const ExperimentalDesign::SampleSection& sampleSection,
const String& bioreplicate,
const String& condition)
{
// Sample Section must contain the column that contains the condition used for MSstats
if (!sampleSection.hasFactor(condition))
{
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Sample Section of the experimental design does not contain MSstats_Condition");
}
// Sample Section must contain column for the Bioreplicate
if (!sampleSection.hasFactor(bioreplicate))
{
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Sample Section of the experimental design does not contain MSstats_BioReplicate");
}
}
void MSstatsFile::checkConditionISO_(const ExperimentalDesign::SampleSection& sampleSection,
const String& bioreplicate,
const String& condition,
const String& mixture)
{
checkConditionLFQ_(sampleSection, bioreplicate, condition);
// Sample Section must contain column for Mixture
if (!sampleSection.hasFactor(mixture))
{
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Sample Section of the experimental design does not contain MSstats_Mixture");
}
}
//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.
MSstatsFile::AggregatedConsensusInfo MSstatsFile::aggregateInfo_(const ConsensusMap& consensus_map,
const std::vector<String>& spectra_paths)
{
MSstatsFile::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<MSstatsFile::Intensity> intensities;
vector<MSstatsFile::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.
template <class LineType>
void MSstatsFile::constructFile_(const String& retention_time_summarization_method,
const bool rt_summarization_manual,
TextFile& csv_out,
const std::set<String>& peptideseq_quantifyable,
LineType& peptideseq_to_prefix_to_intensities) const
{
// sanity check that the triples (peptide_sequence, precursor_charge, run) only appears once
set<tuple<String, String, String> > peptideseq_precursor_charge_run;
for (const auto &peptideseq : peptideseq_quantifyable)
{
for (const auto &line :
peptideseq_to_prefix_to_intensities[peptideseq])
{
// First, we collect all retention times and intensities
set<MSstatsFile::Coordinate> retention_times{};
set<MSstatsFile::Intensity> intensities{};
for (const auto &p : line.second)
{
if (retention_times.find(get<1>(p)) != retention_times.end())
{
OPENMS_LOG_WARN << "Peptide ion appears multiple times at the same retention time."
" This is not expected."
<< endl;
}
else
{
retention_times.insert(get<1>(p));
intensities.insert(get<0>(p));
}
}
peptideseq_precursor_charge_run.emplace(line.first.sequence(), line.first.precursor_charge(), line.first.run());
// If the rt summarization method is set to manual, we simply output all it,rt pairs
if (rt_summarization_manual)
{
for (const auto &ity_rt_file : line.second)
{
//RT, common prefix items, intensity, "unique ID (file+spectrumID)"
csv_out.addLine(
String(get<1>(ity_rt_file)) + ',' + line.first.toString() + ',' + String(get<0>(ity_rt_file)) + ','
+ quote_ + get<2>(ity_rt_file) + quote_);
}
}
// Otherwise, the intensities are resolved over the retention times
else
{
MSstatsFile::Intensity intensity(0);
if (retention_time_summarization_method == "max")
{
intensity = *(max_element(intensities.begin(), intensities.end()));
}
else if (retention_time_summarization_method == "min")
{
intensity = *(min_element(intensities.begin(), intensities.end()));
}
else if (retention_time_summarization_method == "mean")
{
intensity = meanIntensity_(intensities);
}
else if (retention_time_summarization_method == "sum")
{
intensity = sumIntensity_(intensities);
}
//common prefix items, aggregated intensity, "unique ID (file of first spectrum in the set of 'same')"
//@todo we could collect all spectrum references contributing to this intensity instead
csv_out.addLine(
line.first.toString() + delim_ + String(intensity) + delim_ + quote_ +
get<2>(*line.second.begin()) + quote_);
}
}
}
}
void MSstatsFile::storeLFQ(const String& filename,
const ConsensusMap& consensus_map,
const ExperimentalDesign& design,
const StringList& reannotate_filenames,
const bool is_isotope_label_type,
const String& bioreplicate,
const String& condition,
const String& retention_time_summarization_method)
{
// 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, bioreplicate, 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 MSstats input to run for OpenMS
map< unsigned, unsigned > msstats_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);
// The Retention Time is additionally written to the output as soon as the user wants to resolve multiple peptides manually
const bool rt_summarization_manual(retention_time_summarization_method == "manual");
if (rt_summarization_manual)
{
OPENMS_LOG_WARN << "WARNING: rt_summarization set to manual."
" One feature might appear at multiple retention times in the output file."
" This is invalid input for standard MSstats."
" Combining of features over retention times is recommended!" << endl;
}
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);
}
// Determine if the experiment has fractions
const bool has_fraction = design.isFractionated();
//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.
MSstatsFile::AggregatedConsensusInfo aggregatedInfo = MSstatsFile::aggregateInfo_(consensus_map, spectra_paths);
// The output file of the MSstats converter
TextFile csv_out;
csv_out.addLine(
String(rt_summarization_manual ? "RetentionTime,": "") +
"ProteinName,PeptideSequence,PrecursorCharge,FragmentIon,"
"ProductCharge,IsotopeLabelType,Condition,BioReplicate,Run," +
String(has_fraction ? "Fraction,": "") + "Intensity,Reference");
// From the MSstats user guide: endogenous peptides (use "L") or labeled reference peptides (use "H").
String isotope_label_type = "L";
if (is_isotope_label_type) //@todo remove? not sure if this is correct. I think DDA LFQ is always "L"
{
// use the channel_id information (?)
isotope_label_type = "H";
}
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 MSstats output
// Several things needs to be considered:
// - We need to map peptide sequences to full features, because then we can ignore peptides
// that are mapped to multiple proteins.
// - We also need to map to the intensities, such that we combine intensities over multiple retention times.
map< String, map< MSstatsLine_, set< tuple<Intensity, Coordinate, String> > > > peptideseq_to_prefix_to_intensities;
for (Size i = 0; i < aggregatedInfo.features.size(); ++i)
{
const BaseFeature &base_feature = aggregatedInfo.features[i];
for (const PeptideIdentification &pep_id : base_feature.getPeptideIdentifications())
{
for (const PeptideHit & pep_hit : pep_id.getHits())
{
// skip decoys
if (pep_hit.isDecoy())
{
continue;
}
//TODO Really double check with Meena Choi (MSStats author) or make it an option! I can't find any info
// on what is correct. For TMT we include them (since it is necessary) (see occurrence above as well when map is built!)
const String & sequence = pep_hit.getSequence().toString(); // to modified string
// 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 two peptides with the same sequence map to different proteins unless something is wrong.
// Also, I think MSstats 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
// MSstats User manual 3.7.3: Unknown precursor charge should be set to 0
const Int precursor_charge = pep_hit.getCharge();
// Unused for DDA data anyway
String fragment_ion = na_string_;
String frag_charge = "0";
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_idx = 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]; // MSstats run according to the file table
const unsigned openms_fractiongroup = path_label_to_fractiongroup[tpl1];
msstats_run_to_openms_fractiongroup[run] = openms_fractiongroup;
// Assemble MSstats line
//TODO since a lot of cols are constant in DDA LFQ, we could reduce the prefix and add the constant
// cols on-the-fly during constructFile_ (so we save during checking duplicates)
MSstatsLine_ prefix(
has_fraction,
accession,
sequence,
precursor_charge,
fragment_ion,
frag_charge,
isotope_label_type,
sampleSection.getFactorValue(sample_idx, condition),
sampleSection.getFactorValue(sample_idx, bioreplicate),
String(run),
(has_fraction ? String(fraction) : "")
);
tuple<Intensity, Coordinate, String> intensity_retention_time = make_tuple(intensity, retention_time, current_filename);
peptideseq_to_prefix_to_intensities[sequence][prefix].insert(intensity_retention_time);
}
}
}
}
// Print the run mapping between MSstats and OpenMS
for (const auto& run_mapping : msstats_run_to_openms_fractiongroup)
{
cout << "MSstats run " << String(run_mapping.first)
<< " corresponds to OpenMS fraction group " << String(run_mapping.second) << endl;
}
constructFile_(retention_time_summarization_method,
rt_summarization_manual,
csv_out,
peptideseq_quantifyable,
peptideseq_to_prefix_to_intensities);
// Store the final assembled CSV file
csv_out.store(filename);
}
void MSstatsFile::storeISO(const String& filename,
const ConsensusMap& consensus_map,
const ExperimentalDesign& design,
const StringList& reannotate_filenames,
const String& bioreplicate,
const String& condition,
const String& mixture,
const String& retention_time_summarization_method)
{
// Experimental Design file
const ExperimentalDesign::SampleSection& sampleSection = design.getSampleSection();
checkConditionISO_(sampleSection, bioreplicate, condition, mixture);
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;
}
// Maps run in MSstats input to run for OpenMS
map< unsigned, unsigned > msstats_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);
// The Retention Time is additionally written to the output as soon as the user wants to resolve multiple peptides manually
bool rt_summarization_manual(retention_time_summarization_method == "manual");
if (!rt_summarization_manual)
{
OPENMS_LOG_WARN << "WARNING: rt_summarization set to something else than 'manual' but MSstatsTMT does aggregation of"
" intensities of peptide-chargestate combinations in the same file itself."
" Reverting to 'manual'" << endl;
rt_summarization_manual = 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.
MSstatsFile::AggregatedConsensusInfo AggregatedInfo = MSstatsFile::aggregateInfo_(consensus_map, spectra_paths);
// The output file of the MSstatsConverter
TextFile csv_out;
csv_out.addLine(String(rt_summarization_manual ? "RetentionTime,": "") +
"ProteinName,PeptideSequence,Charge,Channel,Condition,BioReplicate,Run,Mixture,TechRepMixture,Fraction,Intensity,Reference");
// 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 refactor since shared with LFQ and ISO
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);
std::set<String> peptideseq_quantifyable; //set for deterministic ordering
// Stores all the lines that will be present in the final MSstats output,
// We need to map peptide sequences to full features, because then we can ignore peptides
// that are mapped to multiple proteins. We also need to map to the
// intensities, such that we combine intensities over multiple retention times.
map< String, map< MSstatsTMTLine_, set< tuple<Intensity, Coordinate, String> > > > peptideseq_to_prefix_to_intensities;
for (Size i = 0; i < AggregatedInfo.features.size(); ++i)
{
const BaseFeature &base_feature = AggregatedInfo.features[i];
for (const PeptideIdentification &pep_id : base_feature.getPeptideIdentifications())
{
String nativeID = "NONATIVEID";
if (pep_id.metaValueExists("spectrum_reference"))
{
nativeID = pep_id.getMetaValue("spectrum_reference");
}
for (const PeptideHit & pep_hit : pep_id.getHits())
{
// skip decoys
if (pep_hit.isDecoy())
{
continue;
}
// Variables of the peptide hit
// MSstats User manual 3.7.3: Unknown precursor charge should be set to 0
const Int precursor_charge = (std::max)(pep_hit.getCharge(), 0);
const String & sequence = pep_hit.getSequence().toString();
// 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();
// When using extractProteinAccessionSet, we do not really need to loop over Evidences
// anymore since MSStats does not care about anything else but the Protein accessions
if (isQuantifyable_(accs, accession_to_group))
{
peptideseq_quantifyable.emplace(sequence);
}
else
{
continue; // we don't need the rest of the loop
}
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 channel(AggregatedInfo.consensus_feature_labels[i][j] + 1);
const pair< String, unsigned> tpl1 = make_pair(current_filename, channel);
const unsigned sample = path_label_to_sample[tpl1];
const unsigned fraction = path_label_to_fraction[tpl1];
// Resolve techrepmixture, run
const unsigned openms_fractiongroup = path_label_to_fractiongroup[tpl1];
String techrepmixture = String(sampleSection.getFactorValue(sample, mixture)) + "_" + String(openms_fractiongroup);
String run = techrepmixture + "_" + String(fraction);
// Assemble MSstats line
MSstatsTMTLine_ prefix(
accession,
sequence,
precursor_charge,
String(channel),
sampleSection.getFactorValue(sample, condition),
sampleSection.getFactorValue(sample, bioreplicate),
String(run),
sampleSection.getFactorValue(sample, mixture),
String(techrepmixture),
String(fraction)
);
String identifier = current_filename;
if (rt_summarization_manual)
{
identifier += "_" + nativeID;
}
tuple<Intensity, Coordinate, String> intensity_retention_time = make_tuple(intensity, retention_time, identifier);
peptideseq_to_prefix_to_intensities[sequence][prefix].insert(intensity_retention_time);
}
}
}
}
// Print the run mapping between MSstats and OpenMS
for (const auto& run_mapping : msstats_run_to_openms_fractiongroup)
{
cout << "MSstats run " << String(run_mapping.first)
<< " corresponds to OpenMS TechRepMixture " << String(run_mapping.second) << endl;
}
constructFile_(retention_time_summarization_method,
rt_summarization_manual,
csv_out,
peptideseq_quantifyable,
peptideseq_to_prefix_to_intensities);
// Store the final assembled CSV file
csv_out.store(filename);
}
bool MSstatsFile::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 MSstatsFile::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* > MSstatsFile::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 MSstatsFile::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;
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/Bzip2InputStream.cpp | .cpp | 1,464 | 58 | // 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/Bzip2InputStream.h>
#include <OpenMS/DATASTRUCTURES/String.h>
using namespace xercesc;
namespace OpenMS
{
Bzip2InputStream::Bzip2InputStream(const String & file_name) :
bzip2_(new Bzip2Ifstream(file_name.c_str())), file_current_index_(0)
{
}
Bzip2InputStream::Bzip2InputStream(const char * file_name) :
bzip2_(new Bzip2Ifstream(file_name)), file_current_index_(0)
{
}
/* Bzip2InputStream::Bzip2InputStream()
:bzip2_(NULL)
{
}*/
Bzip2InputStream::~Bzip2InputStream()
{
delete bzip2_;
}
XMLSize_t Bzip2InputStream::readBytes(XMLByte * const to_fill, const XMLSize_t max_to_read)
{
// Figure out whether we can really read.
if (bzip2_->streamEnd())
{
return 0;
}
unsigned char * fill_it = static_cast<unsigned char *>(to_fill);
XMLSize_t actual_read = (XMLSize_t) bzip2_->read((char *)fill_it, static_cast<size_t>(max_to_read));
file_current_index_ += actual_read;
return actual_read;
}
const XMLCh * Bzip2InputStream::getContentType() const
{
return nullptr;
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/TraMLFile.cpp | .cpp | 1,712 | 59 | // 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/TraMLFile.h>
#include <OpenMS/ANALYSIS/TARGETED/TargetedExperiment.h>
#include <OpenMS/FORMAT/VALIDATORS/TraMLValidator.h>
#include <OpenMS/FORMAT/CVMappingFile.h>
#include <OpenMS/FORMAT/HANDLERS/TraMLHandler.h>
#include <OpenMS/SYSTEM/File.h>
namespace OpenMS
{
TraMLFile::TraMLFile() :
XMLFile("/SCHEMAS/TraML1.0.0.xsd", "1.0.0")
{
}
TraMLFile::~TraMLFile() = default;
void TraMLFile::load(const String & filename, TargetedExperiment & exp)
{
Internal::TraMLHandler handler(exp, filename, schema_version_, *this);
parse_(filename, &handler);
}
void TraMLFile::store(const String & filename, const TargetedExperiment & exp) const
{
Internal::TraMLHandler handler(exp, filename, schema_version_, *this);
save_(filename, &handler);
}
bool TraMLFile::isSemanticallyValid(const String & filename, StringList & errors, StringList & warnings)
{
//load mapping
CVMappings mapping;
CVMappingFile().load(File::find("/MAPPING/TraML-mapping.xml"), mapping);
//load cvs
ControlledVocabulary cv;
cv.loadFromOBO("MS", File::find("/CV/psi-ms.obo"));
cv.loadFromOBO("UO", File::find("/CV/unit.obo"));
//validate
Internal::TraMLValidator v(mapping, cv);
bool result = v.validate(filename, errors, warnings);
return result;
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/ConsensusXMLFile.cpp | .cpp | 3,985 | 105 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Clemens Groepl, Marc Sturm, Mathias Walzer $
// --------------------------------------------------------------------------
#include <OpenMS/FORMAT/ConsensusXMLFile.h>
#include <OpenMS/FORMAT/HANDLERS/ConsensusXMLHandler.h>
#include <OpenMS/FORMAT/FileHandler.h>
#include <OpenMS/KERNEL/ConsensusMap.h>
#include <OpenMS/SYSTEM/File.h>
#include <fstream>
using namespace std;
namespace OpenMS
{
ConsensusXMLFile::ConsensusXMLFile() :
XMLFile("/SCHEMAS/ConsensusXML_1_7.xsd", "1.7")
{
}
ConsensusXMLFile::~ConsensusXMLFile() = default;
PeakFileOptions& ConsensusXMLFile::getOptions()
{
return options_;
}
const PeakFileOptions& ConsensusXMLFile::getOptions() const
{
return options_;
}
void ConsensusXMLFile::store(const String& filename, const ConsensusMap& consensus_map)
{
if (!FileHandler::hasValidExtension(filename, FileTypes::CONSENSUSXML))
{
throw Exception::UnableToCreateFile(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename, "invalid file extension, expected '" + FileTypes::typeToName(FileTypes::CONSENSUSXML) + "'");
}
if (!consensus_map.isMapConsistent(&getGlobalLogWarn()))
{
// Currently it is possible that FeatureLinkerUnlabeledQT triggers this exception
// throw Exception::MissingInformation(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "The ConsensusXML file contains invalid maps or references thereof. No data was written! Please fix the file or notify the maintainer of this tool if you did not provide a consensusXML file!");
std::cerr << "The ConsensusXML file contains invalid maps or references thereof. Please fix the file or notify the maintainer of this tool if you did not provide a consensusXML file! Note that this warning will be a fatal error in the next version of OpenMS!" << std::endl;
}
if (Size invalid_unique_ids = consensus_map.applyMemberFunction(&UniqueIdInterface::hasInvalidUniqueId))
{
// TODO Take care *outside* that this does not happen.
// We can detect this here but it is too late to fix the problem;
// there is no straightforward action to be taken in all cases.
// Note also that we are given a const reference.
OPENMS_LOG_INFO << String("ConsensusXMLFile::store(): found ") + invalid_unique_ids + " invalid unique ids" << std::endl;
}
// This will throw if the unique ids are not unique,
// so we never create bad files in this respect.
try
{
consensus_map.updateUniqueIdToIndex();
}
catch (Exception::Postcondition& e)
{
OPENMS_LOG_FATAL_ERROR << e.getName() << ' ' << e.what() << std::endl;
throw;
}
Internal::ConsensusXMLHandler handler(consensus_map, filename);
handler.setOptions(options_);
handler.setLogType(getLogType());
save_(filename, &handler);
}
void ConsensusXMLFile::load(const String& filename, ConsensusMap& consensus_map)
{
consensus_map.clear(true); // clear map
//set DocumentIdentifier
consensus_map.setLoadedFileType(filename);
consensus_map.setLoadedFilePath(filename);
Internal::ConsensusXMLHandler handler(consensus_map, filename);
handler.setOptions(options_);
handler.setLogType(getLogType());
parse_(filename, &handler);
if (!consensus_map.isMapConsistent(&getGlobalLogWarn())) // a warning is printed to LOG_WARN during isMapConsistent()
{
// don't throw exception for now, since this would prevent us from reading old files...
// throw Exception::MissingInformation(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "The ConsensusXML file contains invalid maps or references thereof. Please fix the file!");
}
consensus_map.updateRanges();
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/SVOutStream.cpp | .cpp | 3,568 | 143 | // 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/SVOutStream.h>
#include <OpenMS/CONCEPT/Exception.h>
using namespace std;
namespace OpenMS
{
SVOutStream::SVOutStream(const String& file_out,
const String& sep,
const String& replacement,
String::QuotingMethod quoting)
:
ostream(nullptr), ofs_(nullptr), sep_(sep), replacement_(replacement), nan_("nan"),
inf_("inf"), quoting_(quoting), modify_strings_(true), newline_(true)
{
ofs_ = new std::ofstream;
ofs_->open(file_out.c_str());
if (!ofs_->is_open())
{
throw Exception::FileNotWritable(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, file_out);
}
// bind to filestream
this->rdbuf(ofs_->rdbuf());
// use high decimal precision (appropriate for double):
precision(std::numeric_limits<double>::digits10);
}
SVOutStream::SVOutStream(ostream& out, const String& sep,
const String& replacement,
String::QuotingMethod quoting) :
ostream(out.rdbuf()), ofs_(nullptr), sep_(sep), replacement_(replacement), nan_("nan"),
inf_("inf"), quoting_(quoting), modify_strings_(true), newline_(true)
{
// use high decimal precision (appropriate for double):
precision(std::numeric_limits<double>::digits10);
}
SVOutStream::~SVOutStream()
{
if (ofs_)
{
ofs_->close();
delete ofs_;
}
}
SVOutStream& SVOutStream::operator<<(String str)
{
if (str.find('\n') != String::npos)
{
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "argument must not contain newline characters");
}
if (!newline_)
{
(ostream&) *this << sep_;
}
else
{
newline_ = false;
}
if (!modify_strings_)
{
(ostream&) *this << str;
}
else if (quoting_ != String::NONE)
{
(ostream&) *this << str.quote('"', quoting_);
}
else
{
(ostream&) *this << str.substitute(sep_, replacement_);
}
return *this;
}
SVOutStream& SVOutStream::operator<<(const char* c_str)
{
return operator<<(String(c_str));
}
SVOutStream& SVOutStream::operator<<(const char c)
{
return operator<<(String(c));
}
SVOutStream& SVOutStream::operator<<(const std::string& str)
{
return operator<<((String&)str);
}
SVOutStream& SVOutStream::operator<<(ostream& (*fp)(ostream&))
{
// check for "std::endl":
// this doesn't work in LLVM/clang's libc++ (used on Mac OS X 10.9):
// ostream& (*const endlPointer)(ostream&) = &endl;
// if (fp == endlPointer) newline_ = true;
fp(ss_);
if (ss_.str() == "\n")
{
newline_ = true;
ss_.str("");
}
(ostream&) *this << fp;
return *this;
}
SVOutStream& SVOutStream::operator<<(enum Newline)
{
newline_ = true;
(ostream&) *this << "\n";
return *this;
}
SVOutStream& SVOutStream::write(const String& str)
{
ostream::write(str.c_str(), str.size());
return *this;
}
bool SVOutStream::modifyStrings(bool modify)
{
bool old = modify_strings_;
modify_strings_ = modify;
return old;
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/MascotGenericFile.cpp | .cpp | 18,445 | 469 | // 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/FileHandler.h>
#include <OpenMS/CHEMISTRY/ModificationsDB.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/FORMAT/MascotGenericFile.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/METADATA/Precursor.h>
#include <OpenMS/METADATA/SpectrumSettings.h>
#include <OpenMS/METADATA/SourceFile.h>
#include <OpenMS/METADATA/SpectrumLookup.h>
#include <QtCore/QFileInfo>
#include <QtCore/QRegularExpression>
#include <iomanip> // setw
#define HIGH_PRECISION 5
#define LOW_PRECISION 3
using namespace std;
namespace OpenMS
{
MascotGenericFile::MascotGenericFile() :
ProgressLogger(), DefaultParamHandler("MascotGenericFile"), mod_group_map_()
{
defaults_.setValue("database", "MSDB", "Name of the sequence database");
defaults_.setValue("search_type", "MIS", "Name of the search type for the query", {"advanced"});
defaults_.setValidStrings("search_type", {"MIS","SQ","PMF"});
defaults_.setValue("enzyme", "Trypsin", "The enzyme descriptor to the enzyme used for digestion. (Trypsin is default, None would be best for peptide input or unspecific digestion, for more please refer to your mascot server).");
defaults_.setValue("instrument", "Default", "Instrument definition which specifies the fragmentation rules");
defaults_.setValue("missed_cleavages", 1, "Number of missed cleavages allowed for the enzyme");
defaults_.setMinInt("missed_cleavages", 0);
defaults_.setValue("precursor_mass_tolerance", 3.0, "Tolerance of the precursor peaks");
defaults_.setMinFloat("precursor_mass_tolerance", 0.0);
defaults_.setValue("precursor_error_units", "Da", "Units of the precursor mass tolerance");
defaults_.setValidStrings("precursor_error_units", {"%","ppm","mmu","Da"});
defaults_.setValue("fragment_mass_tolerance", 0.3, "Tolerance of the peaks in the fragment spectrum");
defaults_.setMinFloat("fragment_mass_tolerance", 0.0);
defaults_.setValue("fragment_error_units", "Da", "Units of the fragment peaks tolerance");
defaults_.setValidStrings("fragment_error_units", {"mmu","Da"});
defaults_.setValue("charges", "1,2,3", "Charge states to consider, given as a comma separated list of integers (only used for spectra without precursor charge information)");
defaults_.setValue("taxonomy", "All entries", "Taxonomy specification of the sequences");
vector<String> all_mods;
ModificationsDB::getInstance()->getAllSearchModifications(all_mods);
defaults_.setValue("fixed_modifications", std::vector<std::string>(), "List of fixed modifications, according to UniMod definitions.");
defaults_.setValidStrings("fixed_modifications", ListUtils::create<std::string>(all_mods));
defaults_.setValue("variable_modifications", std::vector<std::string>(), "Variable modifications given as UniMod definitions.");
defaults_.setValidStrings("variable_modifications", ListUtils::create<std::string>(all_mods));
// special modifications, see "updateMembers_" method below:
defaults_.setValue("special_modifications", "Cation:Na (DE),Deamidated (NQ),Oxidation (HW),Phospho (ST),Sulfo (ST)", "Modifications with specificity groups that are used by Mascot and have to be treated specially", {"advanced"});
// list from Mascot 2.4; there's also "Phospho (STY)", but that can be
// represented using "Phospho (ST)" and "Phospho (Y)"
defaults_.setValue("mass_type", "monoisotopic", "Defines the mass type, either monoisotopic or average");
defaults_.setValidStrings("mass_type", {"monoisotopic","average"});
defaults_.setValue("number_of_hits", 0, "Number of hits which should be returned, if 0 AUTO mode is enabled.");
defaults_.setMinInt("number_of_hits", 0);
defaults_.setValue("skip_spectrum_charges", "false", "Sometimes precursor charges are given for each spectrum but are wrong, setting this to 'true' does not write any charge information to the spectrum, the general charge information is however kept.");
defaults_.setValidStrings("skip_spectrum_charges", {"true","false"});
defaults_.setValue("decoy", "false", "Set to true if mascot should generate the decoy database.");
defaults_.setValidStrings("decoy", {"true","false"});
defaults_.setValue("search_title", "OpenMS_search", "Sets the title of the search.", {"advanced"});
defaults_.setValue("username", "OpenMS", "Sets the username which is mentioned in the results file.", {"advanced"});
defaults_.setValue("email", "", "Sets the email which is mentioned in the results file. Note: Some server require that a proper email is provided.");
// the next section should not be shown to TOPP users
Param p;
p.setValue("format", "Mascot generic", "Sets the format type of the peak list, this should not be changed unless you write the header only.", {"advanced"});
p.setValidStrings("format", {"Mascot generic","mzData (.XML)","mzML (.mzML)"}); // Mascot's HTTP interface supports more, but we don't :)
p.setValue("boundary", "GZWgAaYKjHFeUaLOLEIOMq", "MIME boundary for parameter header (if using HTTP format)", {"advanced"});
p.setValue("HTTP_format", "false", "Write header with MIME boundaries instead of simple key-value pairs. For HTTP submission only.", {"advanced"});
p.setValidStrings("HTTP_format", {"true","false"});
p.setValue("content", "all", "Use parameter header + the peak lists with BEGIN IONS... or only one of them.", {"advanced"});
p.setValidStrings("content", {"all","peaklist_only","header_only"});
defaults_.insert("internal:", p);
defaultsToParam_();
}
MascotGenericFile::~MascotGenericFile() = default;
void MascotGenericFile::updateMembers_()
{
// special cases for specificity groups: OpenMS uses e.g. "Deamidated (N)"
// and "Deamidated (Q)", but Mascot only understands "Deamidated (NQ)"
String special_mods = param_.getValue("special_modifications").toString();
vector<String> mod_groups = ListUtils::create<String>(special_mods);
for (StringList::const_iterator mod_it = mod_groups.begin();
mod_it != mod_groups.end(); ++mod_it)
{
String mod = mod_it->prefix(' ');
String residues = mod_it->suffix('(').prefix(')');
for (String::const_iterator res_it = residues.begin();
res_it != residues.end(); ++res_it)
{
mod_group_map_[mod + " (" + String(*res_it) + ")"] = *mod_it;
}
}
}
void MascotGenericFile::store(const String& filename, const PeakMap& experiment, bool compact)
{
if (!FileHandler::hasValidExtension(filename, FileTypes::MGF))
{
throw Exception::UnableToCreateFile(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename, "invalid file extension, expected '" + FileTypes::typeToName(FileTypes::MGF) + "'");
}
if (!File::writable(filename))
{
throw Exception::FileNotWritable(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename);
}
ofstream os(filename.c_str());
store(os, filename, experiment, compact);
os.close();
}
void MascotGenericFile::store(ostream& os, const String& filename, const PeakMap& experiment, bool compact)
{
// stream formatting may get changed, so back up:
const ios_base::fmtflags old_flags = os.flags();
const streamsize old_precision = os.precision();
store_compact_ = compact;
if (param_.getValue("internal:content") != "peaklist_only")
writeHeader_(os);
if (param_.getValue("internal:content") != "header_only")
writeMSExperiment_(os, filename, experiment);
// reset formatting:
os.flags(old_flags);
os.precision(old_precision);
}
void MascotGenericFile::writeParameterHeader_(const String& name, ostream& os)
{
if (param_.getValue("internal:HTTP_format") == "true")
{
os << "--" << param_.getValue("internal:boundary") << "\n" << "Content-Disposition: form-data; name=\"" << name << "\"" << "\n\n";
}
else
{
os << name << "=";
}
}
void MascotGenericFile::writeModifications_(const vector<String>& mods,
ostream& os, bool variable_mods)
{
String tag = variable_mods ? "IT_MODS" : "MODS";
// @TODO: remove handling of special cases when a general solution for
// specificity groups in UniMod is implemented (ticket #387)
set<String> filtered_mods;
for (StringList::const_iterator it = mods.begin(); it != mods.end(); ++it)
{
map<String, String>::iterator pos = mod_group_map_.find(*it);
if (pos == mod_group_map_.end())
{
filtered_mods.insert(*it);
}
else
{
filtered_mods.insert(pos->second);
}
}
for (set<String>::const_iterator it = filtered_mods.begin();
it != filtered_mods.end(); ++it)
{
writeParameterHeader_(tag, os);
os << *it << "\n";
}
}
void MascotGenericFile::writeHeader_(ostream& os)
{
// search title
if (param_.getValue("search_title") != "")
{
writeParameterHeader_("COM", os);
os << param_.getValue("search_title") << "\n";
}
// user name
writeParameterHeader_("USERNAME", os);
os << param_.getValue("username") << "\n";
// email
if (!param_.getValue("email").toString().empty())
{
writeParameterHeader_("USEREMAIL", os);
os << param_.getValue("email") << "\n";
}
// format
writeParameterHeader_("FORMAT", os); // make sure this stays within the first 5 lines of the file, since we use it to recognize our own MGF files in case their file suffix is not MGF
os << param_.getValue("internal:format") << "\n";
// precursor mass tolerance unit : Da
writeParameterHeader_("TOLU", os);
os << param_.getValue("precursor_error_units") << "\n";
// ion mass tolerance unit : Da
writeParameterHeader_("ITOLU", os);
os << param_.getValue("fragment_error_units") << "\n";
// format version
writeParameterHeader_("FORMVER", os);
os << "1.01" << "\n";
// db name
writeParameterHeader_("DB", os);
os << param_.getValue("database") << "\n";
// decoys
if (param_.getValue("decoy").toBool() == true)
{
writeParameterHeader_("DECOY", os);
os << 1 << "\n";
}
// search type
writeParameterHeader_("SEARCH", os);
os << param_.getValue("search_type") << "\n";
// number of peptide candidates in the list
writeParameterHeader_("REPORT", os);
UInt num_hits((UInt)param_.getValue("number_of_hits"));
if (num_hits != 0)
{
os << param_.getValue("number_of_hits") << "\n";
}
else
{
os << "AUTO" << "\n";
}
// cleavage enzyme
writeParameterHeader_("CLE", os);
os << param_.getValue("enzyme") << "\n";
// average/monoisotopic
writeParameterHeader_("MASS", os);
os << param_.getValue("mass_type") << "\n";
// fixed modifications
StringList fixed_mods = ListUtils::toStringList<std::string>(param_.getValue("fixed_modifications"));
writeModifications_(fixed_mods, os);
// variable modifications
StringList var_mods = ListUtils::toStringList<std::string>(param_.getValue("variable_modifications"));
writeModifications_(var_mods, os, true);
// instrument
writeParameterHeader_("INSTRUMENT", os);
os << param_.getValue("instrument") << "\n";
// missed cleavages
writeParameterHeader_("PFA", os);
os << param_.getValue("missed_cleavages") << "\n";
// precursor mass tolerance
writeParameterHeader_("TOL", os);
os << param_.getValue("precursor_mass_tolerance") << "\n";
// ion mass tolerance_
writeParameterHeader_("ITOL", os);
os << param_.getValue("fragment_mass_tolerance") << "\n";
// taxonomy
writeParameterHeader_("TAXONOMY", os);
os << param_.getValue("taxonomy") << "\n";
// charge
writeParameterHeader_("CHARGE", os);
os << param_.getValue("charges") << "\n";
}
void MascotGenericFile::writeSpectrum(ostream& os, const PeakSpectrum& spec, const String& filename, const String& native_id_type_accession)
{
Precursor precursor;
if (!spec.getPrecursors().empty())
{
precursor = spec.getPrecursors()[0];
}
if (spec.getPrecursors().size() > 1)
{
cerr << "Warning: The spectrum written to Mascot file has more than one precursor. The first precursor is used!\n";
}
if (spec.size() >= 10000)
{
String msg = "Spectrum to be written as MGF has " + String(spec.size()) +
" peaks; the upper limit is 10,000. Only centroided data is allowed - this is most likely profile data.";
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
msg);
}
double mz(precursor.getMZ()), rt(spec.getRT());
if (mz == 0)
{
// retention time
cout << "No precursor m/z information for spectrum with rt " << rt
<< " present, skipping spectrum!\n";
}
else
{
os << "\n";
os << "BEGIN IONS\n";
if (!store_compact_)
{
// if a TITLE is available, it was (most likely) parsed from an MGF
// or generated to be written out in an MGF
if (spec.metaValueExists("TITLE"))
{
os << "TITLE=" << spec.getMetaValue("TITLE") << "\n";
}
else
{
os << "TITLE=" << precisionWrapper(mz) << "_" << precisionWrapper(rt)
<< "_" << spec.getNativeID() << "_" << filename << "\n";
}
os << "PEPMASS=" << precisionWrapper(mz) << "\n";
os << "RTINSECONDS=" << precisionWrapper(rt) << "\n";
if (native_id_type_accession == "UNKNOWN")
{
os << "SCANS=" << spec.getNativeID().substr(spec.getNativeID().find_last_of("=")+1) << "\n";
}
else
{
os << "SCANS=" << SpectrumLookup::extractScanNumber(spec.getNativeID(), native_id_type_accession) << "\n";
}
}
else
{
// if a TITLE is available, it was (most likely) parsed from an MGF
// or generated to be written out in an MGF
if (spec.metaValueExists("TITLE"))
{
os << "TITLE=" << spec.getMetaValue("TITLE") << "\n";
}
else
{
os << "TITLE=" << fixed << setprecision(HIGH_PRECISION) << mz << "_"
<< setprecision(LOW_PRECISION) << rt << "_"
<< spec.getNativeID() << "_" << filename << "\n";
}
os << "PEPMASS=" << setprecision(HIGH_PRECISION) << mz << "\n";
os << "RTINSECONDS=" << setprecision(LOW_PRECISION) << rt << "\n";
if (native_id_type_accession == "UNKNOWN")
{
os << "SCANS=" << spec.getNativeID().substr(spec.getNativeID().find_last_of("=")+1) << "\n";
}
else
{
os << "SCANS=" << SpectrumLookup::extractScanNumber(spec.getNativeID(), native_id_type_accession) << "\n";
}
}
int charge(precursor.getCharge());
if (charge != 0)
{
bool skip_spectrum_charges(param_.getValue("skip_spectrum_charges").toBool());
if (!skip_spectrum_charges)
{
String cs = charge < 0 ? "-" : "+";
os << "CHARGE=" << charge << cs << "\n";
}
}
if (!store_compact_)
{
for (PeakSpectrum::const_iterator it = spec.begin(); it != spec.end(); ++it)
{
os << precisionWrapper(it->getMZ()) << " "
<< precisionWrapper(it->getIntensity()) << "\n";
}
}
else
{
for (PeakSpectrum::const_iterator it = spec.begin(); it != spec.end(); ++it)
{
PeakSpectrum::PeakType::IntensityType intensity = it->getIntensity();
if (intensity == 0.0)
{
continue; // skip zero-intensity peaks
}
os << fixed << setprecision(HIGH_PRECISION) << it->getMZ() << " "
<< setprecision(LOW_PRECISION) << intensity << "\n";
}
}
os << "END IONS\n";
}
}
std::pair<String, String> MascotGenericFile::getHTTPPeakListEnclosure(const String& filename) const
{
std::pair<String, String> r;
r.first = String("--" + (std::string)param_.getValue("internal:boundary") + "\n" + R"(Content-Disposition: form-data; name="FILE"; filename=")" + filename + "\"\n\n");
r.second = String("\n\n--" + (std::string)param_.getValue("internal:boundary") + "--\n");
return r;
}
void MascotGenericFile::writeMSExperiment_(ostream& os, const String& filename, const PeakMap& experiment)
{
std::pair<String, String> enc = getHTTPPeakListEnclosure(filename);
if (param_.getValue("internal:HTTP_format").toBool())
{
os << enc.first;
}
QFileInfo fileinfo(filename.c_str());
QString filtered_filename = fileinfo.completeBaseName();
filtered_filename.remove(QRegularExpression("[^a-zA-Z0-9]"));
String native_id_type_accession;
const vector<SourceFile>& sourcefiles = experiment.getSourceFiles();
if (sourcefiles.empty())
{
OPENMS_LOG_WARN << "MascotGenericFile: no native ID accession." << endl;
native_id_type_accession = "UNKNOWN";
}
else
{
native_id_type_accession = experiment.getSourceFiles()[0].getNativeIDTypeAccession();
if (native_id_type_accession.empty())
{
OPENMS_LOG_WARN << "MascotGenericFile: empty native ID accession." << endl;
native_id_type_accession = "UNKNOWN";
}
}
this->startProgress(0, experiment.size(), "storing mascot generic file");
for (Size i = 0; i < experiment.size(); i++)
{
this->setProgress(i);
if (experiment[i].getMSLevel() == 2)
{
writeSpectrum(os, experiment[i], filtered_filename, native_id_type_accession);
}
else if (experiment[i].getMSLevel() == 0)
{
OPENMS_LOG_WARN << "MascotGenericFile: MSLevel is set to 0, ignoring this spectrum!" << "\n";
}
}
// close file
if (param_.getValue("internal:HTTP_format").toBool())
{
os << enc.second;
}
this->endProgress();
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/IBSpectraFile.cpp | .cpp | 10,633 | 291 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Stephan Aiche $
// --------------------------------------------------------------------------
#include <OpenMS/FORMAT/IBSpectraFile.h>
#include <OpenMS/KERNEL/ConsensusMap.h>
#include <OpenMS/METADATA/ProteinIdentification.h>
#include <OpenMS/METADATA/PeptideIdentification.h>
// we need the quantitation types to extract the appropriate channels
#include <OpenMS/ANALYSIS/QUANTITATION/IsobaricQuantitationMethod.h>
#include <OpenMS/ANALYSIS/QUANTITATION/ItraqFourPlexQuantitationMethod.h>
#include <OpenMS/ANALYSIS/QUANTITATION/ItraqEightPlexQuantitationMethod.h>
#include <OpenMS/ANALYSIS/QUANTITATION/TMTSixPlexQuantitationMethod.h>
// we use the TextFile for writing out the content
#include <OpenMS/FORMAT/TextFile.h>
namespace OpenMS
{
// local class to hold quantitation information
/**
@brief Holds all id information contained in a id csv line
*/
struct IdCSV
{
String accession; // Protein AC
String peptide; // Peptide sequence
String modif; // Peptide modification string
Int charge{0}; // Charge state
double theo_mass{-1.}; // Theoretical peptide mass
double exp_mass{-1.}; // Experimentally observed mass
double parent_intens{-1.}; // Parent intensity
double retention_time{-1.}; // Retention time
String spectrum; // Spectrum identifier
String search_engine; // Protein search engine and score
void toStringList(StringList& target_list) const
{
target_list.push_back(accession);
target_list.push_back(peptide);
target_list.push_back(modif);
target_list.push_back(charge);
target_list.push_back(theo_mass);
target_list.push_back(exp_mass);
target_list.push_back(parent_intens);
target_list.push_back(retention_time);
target_list.push_back(spectrum);
target_list.push_back(search_engine);
}
IdCSV() :
accession("UNIDENTIFIED_PROTEIN"),
peptide("UNIDENTIFIED_PEPTIDE"),
modif(""),
spectrum(""),
search_engine("open-ms-generic")
{}
};
IBSpectraFile::IBSpectraFile() = default;
IBSpectraFile::IBSpectraFile(const IBSpectraFile& /* other */)
{
// no members
}
IBSpectraFile& IBSpectraFile::operator=(const IBSpectraFile& /* rhs */) = default;
std::shared_ptr<IsobaricQuantitationMethod> IBSpectraFile::guessExperimentType_(const ConsensusMap& cm)
{
if (cm.getExperimentType() != "labeled_MS2" && cm.getExperimentType() != "itraq")
{
throw Exception::InvalidParameter(__FILE__,
__LINE__,
OPENMS_PRETTY_FUNCTION,
"Given ConsensusMap does not hold any isobaric quantification data.");
}
// we take the map count as approximation
if (cm.getColumnHeaders().size() == 4)
{
return std::shared_ptr<IsobaricQuantitationMethod>(new ItraqFourPlexQuantitationMethod);
}
else if (cm.getColumnHeaders().size() == 6)
{
return std::shared_ptr<IsobaricQuantitationMethod>(new TMTSixPlexQuantitationMethod);
}
else if (cm.getColumnHeaders().size() == 8)
{
return std::shared_ptr<IsobaricQuantitationMethod>(new ItraqEightPlexQuantitationMethod);
}
else
{
throw Exception::InvalidParameter(__FILE__,
__LINE__,
OPENMS_PRETTY_FUNCTION,
"Could not guess isobaric quantification data from ConsensusMap due to non-matching number of input maps.");
}
}
StringList IBSpectraFile::constructHeader_(const IsobaricQuantitationMethod& quantMethod)
{
// construct tsv file header
StringList header;
header.push_back("accession"); // Protein AC
header.push_back("peptide"); // Peptide sequence
header.push_back("modif"); // Peptide modification string
header.push_back("charge"); // Charge state
header.push_back("theo.mass"); // Theoretical peptide mass
header.push_back("exp.mass"); // Experimentally observed mass
header.push_back("parent.intens"); // Parent intensity
header.push_back("retention.time"); // Retention time
header.push_back("spectrum"); // Spectrum identifier
header.push_back("search.engine"); // Protein search engine and score
for (IsobaricQuantitationMethod::IsobaricChannelList::const_iterator it = quantMethod.getChannelInformation().begin();
it != quantMethod.getChannelInformation().end();
++it)
{
header.push_back("X" + String(int(it->center)) + "_mass");
}
for (IsobaricQuantitationMethod::IsobaricChannelList::const_iterator it = quantMethod.getChannelInformation().begin();
it != quantMethod.getChannelInformation().end();
++it)
{
header.push_back("X" + String(int(it->center)) + "_ions");
}
return header;
}
String IBSpectraFile::getModifString_(const AASequence& sequence)
{
String modif = sequence.getNTerminalModificationName();
for (AASequence::ConstIterator aa_it = sequence.begin();
aa_it != sequence.end(); ++aa_it)
{
modif += ":" + aa_it->getModificationName();
}
if (!sequence.getCTerminalModificationName().empty())
{
modif += ":" + sequence.getCTerminalModificationName();
}
return modif;
}
void IBSpectraFile::store(const String& filename, const ConsensusMap& cm)
{
// typdefs for shorter code
typedef std::vector<ProteinHit>::iterator ProtHitIt;
// general settings .. do we need to expose these?
// ----------------------------------------------------------------------
/// Allow also non-unique peptides to be exported
bool allow_non_unique = true;
/// Intensities below this value will be set to 0.0 to avoid numerical problems when quantifying
double intensity_threshold = 0.00001;
// ----------------------------------------------------------------------
// guess experiment type
std::shared_ptr<IsobaricQuantitationMethod> quantMethod = guessExperimentType_(cm);
// we need the protein identifications to reference the protein names
ProteinIdentification protIdent;
bool has_proteinIdentifications = false;
if (!cm.getProteinIdentifications().empty())
{
protIdent = cm.getProteinIdentifications()[0];
has_proteinIdentifications = true;
}
// start the file by adding the tsv header
TextFile textFile;
textFile.addLine(ListUtils::concatenate(constructHeader_(*quantMethod), "\t"));
for (ConsensusMap::ConstIterator cm_iter = cm.begin();
cm_iter != cm.end();
++cm_iter)
{
const ConsensusFeature& cFeature = *cm_iter;
std::vector<IdCSV> entries;
/// 1st we extract the identification information from the consensus feature
if (cFeature.getPeptideIdentifications().empty() || !has_proteinIdentifications)
{
// we store unidentified hits anyway, because the iTRAQ quant is still helpful for normalization
entries.emplace_back();
}
else
{
// protein name:
const PeptideHit& peptide_hit = cFeature.getPeptideIdentifications()[0].getHits()[0];
std::set<String> protein_accessions = peptide_hit.extractProteinAccessionsSet();
if (protein_accessions.size() != 1)
{
if (!allow_non_unique) continue; // we only want unique peptides
}
for (std::set<String>::const_iterator prot_ac = protein_accessions.begin(); prot_ac != protein_accessions.end(); ++prot_ac)
{
IdCSV entry;
entry.charge = cFeature.getPeptideIdentifications()[0].getHits()[0].getCharge();
entry.peptide = cFeature.getPeptideIdentifications()[0].getHits()[0].getSequence().toUnmodifiedString();
entry.theo_mass = cFeature.getPeptideIdentifications()[0].getHits()[0].getSequence().getMonoWeight(Residue::Full, cFeature.getPeptideIdentifications()[0].getHits()[0].getCharge());
// write modif
entry.modif = getModifString_(cFeature.getPeptideIdentifications()[0].getHits()[0].getSequence());
ProtHitIt proteinHit = protIdent.findHit(*prot_ac);
if (proteinHit == protIdent.getHits().end())
{
std::cerr << "Protein referenced in peptide not found...\n";
continue; // protein not found
}
entry.accession = proteinHit->getAccession();
entries.push_back(entry);
}
}
// 2nd we add the quantitative information of the channels
// .. skip features with 0 intensity
if (cFeature.getIntensity() == 0)
{
continue;
}
for (std::vector<IdCSV>::iterator entry = entries.begin();
entry != entries.end();
++entry)
{
// set parent intensity
entry->parent_intens = cFeature.getIntensity();
entry->retention_time = cFeature.getRT();
entry->spectrum = cFeature.getUniqueId();
entry->exp_mass = cFeature.getMZ();
// create output line
StringList currentLine;
// add entry to currentLine
entry->toStringList(currentLine);
// extract channel intensities and positions
std::map<Int, double> intensityMap;
ConsensusFeature::HandleSetType features = cFeature.getFeatures();
for (ConsensusFeature::HandleSetType::const_iterator fIt = features.begin();
fIt != features.end();
++fIt)
{
intensityMap[Int(fIt->getMZ())] = (fIt->getIntensity() > intensity_threshold ? fIt->getIntensity() : 0.0);
}
for (IsobaricQuantitationMethod::IsobaricChannelList::const_iterator it = quantMethod->getChannelInformation().begin();
it != quantMethod->getChannelInformation().end();
++it)
{
currentLine.push_back(String(it->center));
}
for (IsobaricQuantitationMethod::IsobaricChannelList::const_iterator it = quantMethod->getChannelInformation().begin();
it != quantMethod->getChannelInformation().end();
++it)
{
currentLine.push_back(String(intensityMap[int(it->center)]));
}
textFile.addLine(ListUtils::concatenate(currentLine, "\t"));
}
}
// write to file
textFile.store(filename);
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/Bzip2Ifstream.cpp | .cpp | 3,575 | 133 | // 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 <iostream>
#include <OpenMS/FORMAT/Bzip2Ifstream.h>
#include <OpenMS/CONCEPT/Exception.h>
#include <OpenMS/SYSTEM/File.h>
#include <cstdlib>
using namespace std;
namespace OpenMS
{
Bzip2Ifstream::Bzip2Ifstream(const char * filename) :
n_buffer_(0), stream_at_end_(false)
{
file_ = fopen(filename, "rb"); //read binary: always open in binary mode because windows and mac open in text mode
//aborting, ahhh!
if (!file_)
{
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);
}
}
bzip2file_ = BZ2_bzReadOpen(&bzerror_, file_, 0, 0, nullptr, 0);
if (bzerror_ != BZ_OK)
{
close();
throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "bzip2 compression failed: ");
}
}
Bzip2Ifstream::Bzip2Ifstream() :
file_(nullptr), bzip2file_(nullptr), n_buffer_(0), bzerror_(0), stream_at_end_(true)
{
}
Bzip2Ifstream::~Bzip2Ifstream()
{
close();
}
size_t Bzip2Ifstream::read(char * s, size_t n)
{
if (bzip2file_ != nullptr)
{
bzerror_ = BZ_OK;
n_buffer_ = BZ2_bzRead(&bzerror_, bzip2file_, s, (unsigned int)n /* size of buf */);
if (bzerror_ == BZ_OK)
{
return n_buffer_;
}
else if (bzerror_ != BZ_STREAM_END)
{
close();
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, " ", "bzip2 compression failed: ");
}
else
{
close();
return n_buffer_;
}
}
else
{
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "no file for decompression initialized");
}
}
void Bzip2Ifstream::open(const char * filename)
{
close();
file_ = fopen(filename, "rb"); //read binary: always open in binary mode because windows and mac open in text mode
//aborting, ahhh!
if (!file_)
{
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);
}
}
bzip2file_ = BZ2_bzReadOpen(&bzerror_, file_, 0, 0, nullptr, 0);
if (bzerror_ != BZ_OK)
{
close();
throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "bzip2 compression failed: ");
}
stream_at_end_ = false;
}
void Bzip2Ifstream::close()
{
if (bzip2file_ != nullptr)
{
BZ2_bzReadClose(&bzerror_, bzip2file_);
}
if (file_ != nullptr)
{
fclose(file_);
}
file_ = nullptr;
bzip2file_ = nullptr;
stream_at_end_ = true;
}
} //namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/MascotRemoteQuery.cpp | .cpp | 32,417 | 825 | // 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, Daniel Jameson, Chris Bielow, Timo Sachsenberg $
// --------------------------------------------------------------------------
#include <OpenMS/FORMAT/MascotRemoteQuery.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <QtGui/QTextDocument>
#include <QtNetwork/QNetworkReply>
#include <QtNetwork/QNetworkProxy>
#include <QtNetwork/QSslSocket>
#include <QRegularExpression>
// #define MASCOTREMOTEQUERY_DEBUG
// #define MASCOTREMOTEQUERY_DEBUG_FULL_QUERY
using namespace std;
namespace OpenMS
{
MascotRemoteQuery::MascotRemoteQuery(QObject* parent) :
QObject(parent),
DefaultParamHandler("MascotRemoteQuery"),
manager_(nullptr)
{
// server specifications
defaults_.setValue("hostname", "", "Address of the host where Mascot listens, e.g. 'mascot-server' or '127.0.0.1'");
defaults_.setValue("host_port", 80, "Port where the Mascot server listens, 80 should be a good guess");
defaults_.setMinInt("host_port", 0);
defaults_.setValue("server_path", "mascot", "Path on the server where Mascot server listens, 'mascot' should be a good guess");
defaults_.setValue("timeout", 1500, "Timeout in seconds, after which the query is declared as failed."
"This is NOT the whole time the search takes, but the time in between two progress steps. Some Mascot servers freeze during this (unstable network etc) and idle forever"
", the connection is killed. Set this to 0 to disable timeout!");
defaults_.setMinInt("timeout", 0);
defaults_.setValue("boundary", "GZWgAaYKjHFeUaLOLEIOMq", "Boundary for the MIME section", {"advanced"});
// proxy settings
defaults_.setValue("use_proxy", "false", "Flag which enables the proxy usage for the HTTP requests, please specify at least 'proxy_host' and 'proxy_port'", {"advanced"});
defaults_.setValidStrings("use_proxy", {"true","false"});
defaults_.setValue("proxy_host", "", "Host where the proxy server runs on", {"advanced"});
defaults_.setValue("proxy_port", 0, "Port where the proxy server listens", {"advanced"});
defaults_.setMinInt("proxy_port", 0);
defaults_.setValue("proxy_username", "", "Login name for the proxy server, if needed", {"advanced"});
defaults_.setValue("proxy_password", "", "Login password for the proxy server, if needed", {"advanced"});
// login for Mascot security
defaults_.setValue("login", "false", "Flag which should be set 'true' if Mascot security is enabled; also set 'username' and 'password' then.");
defaults_.setValidStrings("login", {"true","false"});
defaults_.setValue("username", "", "Name of the user if login is used (Mascot security must be enabled!)");
defaults_.setValue("password", "", "Password of the user if login is used (Mascot security must be enabled!)");
defaults_.setValue("use_ssl", "false", "Flag indicating whether you want to send requests to an HTTPS server or not (HTTP). Requires OpenSSL to be installed (see openssl.org)");
defaults_.setValidStrings("use_ssl", {"true","false"});
// Mascot export options
defaults_.setValue("export_params", "_ignoreionsscorebelow=0&_sigthreshold=0.99&_showsubsets=1&show_same_sets=1&report=0&percolate=0&query_master=0", "Adjustable export parameters (passed to Mascot's 'export_dat_2.pl' script). Generally only parameters that control which hits to export are safe to adjust/add. Many settings that govern what types of information to include are required by OpenMS and cannot be changed. Note that setting 'query_master' to 1 may lead to incorrect protein references for peptides.", {"advanced"});
defaults_.setValue("skip_export", "false", "For use with an external Mascot Percolator (via GenericWrapper): Run the Mascot search, but do not export the results. The output file produced by MascotAdapterOnline will contain only the Mascot search number.", {"advanced"});
defaults_.setValidStrings("skip_export", {"true","false"});
defaults_.setValue("batch_size", 50000, "Number of spectra processed in one batch by Mascot (default 50000)", {"advanced"});
defaults_.setMinInt("batch_size", 0);
defaultsToParam_();
}
MascotRemoteQuery::~MascotRemoteQuery()
{
#ifdef MASCOTREMOTEQUERY_DEBUG
std::cerr << "MascotRemoteQuery::~MascotRemoteQuery()\n";
#endif
if (manager_) {delete manager_;}
}
void MascotRemoteQuery::timedOut() const
{
OPENMS_LOG_FATAL_ERROR << "Mascot request timed out after " << to_ << " seconds! See 'timeout' parameter for details!" << std::endl;
}
void MascotRemoteQuery::run()
{
// Due to the asynchronous nature of Qt network requests (and the resulting use
// of signals and slots), the information flow in this class is not very
// clear. After the initial call to "run", the steps are roughly as follows:
//
// 1. optional: log into Mascot server (function "login")
// 2. send query (function "execQuery")
// 3. read query result, prepare exporting (function "readResponse")
// 4. send export request (function "getResults")
// 5. Mascot 2.4: read result, check for redirect (function "readResponse")
// 6. Mascot 2.4: request redirected (caching) page (function "getResults")
// (5. and 6. can happen multiple times - keep following redirects)
// 7. Mascot 2.4: read result, check if caching is done (function "readResponse")
// 8. Mascot 2.4: request results again (function "getResults")
// 9. read results, which should now contain the XML (function "readResponse")
//
updateMembers_();
// Make sure we do not mess with the asynchronous nature of the call and
// start a second one while the first one is still running.
if (manager_)
{
throw OpenMS::Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Error: Please call run() only once per MascotRemoteQuery.");
}
manager_ = new QNetworkAccessManager(this);
if (!use_ssl_)
{
manager_->connectToHost(host_name_.c_str(), (UInt)param_.getValue("host_port"));
}
else
{
#ifndef QT_NO_SSL
manager_->connectToHostEncrypted(host_name_.c_str(), (UInt)param_.getValue("host_port"));
#else
// should not happen since it is checked during parameter reading. Kept for safety.
throw OpenMS::Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Error: Usage of SSL encryption requested but the linked QT library was not compiled with SSL support. Please recompile QT.");
#endif
}
connect(this, SIGNAL(gotRedirect(QNetworkReply *)), this, SLOT(followRedirect(QNetworkReply *)));
connect(&timeout_, SIGNAL(timeout()), this, SLOT(timedOut()));
connect(manager_, SIGNAL(finished(QNetworkReply*)), this, SLOT(readResponse(QNetworkReply*)));
if (param_.getValue("login").toBool())
{
login();
}
else
{
execQuery();
}
}
void MascotRemoteQuery::login()
{
#ifdef MASCOTREMOTEQUERY_DEBUG
cerr << "\nvoid MascotRemoteQuery::login()" << "\n";
#endif
QUrl url = buildUrl_(server_path_ + "/cgi/login.pl");
QNetworkRequest request(url);
QByteArray boundary = boundary_.toQString().toUtf8();
request.setHeader(QNetworkRequest::ContentTypeHeader, "multipart/form-data, boundary=" + boundary);
// header
request.setRawHeader("Host", host_name_.c_str());
request.setRawHeader("Cache-Control", "no-cache");
request.setRawHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
// content
QByteArray loginbytes;
QByteArray boundary_string("--" + boundary + "\r\n");
loginbytes.append(boundary_string);
loginbytes.append("Content-Disposition: ");
loginbytes.append("form-data; name=\"username\"\r\n");
loginbytes.append("\r\n");
loginbytes.append(String(param_.getValue("username").toString()).toQString().toUtf8());
loginbytes.append("\r\n");
loginbytes.append(boundary_string);
loginbytes.append("Content-Disposition: ");
loginbytes.append("form-data; name=\"password\"\r\n");
loginbytes.append("\r\n");
loginbytes.append(String(param_.getValue("password").toString()).toQString().toUtf8());
loginbytes.append("\r\n");
loginbytes.append(boundary_string);
loginbytes.append("Content-Disposition: ");
loginbytes.append("form-data; name=\"submit\"\r\n");
loginbytes.append("\r\n");
loginbytes.append("Login\r\n");
loginbytes.append(boundary_string);
loginbytes.append("Content-Disposition: ");
loginbytes.append("form-data; name=\"referer\"\r\n");
loginbytes.append("\r\n");
loginbytes.append("\r\n");
loginbytes.append(boundary_string);
loginbytes.append("Content-Disposition: ");
loginbytes.append("form-data; name=\"display\"\r\n");
loginbytes.append("\r\n");
loginbytes.append("nothing\r\n");
loginbytes.append(boundary_string);
loginbytes.append("Content-Disposition: ");
loginbytes.append("form-data; name=\"savecookie\"\r\n");
loginbytes.append("\r\n");
loginbytes.append("1\r\n");
loginbytes.append(boundary_string);
loginbytes.append("Content-Disposition: ");
loginbytes.append("form-data; name=\"action\"\r\n");
loginbytes.append("\r\n");
loginbytes.append("login\r\n");
loginbytes.append(boundary_string);
loginbytes.append("Content-Disposition: ");
loginbytes.append("form-data; name=\"userid\"\r\n");
loginbytes.append("\r\n");
loginbytes.append("\r\n");
loginbytes.append(boundary_string);
loginbytes.append("Content-Disposition: ");
loginbytes.append("form-data; name=\"onerrdisplay\"\r\n");
loginbytes.append("\r\n");
loginbytes.append("login_prompt\r\n");
loginbytes.append("--" + boundary + "--\r\n");
request.setHeader(QNetworkRequest::ContentLengthHeader, loginbytes.length());
QNetworkReply* pReply = manager_->post(request, loginbytes);
connect(pReply, SIGNAL(uploadProgress(qint64, qint64)), this, SLOT(uploadProgress(qint64, qint64)));
#ifdef MASCOTREMOTEQUERY_DEBUG
logHeader_(request, "send");
cerr << " login sent reply " << pReply << std::endl;
#endif
}
void MascotRemoteQuery::getResults(const QString& results_path)
{
// Tidy up again and run another request...
#ifdef MASCOTREMOTEQUERY_DEBUG
cerr << "\nvoid MascotRemoteQuery::getResults()" << "\n";
cerr << " from path " << results_path.toStdString() << "\n";
#endif
QUrl url = buildUrl_(results_path.toStdString());
QNetworkRequest request(url);
#ifdef MASCOTREMOTEQUERY_DEBUG
cerr << " server_path_ " << server_path_ << std::endl;
cerr << " URL : " << url.toDisplayString().toStdString() << std::endl;
#endif
// header
request.setRawHeader("Host", host_name_.c_str());
// request.setRawHeader("Host", String("http://www.chuchitisch.ch").c_str());
request.setRawHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
request.setRawHeader("Keep-Alive", "300");
request.setRawHeader("Connection", "keep-alive");
if (cookie_ != "")
{
request.setRawHeader(QByteArray::fromStdString("Cookie"), QByteArray::fromStdString(cookie_.toStdString()));
}
QNetworkReply* pReply = manager_->get(request);
connect(pReply, SIGNAL(uploadProgress(qint64, qint64)), this, SLOT(uploadProgress(qint64, qint64)));
#ifdef MASCOTREMOTEQUERY_DEBUG
logHeader_(request, "request results");
cerr << " getResults expects reply " << pReply << std::endl;
#endif
}
void MascotRemoteQuery::followRedirect(QNetworkReply * r)
{
#ifdef MASCOTREMOTEQUERY_DEBUG
cerr << "\nvoid MascotRemoteQuery::followRedirect(QNetworkReply *)" << "\n";
logHeader_(r, "follow redirect");
// print full response
#ifdef MASCOTREMOTEQUERY_DEBUG_FULL_QUERY
QByteArray new_bytes = r->readAll();
QString str = QString::fromUtf8(new_bytes.data(), new_bytes.size());
cerr << "Response of query: " << "\n";
cerr << "-----------------------------------" << "\n";
cerr << QString(new_bytes.constData()).toStdString() << "\n";
cerr << "-----------------------------------" << "\n";
cerr << str.toStdString() << "\n";
#endif
#endif
// parse the location mascot wants us to go
QString location = r->header(QNetworkRequest::LocationHeader).toString();
removeHostName_(location);
QUrl url = buildUrl_(location.toStdString());
QNetworkRequest request(url);
#ifdef MASCOTREMOTEQUERY_DEBUG
cerr << "Location: " << location.toStdString() << "\n";
#endif
// header
request.setRawHeader("Host", host_name_.c_str());
request.setRawHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
request.setRawHeader("Keep-Alive", "300");
request.setRawHeader("Connection", "keep-alive");
if (cookie_ != "")
{
request.setRawHeader(QByteArray::fromStdString("Cookie"), QByteArray::fromStdString(cookie_.toStdString()));
}
#ifdef MASCOTREMOTEQUERY_DEBUG
QNetworkReply* pReply = manager_->get(request);
logHeader_(request, "following redirect");
cerr << " followRedirect expects reply " << pReply << std::endl;
#else
manager_->get(request);
#endif
}
void MascotRemoteQuery::execQuery()
{
#ifdef MASCOTREMOTEQUERY_DEBUG
cerr << "\nvoid MascotRemoteQuery::execQuery()" << "\n";
#endif
QUrl url = buildUrl_(server_path_ + "/cgi/nph-mascot.exe?1");
#ifdef MASCOTREMOTEQUERY_DEBUG
cerr << " server_path_ " << server_path_ << std::endl;
cerr << " URL : " << url.toDisplayString().toStdString() << std::endl;
#endif
QNetworkRequest request(url);
QByteArray boundary = boundary_.toQString().toUtf8();
request.setHeader(QNetworkRequest::ContentTypeHeader, "multipart/form-data, boundary=" + boundary);
// header
request.setRawHeader("Host", host_name_.c_str());
request.setRawHeader("Cache-Control", "no-cache");
request.setRawHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
request.setRawHeader("Accept", "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*");
if (cookie_ != "")
{
request.setRawHeader(QByteArray::fromStdString("Cookie"), QByteArray::fromStdString(cookie_.toStdString()));
}
QByteArray querybytes;
querybytes.append("--" + boundary + "--\n");
querybytes.append("Content-Disposition: ");
querybytes.append("form-data; name=\"QUE\"\n");
querybytes.append("\n");
querybytes.append(query_spectra_.c_str());
querybytes.append("--" + boundary + "--\n");
querybytes.replace("\n", "\r\n");
#ifdef MASCOTREMOTEQUERY_DEBUG
logHeader_(request, "request");
#ifdef MASCOTREMOTEQUERY_DEBUG_FULL_QUERY
cerr << ">>>> Query (begin):" << "\n"
<< querybytes.constData() << "\n"
<< "<<<< Query (end)." << endl;
#endif
#endif
if (to_ > 0)
{
timeout_.start();
}
request.setHeader(QNetworkRequest::ContentLengthHeader, querybytes.length());
QNetworkReply* pReply = manager_->post(request, querybytes);
connect(pReply, SIGNAL(uploadProgress(qint64, qint64)), this, SLOT(uploadProgress(qint64, qint64)));
#ifdef MASCOTREMOTEQUERY_DEBUG
cerr << " execQuery expects reply " << pReply << std::endl;
#endif
}
#ifdef MASCOTREMOTEQUERY_DEBUG
void MascotRemoteQuery::downloadProgress(qint64 bytes_read, qint64 bytes_total)
#else
void MascotRemoteQuery::downloadProgress(qint64 /*bytes_read*/, qint64 /*bytes_total*/)
#endif
{
#ifdef MASCOTREMOTEQUERY_DEBUG
cerr << "void MascotRemoteQuery::downloadProgress(): " << bytes_read << " bytes of " << bytes_total << " read." << "\n";
/*
if (http_->state() == QHttp::Reading)
{
QByteArray new_bytes = http_->readAll();
cerr << "Current response: " << "\n";
cerr << QString(new_bytes.constData()).toStdString() << "\n";
}
*/
#endif
}
#ifdef MASCOTREMOTEQUERY_DEBUG
void MascotRemoteQuery::uploadProgress(qint64 bytes_read, qint64 bytes_total)
#else
void MascotRemoteQuery::uploadProgress(qint64 /* bytes_read */, qint64 /* bytes_total */)
#endif
{
#ifdef MASCOTREMOTEQUERY_DEBUG
cerr << "void MascotRemoteQuery::uploadProgress(): " << bytes_read << " bytes of " << bytes_total << " sent." << "\n";
#endif
}
void MascotRemoteQuery::readResponseHeader(const QNetworkReply* reply)
{
#ifdef MASCOTREMOTEQUERY_DEBUG
cerr << "void MascotRemoteQuery::readResponseHeader(const QNetworkReply* reply)" << "\n";
logHeader_(reply, "read");
#endif
int status = reply->attribute( QNetworkRequest::HttpStatusCodeAttribute ).toInt();
if (status >= 400)
{
error_message_ = String("MascotRemoteQuery: The server returned an error status code '") + status + "': " + reply->attribute( QNetworkRequest::HttpReasonPhraseAttribute ).toString() + "\nTry accessing the server\n " + host_name_ + server_path_ + "\n from your browser and check if it works fine.";
endRun_();
}
// Get session and username and so on...
if (reply->header(QNetworkRequest::SetCookieHeader).isValid())
{
// QVariant qcookie_ = reply->header(QNetworkRequest::SetCookieHeader);
QByteArray tmp = QByteArray::fromStdString(String("Set-Cookie"));
QString response = reply->rawHeader(tmp);
QRegularExpression rx("MASCOT_SESSION=(\\w+);\\spath");
QString mascot_session(rx.match(response).captured(1));
rx.setPattern("MASCOT_USERNAME=(\\w+);\\spath");
QString mascot_username(rx.match(response).captured(1));
rx.setPattern("MASCOT_USERID=(\\d+);\\spath");
QString mascot_user_ID(rx.match(response).captured(1));
//Put the cookie together...
cookie_ = "userName=; userEmail=; MASCOT_SESSION=";
cookie_.append(mascot_session);
cookie_.append("; MASCOT_USERNAME=");
cookie_.append(mascot_username);
cookie_.append("; MASCOT_USERID=");
cookie_.append(mascot_user_ID);
#ifdef MASCOTREMOTEQUERY_DEBUG
cerr << "Cookie created: " << cookie_.toStdString() << "\n";
cerr << "Cookie created from: " << response.toStdString() << "\n";
#endif
}
}
void MascotRemoteQuery::endRun_()
{
#ifdef MASCOTREMOTEQUERY_DEBUG
cerr << "void MascotRemoteQuery::endRun_()" << std::endl;
#endif
// for consumers of this class
emit done();
}
void MascotRemoteQuery::readResponse(QNetworkReply* reply)
{
static QString dat_file_path_;
#ifdef MASCOTREMOTEQUERY_DEBUG
cerr << "\nvoid MascotRemoteQuery::readResponse(const QNetworkReply* reply): ";
if (reply->error())
{
cerr << "'" << reply->errorString().toStdString() << "'" << "\n";
}
else
{
cerr << "\n";
}
cerr << " -- got query " << reply << endl;
#endif
readResponseHeader(reply); // first read and parse the header (also log)
timeout_.stop();
if (reply->error())
{
error_message_ = String("Mascot Server replied: '") + String(reply->errorString().toStdString()) + "'";
cerr << " ending run with " + String("Mascot Server replied: '") + String(reply->errorString().toStdString()) + "'\n";
endRun_();
return;
}
QByteArray new_bytes = reply->readAll();
#ifdef MASCOTREMOTEQUERY_DEBUG_FULL_QUERY
QString str = QString::fromUtf8(new_bytes.data(), new_bytes.size());
cerr << "Response of query: " << "\n";
cerr << "-----------------------------------" << "\n";
cerr << QString(new_bytes.constData()).toStdString() << "\n";
cerr << "-----------------------------------" << "\n";
cerr << str.toStdString() << "\n";
#endif
int status = reply->attribute( QNetworkRequest::HttpStatusCodeAttribute ).toInt();
#ifdef MASCOTREMOTEQUERY_DEBUG
cerr << "HTTP status: " << status << "\n";
cerr << "Response size: " << QString(new_bytes).trimmed().size() << "\n";
#endif
// Catch "ghost queries": strange responses that are completely empty and
// have a HTTP status of zero (and we never actually sent out)
if (QString(new_bytes).trimmed().size() == 0 && status == 0)
{
return;
}
if (QString(new_bytes).trimmed().size() == 0 && status != 303) // status != 303: no redirect
{
error_message_ = "Error: Reply from mascot server is empty! Possible server overload - see the Mascot Admin!";
endRun_();
return;
}
// Successful login? fire off the search
if (new_bytes.contains("Logged in successfu")) // Do not use the whole string. Currently Mascot writes 'successfully', but that might change...
{
OPENMS_LOG_INFO << "Login successful!" << std::endl;
execQuery();
}
else if (new_bytes.contains("Error: You have entered an invalid password"))
{
error_message_ = "Error: You have entered an invalid password";
endRun_();
}
else if (new_bytes.contains("is not a valid user"))
{
error_message_ = "Error: Username is not valid";
endRun_();
}
else if (new_bytes.contains("Click here to see Search Report"))
{
//Extract filename from this...
//e.g. data might look like
// <A HREF="../cgi/master_results.pl?file=../data/20100728/F018032.dat">Click here to see Search Report</A>
QString response(new_bytes);
QRegularExpression rx(R"(file=(.+/\d+/\w+\.dat))");
rx.setPatternOptions(QRegularExpression::InvertedGreedinessOption);
dat_file_path_ = rx.match(response).captured(1);
search_identifier_ = getSearchIdentifierFromFilePath(dat_file_path_);
if (param_.exists("skip_export") &&
(param_.getValue("skip_export") == "true"))
{
endRun_();
return;
}
QString results_path("");
results_path.append(server_path_.toQString());
results_path.append("/cgi/export_dat_2.pl?file=");
results_path.append(dat_file_path_);
#ifdef MASCOTREMOTEQUERY_DEBUG
cerr << "Results path to export: " << results_path.toStdString() << "\n";
#endif
// see http://www.matrixscience.com/help/export_help.html for parameter documentation
String required_params = "&do_export=1&export_format=XML&generate_file=1&group_family=1&peptide_master=1&protein_master=1&search_master=1&show_unassigned=1&show_mods=1&show_header=1&show_params=1&prot_score=1&pep_exp_z=1&pep_score=1&pep_seq=1&pep_homol=1&pep_ident=1&pep_expect=1&pep_var_mod=1&pep_scan_title=1&query_qualifiers=1&query_peaks=1&query_raw=1&query_title=1";
// TODO: check that export_params don't contain _show_decoy_report=1. This would add <decoy> at the top of the XML document and we can't easily distinguish the two files (target/decoy) from the search results later.
String adjustable_params = param_.getValue("export_params").toString();
results_path.append(required_params.toQString() + "&" +
adjustable_params.toQString());
// results_path.append("&show_same_sets=1&show_unassigned=1&show_queries=1&do_export=1&export_format=XML&pep_rank=1&_sigthreshold=0.99&_showsubsets=1&show_header=1&prot_score=1&pep_exp_z=1&pep_score=1&pep_seq=1&pep_homol=1&pep_ident=1&show_mods=1&pep_var_mod=1&protein_master=1&search_master=1&show_params=1&pep_scan_title=1&query_qualifiers=1&query_peaks=1&query_raw=1&query_title=1&pep_expect=1&peptide_master=1&generate_file=1&group_family=1");
// Finished search, fire off results retrieval
getResults(results_path);
}
else if (status == 303)
{
#ifdef MASCOTREMOTEQUERY_DEBUG
cerr << "Retrieved redirect \n";
#endif
emit gotRedirect(reply);
}
// mascot 2.4 export page done
else if (new_bytes.contains("Finished after") && new_bytes.contains("<a id=\"continuation-link\""))
{
// parsing mascot 2.4 continuation download link
// <p>Finished after 0 s. <a id="continuation-link" ..
QString response(new_bytes);
QRegularExpression rx("<a id=\"continuation-link\" href=\"(.*)\"");
rx.setPatternOptions(QRegularExpression::InvertedGreedinessOption);
QString results_path = rx.match(response).captured(1);
// fill result link again and download
removeHostName_(results_path);
//Finished search, fire off results retrieval
getResults(results_path);
}
else
{
// check whether Mascot responded using an error code e.g. [M00440], pipe through results else
QString response_text = new_bytes;
QRegularExpression mascot_error_regex(R"(\[M[0-9][0-9][0-9][0-9][0-9]\])");
QRegularExpressionMatch match;
if (response_text.contains(mascot_error_regex, &match))
{
OPENMS_LOG_ERROR << "Received response with Mascot error message!" << std::endl;
if (match.captured() == "[M00380]")
{
// we know this error, so we give a much shorter and readable error message for the user
error_message_ = "You must enter an email address and user name when using the Matrix Science public web site [M00380].";
OPENMS_LOG_ERROR << error_message_ << std::endl;
}
else
{
OPENMS_LOG_ERROR << "Error code: " << match.captured().toStdString() << std::endl;
error_message_ = response_text;
}
endRun_();
}
else
{
// seems to be fine so grab the xml
#ifdef MASCOTREMOTEQUERY_DEBUG
cerr << "Get the XML File" << "\n";
#endif
if (new_bytes.contains("<decoy>"))
{
mascot_decoy_xml_ = new_bytes;
endRun_();
}
else
{
mascot_xml_ = new_bytes;
// now retrieve decos
if (export_decoys_)
{
QString results_path("");
results_path.append(server_path_.toQString());
results_path.append("/cgi/export_dat_2.pl?file=");
results_path.append(dat_file_path_); // export again from dat file (now decoys)
// see http://www.matrixscience.com/help/export_help.html for parameter documentation
String required_params = "&do_export=1&export_format=XML&generate_file=1&group_family=1&peptide_master=1&protein_master=1&search_master=1&show_unassigned=1&show_mods=1&show_header=1&show_params=1&prot_score=1&pep_exp_z=1&pep_score=1&pep_seq=1&pep_homol=1&pep_ident=1&pep_expect=1&pep_var_mod=1&pep_scan_title=1&query_qualifiers=1&query_peaks=1&query_raw=1&query_title=1";
// TODO: check that export_params don't contain _show_decoy_report=1. This would add <decoy> at the top of the XML document and we can't easily distinguish the two files (target/decoy) from the search results later.
String adjustable_params = param_.getValue("export_params").toString();
results_path.append(required_params.toQString() + "&" +
adjustable_params.toQString() + "&_show_decoy_report=1&show_decoy=1"); // request
getResults(results_path);
}
else
{
endRun_();
}
}
}
}
}
void MascotRemoteQuery::setQuerySpectra(const String& exp)
{
query_spectra_ = exp;
}
const QByteArray& MascotRemoteQuery::getMascotXMLResponse() const
{
return mascot_xml_;
}
const QByteArray& MascotRemoteQuery::getMascotXMLDecoyResponse() const
{
return mascot_decoy_xml_;
}
void MascotRemoteQuery::setExportDecoys(const bool b)
{
export_decoys_ = b;
}
bool MascotRemoteQuery::hasError() const
{
return !error_message_.empty();
}
const String& MascotRemoteQuery::getErrorMessage() const
{
return error_message_;
}
String MascotRemoteQuery::getSearchIdentifier() const
{
return search_identifier_;
}
void MascotRemoteQuery::updateMembers_()
{
#ifdef MASCOTREMOTEQUERY_DEBUG
cerr << "MascotRemoteQuery::updateMembers_()" << "\n";
#endif
server_path_ = param_.getValue("server_path").toString();
//MascotRemoteQuery_test
if (!server_path_.empty())
{
server_path_ = "/" + server_path_;
}
host_name_ = param_.getValue("hostname").toString();
use_ssl_ = param_.getValue("use_ssl").toBool();
#ifndef QT_NO_SSL
if (use_ssl_ && !QSslSocket::supportsSsl())
{
throw OpenMS::Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Error: Usage of SSL encryption requested but the OpenSSL library was not found at runtime. Please install OpenSSL system-wide.");
}
#else
if (use_ssl_)
{
throw OpenMS::Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Error: Usage of SSL encryption requested but the linked QT library was not compiled with SSL support. Please recompile QT.");
}
#endif
boundary_ = param_.getValue("boundary").toString();
cookie_ = "";
mascot_xml_ = "";
mascot_decoy_xml_ = "";
to_ = param_.getValue("timeout");
timeout_.setInterval(1000 * to_);
requires_login_ = param_.getValue("login").toBool();
bool use_proxy(param_.getValue("use_proxy").toBool());
if (use_proxy)
{
QNetworkProxy proxy;
proxy.setType(QNetworkProxy::Socks5Proxy);
String proxy_host(param_.getValue("proxy_host").toString());
proxy.setHostName(proxy_host.toQString());
String proxy_port(param_.getValue("proxy_port").toString());
proxy.setPort(proxy_port.toInt());
String proxy_password(param_.getValue("proxy_password").toString());
proxy.setPassword(proxy_password.toQString());
String proxy_username(param_.getValue("proxy_username").toString());
if (!proxy_username.empty())
{
proxy.setUser(proxy_username.toQString());
}
QNetworkProxy::setApplicationProxy(proxy);
}
return;
}
void MascotRemoteQuery::removeHostName_(QString& url)
{
if (url.startsWith("http://"))
url.remove("http://");
else if (url.startsWith("https://"))
url.remove("https://");
if (!url.startsWith(host_name_.toQString()))
{
OPENMS_LOG_ERROR << "Invalid location returned by mascot! Abort." << std::endl;
endRun_();
return;
}
// makes sure that only the first occurrence in the String is replaced,
// in case of an equal server_name_
url.replace(url.indexOf(host_name_.toQString()),
host_name_.toQString().size(), QString(""));
// ensure path starts with /
if (url[0] != '/') url.prepend('/');
}
QUrl MascotRemoteQuery::buildUrl_(const std::string& path)
{
String protocol;
if (use_ssl_)
{
protocol = "https";
}
else
{
protocol = "http";
}
return QUrl(String(protocol + "://" + host_name_ + path).c_str());
}
void MascotRemoteQuery::logHeader_(const QNetworkReply* header, const String& what)
{
QList<QByteArray> header_list = header->rawHeaderList();
cerr << ">>>> Header to " << what << " (begin):\n";
foreach (QByteArray rawHeader, header_list)
{
cerr << " " << rawHeader.toStdString() << " : " << header->rawHeader(rawHeader).toStdString() << std::endl;
}
cerr << "<<<< Header to " << what << " (end)." << endl;
}
void MascotRemoteQuery::logHeader_(const QNetworkRequest& header, const String& what)
{
QList<QByteArray> header_list = header.rawHeaderList();
cerr << ">>>> Header to " << what << " (begin):\n";
foreach (QByteArray rawHeader, header_list)
{
cerr << " " << rawHeader.toStdString() << " : " << header.rawHeader(rawHeader).toStdString() << std::endl;
}
cerr << "<<<< Header to " << what << " (end)." << endl;
}
String MascotRemoteQuery::getSearchIdentifierFromFilePath(const String& path) const
{
#ifdef MASCOTREMOTEQUERY_DEBUG
std::cerr << "MascotRemoteQuery::getSearchIdentifierFromFilePath " << path << std::endl;
#endif
size_t pos = path.find_last_of("/\\");
String tmp = path.substr(pos + 1);
pos = tmp.find_last_of(".");
tmp = tmp.substr(1, pos - 1);
#ifdef MASCOTREMOTEQUERY_DEBUG
std::cerr << "MascotRemoteQuery::getSearchIdentifierFromFilePath will return" << tmp << std::endl;
#endif
return tmp;
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/Base64.cpp | .cpp | 11,714 | 285 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm, Chris Bielow, Moritz Aubermann $
// --------------------------------------------------------------------------
#include <OpenMS/FORMAT/Base64.h>
#include <OpenMS/SYSTEM/SIMDe.h>
using namespace std;
namespace OpenMS
{
const simde__m128i mask1_ = simde_mm_set1_epi32(0x3F000000); // 00111111 00000000 00000000 00000000
const simde__m128i mask2_ = simde_mm_set1_epi32(0x003F0000); // 00000000 00111111 00000000 00000000
const simde__m128i mask3_ = simde_mm_set1_epi32(0x00003F00); // 00000000 00000000 00111111 00000000
const simde__m128i mask4_ = simde_mm_set1_epi32(0x0000003F); // 00000000 00000000 00000000 00111111
const simde__m128i mask1d_ = simde_mm_set1_epi32(0xFF000000); // 11111111 00000000 00000000 00000000
const simde__m128i mask2d_ = simde_mm_set1_epi32(0x00FF0000); // 00000000 11111111 00000000 00000000
const simde__m128i mask3d_ = simde_mm_set1_epi32(0x0000FF00); // 00000000 00000000 11111111 00000000
const simde__m128i mask4d_ = simde_mm_set1_epi32(0x000000FF); // 00000000 00000000 00000000 11111111
// difference between base64 encoding and ascii encoding, used to cast from base64 binaries to characters
const simde__m128i difference_A_ = simde_mm_set1_epi8('A');
const simde__m128i difference_a_ = simde_mm_set1_epi8('a' - 26);
const simde__m128i difference_0_ = simde_mm_set1_epi8('0' - 52);
const simde__m128i difference_plus_ = simde_mm_set1_epi8('+');
const simde__m128i difference_slash_ = simde_mm_set1_epi8('/');
const simde__m128i shuffle_mask_1_ = simde_mm_setr_epi8(2, 2, 1, 0, 5, 5, 4, 3, 8, 8, 7, 6, 11, 11, 10, 9);
const simde__m128i shuffle_mask_2_ = simde_mm_setr_epi8(3, 2, 1, 0, 7, 6, 5, 4, 11, 10, 9, 8, 15, 14, 13, 12);
const simde__m128i shuffle_mask_big_endian_ = simde_mm_setr_epi8(0, 1, 2, 2, 3, 4, 5, 5, 6, 7, 8, 8, 9, 10, 11, 11);
// second shuffle doesnt need to happen
// decoding shuffle masks:
// shuffle_mask_2 gets used
const simde__m128i shuffle_mask_d_2_ = simde_mm_setr_epi8(3, 2, 1, 7, 6, 5, 11, 10, 9, 15, 14, 13, 0, 4, 8, 12);
/// Encode the first 12 bytes of a 128 bit simde integer type to base64
void registerEncoder_(simde__m128i& data)
{
if constexpr (!OPENMS_IS_BIG_ENDIAN)
{
data = simde_mm_shuffle_epi8(data, shuffle_mask_1_);
// by shuffling every 3 8bit ASCII Letters now take up 4 bytes, "ABC" gets shuffled to "CCBA" to match the 4 bytes of the Base64 Encoding, and deal with little Endianness.
}
else
{
data = simde_mm_shuffle_epi8(data, shuffle_mask_big_endian_);
}
// shifting and masking data, so now every 6 bit of the ASCII encoding have their own byte.
// shifting over 32 bits takes endianness into account, which needs to be accounted for when shuffeling
data = (simde_mm_srli_epi32(data, 2) & mask1_) | (simde_mm_srli_epi32(data, 4) & mask2_) | (simde_mm_srli_epi32(data, 6) & mask3_) | (data & mask4_);
if constexpr (!OPENMS_IS_BIG_ENDIAN) // otherwise the data already is ordered correctly
{
data = simde_mm_shuffle_epi8(data, shuffle_mask_2_);
}
// masking data and adding/substracting to match base64 codes to fitting characters
simde__m128i capital_mask = simde_mm_cmplt_epi8(data, simde_mm_set1_epi8(26)); // (a < b) ? 0xFF : 0x00
simde__m128i all_mask = capital_mask;
simde__m128i lower_case_mask = simde_mm_andnot_si128(all_mask, simde_mm_cmplt_epi8(data, simde_mm_set1_epi8(52))); // not allMask and b where b is 0xFF if binaries are smaller than 52
all_mask |= lower_case_mask;
simde__m128i number_mask = simde_mm_andnot_si128(all_mask, simde_mm_cmplt_epi8(data, simde_mm_set1_epi8(62)));
all_mask |= number_mask;
simde__m128i plus_mask = simde_mm_andnot_si128(all_mask, simde_mm_cmplt_epi8(data, simde_mm_set1_epi8(63)));
all_mask |= plus_mask;
simde__m128i& slash_negative_mask = all_mask;
data = (capital_mask & simde_mm_add_epi8(data, difference_A_)) | (lower_case_mask & simde_mm_add_epi8(data, difference_a_)) | (number_mask & simde_mm_add_epi8(data, difference_0_)) |
(plus_mask & difference_plus_) | (simde_mm_andnot_si128(slash_negative_mask, difference_slash_));
}
void registerDecoder_(simde__m128i& data)
{
// ASCII letters must be translated over to base64. This cannot be achieved by just adding/substracting a single value
// from each letter since in ASCII Alphabet capital letters aren't followed up by small Letters, and small Letters not by numbers (..).
// Therefore certain kinds of characters must be masked out for further processing:
// plusMask equals 0xFF for each corresponding plus, otherwise its 0
simde__m128i plusMask = simde_mm_cmpeq_epi8(data, difference_plus_);
simde__m128i allMask = plusMask;
// slashMask similar to plusMask
simde__m128i slashMask = simde_mm_cmpeq_epi8(data, difference_slash_);
allMask |= slashMask;
// for number mask: all characters less than '9' plus 1 must be numbers, '+' or '/' because input is Base64
// therefore "not allMask and less than '9' + 1 (see allNumbers in header) " applied on data sets all bytes corresponding to numbers in the mask to 0xFF
simde__m128i numberMask = simde_mm_andnot_si128(allMask, simde_mm_cmplt_epi8(data, simde_mm_set1_epi8('9' + 1)));
allMask |= numberMask;
simde__m128i bigLetterMask = simde_mm_andnot_si128(allMask, simde_mm_cmplt_epi8(data, simde_mm_set1_epi8('Z' + 1)));
allMask |= bigLetterMask;
simde__m128i smallLetterMask = simde_mm_andnot_si128(allMask, simde_mm_cmplt_epi8(data, simde_mm_set1_epi8('z' + 1)));
// match ASCII characters with coresponding Base64 codes:
data = (plusMask & simde_mm_set1_epi8(62)) | (slashMask & simde_mm_set1_epi8(63)) | (numberMask & simde_mm_add_epi8(data, simde_mm_set1_epi8(4))) |
(bigLetterMask & simde_mm_sub_epi8(data, simde_mm_set1_epi8(65))) | // ASCII 'A' is 65, Base64 'A' is 0
(smallLetterMask & simde_mm_sub_epi8(data, simde_mm_set1_epi8(71)));
// convert little endian to big endian:
data = simde_mm_shuffle_epi8(data, shuffle_mask_2_);
// the actual magic (conversion base64 to ASCII) happens here by shifting and masking:
data = simde_mm_slli_epi32((data & mask1d_), 2) | simde_mm_slli_epi32((data & mask2d_), 4) | simde_mm_slli_epi32((data & mask3d_), 6) | simde_mm_slli_epi32((data & mask4d_), 8);
// convert big endian to little endian
data = simde_mm_shuffle_epi8(data, shuffle_mask_d_2_);
}
void Base64::stringSimdEncoder_(std::string& in, std::string& out)
{
out.resize((Size)(in.size() / 3) * 4 + 16); // resize output array, so the register encoder doesnt write memory to unallocated memory
uint8_t padding = (3 - in.size() % 3) % 3;
const int loop = in.size() / 12;
in.resize(in.size() + 4, '\0');
// otherwise there are cases where register encoder isnt allowed to access last bytes
simde__m128i data {};
// loop through input as long as it's safe to access memory
for (int i = 0; i < loop; i++)
{
// each time the last 4 out of 16 byte string data get lost through processing, therefore jumps of 12 bytes (/characters)
data = simde_mm_lddqu_si128((simde__m128i*)&in[12 * i]);
registerEncoder_(data);
simde_mm_storeu_si128((simde__m128*)&out[i * 16], data);
}
size_t read = loop * 12;
size_t written = loop * 16;
// create buffer to translate last bytes without accessing memory that hasn't been allocated
std::array<char, 16> buffer {};
memcpy(&buffer[0], &in[read], in.size() - read - 4); // minus 4 because of 4 appended null bytes
data = simde_mm_lddqu_si128((simde__m128i*)&buffer[0]);
registerEncoder_(data);
simde_mm_storeu_si128((simde__m128*)&out[written], data);
in.resize(in.size() - 4); // remove null bytes
// resizing out and add padding if necessary
if (padding)
{
size_t newsize = ceil((double)in.size() / 3.) * 4;
out.resize(newsize);
for (size_t j = newsize - 1; j >= newsize - padding; j--)
{
out[j] = '=';
}
}
else
{
out.resize((in.size() / 3) * 4);
}
}
void Base64::stringSimdDecoder_(const std::string& in, std::string& out)
{
out.clear();
const char* inPtr = &in[0];
// padding count:
uint8_t g = 0;
if (in[in.size() - 1] == '=')
g++;
if (in[in.size() - 2] == '=')
g++;
unsigned outsize = (in.size() / 16) * 12 + 16;
// not final size (final rezize later to cutoff unwanted characters)
out.resize(outsize);
char* outPtr = &out[0];
int loop = in.size() / 16;
for (int i = 0; i < loop; i++)
{
simde__m128i data = simde_mm_lddqu_si128((simde__m128i*)(inPtr + i * 16));
registerDecoder_(data);
simde_mm_storeu_si128((simde__m128*)(outPtr + i * 12), data);
}
size_t read = loop * 16;
std::array<char, 16> rest;
std::fill(rest.begin(), rest.end(), 'x');
std::copy(in.begin() + read, in.end(), rest.begin());
simde__m128i data = simde_mm_lddqu_si128((simde__m128i*)&rest[0]);
registerDecoder_(data);
size_t written = loop * 12;
simde_mm_storeu_si128((simde__m128*)(outPtr + written), data);
// cutting off decoding of appendix
outsize = (in.size() / 4) * 3 - g;
out.resize(outsize);
}
const char Base64::encoder_[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const char Base64::decoder_[] = "|$$$}rstuvwxyz{$$$$$$$>?@ABCDEFGHIJKLMNOPQRSTUVW$$$$$$XYZ[\\]^_`abcdefghijklmnopq";
void Base64::encodeStrings(const std::vector<String>& in, String& out, bool zlib_compression, bool append_null_byte)
{
out.clear();
if (in.empty())
{
return;
}
std::string str;
for (Size i = 0; i < in.size(); ++i)
{
str.append(in[i]);
if (append_null_byte)
{
str.push_back('\0');
}
}
if (zlib_compression)
{
String compressed;
ZlibCompression::compressString(str, compressed);
Base64::stringSimdEncoder_(compressed, out);
}
else
{
Base64::stringSimdEncoder_(str, out);
}
}
void Base64::decodeStrings(const String& in, std::vector<String>& out, bool zlib_compression)
{
out.clear();
// The length of a base64 string is a always a multiple of 4 (always 3
// bytes are encoded as 4 characters)
if (in.size() < 4)
{
return;
}
String decoded;
decodeSingleString(in, decoded, zlib_compression);
const char* first_sep = decoded.data(); // start of current string
const char* next_sep = 0; // end of current string (past the end)
while (first_sep < decoded.data() + decoded.size())
{
next_sep = strchr(first_sep, '\0');
if (first_sep + 1 < next_sep) // non-empty string
{
out.push_back(String(first_sep, next_sep - first_sep));
}
first_sep = next_sep + 1; // move to substring
}
}
void Base64::decodeSingleString(const String& in, String& out, bool zlib_compression)
{
// The length of a base64 string is a always a multiple of 4 (always 3
// bytes are encoded as 4 characters)
if (in.size() < 4)
{
return;
}
if (zlib_compression)
{
String decoded;
stringSimdDecoder_(in, decoded);
ZlibCompression::uncompressString(decoded, out);
}
else
{
stringSimdDecoder_(in, out);
}
}
} //end OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/MsInspectFile.cpp | .cpp | 545 | 22 | // 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/MsInspectFile.h>
using namespace std;
namespace OpenMS
{
MsInspectFile::MsInspectFile() = default;
MsInspectFile::~MsInspectFile() = default;
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/QcMLFile.cpp | .cpp | 68,703 | 2,132 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Mathias Walzer, Axel Walter $
// $Authors: Mathias Walzer $
// --------------------------------------------------------------------------
#include <OpenMS/FORMAT/QcMLFile.h>
#include <OpenMS/FORMAT/HANDLERS/XMLHandler.h>
#include <OpenMS/FORMAT/XMLFile.h>
#include <OpenMS/FORMAT/ControlledVocabulary.h>
#include <OpenMS/SYSTEM/File.h>
#include <OpenMS/KERNEL/FeatureMap.h>
#include <OpenMS/KERNEL/ConsensusMap.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/MATH/MathFunctions.h>
#include <OpenMS/MATH/StatisticFunctions.h>
#include <QtCore/QFileInfo>
#include <fstream>
#include <set>
using namespace std;
namespace OpenMS
{
QcMLFile::QualityParameter::QualityParameter() :
name(),
id(),
value(),
cvRef(),
cvAcc(),
unitRef(),
unitAcc(),
flag()
{
}
QcMLFile::QualityParameter::QualityParameter(const QualityParameter& rhs) = default;
QcMLFile::QualityParameter& QcMLFile::QualityParameter::operator=(const QualityParameter& rhs)
{
if (this != &rhs)
{
name = rhs.name;
id = rhs.id;
value = rhs.value;
cvRef = rhs.cvRef;
cvAcc = rhs.cvAcc;
unitRef = rhs.unitRef;
unitAcc = rhs.unitAcc;
flag = rhs.flag;
}
return *this;
}
bool QcMLFile::QualityParameter::operator<(const QualityParameter& rhs) const
{
return name.toQString() < rhs.name.toQString();
}
bool QcMLFile::QualityParameter::operator>(const QualityParameter& rhs) const
{
return name.toQString() > rhs.name.toQString();
}
bool QcMLFile::QualityParameter::operator==(const QualityParameter& rhs) const
{
return name.toQString() == rhs.name.toQString();
}
String QcMLFile::QualityParameter::toXMLString(UInt indentation_level) const
{
String indent = String(indentation_level, '\t');
String s = indent;
s += "<qualityParameter";
s += " name=\"" + name + "\"" + " ID=\"" + id + "\"" + " cvRef=\"" + cvRef + "\"" + " accession=\"" + cvAcc + "\"";
if (!value.empty())
{
s += " value=\"" + value + "\"";
}
if (!unitRef.empty())
{
s += " unitRef=\"" + unitRef + "\"";
}
if (!unitAcc.empty())
{
s += " unitAcc=\"" + unitAcc + "\"";
}
if (!flag.empty())
{
s += " flag=\"true\"";
}
s += "/>\n";
return s;
}
QcMLFile::Attachment::Attachment() :
name(),
id(),
value(),
cvRef(),
cvAcc(),
unitRef(),
unitAcc(),
qualityRef(),
colTypes(),
tableRows()
{
}
QcMLFile::Attachment::Attachment(const Attachment& rhs) = default;
QcMLFile::Attachment& QcMLFile::Attachment::operator=(const Attachment& rhs)
{
if (this != &rhs)
{
name = rhs.name;
id = rhs.id;
value = rhs.value;
cvRef = rhs.cvRef;
cvAcc = rhs.cvAcc;
unitRef = rhs.unitRef;
unitAcc = rhs.unitAcc;
binary = rhs.binary;
qualityRef = rhs.qualityRef;
colTypes = rhs.colTypes;
tableRows = rhs.tableRows;
}
return *this;
}
bool QcMLFile::Attachment::operator<(const Attachment& rhs) const
{
return name.toQString() < rhs.name.toQString();
}
bool QcMLFile::Attachment::operator>(const Attachment& rhs) const
{
return name.toQString() > rhs.name.toQString();
}
bool QcMLFile::Attachment::operator==(const Attachment& rhs) const
{
return name.toQString() == rhs.name.toQString();
}
String QcMLFile::Attachment::toCSVString(const String& separator) const
{
String s = "";
if ((!colTypes.empty()) && (!tableRows.empty()))
{
String replacement = "_";
if (separator == replacement)
{
replacement = "$";
}
std::vector<String> copy = colTypes;
for (std::vector<String>::iterator it = copy.begin(); it != copy.end(); ++it)
{
it->substitute(separator, replacement);
}
s += ListUtils::concatenate(copy, separator).trim();
s += "\n";
for (std::vector<std::vector<String> >::const_iterator it = tableRows.begin(); it != tableRows.end(); ++it)
{
std::vector<String> copy_row = *it;
for (std::vector<String>::iterator sit = copy_row.begin(); sit != copy_row.end(); ++sit)
{
sit->substitute(separator, replacement);
}
s += ListUtils::concatenate(copy_row, separator).trim();
s += "\n";
}
}
return s;
}
//TODO CHANGE TO ACCEPTABLE WAY OF GENERATING A PRETTY XML FILE
String QcMLFile::Attachment::toXMLString(UInt indentation_level) const
{
//TODO manage IDREF to qp internally
String indent = String(indentation_level, '\t');
String s = indent;
s += "<attachment ";
s += " name=\"" + name + "\"" + " ID=\"" + id + "\"" + " cvRef=\"" + cvRef + "\"" + " accession=\"" + cvAcc + "\"";
if (!value.empty())
{
s += " value=\"" + value + "\"";
}
if (!unitRef.empty())
{
s += " unitRef=\"" + unitRef + "\"";
}
if (!unitAcc.empty())
{
s += " unitAcc=\"" + unitAcc + "\"";
}
if (!qualityRef.empty())
{
s += " qualityParameterRef=\"" + qualityRef + "\"";
}
if (!binary.empty())
{
s += ">\n";
s += indent + "\t" + "<binary>" + binary + "</binary>\n";
s += indent + "</attachment>\n";
}
else if ((!colTypes.empty()) && (!tableRows.empty()))
{
s += ">\n";
s += "<table>";
s += indent + "\t" + "<tableColumnTypes>";
std::vector<String> copy = colTypes;
for (String& it : copy)
{
it.substitute(String(" "), String("_"));
}
s += ListUtils::concatenate(copy, " ").trim();
s += "</tableColumnTypes>\n";
for (std::vector<std::vector<String> >::const_iterator it = tableRows.begin(); it != tableRows.end(); ++it)
{
s += indent + "\t" + "<tableRowValues>";
std::vector<String> copy_row = *it;
for (String& sit : copy_row)
{
sit.substitute(String(" "), String("_"));
}
s += ListUtils::concatenate(*it, " ").trim();
s += "</tableRowValues>\n";
}
s += "</table>";
s += indent + "</attachment>\n";
}
else
{
//TODO warning invalid attachment!
return "";
}
return s;
}
QcMLFile::QcMLFile() :
XMLHandler("", "0.7"), XMLFile("/SCHEMAS/qcml.xsd", "0.7"), ProgressLogger() //TODO keep version up-to-date
{
}
QcMLFile::~QcMLFile() = default;
void QcMLFile::addRunQualityParameter(const String& run_id, const QualityParameter& qp)
{
// TODO warn that run has to be registered!
std::map<String, std::vector<QcMLFile::QualityParameter> >::const_iterator qpsit = runQualityQPs_.find(run_id); //if 'filename is a ID:'
if (qpsit != runQualityQPs_.end())
{
runQualityQPs_[run_id].push_back(qp);
}
else
{
std::map<String, String>::const_iterator qpsit = run_Name_ID_map_.find(run_id); //if 'filename' is a name
if (qpsit != run_Name_ID_map_.end())
{
runQualityQPs_[qpsit->second].push_back(qp);
}
}
//TODO redundancy check
}
void QcMLFile::addSetQualityParameter(const String& set_id, const QualityParameter& qp)
{
// TODO warn that set has to be registered!
std::map<String, std::vector<QcMLFile::QualityParameter> >::const_iterator qpsit = setQualityQPs_.find(set_id); //if 'filename is a ID:'
if (qpsit != setQualityQPs_.end())
{
setQualityQPs_[set_id].push_back(qp);
}
else
{
std::map<String, String>::const_iterator qpsit = set_Name_ID_map_.find(set_id); //if 'filename' is a name
if (qpsit != set_Name_ID_map_.end())
{
setQualityQPs_[qpsit->second].push_back(qp);
}
}
//TODO redundancy check
}
void QcMLFile::addRunAttachment(const String& run_id, const Attachment& at)
{
runQualityAts_[run_id].push_back(at); //TODO permit AT without a QP (or enable orphan write out in store),redundancy check
}
void QcMLFile::addSetAttachment(const String& run_id, const Attachment& at)
{
setQualityAts_[run_id].push_back(at); //TODO add file QP to set member
}
void QcMLFile::getRunNames(std::vector<String>& ids) const
{
ids.clear();
for (const auto& m : run_Name_ID_map_) ids.push_back(m.first);
}
void QcMLFile::getRunIDs(std::vector<String>& ids) const
{
ids.clear();
for (const auto& m : runQualityQPs_) ids.push_back(m.first);
}
bool QcMLFile::existsRun(const String& filename, bool checkname) const
{
std::map<String, std::vector<QcMLFile::QualityParameter> >::const_iterator qpsit = runQualityQPs_.find(filename); //if 'filename is a ID:'
if (qpsit != runQualityQPs_.end()) //NO, do not!: permit AT without a QP
{
return true;
}
else if (checkname)
{
std::map<String, String>::const_iterator qpsit = run_Name_ID_map_.find(filename); //if 'filename' is a name
if (qpsit != run_Name_ID_map_.end()) //NO, do not!: permit AT without a QP
{
return true;
}
}
return false;
}
bool QcMLFile::existsSet(const String& filename, bool checkname) const
{
std::map<String, std::vector<QcMLFile::QualityParameter> >::const_iterator qpsit = setQualityQPs_.find(filename); //if 'filename is a ID:'
if (qpsit != setQualityQPs_.end()) //NO, do not!: permit AT without a QP
{
return true;
}
else if (checkname)
{
std::map<String, String>::const_iterator qpsit = set_Name_ID_map_.find(filename); //if 'filename' is a name
if (qpsit != set_Name_ID_map_.end()) //NO, do not!: permit AT without a QP
{
return true;
}
}
return false;
}
void QcMLFile::existsRunQualityParameter(const String& filename, const String& qpname, std::vector<String>& ids) const
{
ids.clear();
std::map<String, std::vector<QcMLFile::QualityParameter> >::const_iterator qpsit = runQualityQPs_.find(filename);
if (qpsit == runQualityQPs_.end()) //try name mapping if 'filename' is no ID but name
{
std::map<String, String>::const_iterator mapsit = run_Name_ID_map_.find(filename);
if (mapsit != run_Name_ID_map_.end())
{
qpsit = runQualityQPs_.find(mapsit->second);
}
}
if (qpsit != runQualityQPs_.end())
{
for (std::vector<QcMLFile::QualityParameter>::const_iterator qit = qpsit->second.begin(); qit != qpsit->second.end(); ++qit)
{
if (qpname == qit->cvAcc)
{
ids.push_back(qit->id);
}
}
}
}
void QcMLFile::existsSetQualityParameter(const String& filename, const String& qpname, std::vector<String>& ids) const
{
ids.clear();
std::map<String, std::vector<QcMLFile::QualityParameter> >::const_iterator qpsit = setQualityQPs_.find(filename);
if (qpsit == setQualityQPs_.end()) //try name mapping if 'filename' is no ID but name
{
std::map<String, String>::const_iterator mapsit = set_Name_ID_map_.find(filename);
if (mapsit != set_Name_ID_map_.end())
{
qpsit = setQualityQPs_.find(mapsit->second);
}
}
if (qpsit != setQualityQPs_.end())
{
for (std::vector<QcMLFile::QualityParameter>::const_iterator qit = qpsit->second.begin(); qit != qpsit->second.end(); ++qit)
{
//~ std::cout << qit->name << "setexists" << std::endl;
//~ std::cout << qpname << "qpname" << std::endl;
if (qpname == qit->cvAcc)
{
ids.push_back(qit->id);
}
}
}
}
void QcMLFile::removeQualityParameter(const String& r, std::vector<String>& ids)
{
removeAttachment(r, ids);
for (Size i = 0; i < ids.size(); ++i)
{
std::vector<QcMLFile::QualityParameter>::iterator qit = runQualityQPs_[r].begin();
while (qit != runQualityQPs_[r].end())
{
if (qit->id == ids[i])
{
qit = runQualityQPs_[r].erase(qit);
}
else
{
++qit;
}
}
qit = setQualityQPs_[r].begin();
while (qit != setQualityQPs_[r].end())
{
if (qit->id == ids[i])
{
qit = setQualityQPs_[r].erase(qit);
}
else
{
++qit;
}
}
}
}
void QcMLFile::removeAttachment(const String& r, std::vector<String>& ids, const String& at)
{
bool not_all = !at.empty();
for (Size i = 0; i < ids.size(); ++i)
{
std::vector<QcMLFile::Attachment>::iterator qit = runQualityAts_[r].begin();
while (qit != runQualityAts_[r].end())
{
if (qit->qualityRef == ids[i] && ((qit->name == at) || (!not_all)))
{
qit = runQualityAts_[r].erase(qit);
}
else
{
++qit;
}
}
qit = setQualityAts_[r].begin();
while (qit != setQualityAts_[r].end())
{
if (qit->qualityRef == ids[i] && ((qit->name == at) || (!not_all)))
{
qit = setQualityAts_[r].erase(qit);
}
else
{
++qit;
}
}
}
}
void QcMLFile::removeAttachment(const String& r, const String& at)
{
if (existsRun(r))
{
std::vector<QcMLFile::Attachment>::iterator qit = runQualityAts_[r].begin();
//~ cout << "remove from " << r << endl;
while (qit != runQualityAts_[r].end())
{
if (qit->cvAcc == at)
{
qit = runQualityAts_[r].erase(qit);
//~ cout << "remove " << at << endl;
}
else
{
++qit;
}
}
}
if (existsSet(r))
{
std::vector<QcMLFile::Attachment>::iterator qit = setQualityAts_[r].begin();
while (qit != setQualityAts_[r].end())
{
if (qit->cvAcc == at)
{
qit = setQualityAts_[r].erase(qit);
}
else
{
++qit;
}
}
}
}
void QcMLFile::removeAllAttachments(const String& at)
{
for (std::map<String, std::vector<Attachment> >::iterator it = runQualityAts_.begin(); it != runQualityAts_.end(); ++it)
{
removeAttachment(it->first, at);
}
}
void QcMLFile::registerRun(const String& id, const String& name)
{
runQualityQPs_[id] = std::vector<QualityParameter>();
runQualityAts_[id] = std::vector<Attachment>();
run_Name_ID_map_[name] = id;
}
void QcMLFile::registerSet(const String& id, const String& name, const std::set<String>& names)
{
setQualityQPs_[id] = std::vector<QualityParameter>();
setQualityAts_[id] = std::vector<Attachment>();
set_Name_ID_map_[name] = id;
setQualityQPs_members_[id] = names;
}
void QcMLFile::merge(const QcMLFile& addendum, const String& setname)
{
//~ runs (and create set if setname not empty)
for (std::map<String, std::vector<QualityParameter> >::const_iterator it = addendum.runQualityQPs_.begin(); it != addendum.runQualityQPs_.end(); ++it)
{
runQualityQPs_[it->first].insert(runQualityQPs_[it->first].end(), it->second.begin(), it->second.end());
std::sort(runQualityQPs_[it->first].begin(), runQualityQPs_[it->first].end());
runQualityQPs_[it->first].erase(std::unique(runQualityQPs_[it->first].begin(), runQualityQPs_[it->first].end()), runQualityQPs_[it->first].end());
if (!setname.empty())
{
setQualityQPs_members_[setname].insert(it->first);
}
}
for (std::map<String, std::vector<Attachment> >::const_iterator it = addendum.runQualityAts_.begin(); it != addendum.runQualityAts_.end(); ++it)
{
runQualityAts_[it->first].insert(runQualityAts_[it->first].end(), it->second.begin(), it->second.end());
std::sort(runQualityAts_[it->first].begin(), runQualityAts_[it->first].end());
runQualityAts_[it->first].erase(std::unique(runQualityAts_[it->first].begin(), runQualityAts_[it->first].end()), runQualityAts_[it->first].end());
if (!setname.empty())
{
setQualityQPs_members_[setname].insert(it->first);
}
}
// sets
//~ TODO sets are not supposed to overlap - throw error if so
setQualityQPs_members_.insert(addendum.setQualityQPs_members_.begin(), addendum.setQualityQPs_members_.end());
for (std::map<String, std::vector<QualityParameter> >::const_iterator it = addendum.setQualityQPs_.begin(); it != addendum.setQualityQPs_.end(); ++it)
{
setQualityQPs_[it->first].insert(setQualityQPs_[it->first].end(), it->second.begin(), it->second.end());
std::sort(setQualityQPs_[it->first].begin(), setQualityQPs_[it->first].end());
setQualityQPs_[it->first].erase(std::unique(setQualityQPs_[it->first].begin(), setQualityQPs_[it->first].end()), setQualityQPs_[it->first].end());
}
for (std::map<String, std::vector<Attachment> >::const_iterator it = addendum.setQualityAts_.begin(); it != addendum.setQualityAts_.end(); ++it)
{
setQualityAts_[it->first].insert(setQualityAts_[it->first].end(), it->second.begin(), it->second.end());
std::sort(setQualityAts_[it->first].begin(), setQualityAts_[it->first].end());
setQualityAts_[it->first].erase(std::unique(setQualityAts_[it->first].begin(), setQualityAts_[it->first].end()), setQualityAts_[it->first].end());
}
}
String QcMLFile::exportAttachment(const String& filename, const String& qpname) const
{
std::map<String, std::vector<QcMLFile::Attachment> >::const_iterator qpsit = runQualityAts_.find(filename);
if (qpsit == runQualityAts_.end()) //try name mapping if 'filename' is no ID but name
{
std::map<String, String>::const_iterator mapsit = run_Name_ID_map_.find(filename);
if (mapsit != run_Name_ID_map_.end())
{
qpsit = runQualityAts_.find(mapsit->second);
}
}
if (qpsit != runQualityAts_.end())
{
for (std::vector<QcMLFile::Attachment>::const_iterator qit = qpsit->second.begin(); qit != qpsit->second.end(); ++qit)
{
if ((qpname == qit->name) || (qpname == qit->cvAcc))
{
return qit->toCSVString("\t");
//~ return qit->toXMLString(1);
}
}
}
// if the return statement wasn't hit from runs maybe it is from sets?
qpsit = setQualityAts_.find(filename);
if (qpsit == setQualityAts_.end()) //try name mapping if 'filename' is no ID but name
{
std::map<String, String>::const_iterator mapsit = set_Name_ID_map_.find(filename);
if (mapsit != set_Name_ID_map_.end())
{
qpsit = setQualityAts_.find(mapsit->second);
}
}
if (qpsit != setQualityAts_.end())
{
for (std::vector<QcMLFile::Attachment>::const_iterator qit = qpsit->second.begin(); qit != qpsit->second.end(); ++qit)
{
if ((qpname == qit->name) || (qpname == qit->cvAcc))
{
return qit->toCSVString("\t");
//~ return qit->toXMLString(1);
}
}
}
return "";
}
String QcMLFile::exportQP(const String& filename, const String& qpname) const
{
std::map<String, std::vector<QcMLFile::QualityParameter> >::const_iterator qpsit = runQualityQPs_.find(filename);
if (qpsit == runQualityQPs_.end()) //try name mapping if 'filename' is no ID but name
{
std::map<String, String>::const_iterator mapsit = run_Name_ID_map_.find(filename);
if (mapsit != run_Name_ID_map_.end())
{
qpsit = runQualityQPs_.find(mapsit->second);
}
}
if (qpsit != runQualityQPs_.end())
{
for (std::vector<QcMLFile::QualityParameter>::const_iterator qit = qpsit->second.begin(); qit != qpsit->second.end(); ++qit)
{
if (qpname == qit->cvAcc)
{
return /* "\""+ */ qit->value /* +"\"" */;
}
}
}
// if the return statement wasn't hit from runs maybe it is from sets?
qpsit = setQualityQPs_.find(filename);
if (qpsit == setQualityQPs_.end()) //try name mapping if 'filename' is no ID but name
{
std::map<String, String>::const_iterator mapsit = set_Name_ID_map_.find(filename);
if (mapsit != set_Name_ID_map_.end())
{
qpsit = setQualityQPs_.find(mapsit->second);
}
}
if (qpsit != setQualityQPs_.end())
{
for (std::vector<QcMLFile::QualityParameter>::const_iterator qit = qpsit->second.begin(); qit != qpsit->second.end(); ++qit)
{
if (qpname == qit->name)
{
return /* "\""+ */ qit->value /* +"\"" */;
}
}
}
return "N/A";
}
String QcMLFile::exportQPs(const String& filename, const StringList& qpnames) const
{
String ret = "";
for (StringList::const_iterator qit = qpnames.begin(); qit != qpnames.end(); ++qit)
{
ret += exportQP(filename, *qit);
ret += ",";
}
return ret;
}
String QcMLFile::map2csv(const std::map<String, std::map<String, String> >& cvs_table, const String& separator) const
{
String ret = "";
std::vector<String> cols;
if (!cvs_table.empty())
{
for (std::map<String, String>::const_iterator it = cvs_table.begin()->second.begin(); it != cvs_table.begin()->second.end(); ++it)
{
cols.push_back(it->first);
}
ret += "qp";
ret += separator;
for (std::vector<String>::const_iterator jt = cols.begin(); jt != cols.end(); ++jt)
{
ret += *jt;
ret += separator;
}
ret += "\n";
for (std::map<String, std::map<String, String> >::const_iterator it = cvs_table.begin(); it != cvs_table.end(); ++it)
{
ret += it->first;
ret += separator;
for (std::vector<String>::const_iterator jt = cols.begin(); jt != cols.end(); ++jt)
{
std::map<String, String>::const_iterator found = it->second.find(*jt);
if (found != it->second.end())
{
ret += found->second;
ret += separator;
} //TODO else throw error
}
ret += "\n";
}
}
return ret;
}
String QcMLFile::exportIDstats(const String& filename) const
{
std::map<String, std::vector<QualityParameter> >::const_iterator found = setQualityQPs_.find(filename);
if (found == setQualityQPs_.end()) //try name mapping if 'filename' is no ID but name
{
std::map<String, String>::const_iterator mapsit = set_Name_ID_map_.find(filename);
if (mapsit != set_Name_ID_map_.end())
{
found = setQualityQPs_.find(mapsit->second);
}
}
if (found != setQualityQPs_.end())
{
std::map<String, std::map<String, String> > cvs_table;
for (const QualityParameter& it : found->second)
{
if (it.cvAcc == "QC:0000043" || it.cvAcc == "QC:0000044" || it.cvAcc == "QC:0000045" || it.cvAcc == "QC:0000046" || it.cvAcc == "QC:0000047")
{
cvs_table["id"][it.name.prefix(' ')] = it.value;
}
else if (it.cvAcc == "QC:0000053" || it.cvAcc == "QC:0000054" || it.cvAcc == "QC:0000055" || it.cvAcc == "QC:0000056" || it.cvAcc == "QC:0000057")
{
cvs_table["ms2"][it.name.prefix(' ')] = it.value;
}
}
if (!cvs_table.empty())
{
return map2csv(cvs_table, "\t");
}
}
return "";
}
void QcMLFile::collectSetParameter(const String& setname, const String& qp, std::vector<String>& ret)
{
for (std::set<String>::const_iterator it = setQualityQPs_members_[setname].begin(); it != setQualityQPs_members_[setname].end(); ++it)
{
for (const QualityParameter& jt : runQualityQPs_[*it])
{
if (jt.cvAcc == qp)
{
ret.push_back(jt.value);
}
}
}
}
void QcMLFile::load(const String& filename)
{
//Filename for error messages in XMLHandler
file_ = filename;
runQualityQPs_.clear(); // clear
runQualityAts_.clear(); // clear
setQualityQPs_.clear(); // clear
setQualityAts_.clear(); // clear
setQualityQPs_members_.clear(); // clear
parse_(filename, this);
}
void QcMLFile::startElement(const XMLCh* const /*uri*/, const XMLCh* const /*local_name*/, const XMLCh* const qname, const xercesc::Attributes& attributes)
{
tag_ = sm_.convert(qname);
String parent_tag;
if (!open_tags_.empty())
{
parent_tag = open_tags_.back();
}
open_tags_.push_back(tag_);
static set<String> to_ignore;
if (to_ignore.empty())
{
to_ignore.insert("tableColumnTypes"); // will be handled entirely in characters.
to_ignore.insert("tableRowValues"); // ...
to_ignore.insert("binary"); // ...
}
if (to_ignore.find(tag_) != to_ignore.end())
{
return;
}
String tmp_str;
if (tag_ == "qcML")
{
startProgress(0, 0, "loading qcML file");
progress_ = 0;
setProgress(++progress_);
}
else if (tag_ == "runQuality")
{
run_id_ = attributeAsString_(attributes, "ID"); //TODO!
setProgress(++progress_);
qps_.clear();
ats_.clear();
qp_ = QualityParameter();
at_ = Attachment();
name_ = "";
//for the run name wait for the qp with the right cv, otherwise use a uid
}
else if (tag_ == "qualityParameter")
{
optionalAttributeAsString_(qp_.value, attributes, "value");
optionalAttributeAsString_(qp_.unitAcc, attributes, "unitAccession");
optionalAttributeAsString_(qp_.unitRef, attributes, "unitCvRef");
optionalAttributeAsString_(qp_.flag, attributes, "flag");
qp_.cvRef = attributeAsString_(attributes, "cvRef");
qp_.cvAcc = attributeAsString_(attributes, "accession");
qp_.id = attributeAsString_(attributes, "ID");
qp_.name = attributeAsString_(attributes, "name");
if (parent_tag == "runQuality")
{
if (qp_.cvAcc == "MS:1000577") //no own qc cv
{
name_ = qp_.value;
}
}
else //setQuality
{
if (qp_.cvAcc == "MS:1000577") //TODO make sure these exist in runs later!
{
names_.insert(qp_.value);
}
if (qp_.cvAcc == "QC:0000058") //id: MS:1000577 name: raw data file - with value of the file name of the run
{
name_ = qp_.value;
}
}
}
else if (tag_ == "attachment")
{
optionalAttributeAsString_(at_.value, attributes, "value");
optionalAttributeAsString_(at_.unitAcc, attributes, "unitAccession");
optionalAttributeAsString_(at_.unitRef, attributes, "unitCvRef");
at_.cvRef = attributeAsString_(attributes, "cvRef");
at_.cvAcc = attributeAsString_(attributes, "accession");
at_.name = attributeAsString_(attributes, "name");
at_.id = attributeAsString_(attributes, "ID");
at_.qualityRef = attributeAsString_(attributes, "qualityParameterRef");
}
else if (tag_ == "setQuality")
{
setProgress(++progress_);
run_id_ = attributeAsString_(attributes, "ID"); //TODO!
qps_.clear();
ats_.clear();
qp_ = QualityParameter();
at_ = Attachment();
name_ = "";
}
}
void QcMLFile::characters(const XMLCh* const chars, const XMLSize_t /*length*/)
{
if (tag_ == "tableRowValues")
{
String s = sm_.convert(chars);
s.trim();
if (!s.empty()) // always two notifications for a row, only the first one contains chars - dunno why
{
s.split(" ", row_);
}
}
else if (tag_ == "tableColumnTypes")
{
String s = sm_.convert(chars);
if (!s.empty()) // always two notifications for a row, only the first one contains chars - dunno why
{
s.split(" ", header_);
}
}
else if (tag_ == "binary")
{
//chars may be split to several chunks => concatenate them
at_.binary += sm_.convert(chars);
//~ at_.binary = "bla";
}
}
void QcMLFile::endElement(const XMLCh* const /*uri*/, const XMLCh* const /*local_name*/, const XMLCh* const qname)
{
static set<String> to_ignore;
if (to_ignore.empty())
{
//~ to_ignore.insert("binary");
}
tag_ = sm_.convert(qname);
//determine parent tag
String parent_tag;
if (open_tags_.size() > 1)
{
parent_tag = *(open_tags_.end() - 2);
}
String parent_parent_tag;
if (open_tags_.size() > 2)
{
parent_parent_tag = *(open_tags_.end() - 3);
}
//close current tag
open_tags_.pop_back();
if (to_ignore.find(tag_) != to_ignore.end())
{
return;
}
if (tag_ == "tableColumnTypes")
{
at_.colTypes.swap(header_);
header_.clear();
}
else if (tag_ == "tableRowValues")
{
if (!row_.empty())
{
at_.tableRows.push_back(row_);
}
row_.clear();
}
else if (tag_ == "qualityParameter")
{
if (!(qp_.cvAcc == "MS:1000577" && parent_tag == "setQuality")) //set members get treated differently!
{
qps_.push_back(qp_);
qp_ = QualityParameter();
}
}
else if (tag_ == "attachment")
{
ats_.push_back(at_);
at_ = Attachment();
}
else if (tag_ == "runQuality")
{
if (name_.empty())
{
name_ = run_id_;
//~ name_ = String(UniqueIdGenerator::getUniqueId());
//TODO give warning that a run should have a name cv!!!
}
registerRun(run_id_, name_);
for (const QualityParameter& it : qps_)
{
addRunQualityParameter(run_id_, it);
}
for (const Attachment& it : ats_)
{
addRunAttachment(run_id_, it);
}
ats_.clear();
qps_.clear();
}
else if (tag_ == "setQuality")
{
if (name_.empty())
{
name_ = run_id_;
//~ name_ = String(UniqueIdGenerator::getUniqueId());
//TODO give warning that a run should have a name cv!!!
}
registerSet(run_id_, name_, names_);
for (const QualityParameter& it : qps_)
{
addSetQualityParameter(run_id_, it);
}
for (const Attachment& it : ats_)
{
addSetAttachment(run_id_, it);
}
ats_.clear();
qps_.clear();
}
}
float calculateSNmedian(const MSSpectrum& spec, bool norm = true)
{
if (spec.empty())
{
return 0;
}
vector<UInt> intensities;
for (auto& pt : spec)
{
intensities.push_back(pt.getIntensity());
}
float median = Math::median(intensities.begin(), intensities.end());
float maxi = spec.back().getIntensity();
if (!norm)
{
float sn_by_max2median = maxi / median;
return sn_by_max2median;
}
float sign_int= 0;
float nois_int = 0;
size_t sign_cnt= 0;
size_t nois_cnt = 0;
for (const Peak1D& pt : spec)
{
if (pt.getIntensity() <= median)
{
++nois_cnt;
nois_int += pt.getIntensity();
}
else
{
++sign_cnt;
sign_int += pt.getIntensity();
}
}
if (sign_cnt == 0 || nois_cnt == 0 || nois_int <= 0)
{
return 0;
}
return (sign_int / sign_cnt) / (nois_int / nois_cnt);
}
void QcMLFile::collectQCData(vector<ProteinIdentification>& prot_ids,
PeptideIdentificationList& pep_ids,
const FeatureMap& feature_map,
const ConsensusMap& consensus_map,
const String& inputfile_raw,
const bool remove_duplicate_features,
const MSExperiment& exp)
{
// fetch vocabularies
ControlledVocabulary cv;
cv.loadFromOBO("PSI-MS", File::find("/CV/psi-ms.obo"));
cv.loadFromOBO("QC", File::find("/CV/qc-cv.obo"));
cv.loadFromOBO("QC", File::find("/CV/qc-cv-legacy.obo"));
//-------------------------------------------------------------
// MS acquisition
//------------------------------------------------------------
String base_name = QFileInfo(QString::fromStdString(inputfile_raw)).baseName();
UInt min_mz = std::numeric_limits<UInt>::max();
UInt max_mz = 0;
std::map<Size, UInt> mslevelcounts;
registerRun(base_name,base_name); //TODO use UIDs
//---base MS aquisition qp
String msaq_ref = base_name + "_msaq";
QcMLFile::QualityParameter qp;
qp.id = msaq_ref; ///< Identifier
qp.cvRef = "QC"; ///< cv reference
qp.cvAcc = "QC:0000004";
try
{
const ControlledVocabulary::CVTerm& term = cv.getTerm(qp.cvAcc);
qp.name = term.name; ///< Name
}
catch (...)
{
qp.name = "mzML file"; ///< Name
}
addRunQualityParameter(base_name, qp);
//---file origin qp
qp = QcMLFile::QualityParameter();
qp.name = "mzML file"; ///< Name
qp.id = base_name + "_run_name"; ///< Identifier
qp.cvRef = "MS"; ///< cv reference
qp.cvAcc = "MS:1000577";
qp.value = base_name;
addRunQualityParameter(base_name, qp);
qp = QcMLFile::QualityParameter();
qp.name = "instrument model"; ///< Name
qp.id = base_name + "_instrument_name"; ///< Identifier
qp.cvRef = "MS"; ///< cv reference
qp.cvAcc = "MS:1000031";
qp.value = exp.getInstrument().getName();
addRunQualityParameter(base_name, qp);
qp = QcMLFile::QualityParameter();
qp.name = "completion time"; ///< Name
qp.id = base_name + "_date"; ///< Identifier
qp.cvRef = "MS"; ///< cv reference
qp.cvAcc = "MS:1000747";
qp.value = exp.getDateTime().getDate();
addRunQualityParameter(base_name, qp);
//---precursors and SN
QcMLFile::Attachment at;
at.cvRef = "QC"; ///< cv reference
at.cvAcc = "QC:0000044";
at.qualityRef = msaq_ref;
at.id = base_name + "_precursors"; ///< Identifier
try
{
const ControlledVocabulary::CVTerm& term = cv.getTerm(at.cvAcc);
at.name = term.name; ///< Name
}
catch (...)
{
at.name = "precursors"; ///< Name
}
at.colTypes.emplace_back("MS:1000894_[sec]"); // RT
at.colTypes.emplace_back("MS:1000040"); // MZ
at.colTypes.emplace_back("MS:1000041"); // charge
at.colTypes.emplace_back("S/N"); // S/N
at.colTypes.emplace_back("peak count"); // peak count
for (Size i = 0; i < exp.size(); ++i)
{
mslevelcounts[exp[i].getMSLevel()]++;
if (exp[i].getMSLevel() == 2)
{
if (exp[i].getPrecursors().front().getMZ() < min_mz)
{
min_mz = exp[i].getPrecursors().front().getMZ();
}
if (exp[i].getPrecursors().front().getMZ() > max_mz)
{
max_mz = exp[i].getPrecursors().front().getMZ();
}
std::vector<String> row;
row.emplace_back(exp[i].getRT());
row.emplace_back(exp[i].getPrecursors().front().getMZ());
row.emplace_back(exp[i].getPrecursors().front().getCharge());
row.emplace_back(calculateSNmedian(exp[i]));
row.emplace_back(exp[i].size());
at.tableRows.push_back(row);
}
}
addRunAttachment(base_name, at);
//---aquisition results qp
qp = QcMLFile::QualityParameter();
qp.cvRef = "QC"; ///< cv reference
qp.cvAcc = "QC:0000006"; ///< cv accession for "aquisition results"
qp.id = base_name + "_ms1aquisition"; ///< Identifier
qp.value = String(mslevelcounts[1]);
try
{
const ControlledVocabulary::CVTerm& term = cv.getTerm(qp.cvAcc);
qp.name = term.name; ///< Name
}
catch (...)
{
qp.name = "number of ms1 spectra"; ///< Name
}
addRunQualityParameter(base_name, qp);
qp = QcMLFile::QualityParameter();
qp.cvRef = "QC"; ///< cv reference
qp.cvAcc = "QC:0000007"; ///< cv accession for "aquisition results"
qp.id = base_name + "_ms2aquisition"; ///< Identifier
qp.value = String(mslevelcounts[2]);
try
{
const ControlledVocabulary::CVTerm& term = cv.getTerm(qp.cvAcc);
qp.name = term.name; ///< Name
}
catch (...)
{
qp.name = "number of ms2 spectra"; ///< Name
}
addRunQualityParameter(base_name, qp);
qp = QcMLFile::QualityParameter();
qp.cvRef = "QC"; ///< cv reference
qp.cvAcc = "QC:0000008"; ///< cv accession for "aquisition results"
qp.id = base_name + "_Chromaquisition"; ///< Identifier
qp.value = String(exp.getChromatograms().size());
try
{
const ControlledVocabulary::CVTerm& term = cv.getTerm(qp.cvAcc);
qp.name = term.name; ///< Name
}
catch (...)
{
qp.name = "number of chromatograms"; ///< Name
}
addRunQualityParameter(base_name, qp);
at = QcMLFile::Attachment();
at.cvRef = "QC"; ///< cv reference
at.cvAcc = "QC:0000009";
at.qualityRef = msaq_ref;
at.id = base_name + "_mzrange"; ///< Identifier
try
{
const ControlledVocabulary::CVTerm& term = cv.getTerm(at.cvAcc);
at.name = term.name; ///< Name
}
catch (...)
{
at.name = "MS MZ aquisition ranges"; ///< Name
}
at.colTypes.emplace_back("QC:0000010"); //MZ
at.colTypes.emplace_back("QC:0000011"); //MZ
std::vector<String> rowmz;
rowmz.emplace_back(min_mz);
rowmz.emplace_back(max_mz);
at.tableRows.push_back(rowmz);
addRunAttachment(base_name, at);
at = QcMLFile::Attachment();
at.cvRef = "QC"; ///< cv reference
at.cvAcc = "QC:0000012";
at.qualityRef = msaq_ref;
at.id = base_name + "_rtrange"; ///< Identifier
try
{
const ControlledVocabulary::CVTerm& term = cv.getTerm(at.cvAcc);
at.name = term.name; ///< Name
}
catch (...)
{
at.name = "MS RT aquisition ranges"; ///< Name
}
at.colTypes.emplace_back("QC:0000013"); //MZ
at.colTypes.emplace_back("QC:0000014"); //MZ
std::vector<String> rowrt;
rowrt.emplace_back(exp.begin()->getRT());
rowrt.emplace_back(exp.getSpectra().back().getRT());
at.tableRows.push_back(rowrt);
addRunAttachment(base_name, at);
//---ion current stability ( & tic ) qp
at = QcMLFile::Attachment();
at.cvRef = "QC"; ///< cv reference
at.cvAcc = "QC:0000022";
at.qualityRef = msaq_ref;
at.id = base_name + "_tics"; ///< Identifier
try
{
const ControlledVocabulary::CVTerm& term = cv.getTerm(at.cvAcc);
at.name = term.name; ///< Name
}
catch (...)
{
at.name = "MS TICs"; ///< Name
}
at.colTypes.emplace_back("MS:1000894_[sec]");
at.colTypes.emplace_back("MS:1000285");
Size below_10k = 0;
std::vector<OpenMS::Chromatogram> chroms = exp.getChromatograms();
if (!chroms.empty()) //real TIC from the mzML
{
for (Size t = 0; t < chroms.size(); ++t)
{
if (chroms[t].getChromatogramType() == ChromatogramSettings::ChromatogramType::TOTAL_ION_CURRENT_CHROMATOGRAM)
{
for (Size i = 0; i < chroms[t].size(); ++i)
{
double sum = chroms[t][i].getIntensity();
if (sum < 10000)
{
++below_10k;
}
std::vector<String> row;
row.emplace_back(chroms[t][i].getRT() * 60);
row.emplace_back(sum);
at.tableRows.push_back(row);
}
break; // what if there are more than one? should generally not be though ...
}
}
addRunAttachment(base_name, at);
qp = QcMLFile::QualityParameter();
qp.id = base_name + "_ticslump"; ///< Identifier
qp.cvRef = "QC"; ///< cv reference
qp.cvAcc = "QC:0000023";
qp.value = String((100 / exp.size()) * below_10k);
try
{
const ControlledVocabulary::CVTerm& term = cv.getTerm(qp.cvAcc);
qp.name = term.name; ///< Name
}
catch (...)
{
qp.name = "percentage of tic slumps"; ///< Name
}
addRunQualityParameter(base_name, qp);
}
// -- reconstructed TIC or RIC from the MS1 intensities
at = QcMLFile::Attachment();
at.cvRef = "QC"; ///< cv reference
at.cvAcc = "QC:0000056";
at.qualityRef = msaq_ref;
at.id = base_name + "_rics"; ///< Identifier
try
{
const ControlledVocabulary::CVTerm& term = cv.getTerm(at.cvAcc);
at.name = term.name; ///< Name
}
catch (...)
{
at.name = "MS RICs"; ///< Name
}
at.colTypes.emplace_back("MS:1000894_[sec]");
at.colTypes.emplace_back("MS:1000285");
at.colTypes.emplace_back("S/N");
at.colTypes.emplace_back("peak count");
Size prev = 0;
below_10k = 0;
Size jumps = 0;
Size drops = 0;
Size fact = 10;
for (Size i = 0; i < exp.size(); ++i)
{
if (exp[i].getMSLevel() == 1)
{
UInt sum = 0;
for (Size j = 0; j < exp[i].size(); ++j)
{
sum += exp[i][j].getIntensity();
}
if (prev > 0 && sum > fact * prev) // no jumps after complete drops (or [re]starts)
{
++jumps;
}
else if (sum < fact*prev)
{
++drops;
}
if (sum < 10000)
{
++below_10k;
}
prev = sum;
std::vector<String> row;
row.emplace_back(exp[i].getRT());
row.emplace_back(sum);
row.emplace_back(calculateSNmedian(exp[i]));
row.emplace_back(exp[i].size());
at.tableRows.push_back(row);
}
}
addRunAttachment(base_name, at);
qp = QcMLFile::QualityParameter();
qp.id = base_name + "_ricslump"; ///< Identifier
qp.cvRef = "QC"; ///< cv reference
qp.cvAcc = "QC:0000057";
qp.value = String((100 / exp.size()) * below_10k);
try
{
const ControlledVocabulary::CVTerm& term = cv.getTerm(qp.cvAcc);
qp.name = term.name; ///< Name
}
catch (...)
{
qp.name = "percentage of ric slumps"; ///< Name
}
addRunQualityParameter(base_name, qp);
qp = QcMLFile::QualityParameter();
qp.id = base_name + "_ricjump"; ///< Identifier
qp.cvRef = "QC"; ///< cv reference
qp.cvAcc = "QC:0000059";
qp.value = String(jumps);
try
{
const ControlledVocabulary::CVTerm& term = cv.getTerm(qp.cvAcc);
qp.name = term.name; ///< Name
}
catch (...)
{
qp.name = "IS-1A"; ///< Name
}
addRunQualityParameter(base_name, qp);
qp = QcMLFile::QualityParameter();
qp.id = base_name + "_ricdump"; ///< Identifier
qp.cvRef = "QC"; ///< cv reference
qp.cvAcc = "QC:0000060";
qp.value = String(drops);
try
{
const ControlledVocabulary::CVTerm& term = cv.getTerm(qp.cvAcc);
qp.name = term.name; ///< Name
}
catch (...)
{
qp.name = "IS-1B"; ///< Name
}
addRunQualityParameter(base_name, qp);
//---injection times MSn
at = QcMLFile::Attachment();
at.cvRef = "QC"; ///< cv reference
at.cvAcc = "QC:0000018";
at.qualityRef = msaq_ref;
at.id = base_name + "_ms2inj"; ///< Identifier
try
{
const ControlledVocabulary::CVTerm& term = cv.getTerm(at.cvAcc);
at.name = term.name; ///< Name
}
catch (...)
{
at.name = "MS2 injection time"; ///< Name
}
at.colTypes.emplace_back("MS:1000894_[sec]");
at.colTypes.emplace_back("MS:1000927");
for (Size i = 0; i < exp.size(); ++i)
{
if (exp[i].getMSLevel() > 1 && !exp[i].getAcquisitionInfo().empty())
{
for (Size j = 0; j < exp[i].getAcquisitionInfo().size(); ++j)
{
if (exp[i].getAcquisitionInfo()[j].metaValueExists("MS:1000927"))
{
std::vector<String> row;
row.emplace_back(exp[i].getRT());
row.emplace_back(exp[i].getAcquisitionInfo()[j].getMetaValue("MS:1000927"));
at.tableRows.push_back(row);
}
}
}
}
if (!at.tableRows.empty())
{
addRunAttachment(base_name, at);
}
//-------------------------------------------------------------
// MS id
//------------------------------------------------------------
if (!prot_ids.empty() && !pep_ids.empty())
{
ProteinIdentification::SearchParameters params = prot_ids[0].getSearchParameters();
vector<String> var_mods = params.variable_modifications;
//~ boost::regex re("(?<=[KR])(?=[^P])");
String msid_ref = base_name + "_msid";
QcMLFile::QualityParameter qp;
qp.id = msid_ref; ///< Identifier
qp.cvRef = "QC"; ///< cv reference
qp.cvAcc = "QC:0000025";
try
{
const ControlledVocabulary::CVTerm& term = cv.getTerm(qp.cvAcc);
qp.name = term.name; ///< Name
}
catch (...)
{
qp.name = "MS identification result details"; ///< Name
}
addRunQualityParameter(base_name, qp);
at = QcMLFile::Attachment();
at.cvRef = "QC"; ///< cv reference
at.cvAcc = "QC:0000026";
at.qualityRef = msid_ref;
at.id = base_name + "_idsetting"; ///< Identifier
try
{
const ControlledVocabulary::CVTerm& term = cv.getTerm(at.cvAcc);
at.name = term.name; ///< Name
}
catch (...)
{
at.name = "MS id settings"; ///< Name
}
at.colTypes.emplace_back("MS:1001013"); //MS:1001013 db name MS:1001016 version MS:1001020 taxonomy
at.colTypes.emplace_back("MS:1001016");
at.colTypes.emplace_back("MS:1001020");
std::vector<String> row;
row.emplace_back(prot_ids.front().getSearchParameters().db);
row.emplace_back(prot_ids.front().getSearchParameters().db_version);
row.emplace_back(prot_ids.front().getSearchParameters().taxonomy);
at.tableRows.push_back(row);
addRunAttachment(base_name, at);
UInt spectrum_count = 0;
Size peptide_hit_count = 0;
Size protein_hit_count = 0;
set<String> peptides;
set<String> proteins;
Size missedcleavages = 0;
for (Size i = 0; i < pep_ids.size(); ++i)
{
if (!pep_ids[i].empty())
{
++spectrum_count;
peptide_hit_count += pep_ids[i].getHits().size();
const vector<PeptideHit>& temp_hits = pep_ids[i].getHits();
for (Size j = 0; j < temp_hits.size(); ++j)
{
peptides.insert(temp_hits[j].getSequence().toString());
}
}
}
for (set<String>::iterator it = peptides.begin(); it != peptides.end(); ++it)
{
for (String::const_iterator st = it->begin(); st != it->end() - 1; ++st)
{
if (*st == 'K' || *st == 'R')
{
++missedcleavages;
}
}
}
for (Size i = 0; i < prot_ids.size(); ++i)
{
protein_hit_count += prot_ids[i].getHits().size();
const vector<ProteinHit>& temp_hits = prot_ids[i].getHits();
for (Size j = 0; j < temp_hits.size(); ++j)
{
proteins.insert(temp_hits[j].getAccession());
}
}
qp = QcMLFile::QualityParameter();
qp.cvRef = "QC"; ///< cv reference
qp.cvAcc = "QC:0000037"; ///< cv accession
qp.id = base_name + "_misscleave"; ///< Identifier
qp.value = missedcleavages;
try
{
const ControlledVocabulary::CVTerm& term = cv.getTerm(qp.cvAcc);
qp.name = term.name; ///< Name
}
catch (...)
{
qp.name = "total number of missed cleavages"; ///< Name
}
addRunQualityParameter(base_name, qp);
qp = QcMLFile::QualityParameter();
qp.cvRef = "QC"; ///< cv reference
qp.cvAcc = "QC:0000032"; ///< cv accession
qp.id = base_name + "_totprot"; ///< Identifier
qp.value = protein_hit_count;
try
{
const ControlledVocabulary::CVTerm& term = cv.getTerm(qp.cvAcc);
qp.name = term.name; ///< Name
}
catch (...)
{
qp.name = "total number of identified proteins"; ///< Name
}
addRunQualityParameter(base_name, qp);
qp = QcMLFile::QualityParameter();
qp.cvRef = "QC"; ///< cv reference
qp.cvAcc = "QC:0000033"; ///< cv accession
qp.id = base_name + "_totuniqprot"; ///< Identifier
qp.value = String(proteins.size());
try
{
const ControlledVocabulary::CVTerm& term = cv.getTerm(qp.cvAcc);
qp.name = term.name; ///< Name
}
catch (...)
{
qp.name = "total number of uniquely identified proteins"; ///< Name
}
addRunQualityParameter(base_name, qp);
qp = QcMLFile::QualityParameter();
qp.cvRef = "QC"; ///< cv reference
qp.cvAcc = "QC:0000029"; ///< cv accession
qp.id = base_name + "_psms"; ///< Identifier
qp.value = String(spectrum_count);
try
{
const ControlledVocabulary::CVTerm& term = cv.getTerm(qp.cvAcc);
qp.name = term.name; ///< Name
}
catch (...)
{
qp.name = "total number of PSM"; ///< Name
}
addRunQualityParameter(base_name, qp);
qp = QcMLFile::QualityParameter();
qp.cvRef = "QC"; ///< cv reference
qp.cvAcc = "QC:0000030"; ///< cv accession
qp.id = base_name + "_totpeps"; ///< Identifier
qp.value = String(peptide_hit_count);
try
{
const ControlledVocabulary::CVTerm& term = cv.getTerm(qp.cvAcc);
qp.name = term.name; ///< Name
}
catch (...)
{
qp.name = "total number of identified peptides"; ///< Name
}
addRunQualityParameter(base_name, qp);
qp = QcMLFile::QualityParameter();
qp.cvRef = "QC"; ///< cv reference
qp.cvAcc = "QC:0000031"; ///< cv accession
qp.id = base_name + "_totuniqpeps"; ///< Identifier
qp.value = String(peptides.size());
try
{
const ControlledVocabulary::CVTerm& term = cv.getTerm(qp.cvAcc);
qp.name = term.name; ///< Name
}
catch (...)
{
qp.name = "total number of uniquely identified peptides"; ///< Name
}
addRunQualityParameter(base_name, qp);
at = QcMLFile::Attachment();
at.cvRef = "QC"; ///< cv reference
at.cvAcc = "QC:0000038";
at.qualityRef = msid_ref;
at.id = base_name + "_massacc"; ///< Identifier
try
{
const ControlledVocabulary::CVTerm& term = cv.getTerm(at.cvAcc);
at.name = term.name; ///< Name
}
catch (...)
{
at.name = "delta ppm tables";
}
//~ delta ppm QC:0000039 RT MZ uniqueness ProteinID MS:1000885 target/decoy Score PeptideSequence MS:1000889 Annots string Similarity Charge UO:0000219 TheoreticalWeight UO:0000221 Oxidation_(M)
at.colTypes.emplace_back("RT");
at.colTypes.emplace_back("MZ");
at.colTypes.emplace_back("Score");
at.colTypes.emplace_back("PeptideSequence");
at.colTypes.emplace_back("Charge");
at.colTypes.emplace_back("TheoreticalWeight");
at.colTypes.emplace_back("delta_ppm");
// at.colTypes.push_back("S/N");
for (UInt w = 0; w < var_mods.size(); ++w)
{
at.colTypes.push_back(String(var_mods[w]).substitute(' ', '_'));
}
std::vector<double> deltas;
//~ prot_ids[0].getSearchParameters();
for (PeptideIdentification& pep_id : pep_ids)
{
if (!pep_id.getHits().empty())
{
std::vector<String> row;
row.emplace_back(pep_id.getRT());
row.emplace_back(pep_id.getMZ());
PeptideHit tmp = pep_id.getHits().front(); //N.B.: depends on score & sort
vector<UInt> pep_mods;
for (UInt w = 0; w < var_mods.size(); ++w)
{
pep_mods.push_back(0);
}
for (const Residue& z : tmp.getSequence())
{
Residue res = z;
String temp;
if (res.isModified() && res.getModificationName() != "Carbamidomethyl")
{
temp = res.getModificationName() + " (" + res.getOneLetterCode() + ")";
//cout<<res.getModification()<<endl;
for (UInt w = 0; w < var_mods.size(); ++w)
{
if (temp == var_mods[w])
{
//cout<<temp;
pep_mods[w] += 1;
}
}
}
}
row.emplace_back(tmp.getScore());
row.push_back(tmp.getSequence().toString().removeWhitespaces());
row.emplace_back(tmp.getCharge());
double mz = tmp.getSequence().getMZ(tmp.getCharge());
row.emplace_back(mz);
double dppm = (pep_id.getMZ()-mz)/(mz*(double)1e-6);
row.emplace_back(dppm);
deltas.push_back(dppm);
for (UInt w = 0; w < var_mods.size(); ++w)
{
row.emplace_back(pep_mods[w]);
}
at.tableRows.push_back(row);
}
}
addRunAttachment(base_name, at);
qp = QcMLFile::QualityParameter();
qp.cvRef = "QC"; ///< cv reference
qp.cvAcc = "QC:0000040"; ///< cv accession
qp.id = base_name + "_mean_delta"; ///< Identifier
qp.value = String(OpenMS::Math::mean(deltas.begin(), deltas.end()));
try
{
const ControlledVocabulary::CVTerm& term = cv.getTerm(qp.cvAcc);
qp.name = term.name; ///< Name
}
catch (...)
{
qp.name = "mean delta ppm"; ///< Name
}
addRunQualityParameter(base_name, qp);
qp = QcMLFile::QualityParameter();
qp.cvRef = "QC"; ///< cv reference
qp.cvAcc = "QC:0000041"; ///< cv accession
qp.id = base_name + "_median_delta"; ///< Identifier
qp.value = String(OpenMS::Math::median(deltas.begin(), deltas.end(), false));
try
{
const ControlledVocabulary::CVTerm& term = cv.getTerm(qp.cvAcc);
qp.name = term.name; ///< Name
}
catch (...)
{
qp.name = "median delta ppm"; ///< Name
}
addRunQualityParameter(base_name, qp);
qp = QcMLFile::QualityParameter();
qp.cvRef = "QC"; ///< cv reference
qp.cvAcc = "QC:0000035"; ///< cv accession
qp.id = base_name + "_ratio_id"; ///< Identifier
qp.value = String(double(pep_ids.size()) / double(mslevelcounts[2]));
try
{
const ControlledVocabulary::CVTerm& term = cv.getTerm(qp.cvAcc);
qp.name = term.name; ///< Name
}
catch (...)
{
qp.name = "id ratio"; ///< Name
}
addRunQualityParameter(base_name, qp);
}
//-------------------------------------------------------------
// MS quantitation
//------------------------------------------------------------
String msqu_ref = base_name + "_msqu";
if (!feature_map.empty())
{
qp = QcMLFile::QualityParameter();
qp.cvRef = "QC"; ///< cv reference
qp.cvAcc = "QC:0000045"; ///< cv accession
qp.id = msqu_ref; ///< Identifier
try
{
const ControlledVocabulary::CVTerm& term = cv.getTerm(qp.cvAcc);
qp.name = term.name; ///< Name
}
catch (...)
{
qp.name = "MS quantification result details"; ///< Name
}
addRunQualityParameter(base_name, qp);
qp = QcMLFile::QualityParameter();
qp.cvRef = "QC"; ///< cv reference
qp.cvAcc = "QC:0000046"; ///< cv accession
qp.id = base_name + "_feature_count"; ///< Identifier
qp.value = String(feature_map.size());
try
{
const ControlledVocabulary::CVTerm& term = cv.getTerm(qp.cvAcc);
qp.name = term.name; ///< Name
}
catch (...)
{
qp.name = "number of features"; ///< Name
}
addRunQualityParameter(base_name, qp);
}
if (!feature_map.empty() && !remove_duplicate_features)
{
QcMLFile::Attachment at;
at = QcMLFile::Attachment();
at.cvRef = "QC"; ///< cv reference
at.cvAcc = "QC:0000047";
at.qualityRef = msqu_ref;
at.id = base_name + "_features"; ///< Identifier
try
{
const ControlledVocabulary::CVTerm& term = cv.getTerm(at.cvAcc);
at.name = term.name; ///< Name
}
catch (...)
{
at.name = "features"; ///< Name
}
at.colTypes.emplace_back("MZ");
at.colTypes.emplace_back("RT");
at.colTypes.emplace_back("Intensity");
at.colTypes.emplace_back("Charge");
at.colTypes.emplace_back("Quality");
at.colTypes.emplace_back("FWHM");
at.colTypes.emplace_back("IDs");
UInt fiter = 0;
UInt ided = 0;
//ofstream out(outputfile_name.c_str());
while (fiter < feature_map.size())
{
std::vector<String> row;
row.emplace_back(feature_map[fiter].getMZ());
row.emplace_back(feature_map[fiter].getRT());
row.emplace_back(feature_map[fiter].getIntensity());
row.emplace_back(feature_map[fiter].getCharge());
row.emplace_back(feature_map[fiter].getOverallQuality());
row.emplace_back(feature_map[fiter].getWidth());
row.emplace_back(feature_map[fiter].getPeptideIdentifications().size());
if (!feature_map[fiter].getPeptideIdentifications().empty())
{
++ided;
}
fiter++;
at.tableRows.push_back(row);
}
addRunAttachment(base_name, at);
qp = QcMLFile::QualityParameter();
qp.cvRef = "QC"; ///< cv reference
qp.cvAcc = "QC:0000058"; ///< cv accession
qp.id = base_name + "_idfeature_count"; ///< Identifier
qp.value = ided;
try
{
const ControlledVocabulary::CVTerm& term = cv.getTerm(qp.cvAcc);
qp.name = term.name; ///< Name
}
catch (...)
{
qp.name = "number of identified features"; ///< Name
}
addRunQualityParameter(base_name, qp);
}
else if (!feature_map.empty() && remove_duplicate_features)
{
QcMLFile::Attachment at;
at = QcMLFile::Attachment();
at.cvRef = "QC"; ///< cv reference
at.cvAcc = "QC:0000047";
at.qualityRef = msqu_ref;
at.id = base_name + "_features"; ///< Identifier
try
{
const ControlledVocabulary::CVTerm& term = cv.getTerm(at.cvAcc);
at.name = term.name; ///< Name
}
catch (...)
{
at.name = "features"; ///< Name
}
at.colTypes.emplace_back("MZ");
at.colTypes.emplace_back("RT");
at.colTypes.emplace_back("Intensity");
at.colTypes.emplace_back("Charge");
FeatureMap map_out;
UInt fiter = 0;
while (fiter < feature_map.size())
{
FeatureMap map_tmp;
for (UInt k = fiter; k <= feature_map.size(); ++k)
{
if (abs(feature_map[fiter].getRT() - feature_map[k].getRT()) < 0.1)
{
//~ cout << fiter << endl;
map_tmp.push_back(feature_map[k]);
}
else
{
fiter = k;
break;
}
}
map_tmp.sortByMZ();
UInt retif = 1;
map_out.push_back(map_tmp[0]);
while (retif < map_tmp.size())
{
if (abs(map_tmp[retif].getMZ() - map_tmp[retif - 1].getMZ()) > 0.01)
{
cout << "equal RT, but mass different" << endl;
map_out.push_back(map_tmp[retif]);
}
retif++;
}
}
addRunAttachment(base_name, at);
}
if (!consensus_map.empty())
{
at = QcMLFile::Attachment();
qp.name = "consensuspoints"; ///< Name
//~ qp.id = base_name + "_consensuses"; ///< Identifier
qp.cvRef = "QC"; ///< cv reference
qp.cvAcc = "QC:xxxxxxxx"; ///< cv accession "feature mapper results"
at.colTypes.emplace_back("Native_spectrum_ID");
at.colTypes.emplace_back("DECON_RT_(sec)");
at.colTypes.emplace_back("DECON_MZ_(Th)");
at.colTypes.emplace_back("DECON_Intensity");
at.colTypes.emplace_back("Feature_RT_(sec)");
at.colTypes.emplace_back("Feature_MZ_(Th)");
at.colTypes.emplace_back("Feature_Intensity");
at.colTypes.emplace_back("Feature_Charge");
for (ConsensusMap::const_iterator cmit = consensus_map.begin(); cmit != consensus_map.end(); ++cmit)
{
const ConsensusFeature& CF = *cmit;
for (ConsensusFeature::const_iterator cfit = CF.begin(); cfit != CF.end(); ++cfit)
{
std::vector<String> row;
FeatureHandle FH = *cfit;
row.emplace_back(CF.getMetaValue("spectrum_native_id"));
row.emplace_back(CF.getRT()); row.emplace_back(CF.getMZ());
row.emplace_back(CF.getIntensity());
row.emplace_back(FH.getRT());
row.emplace_back(FH.getMZ());
row.emplace_back(FH.getCharge());
at.tableRows.push_back(row);
}
}
addRunAttachment(base_name, at);
}
}
void QcMLFile::store(const String& filename) const
{
//~ startProgress(0, 0, "storing qcML file");
//~ progress_ = 0;
//~ setProgress(++progress_);
//~ file should either contain the complete stylesheet injection (including the stylesheet file preamble, the DOCTYPE definition and the stylesheet itself) or be empty
std::string xslt = "";
std::string xslt_ref = "";
try
{
String xslt_file = File::find("XSL/QcML_report_sheet.xsl"); //TODO make this user defined pt.1
std::ifstream in(xslt_file.c_str());
xslt = std::string((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
xslt = xslt.erase(0, xslt.find('\n') + 1);
xslt_ref = "openms-qc-stylesheet"; //TODO make this user defined pt.2
}
catch (Exception::FileNotFound &)
{
warning(STORE, String("No qcml stylesheet found, result will not be viewable in a browser!"));
}
//open stream
ofstream os(filename.c_str());
if (!os)
{
throw Exception::UnableToCreateFile(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename);
}
os.precision(writtenDigits<double>(0.0));
//~ setProgress(++progress_);
//header & xslt
os << "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n";
if (!xslt_ref.empty())
{
os << R"(<?xml-stylesheet type="text/xml" href="#)" << xslt_ref << "\"?>\n";
os << "<!DOCTYPE catelog [\n"
<< " <!ATTLIST xsl:stylesheet\n"
<< " id ID #REQUIRED>\n"
<< " ]>\n";
}
os << "<qcML xmlns=\"https://github.com/qcML/qcml\" >\n"; //TODO creation date into schema!!
//content runs
std::set<String> keys;
for (std::map<String, std::vector<QualityParameter> >::const_iterator it = runQualityQPs_.begin(); it != runQualityQPs_.end(); ++it)
{
keys.insert(it->first);
}
for (std::map<String, std::vector<Attachment> >::const_iterator it = runQualityAts_.begin(); it != runQualityAts_.end(); ++it)
{
keys.insert(it->first);
}
if (!keys.empty())
{
for (std::set<String>::const_iterator it = keys.begin(); it != keys.end(); ++it)
{
os << "\t<runQuality ID=\"" << String(*it) << "\">\n";
std::map<String, std::vector<QualityParameter> >::const_iterator qpsit = runQualityQPs_.find(*it);
if (qpsit != runQualityQPs_.end())
{
for (std::vector<QcMLFile::QualityParameter>::const_iterator qit = qpsit->second.begin(); qit != qpsit->second.end(); ++qit)
{
os << qit->toXMLString(4);
}
}
std::map<String, std::vector<Attachment> >::const_iterator attit = runQualityAts_.find(*it);
if (attit != runQualityAts_.end())
{
for (std::vector<QcMLFile::Attachment>::const_iterator ait = attit->second.begin(); ait != attit->second.end(); ++ait)
{
os << ait->toXMLString(4); //TODO check integrity of reference to qp!
}
}
os << "\t</runQuality>\n";
}
}
//content sets
keys.clear();
for (std::map<String, std::vector<QualityParameter> >::const_iterator it = setQualityQPs_.begin(); it != setQualityQPs_.end(); ++it)
{
keys.insert(it->first);
}
for (std::map<String, std::vector<Attachment> >::const_iterator it = setQualityAts_.begin(); it != setQualityAts_.end(); ++it)
{
keys.insert(it->first);
}
if (!keys.empty())
{
for (std::set<String>::const_iterator it = keys.begin(); it != keys.end(); ++it)
{
os << "\t<setQuality ID=\"" << String(*it) << "\">\n";
//~ TODO warn if key has no entries in members_
//document set members
std::map<String, std::set<String> >::const_iterator jt = setQualityQPs_members_.find(*it);
if (jt != setQualityQPs_members_.end())
{
for (std::set<String>::const_iterator kt = jt->second.begin(); kt != jt->second.end(); ++kt)
{
std::map<String, std::vector<QualityParameter> >::const_iterator rq = runQualityQPs_.find(*kt);
if (rq != runQualityQPs_.end())
{
QcMLFile::QualityParameter qp;
qp.id = *kt; ///< Identifier
qp.name = "set name"; ///< Name
qp.cvRef = "QC"; ///< cv reference
qp.cvAcc = "QC:0000005";
for (const QualityParameter& qit : rq->second)
{
if (qit.cvAcc == "MS:1000577")
{
qp.value = qit.value;
}
}
os << qp.toXMLString(4);
}
else
{
//TODO warn - no mzML file registered for this run
}
}
}
std::map<String, std::vector<QualityParameter> >::const_iterator qpsit = setQualityQPs_.find(*it);
if (qpsit != setQualityQPs_.end())
{
for (const QcMLFile::QualityParameter& qit : qpsit->second)
{
os << qit.toXMLString(4);
}
}
std::map<String, std::vector<Attachment> >::const_iterator attit = setQualityAts_.find(*it);
if (attit != setQualityAts_.end())
{
for (const QcMLFile::Attachment& ait : attit->second)
{
os << ait.toXMLString(4);
}
}
os << "\t</setQuality>\n";
}
}
os << "\t<cvList>\n";
os << "\t<cv uri=\"http://psidev.cvs.sourceforge.net/viewvc/psidev/psi/psi-ms/mzML/controlledVocabulary/psi-ms.obo\" ID=\"psi_cv_ref\" fullName=\"PSI-MS\" version=\"3.41.0\"/>\n";
os << "\t<cv uri=\"https://github.com/qcML/qcML-development/blob/master/cv/qc-cv.obo\" ID=\"qc_cv_ref\" fullName=\"QC-CV\" version=\"0.1.1\"/>\n";
os << "\t<cv uri=\"http://obo.cvs.sourceforge.net/viewvc/obo/obo/ontology/phenotype/unit.obo\" ID=\"uo_cv_ref\" fullName=\"unit\" version=\"1.0.0\"/>\n";
os << "\t</cvList>\n";
if (!xslt_ref.empty())
{
os << xslt << "\n";
}
os << "</qcML>\n";
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/PepNovoInfile.cpp | .cpp | 4,491 | 167 | // 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/PepNovoInfile.h>
#include <OpenMS/CHEMISTRY/ModificationsDB.h>
#include <OpenMS/MATH/MathFunctions.h>
#include <fstream>
using namespace std;
namespace OpenMS
{
PepNovoInfile::PepNovoInfile() = default;
PepNovoInfile::PepNovoInfile(const PepNovoInfile& pepnovo_infile)
{
mods_ = pepnovo_infile.mods_;
mods_and_keys_ = pepnovo_infile.mods_and_keys_;
ptm_file_ = pepnovo_infile.ptm_file_;
}
PepNovoInfile::~PepNovoInfile() = default;
PepNovoInfile& PepNovoInfile::operator=(const PepNovoInfile& pepnovo_infile)
{
if (this != &pepnovo_infile)
{
mods_ = pepnovo_infile.mods_;
mods_and_keys_ = pepnovo_infile.mods_and_keys_;
ptm_file_ = pepnovo_infile.ptm_file_;
}
return *this;
}
bool PepNovoInfile::operator==(const PepNovoInfile& pepnovo_infile) const
{
if (this != &pepnovo_infile)
{
//return ( PTMname_residues_mass_type_ == pepnovo_infile.getModifications() );
return mods_ == pepnovo_infile.mods_;
}
return true;
}
String PepNovoInfile::handlePTMs_(const String& modification, const bool variable)
{
String locations, key, type;
ResidueModification::TermSpecificity ts = ModificationsDB::getInstance()->getModification(modification)->getTermSpecificity();
String origin = ModificationsDB::getInstance()->getModification(modification)->getOrigin();
double mass = ModificationsDB::getInstance()->getModification(modification)->getDiffMonoMass();
String full_name = ModificationsDB::getInstance()->getModification(modification)->getFullName();
String full_id = ModificationsDB::getInstance()->getModification(modification)->getFullId();
if (variable)
{
type = "OPTIONAL";
}
else
{
type = "FIXED";
}
switch (ts)
{
case ResidueModification::C_TERM: locations = "C_TERM";
break;
case ResidueModification::N_TERM: locations = "N_TERM";
break;
case ResidueModification::ANYWHERE: locations = "ALL";
break;
default: throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Invalid term specificity", String(ts));
}
if (ts == ResidueModification::C_TERM)
{
key = "$";
}
else if (ts == ResidueModification::N_TERM)
{
key = "^";
}
//cout<<"origin: "<<origin<<" loc: "<<locations<<endl;
if ((ts == ResidueModification::C_TERM) && (origin == "X"))
{
origin = "C_TERM";
}
else if ((ts == ResidueModification::N_TERM) && (origin == "X"))
{
origin = "N_TERM";
}
else
{
key = origin;
}
if (mass >= 0)
{
key += "+";
}
key += String(int(Math::round(mass)));
String line = "";
line += origin.toUpper();
line += "\t";
line += mass;
line += "\t";
line += type;
line += "\t";
line += locations;
line += "\t";
line += key;
line += "\t";
line += full_name;
mods_and_keys_[key] = full_id;
return line;
}
void PepNovoInfile::store(const String& filename)
{
ptm_file_.store(filename);
}
void PepNovoInfile::setModifications(const StringList& fixed_mods, const StringList& variable_mods)
{
mods_.setModifications(fixed_mods, variable_mods);
mods_and_keys_.clear();
//TextFile ptm_file_;
ptm_file_.addLine("#AA\toffset\ttype\tlocations\tsymbol\tPTM\tname");
// fixed modifications
std::set<String> fixed_modifications = mods_.getFixedModificationNames();
for (std::set<String>::const_iterator it = fixed_modifications.begin(); it != fixed_modifications.end(); ++it)
{
ptm_file_.addLine(handlePTMs_(*it, false));
}
// variable modifications
std::set<String> variable_modifications = mods_.getVariableModificationNames();
for (std::set<String>::const_iterator it = variable_modifications.begin(); it != variable_modifications.end(); ++it)
{
ptm_file_.addLine(handlePTMs_(*it, true));
}
}
void PepNovoInfile::getModifications(std::map<String, String>& modification_key_map) const
{
modification_key_map = mods_and_keys_;
}
} //namespace
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/MRMFeatureQCFile.cpp | .cpp | 11,475 | 291 | // 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/CsvFile.h>
#include <OpenMS/FORMAT/MRMFeatureQCFile.h>
#include <OpenMS/ANALYSIS/OPENSWATH/MRMFeatureQC.h>
#include <OpenMS/SYSTEM/File.h>
#include <OpenMS/DATASTRUCTURES/StringListUtils.h>
#include <boost/regex.hpp>
namespace OpenMS
{
void MRMFeatureQCFile::load(const String& filename, MRMFeatureQC& mrmfqc, const bool is_component_group) const
{
CsvFile csv(filename, ',', false, -1);
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
}
if (!is_component_group) // load component file
{
mrmfqc.component_qcs.clear();
for (Size i = 1; i < csv.rowCount(); ++i)
{
csv.getRow(i, sl);
pushValuesFromLine_(sl, headers, mrmfqc.component_qcs);
}
}
else // load component group file
{
mrmfqc.component_group_qcs.clear();
for (Size i = 1; i < csv.rowCount(); ++i)
{
csv.getRow(i, sl);
pushValuesFromLine_(sl, headers, mrmfqc.component_group_qcs);
}
}
}
void MRMFeatureQCFile::pushValuesFromLine_(
const StringList& line,
const std::map<String, Size>& headers,
std::vector<MRMFeatureQC::ComponentQCs>& c_qcs
) const
{
MRMFeatureQC::ComponentQCs c;
c.component_name = getCastValue_(headers, line, "component_name", "");
if (c.component_name.empty()) return;
c.retention_time_l = getCastValue_(headers, line, "retention_time_l", 0.0);
c.retention_time_u = getCastValue_(headers, line, "retention_time_u", 1e12);
c.intensity_l = getCastValue_(headers, line, "intensity_l", 0.0);
c.intensity_u = getCastValue_(headers, line, "intensity_u", 1e12);
c.overall_quality_l = getCastValue_(headers, line, "overall_quality_l", 0.0);
c.overall_quality_u = getCastValue_(headers, line, "overall_quality_u", 1e12);
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("metaValue_(.+)_(l|u)"))) // capture the metavalue name and the boundary and save them to m[1] and m[2]
{
setPairValue_(String(m[1]), line[i], String(m[2]), c.meta_value_qc);
}
}
c_qcs.push_back(c);
}
void MRMFeatureQCFile::pushValuesFromLine_(
const StringList& line,
const std::map<String, Size>& headers,
std::vector<MRMFeatureQC::ComponentGroupQCs>& cg_qcs
) const
{
MRMFeatureQC::ComponentGroupQCs cg;
cg.component_group_name = getCastValue_(headers, line, "component_group_name", "");
if (cg.component_group_name.empty())
{
return;
}
cg.retention_time_l = getCastValue_(headers, line, "retention_time_l", 0.0);
cg.retention_time_u = getCastValue_(headers, line, "retention_time_u", 1e12);
cg.intensity_l = getCastValue_(headers, line, "intensity_l", 0.0);
cg.intensity_u = getCastValue_(headers, line, "intensity_u", 1e12);
cg.overall_quality_l = getCastValue_(headers, line, "overall_quality_l", 0.0);
cg.overall_quality_u = getCastValue_(headers, line, "overall_quality_u", 1e12);
cg.n_heavy_l = getCastValue_(headers, line, "n_heavy_l", 0);
cg.n_heavy_u = getCastValue_(headers, line, "n_heavy_u", 100);
cg.n_light_l = getCastValue_(headers, line, "n_light_l", 0);
cg.n_light_u = getCastValue_(headers, line, "n_light_u", 100);
cg.n_detecting_l = getCastValue_(headers, line, "n_detecting_l", 0);
cg.n_detecting_u = getCastValue_(headers, line, "n_detecting_u", 100);
cg.n_quantifying_l = getCastValue_(headers, line, "n_quantifying_l", 0);
cg.n_quantifying_u = getCastValue_(headers, line, "n_quantifying_u", 100);
cg.n_identifying_l = getCastValue_(headers, line, "n_identifying_l", 0);
cg.n_identifying_u = getCastValue_(headers, line, "n_identifying_u", 100);
cg.n_transitions_l = getCastValue_(headers, line, "n_transitions_l", 0);
cg.n_transitions_u = getCastValue_(headers, line, "n_transitions_u", 100);
cg.ion_ratio_pair_name_1 = getCastValue_(headers, line, "ion_ratio_pair_name_1", "");
cg.ion_ratio_pair_name_2 = getCastValue_(headers, line, "ion_ratio_pair_name_2", "");
cg.ion_ratio_l = getCastValue_(headers, line, "ion_ratio_l", 0.0);
cg.ion_ratio_u = getCastValue_(headers, line, "ion_ratio_u", 1e12);
cg.ion_ratio_feature_name = getCastValue_(headers, line, "ion_ratio_feature_name", "");
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("metaValue_(.+)_(l|u)"))) // capture the metavalue name and the boundary and save them to m[1] and m[2]
{
setPairValue_(String(m[1]), line[i], String(m[2]), cg.meta_value_qc);
}
}
cg_qcs.push_back(cg);
}
void MRMFeatureQCFile::setPairValue_(
const String& key,
const String& value,
const String& boundary,
std::map<String, std::pair<double,double>>& meta_values_qc
) const
{
std::map<String, std::pair<double,double>>::iterator it = meta_values_qc.find(key);
const double cast_value = value.empty() ? (boundary == "l" ? 0.0 : 1e12) : std::stod(value);
if (it != meta_values_qc.end())
{
if (boundary == "l") it->second.first = cast_value;
else it->second.second = cast_value;
}
else
{
meta_values_qc[key] = boundary == "l"
? std::make_pair(cast_value, 1e12)
: std::make_pair(0.0, cast_value);
}
}
Int MRMFeatureQCFile::getCastValue_(
const std::map<String, Size>& headers,
const StringList& line,
const String& header,
const Int default_value
) const
{
std::map<String, Size>::const_iterator it = headers.find(header);
return it != headers.end() && !line[it->second].empty()
? std::stoi(line[it->second])
: default_value;
}
double MRMFeatureQCFile::getCastValue_(
const std::map<String, Size>& headers,
const StringList& line,
const String& header,
const double default_value
) const
{
std::map<String, Size>::const_iterator it = headers.find(header);
return it != headers.end() && !line[it->second].empty()
? std::stod(line[it->second])
: default_value;
}
String MRMFeatureQCFile::getCastValue_(
const std::map<String, Size>& headers,
const StringList& line,
const String& header,
const String& default_value
) const
{
std::map<String, Size>::const_iterator it = headers.find(header);
return it != headers.end() && !line[it->second].empty()
? line[it->second]
: default_value;
}
void MRMFeatureQCFile::store(const String & filename, const MRMFeatureQC & mrmfqc, const bool is_component_group)
{
if (is_component_group)
{
if (mrmfqc.component_group_qcs.empty()) return;
// Store the ComponentGroupQCs
clear(); // clear the buffer_
// Make the ComponentGroupQCs headers
StringList headers = { "component_group_name", "retention_time_l", "retention_time_u", "intensity_l", "intensity_u", "overall_quality_l", "overall_quality_u",
"n_heavy_l", "n_heavy_u", "n_light_l", "n_light_u", "n_detecting_l", "n_detecting_u", "n_quantifying_l", "n_quantifying_u", "n_identifying_l", "n_identifying_u", "n_transitions_l", "n_transitions_u",
"ion_ratio_pair_name_1", "ion_ratio_pair_name_2", "ion_ratio_l", "ion_ratio_u", "ion_ratio_feature_name" };
for (const auto& meta_data : mrmfqc.component_group_qcs.at(0).meta_value_qc)
{
headers.push_back("metaValue_" + meta_data.first + "_l");
headers.push_back("metaValue_" + meta_data.first + "_u");
}
addRow(headers);
// Make the ComponentGroupQCs rows
for (const auto& component_qc : mrmfqc.component_group_qcs)
{
StringList row(headers.size());
row[0] = component_qc.component_group_name;
row[1] = component_qc.retention_time_l;
row[2] = component_qc.retention_time_u;
row[3] = component_qc.intensity_l;
row[4] = component_qc.intensity_u;
row[5] = component_qc.overall_quality_l;
row[6] = component_qc.overall_quality_u;
row[7] = component_qc.n_heavy_l;
row[8] = component_qc.n_heavy_u;
row[9] = component_qc.n_light_l;
row[10] = component_qc.n_light_u;
row[11] = component_qc.n_detecting_l;
row[12] = component_qc.n_detecting_u;
row[13] = component_qc.n_quantifying_l;
row[14] = component_qc.n_quantifying_u;
row[15] = component_qc.n_identifying_l;
row[16] = component_qc.n_identifying_u;
row[17] = component_qc.n_transitions_l;
row[18] = component_qc.n_transitions_u;
row[19] = component_qc.ion_ratio_pair_name_1;
row[20] = component_qc.ion_ratio_pair_name_2;
row[21] = component_qc.ion_ratio_l;
row[22] = component_qc.ion_ratio_u;
row[23] = component_qc.ion_ratio_feature_name;
size_t meta_data_iter = 24;
for (const auto& meta_data : component_qc.meta_value_qc) {
row[meta_data_iter] = meta_data.second.first;
++meta_data_iter;
row[meta_data_iter] = meta_data.second.second;
++meta_data_iter;
}
addRow(row);
}
CsvFile::store(filename);
}
else
{
if (mrmfqc.component_qcs.empty()) return;
// Store the ComponentQCs
clear(); // clear the buffer_
// Make the ComponentQCs headers
StringList headers = { "component_name","retention_time_l","retention_time_u","intensity_l","intensity_u","overall_quality_l","overall_quality_u" };
for (const auto& meta_data : mrmfqc.component_qcs.at(0).meta_value_qc)
{
headers.push_back("metaValue_" + meta_data.first + "_l");
headers.push_back("metaValue_" + meta_data.first + "_u");
}
addRow(headers);
// Make the ComponentQCs rows
for (const auto& component_qc : mrmfqc.component_qcs)
{
StringList row(headers.size());
row[0] = component_qc.component_name;
row[1] = component_qc.retention_time_l;
row[2] = component_qc.retention_time_u;
row[3] = component_qc.intensity_l;
row[4] = component_qc.intensity_u;
row[5] = component_qc.overall_quality_l;
row[6] = component_qc.overall_quality_u;
size_t meta_data_iter = 7;
for (const auto& meta_data : component_qc.meta_value_qc)
{
row[meta_data_iter] = meta_data.second.first;
++meta_data_iter;
row[meta_data_iter] = meta_data.second.second;
++meta_data_iter;
}
addRow(row);
}
CsvFile::store(filename);
}
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/ParamJSONFile.cpp | .cpp | 10,826 | 328 | // 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/CONCEPT/LogStream.h>
#include <OpenMS/FORMAT/ParamJSONFile.h>
#include <OpenMS/SYSTEM/File.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
{
bool ParamJSONFile::load(const std::string& filename, Param& param)
{
// 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::ifstream ifs {filename};
if (!ifs.good())
{
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);
}
}
try
{
json jsonNode = json::parse(std::ifstream {filename});
auto traverseJSONTree = std::function<void(std::string currentKey, json& node)>{};
traverseJSONTree = [&](std::string currentKey, json& node) {
if (!node.is_object())
{
std::string msg = "Ignoring JSON file '" + filename + "' because of unexpected data type. Expecting a dictionary as type.";
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "", msg);
}
for (const auto& child : node.items())
{
auto key = currentKey + replaceAll(child.key(), "__", ":"); // This converts __ to ':', but ':' would also be an accepted delimiter
auto node = child.value();
if (node.is_null())
{
continue; // No value given
}
// If class member exists with some string, we assume it is a file type annotation
if (node.is_object() && (!node.contains("class") || !node["class"].is_string())) {
traverseJSONTree(key + ":", node);
continue;
}
if (!param.exists(key))
{
std::string msg = "Parameter " + key + " passed to '" + traces.front().name + "' is invalid. To prevent usage of wrong defaults, please update/fix the parameters!";
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "", msg);
}
auto const& entry = param.getEntry(key);
auto value = entry.value;
if (entry.value.valueType() == ParamValue::ValueType::STRING_VALUE)
{
if ((entry.valid_strings.size() == 2 && entry.valid_strings[0] == "true" && entry.valid_strings[1] == "false") ||
(entry.valid_strings.size() == 2 && entry.valid_strings[0] == "false" && entry.valid_strings[1] == "true"))
{
value = node.get<bool>() ? "true" : "false";
}
else if (entry.tags.count("input file"))
{
// If this is an input file and 'is_executable' is set. this can be of 'class: File' or 'type: string'
if (entry.tags.count("is_executable"))
{
if (node.is_object())
{
value = node["path"].get<std::string>();
}
else
{
value = node.get<std::string>();
}
}
// Just a normal input file
else
{
value = node["path"].get<std::string>();
}
}
else
{
value = node.get<std::string>();
}
}
else if (entry.value.valueType() == ParamValue::ValueType::INT_VALUE)
{
value = node.get<int64_t>();
}
else if (entry.value.valueType() == ParamValue::ValueType::DOUBLE_VALUE)
{
value = node.get<double>();
}
else if (entry.value.valueType() == ParamValue::ValueType::STRING_LIST)
{
if (entry.tags.count("input file"))
{
value = node["path"].get<std::vector<std::string>>();
}
else
{
value = node.get<std::vector<std::string>>();
}
}
else if (entry.value.valueType() == ParamValue::ValueType::INT_LIST)
{
value = node.get<std::vector<int>>();
}
else if (entry.value.valueType() == ParamValue::ValueType::DOUBLE_LIST)
{
value = node.get<std::vector<double>>();
}
else if (entry.value.valueType() == ParamValue::ValueType::EMPTY_VALUE)
{
// Nothing happens here
OPENMS_LOG_WARN << "Ignoring entry '" << key << "' because of unknown type 'EMPTY_VALUE'." << std::endl;
}
param.setValue(key, value);
}
};
traverseJSONTree(toolNamespace, jsonNode);
}
catch (const json::exception& e)
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "", e.what());
return false;
}
return true;
}
void ParamJSONFile::store(const std::string& filename, const Param& param, const ToolInfo&) const
{
std::ofstream os;
std::ostream* os_ptr;
if (filename != "-")
{
os.open(filename.c_str(), std::ofstream::out);
if (!os)
{
throw Exception::FileNotWritable(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename);
}
os_ptr = &os;
}
else
{
os_ptr = &std::cout;
}
writeToStream(os_ptr, param);
}
void ParamJSONFile::writeToStream(std::ostream* os_ptr, const Param& param) const
{
#if defined(ENABLE_TDL)
std::ostream& os = *os_ptr;
// 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 {});
json jsonDoc{};
auto param_it = param.begin();
for (auto last = param.end(); param_it != last; ++param_it)
{
for (auto& trace : param_it.getTrace())
{
if (trace.opened)
{
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 trags to tdl compatible tags
std::set<std::string> tags;
for (auto const& t : param_it->tags)
{
if (t == "input file")
{
tags.insert("file");
}
else if (t == "output file")
{
tags.insert("file");
tags.insert("output");
}
else if (t == "output prefix")
{
tags.insert("output");
tags.insert("prefixed");
}
else
{
tags.insert(t);
}
}
// Sets a single value into the tdl library
auto name = param_it->name;
if (stack.size() > 2) {
json node{};
switch (param_it->value.valueType())
{
case ParamValue::INT_VALUE:
node = static_cast<int64_t>(param_it->value);
break;
case ParamValue::DOUBLE_VALUE:
node = static_cast<double>(param_it->value);
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->valid_strings.size() == 2 && param_it->valid_strings[0] == "false" && param_it->valid_strings[1] == "true"))
{
node = param_it->value.toBool();
} else {
if (tags.count("file") > 0 && tags.count("output") == 0) {
node["class"] = "File";
node["path"] = param_it->value.toString();
} else {
node = param_it->value.toString();
}
}
break;
case ParamValue::INT_LIST:
node = param_it->value.toIntVector();
break;
case ParamValue::DOUBLE_LIST:
node = param_it->value.toDoubleVector();
break;
case ParamValue::STRING_LIST:
if (tags.count("file") > 0 && tags.count("output") == 0) {
node["class"] = "File";
node["path"] = param_it->value.toStringVector();
} else {
node = param_it->value.toStringVector();
}
break;
default:
break;
}
// Add newly created node to json document
if (!flatHierarchy) {
// Traverse to the correct node
auto* parent = &jsonDoc;
for (size_t i{3}; i < stack.size(); ++i) {
parent = &(*parent)[stack[i].name];
}
(*parent)[name] = node;
} else {
// Expand name to include all namespaces
for (size_t i{0}; i < stack.size()-3; ++i) {
auto const& e = stack[stack.size()-1-i];
name = e.name + "__" + name;
}
jsonDoc[name] = node;
}
}
}
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);
os << jsonDoc.dump(2);
#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/AbsoluteQuantitationMethodFile.cpp | .cpp | 6,841 | 172 | // 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/AbsoluteQuantitationMethodFile.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <fstream>
#include <boost/regex.hpp>
namespace OpenMS
{
void AbsoluteQuantitationMethodFile::load(const String & filename, std::vector<AbsoluteQuantitationMethod> & aqm_list)
{
aqm_list.clear();
CsvFile::load(filename, ',', false, -1);
std::map<String, Size> headers;
StringList sl;
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 (!( // if any of these headers is missing, warn the user
headers.count("IS_name") &&
headers.count("component_name") &&
headers.count("feature_name") &&
headers.count("concentration_units") &&
headers.count("llod") &&
headers.count("ulod") &&
headers.count("lloq") &&
headers.count("uloq") &&
headers.count("correlation_coefficient") &&
headers.count("n_points") &&
headers.count("transformation_model")
))
{
OPENMS_LOG_WARN << "One or more of the following columns are missing:\n";
OPENMS_LOG_WARN << "IS_name\n";
OPENMS_LOG_WARN << "component_name\n";
OPENMS_LOG_WARN << "feature_name\n";
OPENMS_LOG_WARN << "concentration_units\n";
OPENMS_LOG_WARN << "llod\n";
OPENMS_LOG_WARN << "ulod\n";
OPENMS_LOG_WARN << "lloq\n";
OPENMS_LOG_WARN << "uloq\n";
OPENMS_LOG_WARN << "correlation_coefficient\n";
OPENMS_LOG_WARN << "n_points\n";
OPENMS_LOG_WARN << "transformation_model\n" << std::endl;
}
}
for (Size i = 1; i < rowCount(); ++i)
{
getRow(i, sl);
AbsoluteQuantitationMethod aqm;
parseLine_(sl, headers, aqm);
aqm_list.push_back(aqm);
}
}
void AbsoluteQuantitationMethodFile::parseLine_(
const StringList & line,
const std::map<String, Size> & headers,
AbsoluteQuantitationMethod & aqm
) const
{
StringList tl = line; // trimmed line
for (String& s : tl)
{
s.trim();
}
aqm.setComponentName(headers.count("component_name") ? tl[headers.at("component_name")] : "");
aqm.setFeatureName(headers.count("feature_name") ? tl[headers.at("feature_name")] : "");
aqm.setISName(headers.count("IS_name") ? tl[headers.at("IS_name")] : "");
aqm.setLLOD(!headers.count("llod") || tl[headers.at("llod")].empty() ? 0 : std::stod(tl[headers.at("llod")]));
aqm.setULOD(!headers.count("ulod") || tl[headers.at("ulod")].empty() ? 0 : std::stod(tl[headers.at("ulod")]));
aqm.setLLOQ(!headers.count("lloq") || tl[headers.at("lloq")].empty() ? 0 : std::stod(tl[headers.at("lloq")]));
aqm.setULOQ(!headers.count("uloq") || tl[headers.at("uloq")].empty() ? 0 : std::stod(tl[headers.at("uloq")]));
aqm.setConcentrationUnits(headers.count("concentration_units") ? tl[headers.at("concentration_units")] : "");
aqm.setNPoints(!headers.count("n_points") || tl[headers.at("n_points")].empty() ? 0 : std::stoi(tl[headers.at("n_points")]));
aqm.setCorrelationCoefficient(
!headers.count("correlation_coefficient") || tl[headers.at("correlation_coefficient")].empty()
? 0
: std::stod(tl[headers.at("correlation_coefficient")])
);
aqm.setTransformationModel(headers.count("transformation_model") ? tl[headers.at("transformation_model")] : "");
Param tm_params;
for (const std::pair<const String, Size>& h : headers)
{
const String& header = h.first;
const Size& i = h.second;
boost::smatch m;
if (boost::regex_search(header, m, boost::regex("transformation_model_param_(.+)")))
{
setCastValue_(String(m[1]), tl[i], tm_params);
}
}
aqm.setTransformationModelParams(tm_params);
}
void AbsoluteQuantitationMethodFile::store(
const String& filename,
const std::vector<AbsoluteQuantitationMethod>& aqm_list
)
{
clear(); // clear the buffer_
const String headers = "IS_name,component_name,feature_name,concentration_units,llod,ulod,lloq,uloq,correlation_coefficient,n_points,transformation_model";
StringList split_headers;
headers.split(',', split_headers);
StringList tm_params_names; // transformation model params
if (!aqm_list.empty())
{
const Param tm_params = aqm_list[0].getTransformationModelParams();
for (const Param::ParamEntry& param : tm_params)
{
tm_params_names.insert(tm_params_names.begin(), param.name);
split_headers.insert(split_headers.begin() + 11, "transformation_model_param_" + param.name);
}
}
addRow(split_headers);
for (const AbsoluteQuantitationMethod& aqm : aqm_list)
{
StringList row(split_headers.size());
row[0] = aqm.getISName();
row[1] = aqm.getComponentName();
row[2] = aqm.getFeatureName();
row[3] = aqm.getConcentrationUnits();
row[4] = aqm.getLLOD();
row[5] = aqm.getULOD();
row[6] = aqm.getLLOQ();
row[7] = aqm.getULOQ();
row[8] = aqm.getCorrelationCoefficient();
row[9] = aqm.getNPoints();
row[10] = aqm.getTransformationModel();
const Param tm_params = aqm.getTransformationModelParams();
for (Size i = 0, j = 11; i < tm_params_names.size(); ++i, ++j)
{
row[j] = tm_params.exists(tm_params_names[i]) ? tm_params.getValue(tm_params_names[i]).toString() : "";
}
addRow(row);
}
CsvFile::store(filename);
}
void AbsoluteQuantitationMethodFile::setCastValue_(const String& key, const String& value, Param& params) const
{
const std::vector<String> param_doubles {
"slope", "intercept", "wavelength", "span", "delta", "x_datum_min", "y_datum_min", "x_datum_max", "y_datum_max"
};
const std::vector<String> param_ints {"num_nodes", "boundary_condition", "num_iterations"};
if (std::find(param_doubles.begin(), param_doubles.end(), key) != param_doubles.end())
{
params.setValue(key, value.empty() ? 0 : std::stod(value));
}
else if (std::find(param_ints.begin(), param_ints.end(), key) != param_ints.end())
{
params.setValue(key, value.empty() ? 0 : std::stoi(value));
}
else
{
params.setValue(key,value);
}
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/ControlledVocabulary.cpp | .cpp | 22,219 | 677 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm, Andreas Bertsch, Mathias Walzer $
// --------------------------------------------------------------------------
#include <OpenMS/FORMAT/ControlledVocabulary.h>
#include <OpenMS/DATASTRUCTURES/DataValue.h>
#include <OpenMS/FORMAT/HANDLERS/XMLHandler.h>
#include <OpenMS/SYSTEM/File.h>
#include <iostream>
#include <fstream>
#include <map>
using namespace std;
namespace OpenMS
{
ControlledVocabulary::CVTerm::CVTerm() :
name(),
id(),
parents(),
children(),
obsolete(false),
description(),
synonyms(),
unparsed(),
xref_type(XRefType::NONE),
xref_binary()
{
}
ControlledVocabulary::CVTerm::CVTerm(const CVTerm& rhs) = default;
ControlledVocabulary::CVTerm& ControlledVocabulary::CVTerm::operator=(const CVTerm& rhs)
{
if (this != &rhs)
{
name = rhs.name;
id = rhs.id;
parents = rhs.parents;
children = rhs.children;
obsolete = rhs.obsolete;
description = rhs.description;
synonyms = rhs.synonyms;
unparsed = rhs.unparsed;
xref_type = rhs.xref_type;
xref_binary = rhs.xref_binary;
units = rhs.units;
}
return *this;
}
String ControlledVocabulary::CVTerm::getXRefTypeName(XRefType type)
{
switch (type)
{
case XRefType::XSD_STRING: return "xsd:string";
case XRefType::XSD_INTEGER: return "xsd:integer";
case XRefType::XSD_DECIMAL: return "xsd:decimal";
case XRefType::XSD_NEGATIVE_INTEGER: return "xsd:negativeInteger";
case XRefType::XSD_POSITIVE_INTEGER: return "xsd:positiveInteger";
case XRefType::XSD_NON_NEGATIVE_INTEGER: return "xsd:nonNegativeInteger";
case XRefType::XSD_NON_POSITIVE_INTEGER: return "xsd:nonPositiveInteger";
case XRefType::XSD_BOOLEAN: return "xsd:boolean";
case XRefType::XSD_DATE: return "xsd:date";
case XRefType::XSD_ANYURI: return "xsd:anyURI";
default: return "none";
}
}
// bool ControlledVocabulary::CVTerm::isSearchEngineSpecificScore()
// { //maybe unsafe?
// if (this->parents.find("MS:1001143")!=this->parents.end()) return true;
// return false;
// }
bool ControlledVocabulary::CVTerm::isHigherBetterScore(ControlledVocabulary::CVTerm term)
{
// for (StringList::const_iterator unp = this->unparsed.begin(); unp != this->unparsed.end(); ++unp)
// {
// if (unp->hasPrefix("relationship: has_order MS:1002108")) return true;
// }
// return false;
//most scores are higher better, but most entries in CV for these are not annotated -> default is true
for (StringList::const_iterator unp = term.unparsed.begin(); unp != term.unparsed.end(); ++unp)
{
if (unp->hasPrefix("relationship: has_order MS:1002109")) return false;
}
return true;
}
String ControlledVocabulary::CVTerm::toXMLString(const OpenMS::String& ref, const String& value) const
{
String s = "<cvParam accession=\"" + id + "\" cvRef=\"" + ref + "\" name=\"" + Internal::XMLHandler::writeXMLEscape(name);
if (!value.empty())
{
s += "\" value=\"" + Internal::XMLHandler::writeXMLEscape(value);
}
s += "\"/>";
return s;
//~ TODO: handle unknown cvparams in ControlledVocabulary to get same formatting but more userdefined interface
}
String ControlledVocabulary::CVTerm::toXMLString(const OpenMS::String& ref, const OpenMS::DataValue& value) const
{
String s = "<cvParam accession=\"" + id + "\" cvRef=\"" + ref + "\" name=\"" + Internal::XMLHandler::writeXMLEscape(name);
if (!value.isEmpty())
{
s += "\" value=\"" + Internal::XMLHandler::writeXMLEscape(value);
}
if (value.hasUnit())
{
String un = *(this->units.begin());
s += "\" unitAccession=\"" + un + "\" unitCvRef=\"" + un.prefix(2);
// TODO: Currently we do not store the unit name in the CVTerm, only the
// accession number (we would need the ControlledVocabulary to look up
// the unit CVTerm).
// "\" unitName=\"" + unit.name
}
s += "\"/>";
return s;
}
ControlledVocabulary::ControlledVocabulary() = default;
ControlledVocabulary::~ControlledVocabulary() = default;
void ControlledVocabulary::loadFromOBO(const String& name, const String& filename)
{
bool in_term = false;
name_ = name;
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, line_wo_spaces;
CVTerm term;
//parse file
while (getline(is, line, '\n'))
{
line.trim();
line_wo_spaces = line;
line_wo_spaces.removeWhitespaces();
//do nothing for empty lines
if (line.empty())
{
continue;
}
if (line_wo_spaces.hasPrefix("data-version:"))
{
version_ = line.substr(line.find(':') + 1).trim();
}
if (line_wo_spaces.hasPrefix("default-namespace:"))
{
label_ = line.substr(line.find(':') + 1).trim();
}
if (line_wo_spaces.hasPrefix("remark:URL:"))
{
// Find the position of "http://" or "https://"
size_t httpPos = line.find("http://");
size_t httpsPos = line.find("https://");
// Determine the starting position of the URL
if (httpPos != std::string::npos)
{
url_ = line.substr(httpPos).trim();
} else if (httpsPos != std::string::npos)
{
url_ = line.substr(httpsPos).trim();
} else
{
// No URL found
std::cerr << "No URL found in the line." << std::endl;
}
}
//********************************************************************************
//stanza line
if (line_wo_spaces[0] == '[')
{
//[term] stanza
if (line_wo_spaces.toLower() == "[term]") //new term
{
in_term = true;
if (!term.id.empty()) //store last term
{
terms_[term.id] = term;
}
//clear temporary term members
term = CVTerm();
}
// other stanza => not in a term
else
{
in_term = false;
}
}
//********************************************************************************
//data line
else if (in_term)
{
if (line_wo_spaces.hasPrefix("id:"))
{
term.id = line.substr(line.find(':') + 1).trim();
}
else if (line_wo_spaces.hasPrefix("name:"))
{
term.name = line.substr(line.find(':') + 1).trim();
}
else if (line_wo_spaces.hasPrefix("is_a:"))
{
if (line.has('!'))
{
String parent_id = line.substr(line.find(':') + 1).prefix('!').trim();
term.parents.insert(parent_id);
//check if the parent term name is correct
String parent_name = line.suffix('!').trim();
if (!checkName_(parent_id, parent_name))
cerr << "Warning: while loading term '" << term.id << "' of CV '" << name_ << "': parent term name '" << parent_name << "' and id '" << parent_id << "' differ." << "\n";
}
else
{
term.parents.insert(line.substr(line.find(':') + 1).trim());
}
}
// brenda tissue special relationships, DRV (derived and part of)
else if (line_wo_spaces.hasPrefix("relationship:DRV") && name == "brenda")
{
if (line.has('!'))
{
// e.g. relationship: DRV BTO:0000142 ! brain
String parent_id = line.substr(line.find("DRV") + 4).prefix(':') + ":" + line.suffix(':').prefix('!').trim();
term.parents.insert(parent_id);
//check if the parent term name is correct
String parent_name = line.suffix('!').trim();
if (!checkName_(parent_id, parent_name))
cerr << "Warning: while loading term '" << term.id << "' of CV '" << name_ << "': DRV relationship term name '" << parent_name << "' and id '" << parent_id << "' differ." << "\n";
}
else
{
// e.g. relationship: DRV BTO:0000142
term.parents.insert(line.substr(line.find("DRV") + 4).prefix(':') + ":" + line.suffix(':').trim());
}
}
else if (line_wo_spaces.hasPrefix("relationship:part_of") && name == "brenda")
{
if (line.has('!'))
{
String parent_id = line.substr(line.find("part_of") + 8).prefix(':') + ":" + line.suffix(':').prefix('!').trim();
term.parents.insert(parent_id);
//check if the parent term name is correct
String parent_name = line.suffix('!').trim();
if (!checkName_(parent_id, parent_name))
{
cerr << "Warning: while loading term '" << term.id << "' of CV '" << name_ << "': part_of relationship term name '" << parent_name << "' and id '" << parent_id << "' differ." << "\n";
}
}
else
{
term.parents.insert(line.substr(line.find("part_of") + 8).prefix(':') + ":" + line.suffix(':').trim());
}
}
else if (line_wo_spaces.hasPrefix("relationship:has_units"))
{
if (line.has('!'))
{
String unit_id = line.substr(line.find("has_units") + 10).prefix(':') + ":" + line.suffix(':').prefix('!').trim();
term.units.insert(unit_id);
//check if the parent term name is correct
String unit_name = line.suffix('!').trim();
if (!checkName_(unit_id, unit_name))
{
cerr << "Warning: while loading term '" << term.id << "' of CV '" << name_ << "': has_units relationship term name '" << unit_name << "' and id '" << unit_id << "' differ." << "\n";
}
}
else
{
term.units.insert(line.substr(line.find("has_units") + 10).prefix(':') + ":" + line.suffix(':').trim());
}
}
else if (line_wo_spaces.hasPrefix("def:"))
{
String description = line.substr(line.find('"') + 1);
description.trim();
description = description.substr(0, description.find('"'));
description.trim();
term.description = description;
}
else if (line_wo_spaces.hasPrefix("synonym:"))
{
String synonym = line.substr(line.find('"') + 1);
synonym.trim();
synonym = synonym.substr(0, synonym.find('"'));
synonym.trim();
term.synonyms.push_back(synonym);
}
else if (line_wo_spaces == "is_obsolete:true")
{
term.obsolete = true;
}
else if (line_wo_spaces.hasPrefix("xref:value-type")
|| line_wo_spaces.hasPrefix("xref_analog:value-type")
)
{
line_wo_spaces.remove('\\');
if (line_wo_spaces.hasSubstring("value-type:xsd:string"))
{
term.xref_type = CVTerm::XRefType::XSD_STRING;
continue;
}
if (line_wo_spaces.hasSubstring("value-type:xsd:integer") || line_wo_spaces.hasSubstring("value-type:xsd:int"))
{
term.xref_type = CVTerm::XRefType::XSD_INTEGER;
continue;
}
if (line_wo_spaces.hasSubstring("value-type:xsd:decimal") ||
line_wo_spaces.hasSubstring("value-type:xsd:float") ||
line_wo_spaces.hasSubstring("value-type:xsd:double"))
{
term.xref_type = CVTerm::XRefType::XSD_DECIMAL;
continue;
}
if (line_wo_spaces.hasSubstring("value-type:xsd:negativeInteger"))
{
term.xref_type = CVTerm::XRefType::XSD_NEGATIVE_INTEGER;
continue;
}
if (line_wo_spaces.hasSubstring("value-type:xsd:positiveInteger"))
{
term.xref_type = CVTerm::XRefType::XSD_POSITIVE_INTEGER;
continue;
}
if (line_wo_spaces.hasSubstring("value-type:xsd:nonNegativeInteger"))
{
term.xref_type = CVTerm::XRefType::XSD_NON_NEGATIVE_INTEGER;
continue;
}
if (line_wo_spaces.hasSubstring("value-type:xsd:nonPositiveInteger"))
{
term.xref_type = CVTerm::XRefType::XSD_NON_POSITIVE_INTEGER;
continue;
}
if (line_wo_spaces.hasSubstring("value-type:xsd:boolean") || line_wo_spaces.hasSubstring("value-type:xsd:bool"))
{
term.xref_type = CVTerm::XRefType::XSD_BOOLEAN;
continue;
}
if (line_wo_spaces.hasSubstring("value-type:xsd:date"))
{
term.xref_type = CVTerm::XRefType::XSD_DATE;
continue;
}
if (line_wo_spaces.hasSubstring("value-type:xsd:anyURI"))
{
term.xref_type = CVTerm::XRefType::XSD_ANYURI;
continue;
}
cerr << "ControlledVocabulary: OBOFile: unknown xsd type: " << line_wo_spaces << ", ignoring" << "\n";
}
else if (line_wo_spaces.hasPrefix("relationship:has_value_type")) // since newer obo type in relationship instead of xref
{
if (line_wo_spaces.hasSubstring("xsd:string"))
{
term.xref_type = CVTerm::XRefType::XSD_STRING;
continue;
}
if (line_wo_spaces.hasSubstring("xsd:integer")
|| line_wo_spaces.hasSubstring("xsd:int"))
{
term.xref_type = CVTerm::XRefType::XSD_INTEGER;
continue;
}
if (line_wo_spaces.hasSubstring("xsd:decimal") ||
line_wo_spaces.hasSubstring("xsd:float") ||
line_wo_spaces.hasSubstring("xsd:double"))
{
term.xref_type = CVTerm::XRefType::XSD_DECIMAL;
continue;
}
if (line_wo_spaces.hasSubstring("xsd:negativeInteger"))
{
term.xref_type = CVTerm::XRefType::XSD_NEGATIVE_INTEGER;
continue;
}
if (line_wo_spaces.hasSubstring("xsd:positiveInteger"))
{
term.xref_type = CVTerm::XRefType::XSD_POSITIVE_INTEGER;
continue;
}
if (line_wo_spaces.hasSubstring("xsd:nonNegativeInteger"))
{
term.xref_type = CVTerm::XRefType::XSD_NON_NEGATIVE_INTEGER;
continue;
}
if (line_wo_spaces.hasSubstring("xsd:nonPositiveInteger"))
{
term.xref_type = CVTerm::XRefType::XSD_NON_POSITIVE_INTEGER;
continue;
}
if (line_wo_spaces.hasSubstring("xsd:boolean")
|| line_wo_spaces.hasSubstring("xsd:bool"))
{
term.xref_type = CVTerm::XRefType::XSD_BOOLEAN;
continue;
}
if (line_wo_spaces.hasSubstring("xsd:date"))
{
term.xref_type = CVTerm::XRefType::XSD_DATE;
continue;
}
if (line_wo_spaces.hasSubstring("xsd:anyURI"))
{
term.xref_type = CVTerm::XRefType::XSD_ANYURI;
continue;
}
if (
line_wo_spaces.hasSubstring("MS:1002711") ||
line_wo_spaces.hasSubstring("MS:1002712") ||
line_wo_spaces.hasSubstring("MS:1002713")
)
{
term.xref_type = CVTerm::XRefType::XSD_STRING; // store list as string
continue;
}
cerr << "ControlledVocabulary: OBOFile: unknown xsd type: " << line_wo_spaces << ", ignoring" << "\n";
}
else if (line_wo_spaces.hasPrefix("xref:binary-data-type") || line_wo_spaces.hasPrefix("xref_analog:binary-data-type"))
{
line_wo_spaces.remove('\\');
//remove description (if present)
// according to rev1165 of the cv comments are here quoted, see http://psidev.cvs.sourceforge.net/viewvc/psidev/psi/psi-ms/mzML/controlledVocabulary/psi-ms.obo?revision=1.165&view=markup
if (line_wo_spaces.has('\"'))
{
line_wo_spaces = line_wo_spaces.substr(0, line_wo_spaces.find('\"'));
}
//trim prefix
line_wo_spaces = line_wo_spaces.substr(22);
//trim just to be sure
line_wo_spaces.trim();
term.xref_binary.push_back(line_wo_spaces);
}
else if (!line.empty())
{
term.unparsed.push_back(line);
}
}
}
if (!term.id.empty()) //store last term
{
terms_[term.id] = term;
}
// now build all child terms
for (auto it = terms_.begin(); it != terms_.end(); ++it)
{
//cerr << it->first << "\n";
for (auto pit = it->second.parents.begin(); pit != it->second.parents.end(); ++pit)
{
//cerr << "Parent: " << *pit << "\n";
terms_[*pit].children.insert(it->first);
}
auto mit = namesToIds_.find(it->second.name);
if (mit == namesToIds_.end())
{
namesToIds_.insert(pair<String, String>(it->second.name, it->first));
}
else
{
//~ TODO that case would be bad do something
String s = it->second.name + it->second.description;
namesToIds_.insert(pair<String, String>(s, it->first));
}
}
}
const ControlledVocabulary::CVTerm& ControlledVocabulary::getTerm(const String& id) const
{
if (const auto it = terms_.find(id); it == terms_.end())
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Invalid CV identifier!", id);
}
else
{
return it->second;
}
}
const std::map<String, ControlledVocabulary::CVTerm>& ControlledVocabulary::getTerms() const
{
return terms_;
}
void ControlledVocabulary::getAllChildTerms(set<String>& terms, const String& parent) const
{
//cerr << "Parent: " << parent << "\n";
for (const auto& child : getTerm(parent).children)
{
terms.insert(child);
//TODO: This is not safe for cyclic graphs. Are they allowed in CVs?
getAllChildTerms(terms, child);
}
}
const ControlledVocabulary::CVTerm& ControlledVocabulary::getTermByName(const String& name, const String& desc) const
{
//slow, but Vocabulary is very finite and this method will be called only a few times during write of a ML file using a CV
auto it = namesToIds_.find(name);
if (it == namesToIds_.end())
{
if (!desc.empty())
{
it = namesToIds_.find(String(name + desc));
if (it == namesToIds_.end())
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Invalid CV name!", name);
}
}
else
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Invalid CV name!", name);
}
}
return terms_.at(it->second);
}
bool ControlledVocabulary::exists(const String& id) const
{
return terms_.find(id) != terms_.end();
}
const ControlledVocabulary::CVTerm* ControlledVocabulary::checkAndGetTermByName(const OpenMS::String& name) const
{
const auto it = namesToIds_.find(name);
if (it == namesToIds_.end()) return nullptr;
return &terms_.at(it->second);
}
bool ControlledVocabulary::hasTermWithName(const OpenMS::String& name) const
{
const auto it = namesToIds_.find(name);
return it != namesToIds_.end();
}
bool ControlledVocabulary::isChildOf(const String& child, const String& parent) const
{
// cout << "CHECK child:" << child << " parent: " << parent << "\n";
const CVTerm& ch = getTerm(child);
for (const auto & it : ch.parents)
{
// cout << "Parent: " << it << "\n";
// check if it is a direct parent
if (it == parent)
{
return true;
}
// check if it is an indirect parent
else if (isChildOf(it, parent))
{
return true;
}
}
return false;
}
std::ostream& operator<<(std::ostream& os, const ControlledVocabulary& cv)
{
for (const auto & it : cv.terms_)
{
os << "[Term]\n";
os << "id: '" << it.second.id << "'\n";
os << "name: '" << it.second.name << "'\n";
for (const auto & parent_term : it.second.parents)
{
cout << "is_a: '" << parent_term << "'\n";
}
}
return os;
}
const String& ControlledVocabulary::name() const
{
return name_;
}
const String& ControlledVocabulary::label() const
{
return label_;
}
const String& ControlledVocabulary::version() const
{
return version_;
}
const String& ControlledVocabulary::url() const
{
return url_;
}
const ControlledVocabulary& ControlledVocabulary::getPSIMSCV()
{
static const ControlledVocabulary cv = []() {
ControlledVocabulary cv;
cv.loadFromOBO("MS", File::find("/CV/psi-ms.obo"));
cv.loadFromOBO("PATO", File::find("/CV/quality.obo"));
cv.loadFromOBO("UO", File::find("/CV/unit.obo"));
cv.loadFromOBO("BTO", File::find("/CV/brenda.obo"));
cv.loadFromOBO("GO", File::find("/CV/goslim_goa.obo"));
return cv;
}();
return cv;
}
bool ControlledVocabulary::checkName_(const String& id, const String& name, bool ignore_case) const
{
if (!exists(id))
{
return true; //what?!
}
String parent_name = name;
String real_parent_name = getTerm(id).name;
if (ignore_case)
{
parent_name.toLower();
real_parent_name.toLower();
}
return real_parent_name == parent_name;
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/FeatureXMLFile.cpp | .cpp | 3,653 | 124 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Marc Sturm, Chris Bielow, Clemens Groepl $
// --------------------------------------------------------------------------
#include <OpenMS/FORMAT/FeatureXMLFile.h>
#include <OpenMS/FORMAT/HANDLERS/FeatureXMLHandler.h>
#include <OpenMS/KERNEL/FeatureMap.h>
#include <OpenMS/FORMAT/IdXMLFile.h>
#include <OpenMS/METADATA/DataProcessing.h>
#include <OpenMS/CHEMISTRY/ProteaseDB.h>
#include <OpenMS/FORMAT/FileHandler.h>
#include <fstream>
using namespace std;
namespace OpenMS
{
FeatureXMLFile::FeatureXMLFile() :
Internal::XMLFile("/SCHEMAS/FeatureXML_1_9.xsd", "1.9")
{
}
FeatureXMLFile::~FeatureXMLFile() = default;
Size FeatureXMLFile::loadSize(const String& filename)
{
FeatureMap dummy;
Internal::FeatureXMLHandler handler(dummy, filename);
handler.setOptions(options_);
handler.setSizeOnly(true);
handler.setLogType(getLogType());
parse_(filename, &handler);
return handler.getSize();
}
void FeatureXMLFile::load(const String& filename, FeatureMap& feature_map)
{
feature_map.clear(true);
//set DocumentIdentifier
feature_map.setLoadedFileType(filename);
feature_map.setLoadedFilePath(filename);
Internal::FeatureXMLHandler handler(feature_map, filename);
handler.setOptions(options_);
handler.setLogType(getLogType());
parse_(filename, &handler);
// !!! Hack: set feature FWHM from meta info entries as
// long as featureXML doesn't support a width entry.
// See also hack in BaseFeature::setWidth().
for (auto& feature : feature_map)
{
if (feature.metaValueExists("FWHM"))
{
feature.setWidth((double)feature.getMetaValue("FWHM"));
}
}
// put ranges into defined state
feature_map.updateRanges();
}
void FeatureXMLFile::store(const String& filename, const FeatureMap& feature_map)
{
if (!FileHandler::hasValidExtension(filename, FileTypes::FEATUREXML))
{
throw Exception::UnableToCreateFile(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename, "invalid file extension, expected '" + FileTypes::typeToName(FileTypes::FEATUREXML) + "'");
}
if (Size invalid_unique_ids = feature_map.applyMemberFunction(&UniqueIdInterface::hasInvalidUniqueId))
{
// TODO Take care *outside* that this does not happen.
// We can detect this here but it is too late to fix the problem;
// there is no straightforward action to be taken in all cases.
// Note also that we are given a const reference.
OPENMS_LOG_INFO << String("FeatureXMLHandler::store(): found ") + invalid_unique_ids + " invalid unique ids" << std::endl;
}
// This will throw if the unique ids are not unique,
// so we never create bad files in this respect.
try
{
feature_map.updateUniqueIdToIndex();
}
catch (Exception::Postcondition& e)
{
OPENMS_LOG_FATAL_ERROR << e.getName() << ' ' << e.what() << std::endl;
throw;
}
Internal::FeatureXMLHandler handler(feature_map, filename);
handler.setOptions(options_);
handler.setLogType(getLogType());
save_(filename, &handler);
}
FeatureFileOptions& FeatureXMLFile::getOptions()
{
return options_;
}
const FeatureFileOptions& FeatureXMLFile::getOptions() const
{
return options_;
}
void FeatureXMLFile::setOptions(const FeatureFileOptions& options)
{
options_ = options;
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/PepNovoOutfile.cpp | .cpp | 14,675 | 409 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Sandro Andreotti, Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/METADATA/ProteinIdentification.h>
#include <OpenMS/CHEMISTRY/ModificationsDB.h>
#include <OpenMS/FORMAT/PepNovoOutfile.h>
#include <OpenMS/SYSTEM/File.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <fstream>
using namespace std;
namespace OpenMS
{
PepNovoOutfile::PepNovoOutfile() = default;
PepNovoOutfile::PepNovoOutfile(const PepNovoOutfile &) = default;
PepNovoOutfile::~PepNovoOutfile() = default;
PepNovoOutfile & PepNovoOutfile::operator=(const PepNovoOutfile &) = default;
bool PepNovoOutfile::operator==(const PepNovoOutfile &) const
{
return true;
}
void
PepNovoOutfile::load(
const std::string & result_filename,
PeptideIdentificationList & peptide_identifications,
ProteinIdentification & protein_identification,
const double & score_threshold,
const IndexPosMappingType & index_to_precursor,
const map<String, String> & pnovo_modkey_to_mod_id
)
{
// generally used variables
StringList substrings;
map<String, Int> columns;
PeptideHit peptide_hit;
String
line,
score_type = "PepNovo",
version = "unknown",
identifier,
filename,
sequence,
sequence_with_mods;
DateTime datetime = DateTime::now(); // there's no date given from PepNovo
protein_identification.setDateTime(datetime);
peptide_identifications.clear();
PeptideIdentification peptide_identification;
protein_identification = ProteinIdentification();
// open the result
ifstream result_file(result_filename.c_str());
if (!result_file)
{
if (!File::exists(result_filename))
{
throw Exception::FileNotFound(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, result_filename);
}
else if (!File::readable(result_filename))
{
throw Exception::FileNotReadable(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, result_filename);
}
else
{
throw Exception::IOException(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, result_filename);
}
}
Size line_number(0); // used to report in which line an error occurred
Size id_count(0); // number of IDs seen (not necessarily the ones finally returned)
getSearchEngineAndVersion(result_filename, protein_identification);
//if information could not be retrieved from the outfile use defaults
if (protein_identification.getSearchEngineVersion().empty())
{
protein_identification.setSearchEngine("PepNovo");
protein_identification.setSearchEngineVersion(version);
}
identifier = protein_identification.getSearchEngine() + "_" + datetime.getDate();
protein_identification.setIdentifier(identifier);
map<String, String> mod_mask_map;
const vector<String> & mods = protein_identification.getSearchParameters().variable_modifications;
for (const String& mod_it : mods)
{
if (mod_it.empty())
continue;
//cout<<*mod_it<<endl;
if (pnovo_modkey_to_mod_id.find(mod_it) != pnovo_modkey_to_mod_id.end())
{
//cout<<keys_to_id.find(*mod_it)->second<<endl;
const ResidueModification* tmp_mod = ModificationsDB::getInstance()->getModification(pnovo_modkey_to_mod_id.find(mod_it)->second);
if (mod_it.prefix(1) == "^" || mod_it.prefix(1) == "$")
{
mod_mask_map[mod_it] = "(" + tmp_mod->getId() + ")";
}
else
{
mod_mask_map[mod_it] = String(tmp_mod->getOrigin()) + "(" + tmp_mod->getId() + ")";
}
}
else
{
if (mod_it.prefix(1) != "^" && mod_it.prefix(1) != "$")
{
mod_mask_map[mod_it] = mod_it.prefix(1) + "[" + mod_it.substr(1) + "]";
//cout<<mod_mask_map[*mod_it]<<endl;
}
else
{
mod_mask_map[mod_it] = "[" + mod_it + "]";
//cout<<mod_mask_map[*mod_it]<<endl;
}
}
}
Size index;
while (getline(result_file, line))
{
if (!line.empty() && (line[line.length() - 1] < 33))
{
line.resize(line.length() - 1); // remove weird EOL character
}
line.trim();
++line_number;
if (line.hasPrefix(">> ")) // >> 1 /home/shared/pepnovo/4611_raw_ms2_picked.mzXML.1001.2.dta
{
++id_count;
if (!peptide_identification.empty() && !peptide_identification.getHits().empty())
{
peptide_identifications.push_back(peptide_identification);
}
line.split(' ', substrings);
//String index = File::basename(line.substr(line.find(' ', strlen(">> ")) + 1));
if (substrings.size() < 3)
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Not enough columns (spectrum Id) in file in line " + String(line_number) + String(" (should be 2 or more)!"), result_filename);
}
try
{
index = substrings[2].trim().toInt();
}
catch (...)
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Expected an index number in line " + String(line_number) + String(" at position 2 (line was: '" + line + "')!"), result_filename);
}
//cout<<"INDEX: "<<index<<endl;
peptide_identification = PeptideIdentification();
bool success = false;
if (!index_to_precursor.empty())
{
if (index_to_precursor.find(index) != index_to_precursor.end())
{
peptide_identification.setRT(index_to_precursor.find(index)->second.first);
peptide_identification.setMZ(index_to_precursor.find(index)->second.second);
success = true;
}
else
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Index '" + String(index) + String("' in line '" + line + "' not found in index table (line was: '" + line + "')!"), result_filename);
}
}
if (!success)
{ // try to reconstruct from title entry (usually sensible when MGF is supplied to PepNovo)
try
{
if (substrings.size() >= 4)
{
StringList parts = ListUtils::create<String>(substrings[3], '_');
if (parts.size() >= 2)
{
peptide_identification.setRT(parts[1].toDouble());
peptide_identification.setMZ(parts[0].toDouble());
success = true;
}
}
}
catch (...)
{
}
if (!success)
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Precursor could not be reconstructed from title '" + substrings[3] + String("' in line '" + line + "' (line was: '" + line + "')!"), result_filename);
}
}
peptide_identification.setSignificanceThreshold(score_threshold);
peptide_identification.setScoreType(score_type);
peptide_identification.setIdentifier(identifier);
}
else if (line.hasPrefix("#Index")) // #Index Prob Score N-mass C-Mass [M+H] Charge Sequence
{
if (columns.empty()) // map the column names to their column number
{
line.split('\t', substrings);
for (vector<String>::const_iterator s_i = substrings.begin(); s_i != substrings.end(); ++s_i)
{
if ((*s_i) == "#Index")
{
columns["Index"] = s_i - substrings.begin();
}
else if ((*s_i) == "RnkScr")
{
columns["RnkScr"] = s_i - substrings.begin();
}
else if ((*s_i) == "PnvScr")
{
columns["PnvScr"] = s_i - substrings.begin();
}
else if ((*s_i) == "N-Gap")
{
columns["N-Gap"] = s_i - substrings.begin();
}
else if ((*s_i) == "C-Gap")
{
columns["C-Gap"] = s_i - substrings.begin();
}
else if ((*s_i) == "[M+H]")
{
columns["[M+H]"] = s_i - substrings.begin();
}
else if ((*s_i) == "Charge")
{
columns["Charge"] = s_i - substrings.begin();
}
else if ((*s_i) == "Sequence")
{
columns["Sequence"] = s_i - substrings.begin();
}
}
if (columns.size() != 8)
{
result_file.close();
result_file.clear();
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Not enough columns in file in line " + String(line_number) + String(" (should be 8)!"), result_filename);
}
}
while (getline(result_file, line))
{
++line_number;
if (!line.empty() && (line[line.length() - 1] < 33))
{
line.resize(line.length() - 1);
}
line.trim();
if (line.empty())
{
break;
}
line.split('\t', substrings);
if (!substrings.empty())
{
if (substrings.size() != 8)
{
result_file.close();
result_file.clear();
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Not enough columns in file in line " + String(line_number) + String(" (should be 8)!"), result_filename);
}
if (substrings[columns["RnkScr"]].toFloat() >= score_threshold)
{
peptide_hit = PeptideHit();
peptide_hit.setCharge(substrings[columns["Charge"]].toInt());
peptide_hit.setRank(substrings[columns["Index"]].toInt() + 1);
peptide_hit.setScore(substrings[columns["RnkScr"]].toFloat());
peptide_hit.setMetaValue("PnvScr", substrings[columns["PnvScr"]].toFloat());
peptide_hit.setMetaValue("N-Gap", substrings[columns["N-Gap"]].toFloat());
peptide_hit.setMetaValue("C-Gap", substrings[columns["C-Gap"]].toFloat());
peptide_hit.setMetaValue("MZ", substrings[columns["[M+H]"]].toFloat());
sequence = substrings[columns["Sequence"]];
for (map<String, String>::iterator mask_it = mod_mask_map.begin(); mask_it != mod_mask_map.end(); ++mask_it)
{
if (mask_it->first.hasPrefix("^") && sequence.hasSubstring(mask_it->first))
{
sequence.substitute(mask_it->first, "");
sequence = mask_it->second + sequence;
}
//cout<<mask_it->first<<" "<<mask_it->second<<endl;
sequence.substitute(mask_it->first, mask_it->second);
}
peptide_hit.setSequence(AASequence::fromString(sequence));
peptide_identification.insertHit(peptide_hit);
}
}
}
}
}
if (!peptide_identifications.empty() || !peptide_identification.getHits().empty())
{
peptide_identifications.push_back(peptide_identification);
}
result_file.close();
result_file.clear();
OPENMS_LOG_INFO << "Parsed " << id_count << " ids, retained " << peptide_identifications.size() << "." << std::endl;
}
void
PepNovoOutfile::getSearchEngineAndVersion(
const String & pepnovo_output_without_parameters_filename,
ProteinIdentification & protein_identification)
{
ifstream pepnovo_output_without_parameters(pepnovo_output_without_parameters_filename.c_str());
if (!pepnovo_output_without_parameters)
{
if (!File::exists(pepnovo_output_without_parameters_filename))
{
throw Exception::FileNotFound(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, pepnovo_output_without_parameters_filename);
}
else if (!File::readable(pepnovo_output_without_parameters_filename))
{
throw Exception::FileNotReadable(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, pepnovo_output_without_parameters_filename);
}
else
{
throw Exception::IOException(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, pepnovo_output_without_parameters_filename);
}
}
ProteinIdentification::SearchParameters search_param;
// searching for something like this: PepNovo v1.03
String line;
vector<String> substrings;
while (getline(pepnovo_output_without_parameters, line))
{
if (!line.empty() && (line[line.length() - 1] < 33))
{
line.resize(line.length() - 1);
}
line.trim();
if (line.empty())
{
continue;
}
if (line.hasPrefix("PepNovo"))
{
line.split(',', substrings);
if (substrings.size() == 2) //previous version of PepNovo
{
protein_identification.setSearchEngine(substrings[0].trim());
protein_identification.setSearchEngineVersion(substrings[1].trim()); //else something is strange and we use defaults later
}
else
{
line.split(' ', substrings);
if (substrings.size() == 3)
{
protein_identification.setSearchEngine(substrings[0].trim());
protein_identification.setSearchEngineVersion(substrings[2].trim()); //else something is strange and we use defaults later
}
}
}
if (line.hasPrefix("PM"))
{
line.split(' ', substrings);
search_param.precursor_mass_tolerance = substrings.back().toFloat();
}
if (line.hasPrefix("Fragment"))
{
line.split(' ', substrings);
search_param.fragment_mass_tolerance = substrings.back().toFloat();
}
if (line.hasPrefix("PTM"))
{
line.split(':', substrings);
substrings.erase(substrings.begin());
for (vector<String>::iterator ptm_it = substrings.begin(); ptm_it != substrings.end(); ++ptm_it)
{
ptm_it->trim();
}
if (!substrings.empty() && substrings[0] != "None")
{
search_param.variable_modifications = substrings;
}
}
if (line.hasPrefix(">>"))
{
break;
}
}
protein_identification.setSearchParameters(search_param);
}
} //namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/DTAFile.cpp | .cpp | 564 | 24 | // 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/DTAFile.h>
using namespace std;
namespace OpenMS
{
DTAFile::DTAFile() :
default_ms_level_(2) // set default to MS2
{
}
DTAFile::~DTAFile() = default;
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/GzipInputStream.cpp | .cpp | 1,492 | 58 | // 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/GzipInputStream.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/FORMAT/GzipIfstream.h>
using namespace xercesc;
namespace OpenMS
{
GzipInputStream::GzipInputStream(const String & file_name) :
gzip_(new GzipIfstream(file_name.c_str())), file_current_index_(0)
{
}
GzipInputStream::GzipInputStream(const char * file_name) :
gzip_(new GzipIfstream(file_name)), file_current_index_(0)
{
}
GzipInputStream::~GzipInputStream()
{
delete gzip_;
}
bool GzipInputStream::getIsOpen() const
{
return gzip_->isOpen();
}
XMLSize_t GzipInputStream::readBytes(XMLByte * const to_fill, const XMLSize_t max_to_read)
{
// Figure out whether we can really read.
if (gzip_->streamEnd())
{
return 0;
}
unsigned char * fill_it = static_cast<unsigned char *>(to_fill);
XMLSize_t actual_read = (XMLSize_t) gzip_->read((char *)fill_it, static_cast<size_t>(max_to_read));
file_current_index_ += actual_read;
return actual_read;
}
const XMLCh * GzipInputStream::getContentType() const
{
return nullptr;
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/ChromeleonFile.cpp | .cpp | 4,798 | 130 | // 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/ChromeleonFile.h>
#include <OpenMS/FORMAT/TextFile.h>
#include <OpenMS/SYSTEM/File.h>
#include <boost/regex.hpp>
#include <fstream>
namespace OpenMS
{
void ChromeleonFile::load(const String& filename, MSExperiment& experiment) const
{
experiment.clear(true);
std::ifstream ifs(filename, std::ifstream::in);
if (!ifs.is_open())
{
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;
MSChromatogram chromatogram;
boost::smatch m;
boost::regex re_channel("^Channel\t(.*)", boost::regex::no_mod_s);
boost::regex re_injection("^Injection\t(.*)", boost::regex::no_mod_s);
boost::regex re_processing_method("^Processing Method\t(.*)", boost::regex::no_mod_s);
boost::regex re_instrument_method("^Instrument Method\t(.*)", boost::regex::no_mod_s);
boost::regex re_injection_date("^Injection Date\t(.*)", boost::regex::no_mod_s);
boost::regex re_injection_time("^Injection Time\t(.*)", boost::regex::no_mod_s);
boost::regex re_detector("^Detector\t(.*)", boost::regex::no_mod_s);
boost::regex re_signal_quantity("^Signal Quantity\t(.*)", boost::regex::no_mod_s);
boost::regex re_signal_unit("^Signal Unit\t(.*)", boost::regex::no_mod_s);
boost::regex re_signal_info("^Signal Info\t(.*)", boost::regex::no_mod_s);
boost::regex re_raw_data("^Raw Data:", boost::regex::no_mod_s);
boost::regex re_chromatogram_data("^Chromatogram Data:", boost::regex::no_mod_s);
while (!ifs.eof())
{
TextFile::getLine(ifs, line);
if (boost::regex_match(line, m, re_injection))
{
experiment.setMetaValue("mzml_id", m.str(1));
}
else if (boost::regex_match(line, m, re_channel))
{
experiment.setMetaValue("acq_method_name", m.str(1));
}
else if (boost::regex_match(line, m, re_processing_method))
{
experiment.getExperimentalSettings().getInstrument().getSoftware().setName(m.str(1));
}
else if (boost::regex_match(line, m, re_instrument_method))
{
experiment.getExperimentalSettings().getInstrument().setName(m.str(1));
}
else if (boost::regex_match(line, m, re_injection_date))
{
experiment.setMetaValue("injection_date", m.str(1));
}
else if (boost::regex_match(line, m, re_injection_time))
{
experiment.setMetaValue("injection_time", m.str(1));
}
else if (boost::regex_match(line, m, re_detector))
{
experiment.setMetaValue("detector", m.str(1));
}
else if (boost::regex_match(line, m, re_signal_quantity))
{
experiment.setMetaValue("signal_quantity", m.str(1));
}
else if (boost::regex_match(line, m, re_signal_unit))
{
experiment.setMetaValue("signal_unit", m.str(1));
}
else if (boost::regex_match(line, m, re_signal_info))
{
experiment.setMetaValue("signal_info", m.str(1));
}
else if (boost::regex_match(line, m, re_raw_data) ||
boost::regex_match(line, m, re_chromatogram_data))
{
TextFile::getLine(ifs, line); // remove the subsequent line, right before the raw data
break;
}
}
while (!ifs.eof())
{
TextFile::getLine(ifs, line);
std::vector<String> substrings;
line.split('\t', substrings);
if (substrings.size() == 3)
{
chromatogram.push_back(ChromatogramPeak(
removeCommasAndParseDouble(substrings[0]),
removeCommasAndParseDouble(substrings[2])));
}
else if (line.empty())
{
continue; // skips eventual empty lines, eg. the last before EOF
}
else
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, line, "Couldn't parse the raw data.");
}
}
ifs.close();
experiment.addChromatogram(chromatogram);
}
double ChromeleonFile::removeCommasAndParseDouble(String& number) const
{
return number.remove(',').toDouble();
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/SequestInfile.cpp | .cpp | 35,245 | 922 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Martin Langwisch $
// --------------------------------------------------------------------------
#include <OpenMS/FORMAT/SequestInfile.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
{
SequestInfile::SequestInfile() :
neutral_losses_for_ions_("0 1 1"),
ion_series_weights_("0.0 1.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0"),
protein_mass_filter_("0 0"),
precursor_mass_tolerance_(0),
peak_mass_tolerance_(0),
match_peak_tolerance_(0),
ion_cutoff_percentage_(0),
peptide_mass_unit_(0),
output_lines_(0),
enzyme_number_(0),
max_AA_per_mod_per_peptide_(0),
max_mods_per_peptide_(0),
nucleotide_reading_frame_(0),
max_internal_cleavage_sites_(0),
match_peak_count_(0),
match_peak_allowed_error_(0),
show_fragment_ions_(true),
print_duplicate_references_(true),
remove_precursor_near_peaks_(false),
mass_type_parent_(false),
mass_type_fragment_(false),
normalize_xcorr_(false),
residues_in_upper_case_(true)
{
setStandardEnzymeInfo_();
}
SequestInfile::SequestInfile(const SequestInfile & sequest_infile)
{
enzyme_info_ = sequest_infile.getEnzymeInfo_(),
database_ = sequest_infile.getDatabase(),
neutral_losses_for_ions_ = sequest_infile.getNeutralLossesForIons(),
ion_series_weights_ = sequest_infile.getIonSeriesWeights(),
partial_sequence_ = sequest_infile.getPartialSequence(),
sequence_header_filter_ = sequest_infile.getSequenceHeaderFilter();
precursor_mass_tolerance_ = sequest_infile.getPrecursorMassTolerance(),
peak_mass_tolerance_ = sequest_infile.getPeakMassTolerance(),
ion_cutoff_percentage_ = sequest_infile.getIonCutoffPercentage(),
protein_mass_filter_ = sequest_infile.getProteinMassFilter(),
match_peak_tolerance_ = sequest_infile.getMatchPeakTolerance(),
peptide_mass_unit_ = sequest_infile.getPeptideMassUnit(),
output_lines_ = sequest_infile.getOutputLines(),
enzyme_number_ = sequest_infile.getEnzymeNumber(),
max_AA_per_mod_per_peptide_ = sequest_infile.getMaxAAPerModPerPeptide(),
max_mods_per_peptide_ = sequest_infile.getMaxModsPerPeptide(),
nucleotide_reading_frame_ = sequest_infile.getNucleotideReadingFrame(),
max_internal_cleavage_sites_ = sequest_infile.getMaxInternalCleavageSites(),
match_peak_count_ = sequest_infile.getMatchPeakCount(),
match_peak_allowed_error_ = sequest_infile.getMatchPeakAllowedError();
show_fragment_ions_ = sequest_infile.getShowFragmentIons(),
print_duplicate_references_ = sequest_infile.getPrintDuplicateReferences(),
remove_precursor_near_peaks_ = sequest_infile.getRemovePrecursorNearPeaks(),
mass_type_parent_ = sequest_infile.getMassTypeParent(),
mass_type_fragment_ = sequest_infile.getMassTypeFragment(),
normalize_xcorr_ = sequest_infile.getNormalizeXcorr(),
residues_in_upper_case_ = sequest_infile.getResiduesInUpperCase();
PTMname_residues_mass_type_ = sequest_infile.getModifications();
}
SequestInfile::~SequestInfile()
{
PTMname_residues_mass_type_.clear();
}
SequestInfile & SequestInfile::operator=(const SequestInfile & sequest_infile)
{
if (this == &sequest_infile)
return *this;
enzyme_info_ = sequest_infile.getEnzymeInfo_();
database_ = sequest_infile.getDatabase();
neutral_losses_for_ions_ = sequest_infile.getNeutralLossesForIons();
ion_series_weights_ = sequest_infile.getIonSeriesWeights();
partial_sequence_ = sequest_infile.getPartialSequence();
sequence_header_filter_ = sequest_infile.getSequenceHeaderFilter();
precursor_mass_tolerance_ = sequest_infile.getPrecursorMassTolerance();
peak_mass_tolerance_ = sequest_infile.getPeakMassTolerance();
ion_cutoff_percentage_ = sequest_infile.getIonCutoffPercentage();
protein_mass_filter_ = sequest_infile.getProteinMassFilter();
match_peak_tolerance_ = sequest_infile.getMatchPeakTolerance();
peptide_mass_unit_ = sequest_infile.getPeptideMassUnit();
output_lines_ = sequest_infile.getOutputLines();
enzyme_number_ = sequest_infile.getEnzymeNumber();
max_AA_per_mod_per_peptide_ = sequest_infile.getMaxAAPerModPerPeptide();
max_mods_per_peptide_ = sequest_infile.getMaxModsPerPeptide();
nucleotide_reading_frame_ = sequest_infile.getNucleotideReadingFrame();
max_internal_cleavage_sites_ = sequest_infile.getMaxInternalCleavageSites();
match_peak_count_ = sequest_infile.getMatchPeakCount();
match_peak_allowed_error_ = sequest_infile.getMatchPeakAllowedError();
show_fragment_ions_ = sequest_infile.getShowFragmentIons();
print_duplicate_references_ = sequest_infile.getPrintDuplicateReferences();
remove_precursor_near_peaks_ = sequest_infile.getRemovePrecursorNearPeaks();
mass_type_parent_ = sequest_infile.getMassTypeParent();
mass_type_fragment_ = sequest_infile.getMassTypeFragment();
normalize_xcorr_ = sequest_infile.getNormalizeXcorr();
residues_in_upper_case_ = sequest_infile.getResiduesInUpperCase();
PTMname_residues_mass_type_ = sequest_infile.getModifications();
return *this;
}
bool SequestInfile::operator==(const SequestInfile & sequest_infile) const
{
bool equal = true;
equal &= (enzyme_info_ == sequest_infile.getEnzymeInfo_());
equal &= (database_ == sequest_infile.getDatabase());
equal &= (neutral_losses_for_ions_ == sequest_infile.getNeutralLossesForIons());
equal &= (ion_series_weights_ == sequest_infile.getIonSeriesWeights());
equal &= (partial_sequence_ == sequest_infile.getPartialSequence());
equal &= (sequence_header_filter_ == sequest_infile.getSequenceHeaderFilter());
equal &= (precursor_mass_tolerance_ == sequest_infile.getPrecursorMassTolerance());
equal &= (peak_mass_tolerance_ == sequest_infile.getPeakMassTolerance());
equal &= (ion_cutoff_percentage_ == sequest_infile.getIonCutoffPercentage());
equal &= (protein_mass_filter_ == sequest_infile.getProteinMassFilter());
equal &= (match_peak_tolerance_ == sequest_infile.getMatchPeakTolerance());
equal &= (peptide_mass_unit_ == sequest_infile.getPeptideMassUnit());
equal &= (output_lines_ == sequest_infile.getOutputLines());
equal &= (enzyme_number_ == sequest_infile.getEnzymeNumber());
equal &= (max_AA_per_mod_per_peptide_ == sequest_infile.getMaxAAPerModPerPeptide());
equal &= (max_mods_per_peptide_ == sequest_infile.getMaxModsPerPeptide());
equal &= (nucleotide_reading_frame_ == sequest_infile.getNucleotideReadingFrame());
equal &= (max_internal_cleavage_sites_ == sequest_infile.getMaxInternalCleavageSites());
equal &= (match_peak_count_ == sequest_infile.getMatchPeakCount());
equal &= (match_peak_allowed_error_ == sequest_infile.getMatchPeakAllowedError());
equal &= (show_fragment_ions_ == sequest_infile.getShowFragmentIons());
equal &= (print_duplicate_references_ == sequest_infile.getPrintDuplicateReferences());
equal &= (remove_precursor_near_peaks_ == sequest_infile.getRemovePrecursorNearPeaks());
equal &= (mass_type_parent_ == sequest_infile.getMassTypeParent());
equal &= (mass_type_fragment_ == sequest_infile.getMassTypeFragment());
equal &= (normalize_xcorr_ == sequest_infile.getNormalizeXcorr());
equal &= (residues_in_upper_case_ == sequest_infile.getResiduesInUpperCase());
equal &= (PTMname_residues_mass_type_ == sequest_infile.getModifications());
return equal;
}
void
SequestInfile::store(
const String & filename)
{
ofstream ofs(filename.c_str());
if (!ofs)
{
throw Exception::UnableToCreateFile(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename);
}
stringstream file_content;
float dyn_n_term_mod(0.0), dyn_c_term_mod(0.0), stat_n_term_mod(0.0), stat_c_term_mod(0.0), stat_n_term_prot_mod(0.0), stat_c_term_prot_mod(0.0);
map<char, float> stat_mods, dyn_mods;
map<char, float> * mods_p = nullptr;
// compute the masses for the amino acids, divided into fixed and optional modifications
float mass(0.0);
String residues, dyn_mods_string;
for (map<String, vector<String> >::const_iterator mods_i = PTMname_residues_mass_type_.begin(); mods_i != PTMname_residues_mass_type_.end(); ++mods_i)
{
if (mods_i->second[0] == "CTERM")
{
if (mods_i->second[2] == "OPT")
{
dyn_c_term_mod += mods_i->second[1].toFloat();
}
if (mods_i->second[2] == "FIX")
{
stat_c_term_mod += mods_i->second[1].toFloat();
}
}
else if (mods_i->second[0] == "NTERM")
{
if (mods_i->second[2] == "OPT")
{
dyn_n_term_mod += mods_i->second[1].toFloat();
}
if (mods_i->second[2] == "FIX")
{
stat_n_term_mod += mods_i->second[1].toFloat();
}
}
else if (mods_i->second[0] == "CTERM_PROT")
{
stat_c_term_prot_mod += mods_i->second[1].toFloat();
}
else if (mods_i->second[0] == "NTERM_PROT")
{
stat_n_term_prot_mod += mods_i->second[1].toFloat();
}
else
{
if (mods_i->second[2] == "FIX")
{
mods_p = &stat_mods;
}
else
{
mods_p = &dyn_mods;
}
mass = mods_i->second[1].toFloat();
residues = mods_i->second[0];
for (String::const_iterator residue_i = residues.begin(); residue_i != residues.end(); ++residue_i)
(*mods_p)[*residue_i] += mass;
}
}
// now put together all optional modifications with the same mass change
map<float, String> dyn_mods_masses;
for (map<char, float>::const_iterator dyn_mod_i = dyn_mods.begin(); dyn_mod_i != dyn_mods.end(); ++dyn_mod_i)
{
dyn_mods_masses[dyn_mod_i->second].append(1, dyn_mod_i->first);
}
// and write them down
if (dyn_mods_masses.empty())
{
dyn_mods_string = "0 X";
}
else
{
for (map<float, String>::const_iterator dyn_mod_i = dyn_mods_masses.begin(); dyn_mod_i != dyn_mods_masses.end(); ++dyn_mod_i)
{
dyn_mods_string.append(String(dyn_mod_i->first) + " " + dyn_mod_i->second + " ");
}
dyn_mods_string.erase(dyn_mods_string.length() - 1);
}
// the header
file_content << "[SEQUEST]" << "\n";
file_content << "database_name = " << database_ << "\n";
file_content << "peptide_mass_tolerance = " << precursor_mass_tolerance_ << "\n";
file_content << "peptide_mass_units = " << peptide_mass_unit_ << "; 0=amu, 1=mmu, 2=ppm" << "\n";
file_content << "ion_series = " << neutral_losses_for_ions_ << " " << ion_series_weights_ << ";nABY ABCDVWXYZ" << "\n";
file_content << "fragment_ion_tolerance = " << peak_mass_tolerance_ << "\n";
file_content << "num_output_lines = " << output_lines_ << "\n";
file_content << "num_results = " << output_lines_ << "\n";
file_content << "num_description_lines = 0" << "\n";
file_content << "show_fragment_ions = " << show_fragment_ions_ << "\n";
file_content << "print_duplicate_references = " << print_duplicate_references_ << "\n";
file_content << "enzyme_number = " << enzyme_number_ << "\n";
file_content << "diff_search_options = " << dyn_mods_string << "\n";
file_content << "term_diff_search_options = " << dyn_n_term_mod << " " << dyn_c_term_mod << "\n";
file_content << "remove_precursor_peak = " << remove_precursor_near_peaks_ << "\n";
file_content << "ion_cutoff_percentage = " << ion_cutoff_percentage_ << "\n";
file_content << "protein_mass_filter = " << protein_mass_filter_ << "\n";
file_content << "max_differential_AA_per_mod = " << max_AA_per_mod_per_peptide_ << "\n";
file_content << "max_differential_per_peptide = " << max_mods_per_peptide_ << "\n";
file_content << "nucleotide_reading_frame = " << nucleotide_reading_frame_ << "; 0=protein db, 1-6, 7 = forward three, 8-reverse three, 9=all six" << "\n";
file_content << "mass_type_parent = " << mass_type_parent_ << "; 0=average masses, 1=monoisotopic masses" << "\n";
file_content << "mass_type_fragment = " << mass_type_fragment_ << "; 0=average masses, 1=monoisotopic masses" << "\n";
file_content << "normalize_xcorr = " << normalize_xcorr_ << "\n";
file_content << "max_internal_cleavage_sites = " << max_internal_cleavage_sites_ << "\n";
file_content << "create_output_files = 1" << "\n";
file_content << "partial_sequence = " << partial_sequence_ << "\n";
file_content << "sequence_header_filter = " << sequence_header_filter_ << "\n";
file_content << "match_peak_count = " << match_peak_count_ << "; number of auto-detected peaks to try matching (max 5)" << "\n";
file_content << "match_peak_allowed_error = " << match_peak_allowed_error_ << "\n";
file_content << "match_peak_tolerance = " << match_peak_tolerance_ << "\n";
file_content << "residues_in_upper_case = " << residues_in_upper_case_ << "\n" << "\n" << "\n";
file_content << "add_Nterm_peptide = " << stat_n_term_mod << "\n";
file_content << "add_Cterm_peptide = " << stat_c_term_mod << "\n";
file_content << "add_Nterm_protein = " << stat_n_term_prot_mod << "\n";
file_content << "add_Cterm_protein = " << stat_c_term_prot_mod << "\n" << "\n";
file_content << "add_G_Glycine = " << stat_mods['G'] << "; added to G - avg. 57.0519, mono. 57.02146" << "\n";
file_content << "add_A_Alanine = " << stat_mods['A'] << "; added to A - avg. 71.0788, mono. 71.03711" << "\n";
file_content << "add_S_Serine = " << stat_mods['S'] << "; added to S - avg. 87.0782, mono. 87.03203" << "\n";
file_content << "add_P_Proline = " << stat_mods['P'] << "; added to P - avg. 97.1167, mono. 97.05276" << "\n";
file_content << "add_V_Valine = " << stat_mods['V'] << "; added to V - avg. 99.1326, mono. 99.06841" << "\n";
file_content << "add_T_Threonine = " << stat_mods['T'] << "; added to T - avg. 101.1051, mono. 101.04768" << "\n";
file_content << "add_C_Cysteine = " << stat_mods['C'] << "; added to C - avg. 103.1388, mono. 103.00919" << "\n";
file_content << "add_L_Leucine = " << stat_mods['L'] << "; added to L - avg. 113.1594, mono. 113.08406" << "\n";
file_content << "add_I_Isoleucine = " << stat_mods['I'] << "; added to I - avg. 113.1594, mono. 113.08406" << "\n";
file_content << "add_X_LorI = " << stat_mods['X'] << "; added to X - avg. 113.1594, mono. 113.08406" << "\n";
file_content << "add_N_Asparagine = " << stat_mods['N'] << "; added to N - avg. 114.1038, mono. 114.04293" << "\n";
file_content << "add_O_Ornithine = " << stat_mods['O'] << "; added to O - avg. 114.1472, mono 114.07931" << "\n";
file_content << "add_B_avg_NandD = " << stat_mods['B'] << "; added to B - avg. 114.5962, mono. 114.53494" << "\n";
file_content << "add_D_Aspartic_Acid = " << stat_mods['D'] << "; added to D - avg. 115.0886, mono. 115.02694" << "\n";
file_content << "add_Q_Glutamine = " << stat_mods['Q'] << "; added to Q - avg. 128.1307, mono. 128.05858" << "\n";
file_content << "add_K_Lysine = " << stat_mods['K'] << "; added to K - avg. 128.1741, mono. 128.09496" << "\n";
file_content << "add_Z_avg_QandE = " << stat_mods['Z'] << "; added to Z - avg. 128.6231, mono. 128.55059" << "\n";
file_content << "add_E_Glutamic_Acid = " << stat_mods['E'] << "; added to E - avg. 129.1155, mono. 129.04259" << "\n";
file_content << "add_M_Methionine = " << stat_mods['M'] << "; added to M - avg. 131.1926, mono. 131.04049" << "\n";
file_content << "add_H_Histidine = " << stat_mods['H'] << "; added to H - avg. 137.1411, mono. 137.05891" << "\n";
file_content << "add_F_Phenylalanine = " << stat_mods['F'] << "; added to F - avg. 147.1766, mono. 147.06841" << "\n";
file_content << "add_R_Arginine = " << stat_mods['R'] << "; added to R - avg. 156.1875, mono. 156.10111" << "\n";
file_content << "add_Y_Tyrosine = " << stat_mods['Y'] << "; added to Y - avg. 163.1760, mono. 163.06333" << "\n";
file_content << "add_W_Tryptophan = " << stat_mods['W'] << "; added to W - avg. 186.2132, mono. 186.07931" << "\n" << "\n";
file_content << getEnzymeInfoAsString();
ofs << file_content.str();
ofs.close();
ofs.clear();
}
const map<String, vector<String> > & SequestInfile::getEnzymeInfo_() const
{
return enzyme_info_;
}
const String
SequestInfile::getEnzymeInfoAsString() const
{
stringstream ss;
Size i(0);
String::size_type max_name_length(0);
String::size_type max_cut_before_length(0);
String::size_type max_doesnt_cut_after_length(0);
ss << "[SEQUEST_ENZYME_INFO]" << "\n";
for (map<String, vector<String> >::const_iterator einfo_i = enzyme_info_.begin(); einfo_i != enzyme_info_.end(); ++einfo_i)
{
max_name_length = max(max_name_length, einfo_i->first.length());
max_cut_before_length = max(max_cut_before_length, einfo_i->second[1].length());
max_doesnt_cut_after_length = max(max_doesnt_cut_after_length, einfo_i->second[2].length());
}
for (map<String, vector<String> >::const_iterator einfo_i = enzyme_info_.begin(); einfo_i != enzyme_info_.end(); ++einfo_i, ++i)
{
ss << i << ". " << einfo_i->first << String(max_name_length + 5 - einfo_i->first.length(), ' ') << einfo_i->second[0] << " " << einfo_i->second[1] << String(max_cut_before_length + 5 - einfo_i->second[1].length(), ' ') << einfo_i->second[2] << "\n";
}
return String(ss.str());
}
void
SequestInfile::addEnzymeInfo(vector<String> & enzyme_info)
{
// remove duplicates from the concerned amino acids
set<char> aas;
for (String::const_iterator s_i = enzyme_info[2].begin(); s_i != enzyme_info[2].end(); ++s_i)
{
aas.insert(*s_i);
}
if (enzyme_info[2].length() != aas.size())
{
enzyme_info[2].clear();
enzyme_info[2].reserve(aas.size());
for (set<char>::const_iterator aa_i = aas.begin(); aa_i != aas.end(); ++aa_i)
{
enzyme_info[2].append(1, *aa_i);
}
}
String enzyme_name = enzyme_info[0];
enzyme_info.erase(enzyme_info.begin());
enzyme_info_[enzyme_name] = enzyme_info;
enzyme_number_ = 0;
for (std::map<String, std::vector<String> >::const_iterator einfo_i = enzyme_info_.begin(); einfo_i != enzyme_info_.end(); ++einfo_i, ++enzyme_number_)
{
if (einfo_i->first == enzyme_name)
break;
}
}
const String & SequestInfile::getDatabase() const
{
return database_;
}
void SequestInfile::setDatabase(const String & database)
{
database_ = database;
}
const String & SequestInfile::getNeutralLossesForIons() const
{
return neutral_losses_for_ions_;
}
void SequestInfile::setNeutralLossesForIons(const String & neutral_losses_for_ions)
{
neutral_losses_for_ions_ = neutral_losses_for_ions;
}
const String & SequestInfile::getIonSeriesWeights() const
{
return ion_series_weights_;
}
void SequestInfile::setIonSeriesWeights(const String & ion_series_weights)
{
ion_series_weights_ = ion_series_weights;
}
const String & SequestInfile::getPartialSequence() const
{
return partial_sequence_;
}
void SequestInfile::setPartialSequence(const String & partial_sequence)
{
partial_sequence_ = partial_sequence;
}
const String & SequestInfile::getSequenceHeaderFilter() const
{
return sequence_header_filter_;
}
void SequestInfile::setSequenceHeaderFilter(const String & sequence_header_filter)
{
sequence_header_filter_ = sequence_header_filter;
}
const String & SequestInfile::getProteinMassFilter() const
{
return protein_mass_filter_;
}
void SequestInfile::setProteinMassFilter(const String & protein_mass_filter)
{
protein_mass_filter_ = protein_mass_filter;
}
float SequestInfile::getPrecursorMassTolerance() const
{
return precursor_mass_tolerance_;
}
void SequestInfile::setPrecursorMassTolerance(float precursor_mass_tolerance)
{
precursor_mass_tolerance_ = precursor_mass_tolerance;
}
float SequestInfile::getPeakMassTolerance() const
{
return peak_mass_tolerance_;
}
void SequestInfile::setPeakMassTolerance(float peak_mass_tolerance)
{
peak_mass_tolerance_ = peak_mass_tolerance;
}
float SequestInfile::getMatchPeakTolerance() const
{
return match_peak_tolerance_;
}
void SequestInfile::setMatchPeakTolerance(float match_peak_tolerance)
{
match_peak_tolerance_ = match_peak_tolerance;
}
float SequestInfile::getIonCutoffPercentage() const
{
return ion_cutoff_percentage_;
}
void SequestInfile::setIonCutoffPercentage(float ion_cutoff_percentage)
{
ion_cutoff_percentage_ = ion_cutoff_percentage;
}
Size SequestInfile::getPeptideMassUnit() const
{
return peptide_mass_unit_;
}
void SequestInfile::setPeptideMassUnit(Size peptide_mass_unit)
{
peptide_mass_unit_ = peptide_mass_unit;
}
Size SequestInfile::getOutputLines() const
{
return output_lines_;
}
void SequestInfile::setOutputLines(Size output_lines)
{
output_lines_ = output_lines;
}
Size SequestInfile::getEnzymeNumber() const
{
return enzyme_number_;
}
String SequestInfile::getEnzymeName() const
{
map<String, vector<String> >::const_iterator einfo_i = enzyme_info_.begin();
for (Size enzyme_number = 0; enzyme_number < enzyme_number_; ++enzyme_number, ++einfo_i)
{
}
return einfo_i->first;
}
Size SequestInfile::setEnzyme(const String& enzyme_name)
{
enzyme_number_ = 0;
map<String, vector<String> >::const_iterator einfo_i;
for (einfo_i = enzyme_info_.begin(); einfo_i != enzyme_info_.end(); ++einfo_i, ++enzyme_number_)
{
if (einfo_i->first == enzyme_name)
{
break;
}
}
return (einfo_i == enzyme_info_.end()) ? enzyme_info_.size() : 0;
}
Size SequestInfile::getMaxAAPerModPerPeptide() const
{
return max_AA_per_mod_per_peptide_;
}
void SequestInfile::setMaxAAPerModPerPeptide(Size max_AA_per_mod_per_peptide)
{
max_AA_per_mod_per_peptide_ = max_AA_per_mod_per_peptide;
}
Size SequestInfile::getMaxModsPerPeptide() const
{
return max_mods_per_peptide_;
}
void SequestInfile::setMaxModsPerPeptide(Size max_mods_per_peptide)
{
max_mods_per_peptide_ = max_mods_per_peptide;
}
Size SequestInfile::getNucleotideReadingFrame() const
{
return nucleotide_reading_frame_;
}
void SequestInfile::setNucleotideReadingFrame(Size nucleotide_reading_frame)
{
nucleotide_reading_frame_ = nucleotide_reading_frame;
}
Size SequestInfile::getMaxInternalCleavageSites() const
{
return max_internal_cleavage_sites_;
}
void SequestInfile::setMaxInternalCleavageSites(Size max_internal_cleavage_sites)
{
max_internal_cleavage_sites_ = max_internal_cleavage_sites;
}
Size SequestInfile::getMatchPeakCount() const
{
return match_peak_count_;
}
void SequestInfile::setMatchPeakCount(Size match_peak_count)
{
match_peak_count_ = match_peak_count;
}
Size SequestInfile::getMatchPeakAllowedError() const
{
return match_peak_allowed_error_;
}
void SequestInfile::setMatchPeakAllowedError(Size match_peak_allowed_error)
{
match_peak_allowed_error_ = match_peak_allowed_error;
}
bool SequestInfile::getShowFragmentIons() const
{
return show_fragment_ions_;
}
void SequestInfile::setShowFragmentIons(bool show_fragment_ions)
{
show_fragment_ions_ = show_fragment_ions;
}
bool SequestInfile::getPrintDuplicateReferences() const
{
return print_duplicate_references_;
}
void SequestInfile::setPrintDuplicateReferences(bool print_duplicate_references)
{
print_duplicate_references_ = print_duplicate_references;
}
bool SequestInfile::getRemovePrecursorNearPeaks() const
{
return remove_precursor_near_peaks_;
}
void SequestInfile::setRemovePrecursorNearPeaks(bool remove_precursor_near_peaks)
{
remove_precursor_near_peaks_ = remove_precursor_near_peaks;
}
bool SequestInfile::getMassTypeParent() const
{
return mass_type_parent_;
}
void SequestInfile::setMassTypeParent(bool mass_type_parent)
{
mass_type_parent_ = mass_type_parent;
}
bool SequestInfile::getMassTypeFragment() const
{
return mass_type_fragment_;
}
void SequestInfile::setMassTypeFragment(bool mass_type_fragment)
{
mass_type_fragment_ = mass_type_fragment;
}
bool SequestInfile::getNormalizeXcorr() const
{
return normalize_xcorr_;
}
void SequestInfile::setNormalizeXcorr(bool normalize_xcorr)
{
normalize_xcorr_ = normalize_xcorr;
}
bool SequestInfile::getResiduesInUpperCase() const
{
return residues_in_upper_case_;
}
void SequestInfile::setResiduesInUpperCase(bool residues_in_upper_case)
{
residues_in_upper_case_ = residues_in_upper_case;
}
const map<String, vector<String> > & SequestInfile::getModifications() const
{
return PTMname_residues_mass_type_;
}
void SequestInfile::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
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
// 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 (const String& mod_i : modifications)
{
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);
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!");
}
}
}
}
void SequestInfile::setStandardEnzymeInfo_()
{
vector<String> info;
// cuts n to c? cuts before doesn't cut after
info.emplace_back("0"); info.emplace_back("-"); info.emplace_back("-"); enzyme_info_["No_Enzyme"] = info; info.clear();
info.emplace_back("1"); info.emplace_back("KR"); info.emplace_back("-"); enzyme_info_["Trypsin_Strict"] = info; info.clear();
info.emplace_back("1"); info.emplace_back("KRLNH"); info.emplace_back("-"); enzyme_info_["Trypsin"] = info; info.clear();
info.emplace_back("1"); info.emplace_back("FWYL"); info.emplace_back("-"); enzyme_info_["Chymotrypsin"] = info; info.clear();
info.emplace_back("1"); info.emplace_back("FWY"); info.emplace_back("-"); enzyme_info_["Chymotrypsin_WYF"] = info; info.clear();
info.emplace_back("1"); info.emplace_back("R"); info.emplace_back("-"); enzyme_info_["Clostripain"] = info; info.clear();
info.emplace_back("1"); info.emplace_back("M"); info.emplace_back("-"); enzyme_info_["Cyanogen_Bromide"] = info; info.clear();
info.emplace_back("1"); info.emplace_back("W"); info.emplace_back("-"); enzyme_info_["IodosoBenzoate"] = info; info.clear();
info.emplace_back("1"); info.emplace_back("P"); info.emplace_back("-"); enzyme_info_["Proline_Endopept"] = info; info.clear();
info.emplace_back("1"); info.emplace_back("E"); info.emplace_back("-"); enzyme_info_["GluC"] = info; info.clear();
info.emplace_back("1"); info.emplace_back("ED"); info.emplace_back("-"); enzyme_info_["GluC_ED"] = info; info.clear();
info.emplace_back("1"); info.emplace_back("K"); info.emplace_back("-"); enzyme_info_["LysC"] = info; info.clear();
info.emplace_back("0"); info.emplace_back("D"); info.emplace_back("-"); enzyme_info_["AspN"] = info; info.clear();
info.emplace_back("0"); info.emplace_back("DE"); info.emplace_back("-"); enzyme_info_["AspN_DE"] = info; info.clear();
info.emplace_back("1"); info.emplace_back("ALIV"); info.emplace_back("P"); enzyme_info_["Elastase"] = info; info.clear();
info.emplace_back("1"); info.emplace_back("ALIVKRWFY"); info.emplace_back("P"); enzyme_info_["Elastase/Tryp/Chymo"] = info; info.clear();
info.emplace_back("1"); info.emplace_back("KRLFWYN"); info.emplace_back("-"); enzyme_info_["Trypsin/Chymo"] = info; info.clear();
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/GNPSMetaValueFile.cpp | .cpp | 1,350 | 37 | // 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/GNPSMetaValueFile.h>
#include <OpenMS/FORMAT/SVOutStream.h>
#include <fstream>
#include <iostream>
#include <unordered_map>
namespace OpenMS
{
/**
@brief Generates a meta value table required for GNPS FBMN, as defined here: https://ccms-ucsd.github.io/GNPSDocumentation/metadata/
*/
void GNPSMetaValueFile::store(const ConsensusMap& consensus_map, const String& output_file)
{
StringList mzML_file_paths;
consensus_map.getPrimaryMSRunPath(mzML_file_paths);
std::ofstream outstr(output_file.c_str());
SVOutStream out(outstr, "\t", "_", String::NONE);
out << "" << "filename" << "ATTRIBUTE_MAPID" << std::endl;
Size i = 0;
for (const auto& path: mzML_file_paths)
{
out << String(i) << path.substr(path.find_last_of("/\\")+1) << "MAP"+String(i) << std::endl;
i++;
}
}
} // namespace | C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/XTandemXMLFile.cpp | .cpp | 12,561 | 360 | // 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/XTandemXMLFile.h>
#include <OpenMS/CHEMISTRY/ModificationsDB.h>
#include <OpenMS/METADATA/ProteinIdentification.h>
using namespace xercesc;
using namespace std;
namespace OpenMS
{
XTandemXMLFile::XTandemXMLFile() :
XMLHandler("", 1.1),
XMLFile()
{
// see X! Tandem parameters "protein, quick pyrolidone" and "protein, quick acetyl":
default_nterm_mods_.setModifications("", "Gln->pyro-Glu (N-term Q),Glu->pyro-Glu (N-term E),Acetyl (N-term)");
}
XTandemXMLFile::~XTandemXMLFile() = default;
void XTandemXMLFile::load(const String& filename, ProteinIdentification& protein_identification, PeptideIdentificationList& peptide_ids, ModificationDefinitionsSet& mod_def_set)
{
// File name for error message in XMLHandler
file_ = filename;
mod_def_set_ = mod_def_set;
// reset everything, in case "load" is called multiple times:
is_protein_note_ = is_spectrum_note_ = skip_protein_acc_update_ = false;
peptide_hits_.clear();
protein_hits_.clear();
current_protein_ = tag_ = previous_seq_ = "";
current_charge_ = 0;
current_id_ = current_start_ = current_stop_ = 0;
spectrum_ids_.clear();
enforceEncoding_("ISO-8859-1");
parse_(filename, this);
DateTime now = DateTime::now();
String date_string = now.getDate();
String identifier("XTandem_" + date_string);
//vector<String> accessions;
// convert mapping id -> peptide_hits into peptide hits list
peptide_ids.clear();
for (map<UInt, vector<PeptideHit> >::iterator it = peptide_hits_.begin(); it != peptide_hits_.end(); ++it)
{
PeptideIdentification id;
id.setScoreType("XTandem");
id.setHigherScoreBetter(true);
id.setIdentifier(identifier);
id.setSpectrumReference( spectrum_ids_[it->first]);
id.getHits().swap(it->second);
id.sort();
peptide_ids.push_back(id);
}
protein_identification.getHits().swap(protein_hits_);
// E-values
protein_identification.setHigherScoreBetter(false);
protein_identification.sort();
protein_identification.setScoreType("XTandem");
protein_identification.setSearchEngine("XTandem");
// TODO version of XTandem ???? is not available from performance param section of outputfile (to be parsed)
// TODO Date of search, dito
protein_identification.setDateTime(now);
protein_identification.setIdentifier(identifier);
// TODO search parameters are also available
// mods may be changed, copy them back:
mod_def_set = mod_def_set_;
}
void XTandemXMLFile::startElement(const XMLCh* const /*uri*/, const XMLCh* const /*local_name*/, const XMLCh* const qname, const Attributes& attributes)
{
tag_ = String(sm_.convert(qname));
if (tag_ == "domain")
{
String id_string = attributeAsString_(attributes, "id");
UInt id = id_string.prefix('.').toInt();
current_id_ = id;
PeptideEvidence pe;
// get amino acid before
String pre = attributeAsString_(attributes, "pre");
if (!pre.empty())
{
pe.setAABefore(pre[pre.size()-1]);
}
// get amino acid after
String post = attributeAsString_(attributes, "post");
if (!post.empty())
{
pe.setAAAfter(post[0]);
}
current_start_ = attributeAsInt_(attributes, "start");
pe.setStart(current_start_ - 1);
current_stop_ = attributeAsInt_(attributes, "end");
pe.setEnd(current_stop_ - 1);
pe.setProteinAccession(current_protein_);
String seq = attributeAsString_(attributes, "seq");
// is this the same peptide as before, just in a different protein (scores will be the same)?
if ((peptide_hits_.find(id) == peptide_hits_.end()) || (seq != previous_seq_))
{
PeptideHit hit;
// can't parse sequences permissively because that would skip characters
// that X! Tandem includes when calculating e.g. modification positions,
// potentially leading to errors when assigning mods to residues:
hit.setSequence(AASequence::fromString(seq, false));
hit.setCharge(current_charge_);
// get scores etc.:
hit.setMetaValue("nextscore", attributeAsDouble_(attributes, "nextscore"));
hit.setMetaValue("delta", attributeAsDouble_(attributes, "delta"));
hit.setMetaValue("mass", attributeAsDouble_(attributes, "mh")); // note the different names
hit.setMetaValue("E-Value", attributeAsDouble_(attributes, "expect")); // note the different names
double hyperscore = attributeAsDouble_(attributes, "hyperscore");
hit.setMetaValue("hyperscore", hyperscore);
hit.setScore(hyperscore);
// try to get a, b, c, x, y, z score (optional)
String ions = "abcxyz";
String ion_score = " _score";
String ion_count = " _ions";
for (String::iterator it = ions.begin(); it != ions.end(); ++it)
{
ion_score[0] = *it;
double score;
if (optionalAttributeAsDouble_(score, attributes, ion_score.c_str()))
{
hit.setMetaValue(ion_score, score);
}
ion_count[0] = *it;
UInt count;
if (optionalAttributeAsUInt_(count, attributes, ion_count.c_str()))
{
hit.setMetaValue(ion_count, count);
}
}
peptide_hits_[id].push_back(hit);
previous_seq_ = seq;
}
peptide_hits_[id].back().addPeptideEvidence(pe);
return;
}
if (tag_ == "aa")
{
if (group_type_stack_.empty())
{
error(LOAD, String("Found an 'aa' element outside of a 'group'! Please check your input file."));
}
auto& current_group_type_ = group_type_stack_.top();
// TODO support "aa" entries in the parameter groups (e.g. to read user-specified amino acids)
// currently we just ignore them
if (current_group_type_ == GroupType::MODEL)
{
// e.g. <aa type="S" at="2" modified="42.0106" />
String aa = attributeAsString_(attributes, "type");
Int mod_pos = attributeAsInt_(attributes, "at");
double mass_shift = attributeAsDouble_(attributes, "modified");
AASequence aa_seq = peptide_hits_[current_id_].back().getSequence();
mod_pos -= current_start_; // X! Tandem uses position in the protein
const ResidueModification* res_mod = nullptr;
// first, try to find matching mod in the defined ones:
multimap<double, ModificationDefinition> matches;
if (mod_pos <= 0) // N-terminal mod?
{
mod_def_set_.findMatches(matches, mass_shift, aa,
ResidueModification::N_TERM);
}
else if (mod_pos >= Int(aa_seq.size() - 1)) // C-terminal mod?
{
mod_def_set_.findMatches(matches, mass_shift, aa,
ResidueModification::C_TERM);
}
if (matches.empty())
{
mod_def_set_.findMatches(matches, mass_shift, aa,
ResidueModification::ANYWHERE);
}
if (matches.empty() && (mod_pos <= 0)) // try X! Tandem's default mods
{
default_nterm_mods_.findMatches(matches, mass_shift, aa,
ResidueModification::N_TERM);
if (!matches.empty())
{
// add the match to the mod. set for output (search parameters):
ModificationDefinition mod_def(matches.begin()->second.getModificationName());
mod_def.setFixedModification(false);
mod_def_set_.addModification(mod_def);
}
}
// matches are sorted by mass error - first one is best match:
if (!matches.empty())
{
res_mod = &(matches.begin()->second.getModification());
}
else // no match? strange, let's try all possible modifications
{
ModificationsDB* mod_db = ModificationsDB::getInstance();
// try to find a mod that fits
if (mod_pos <= 0) // can (!) be an N-terminal mod
{
res_mod = mod_db->getBestModificationByDiffMonoMass(mass_shift, 0.01, aa, ResidueModification::N_TERM);
}
else if (mod_pos >= static_cast<int>(aa_seq.size() - 1))
{
res_mod = mod_db->getBestModificationByDiffMonoMass(mass_shift, 0.01, aa, ResidueModification::C_TERM);
}
if (res_mod == nullptr) // if no terminal mod, try normal one
{
res_mod = mod_db->getBestModificationByDiffMonoMass(mass_shift, 0.01, aa, ResidueModification::ANYWHERE);
}
}
if (res_mod == nullptr)
{
error(LOAD, String("No modification found which fits residue '") + aa + "' with mass '" + String(mass_shift) + "'!");
}
else
{
// @TODO: avoid unnecessary conversion of mods from/to string below
if (res_mod->getTermSpecificity() == ResidueModification::N_TERM)
{
aa_seq.setNTerminalModification(res_mod->getFullId());
}
else if (res_mod->getTermSpecificity() == ResidueModification::C_TERM)
{
aa_seq.setCTerminalModification(res_mod->getFullId());
}
else
{
aa_seq.setModification(mod_pos, res_mod->getFullId());
}
peptide_hits_[current_id_].back().setSequence(aa_seq);
}
}
}
if (tag_ == "group")
{
String type = attributeAsString_(attributes, "type");
if (type == "model")
{
group_type_stack_.push(GroupType::MODEL);
Int index = attributes.getIndex(sm_.convert("z").c_str());
if (index >= 0)
{
current_charge_ = String(sm_.convert(attributes.getValue(index))).toInt();
}
previous_seq_ = "";
}
else if (type == "parameter")
{
group_type_stack_.push(GroupType::PARAMETERS);
}
else
{
group_type_stack_.push(GroupType::SUPPORT);
}
}
if (tag_ == "note")
{
String label;
optionalAttributeAsString_(label, attributes, "label");
if (label == "description") // in '<"protein" ...>'
{
is_protein_note_ = true;
}
else if (label == "Description") // in '<group type="support" label="fragment ion mass spectrum">'
{
is_spectrum_note_ = true;
}
}
if (tag_ == "protein")
{
UInt uid = attributeAsInt_(attributes, "uid");
if (protein_uids_.find(uid) == protein_uids_.end()) // new protein
{
ProteinHit hit;
// accession may be overwritten based on '<note label="description">', but set it for now:
current_protein_ = attributeAsString_(attributes, "label");
hit.setAccession(current_protein_);
double score(0);
if (optionalAttributeAsDouble_(score, attributes, "expect"))
{
hit.setScore(score);
}
protein_hits_.push_back(hit);
protein_uids_.insert(uid);
skip_protein_acc_update_ = false;
}
else
{
current_protein_ = attributeAsString_(attributes, "label"); //save it for upcoming peptides (domains)
skip_protein_acc_update_ = true;
}
return;
}
}
void XTandemXMLFile::endElement(const XMLCh* const /*uri*/, const XMLCh* const /*local_name*/, const XMLCh* const qname)
{
tag_ = String(sm_.convert(qname));
if (tag_ == "group")
{
group_type_stack_.pop();
}
}
void XTandemXMLFile::characters(const XMLCh* const chars, const XMLSize_t /*length*/)
{
if (tag_ == "note")
{
if (is_protein_note_)
{
current_protein_ = String(sm_.convert(chars)).trim();
if (!skip_protein_acc_update_)
{
protein_hits_.back().setAccession(current_protein_);
}
}
else if (is_spectrum_note_)
{
spectrum_ids_[current_id_] = String(sm_.convert(chars)).trim();
}
is_protein_note_ = false;
is_spectrum_note_ = false;
}
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/PepXMLFile.cpp | .cpp | 87,937 | 2,184 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow, Hendrik Weisser $
// $Authors: Chris Bielow, Hendrik Weisser $
// --------------------------------------------------------------------------
#include <OpenMS/CHEMISTRY/AASequence.h>
#include <OpenMS/CHEMISTRY/Residue.h>
#include <OpenMS/CONCEPT/Constants.h>
#include <OpenMS/CONCEPT/Exception.h>
#include <OpenMS/FORMAT/PepXMLFile.h>
#include <OpenMS/CHEMISTRY/ElementDB.h>
#include <OpenMS/CHEMISTRY/ModificationsDB.h>
#include <OpenMS/CHEMISTRY/ResidueDB.h>
#include <OpenMS/CHEMISTRY/ProteaseDB.h>
#include <fstream>
using namespace std;
namespace OpenMS
{
String PepXMLFile::AminoAcidModification::toUnimodLikeString() const
{
String desc = "";
if (massdiff_ >= 0)
{
desc += "+" + String(massdiff_);
}
else
{
desc += String(massdiff_);
}
if (!aminoacid_.empty() || !terminus_.empty())
{
desc += " (";
if (!terminus_.empty())
{
if (is_protein_terminus_)
{
desc += "Protein ";
}
{
String t = terminus_;
desc += t.toUpper() + "-term";
}
if (!aminoacid_.empty())
{
desc += " ";
}
}
if (!aminoacid_.empty())
{
String a = aminoacid_;
desc += a.toUpper();
}
desc += ")";
}
return desc;
}
const String& PepXMLFile::AminoAcidModification::getDescription() const
{
return registered_mod_->getFullId();
}
bool PepXMLFile::AminoAcidModification::isVariable() const
{
return is_variable_;
}
double PepXMLFile::AminoAcidModification::getMass() const
{
return mass_;
}
double PepXMLFile::AminoAcidModification::getMassDiff() const
{
return massdiff_;
}
const String& PepXMLFile::AminoAcidModification::getTerminus() const
{
return terminus_;
}
const String& PepXMLFile::AminoAcidModification::getAminoAcid() const
{
return aminoacid_;
}
const ResidueModification* PepXMLFile::AminoAcidModification::getRegisteredMod() const
{
return registered_mod_;
}
const vector<String>& PepXMLFile::AminoAcidModification::getErrors() const
{
return errors_;
}
const ResidueModification*
PepXMLFile::AminoAcidModification::lookupModInPreferredMods_(const vector<const ResidueModification*>& preferred_mods,
const String& aminoacid,
double massdiff,
const String& description,
const ResidueModification::TermSpecificity term_spec,
double tolerance)
{
for (const auto& pref_mod : preferred_mods)
{
if (description == pref_mod->getFullId())
{
return pref_mod;
}
}
for (const auto& pref_mod : preferred_mods)
{
if ((aminoacid.empty() || aminoacid[0] == pref_mod->getOrigin()) &&
(term_spec == ResidueModification::NUMBER_OF_TERM_SPECIFICITY || term_spec == pref_mod->getTermSpecificity()))
{
if (fabs(massdiff - pref_mod->getDiffMonoMass()) < tolerance)
{
return pref_mod;
}
}
}
return nullptr;
}
PepXMLFile::AminoAcidModification::AminoAcidModification(
const String& aminoacid, const String& massdiff, const String& mass,
String variable, const String& description, String terminus, const String& protein_terminus,
const vector<const ResidueModification*>& preferred_fixed_mods,
const vector<const ResidueModification*>& preferred_var_mods,
double tolerance)
{
if (aminoacid.empty() && terminus.empty())
{
throw Exception::MissingInformation(__FILE__,
__LINE__,
OPENMS_PRETTY_FUNCTION,
"Either terminus or amino acid origin or both needs to be set.");
}
aminoacid_ = aminoacid;
massdiff_ = massdiff.toDouble();
mass_ = mass.toDouble();
is_variable_ = variable.toLower() == "y";
description_ = description;
registered_mod_ = nullptr;
terminus_ = terminus.toLower();
is_protein_terminus_ = false;
term_spec_ = ResidueModification::NUMBER_OF_TERM_SPECIFICITY;
if (terminus_ == "nc")
{
errors_.emplace_back("Warning: value 'nc' for aminoacid terminus not supported."
"The modification will be parsed as an unrestricted modification.");
}
if (aminoacid_.size() > 1)
{
errors_.emplace_back("Warning: Single modification specified for multiple amino acids. This is not supported."
"Please split them into one modification per amino acid. Proceeding with first AA...");
}
// BIG NOTE: According to the pepXML schema specification, protein terminus is either "c" or "n" if set.
// BUT: Many tools will put "Y" or "N" there in conjunction with the terminus attribute.
// Unfortunately there is an overlap for the letter "n". We will try to handle both based on upper/lower case:
String protein_terminus_lower = protein_terminus;
protein_terminus_lower = protein_terminus_lower.toLower();
if (protein_terminus_lower == "y")
{
is_protein_terminus_ = true;
}
else if (protein_terminus_lower == "c")
{
is_protein_terminus_ = true;
terminus_ = protein_terminus_lower; // protein_terminus takes precedence. I would assume they are the same
}
else if (protein_terminus == "n")
{
is_protein_terminus_ = true;
terminus_ = protein_terminus;
}
else if (protein_terminus == "N")
{
is_protein_terminus_ = false;
}
// Now set our internal enum based on the inferred values
if (terminus_ == "n")
{
if (is_protein_terminus_)
{
term_spec_ = ResidueModification::PROTEIN_N_TERM;
}
else
{
term_spec_ = ResidueModification::N_TERM;
}
}
else if (terminus_ == "c")
{
if (is_protein_terminus_)
{
term_spec_ = ResidueModification::PROTEIN_C_TERM;
}
else
{
term_spec_ = ResidueModification::C_TERM;
}
}
if (mass_ == massdiff_)
{
errors_.emplace_back("Warning: For modification with mass " + mass + ", mass == massdiff. This is wrong. "
"Please report it to the maintainer of the tool that wrote the pepXML. OpenMS will try to calculate it manually, assuming massdiff is correct.");
if (term_spec_ == ResidueModification::N_TERM || term_spec_ == ResidueModification::PROTEIN_N_TERM)
{
mass_ = massdiff_ + Residue::getInternalToNTerm().getMonoWeight();
}
else if (term_spec_ == ResidueModification::C_TERM || term_spec_ == ResidueModification::PROTEIN_C_TERM)
{
mass_ = massdiff_ + Residue::getInternalToCTerm().getMonoWeight();
}
else
{
mass_ = massdiff_ + ResidueDB::getInstance()->getResidue(aminoacid_)->getMonoWeight(Residue::ResidueType::Internal);
}
}
if (isVariable())
{
registered_mod_ = lookupModInPreferredMods_(preferred_var_mods, aminoacid_, massdiff_,
description_, term_spec_, tolerance);
}
else
{
registered_mod_ = lookupModInPreferredMods_(preferred_fixed_mods, aminoacid_, massdiff_,
description_, term_spec_, tolerance);
}
//TODO push another warning if not found?
if (registered_mod_ == nullptr)
{
// check if the modification is uniquely defined through its description (if given):
if (!description.empty())
{
try
{
registered_mod_ = ModificationsDB::getInstance()->getModification(description, aminoacid, term_spec_);
}
catch (Exception::BaseException&)
{
errors_.emplace_back("Modification '" + description_ + "' of residue '" + aminoacid_ +
"' could not be matched. Trying by modification mass.");
}
}
else
{
errors_.emplace_back("No modification description given. Trying to define by modification mass.");
}
}
if (registered_mod_ == nullptr)
{
//TODO differentiate between integer and non-integer masses like in AASequence?
// Are there non-integer masses in the header of PepXML?
std::vector<const ResidueModification*> mods;
// if terminus was not specified
if (term_spec_ == ResidueModification::NUMBER_OF_TERM_SPECIFICITY) // try least specific search first
{
ModificationsDB::getInstance()->searchModificationsByDiffMonoMassSorted(
mods, massdiff_, mod_tol_, aminoacid_, ResidueModification::ANYWHERE);
}
if (mods.empty())
{
// for unknown terminus it looks for everything, otherwise just for the specific terminus
// TODO we might also need to search for Protein-X-Term in case of X-Term
// since some tools seem to forget to annotate
ModificationsDB::getInstance()->searchModificationsByDiffMonoMassSorted(
mods, massdiff_, mod_tol_, aminoacid_, term_spec_);
}
if (!mods.empty())
{
registered_mod_ = mods[0];
if (mods.size() > 1)
{
String mod_str = mods[0]->getFullId();
for (const auto& m : mods)
{
mod_str += ", " + m->getFullId();
}
errors_.emplace_back("Modification '" + String(mass_) + "' is not uniquely defined by the given data. Using '" +
mods[0]->getFullId() + "' to represent any of '" + mod_str + "'.");
}
}
// If we could not find a registered mod in our DB, create and register it. This will be used later for lookup in the sequences.
else if (massdiff_ != 0)
{
// r will be nullptr if not found. The next line handles it.
const Residue* r = ResidueDB::getInstance()->getResidue(aminoacid_[0]);
//TODO check if it is better to create from mass or massdiff
registered_mod_ = ResidueModification::createUnknownFromMassString(String(massdiff_),
massdiff_,
true,
term_spec_,
r);
//Modification unknown, but trying to continue as we want to be able to read the rest despite
// of the modifications but warning this will fail downstream
errors_.emplace_back(
"Modification '" + String(mass_) + "/delta " + String(massdiff_) +
"' is unknown. Resuming with '" + registered_mod_->getFullId() +
"', which could lead to failures using the data downstream.");
}
}
}
PepXMLFile::PepXMLFile() :
XMLHandler("", "1.12"),
XMLFile("/SCHEMAS/pepXML_v114.xsd", "1.14"),
proteins_(nullptr),
peptides_(nullptr),
lookup_(nullptr),
scan_map_(),
analysis_summary_(false),
keep_native_name_(false),
search_score_summary_(false),
preferred_fixed_modifications_({}),
preferred_variable_modifications_({})
{
const ElementDB* db = ElementDB::getInstance();
hydrogen_ = *db->getElement("Hydrogen");
}
const double PepXMLFile::mod_tol_ = 0.002;
const double PepXMLFile::xtandem_artificial_mod_tol_ = 0.0005; // according to cpp in some old version of xtandem somehow very small fixed modification (electron mass?) gets annotated by X!Tandem. Don't add them as they interfere with other modifications.
PepXMLFile::~PepXMLFile() = default;
void PepXMLFile::store(const String& filename, std::vector<ProteinIdentification>& protein_ids, PeptideIdentificationList& peptide_ids, const String& mz_file, const String& mz_name, bool peptideprophet_analyzed, double rt_tolerance)
{
ofstream f(filename.c_str());
if (!f)
{
throw Exception::UnableToCreateFile(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename);
}
String search_engine_name;
ProteinIdentification::SearchParameters search_params;
if (!protein_ids.empty())
{
if (protein_ids.size() > 1)
{
warning(STORE, "More than one protein identification defined; only first search parameters are written into pepXML; search engine must be the same.");
}
search_params = protein_ids.begin()->getSearchParameters();
if (protein_ids.begin()->getSearchEngine() == "XTandem")
{
search_engine_name = "X! Tandem";
}
else if (protein_ids.begin()->getSearchEngine() == "Mascot")
{
search_engine_name = "MASCOT";
}
else
{
search_engine_name = protein_ids.begin()->getSearchEngine();
//Comet writes "Comet" in pep.xml, so this is ok
}
}
f.precision(writtenDigits<double>(0.0));
String raw_data;
String base_name;
SpectrumMetaDataLookup lookup;
lookup.rt_tolerance = rt_tolerance;
// The mz-File (if given)
if (!mz_file.empty())
{
base_name = FileHandler::stripExtension(File::basename(mz_file));
raw_data = FileTypes::typeToName(FileHandler::getTypeByFileName(mz_file));
PeakMap experiment;
FileHandler fh;
fh.loadExperiment(mz_file, experiment, {}, ProgressLogger::NONE, false, false);
lookup.readSpectra(experiment.getSpectra());
}
else
{
base_name = FileHandler::stripExtension(File::basename(filename));
raw_data = "mzML";
}
// mz_name is input from IDFileConverter for 'base_name' attribute, only necessary if different from 'mz_file'.
if (!mz_name.empty())
{
base_name = mz_name;
}
if (base_name.hasSubstring(".")) // spectrum query name is split by dot, otherwise correct charge can not be read.
{
replace(base_name.begin(), base_name.end(), '.', '_');
}
f << R"(<?xml version="1.0" encoding="UTF-8"?>)" << "\n";
f << R"(<msms_pipeline_analysis date="2007-12-05T17:49:46" xmlns="http://regis-web.systemsbiology.net/pepXML" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://sashimi.sourceforge.net/schema_revision/pepXML/pepXML_v117.xsd" summary_xml=".xml">)" << "\n";
f << "<msms_run_summary base_name=\"" << base_name << R"(" raw_data_type="raw" raw_data=".)" << raw_data << "\" search_engine=\"" << search_engine_name << "\">" << "\n";
String enzyme_name = search_params.digestion_enzyme.getName();
f << "\t<sample_enzyme name=\"";
f << enzyme_name.toLower() << "\">" << "\n";
f << "\t\t<specificity cut=\"";
if (!search_params.digestion_enzyme.getRegEx().empty())
{
vector<String> sub_regex;
search_params.digestion_enzyme.getRegEx().split(")",sub_regex);
boost::match_results<std::string::const_iterator> results;
static const boost::regex e("(.*?)([A-Z]+)(.*?)");
if (boost::regex_match(sub_regex[0], results, e))
{
f << results[2];
}
if (sub_regex[1].hasSubstring("!P"))
{
f << "\" no_cut=\"P";
}
}
f << R"(" sense="C"/>)" << "\n";
f << "\t</sample_enzyme>" << "\n";
f << "\t<search_summary base_name=\"" << base_name;
f << "\" search_engine=\"" << search_engine_name;
f << "\" precursor_mass_type=\"";
if (search_params.mass_type == ProteinIdentification::PeakMassType::MONOISOTOPIC)
{
f << "monoisotopic";
}
else
{
f << "average";
}
f << "\" fragment_mass_type=\"";
if (search_params.mass_type == ProteinIdentification::PeakMassType::MONOISOTOPIC)
{
f << "monoisotopic";
}
else
{
f << "average";
}
f << R"(" out_data_type="" out_data="" search_id="1">)" << "\n";
f << "\t\t<search_database local_path=\"" << search_params.db << R"(" type="AA"/>)" << "\n";
// register modifications
set<String> aa_mods;
set<String> n_term_mods, c_term_mods;
for (PeptideIdentificationList::const_iterator it = peptide_ids.begin();
it != peptide_ids.end(); ++it)
{
if (!it->getHits().empty())
{
PeptideHit h = *it->getHits().begin();
if (h.getSequence().isModified())
{
const AASequence& p = h.getSequence();
if (p.hasNTerminalModification())
{
n_term_mods.insert(p.getNTerminalModification()->getFullId());
}
if (p.hasCTerminalModification())
{
c_term_mods.insert(p.getCTerminalModification()->getFullId());
}
for (Size i = 0; i != p.size(); ++i)
{
if (p[i].isModified())
{
aa_mods.insert(p[i].getModification()->getFullId());
}
}
}
}
}
// write modifications definitions
// <aminoacid_modification aminoacid="C" massdiff="+58.01" mass="161.014664" variable="Y" binary="N" description="Carboxymethyl (C)"/>
for (set<String>::const_iterator it = aa_mods.begin();
it != aa_mods.end(); ++it)
{
const ResidueModification* mod = ModificationsDB::getInstance()->getModification(*it, "", ResidueModification::ANYWHERE);
// compute mass of modified residue
EmpiricalFormula ef = ResidueDB::getInstance()->getResidue(mod->getOrigin())->getFormula(Residue::Internal);
ef += mod->getDiffFormula();
f << "\t\t"
<< "<aminoacid_modification aminoacid=\"" << mod->getOrigin()
<< "\" massdiff=\"" << precisionWrapper(mod->getDiffMonoMass()) << "\" mass=\""
<< precisionWrapper(ef.getMonoWeight())
<< R"(" variable="Y" binary="N" description=")" << *it << "\"/>"
<< "\n";
}
for (set<String>::const_iterator it = n_term_mods.begin(); it != n_term_mods.end(); ++it)
{
const ResidueModification* mod = ModificationsDB::getInstance()->getModification(*it, "", ResidueModification::N_TERM);
f << "\t\t"
<< R"(<terminal_modification terminus="n" massdiff=")"
<< precisionWrapper(mod->getDiffMonoMass()) << "\" mass=\"" << precisionWrapper(mod->getMonoMass())
<< R"(" variable="Y" description=")" << *it
<< R"(" protein_terminus=""/>)" << "\n";
}
for (set<String>::const_iterator it = c_term_mods.begin(); it != c_term_mods.end(); ++it)
{
const ResidueModification* mod = ModificationsDB::getInstance()->getModification(*it, "", ResidueModification::C_TERM);
f << "\t\t"
<< R"(<terminal_modification terminus="c" massdiff=")"
<< precisionWrapper(mod->getDiffMonoMass()) << "\" mass=\"" << precisionWrapper(mod->getMonoMass())
<< R"(" variable="Y" description=")" << *it
<< R"(" protein_terminus=""/>)" << "\n";
}
f << "\t</search_summary>" << "\n";
if (peptideprophet_analyzed)
{
f << "\t<analysis_timestamp analysis=\"peptideprophet\" time=\"2007-12-05T17:49:52\" id=\"1\"/>" << "\n";
}
// Scan index and scan number will be reconstructed if no spectrum lookup is possible to retrieve the values.
// The scan index is generally zero-based and the scan number generally one-based.
Int count(0);
for (const PeptideIdentification& pep : peptide_ids)
{
if (pep.getHits().empty())
{
++count;
continue;
}
for (const PeptideHit& hit : pep.getHits())
{
PeptideHit h = hit;
const AASequence& seq = h.getSequence();
double precursor_neutral_mass = seq.getMonoWeight();
int scan_index = count;
int scan_nr = 0;
if (lookup.empty())
{
if (pep.metaValueExists("RT_index")) // Setting metaValue "RT_index" in XTandemXMLFile in the case of X! Tandem.
{
scan_index = pep.getMetaValue("RT_index");
}
scan_nr = scan_index + 1;
}
else
{
if (pep.metaValueExists("spectrum_reference"))
{
//findByNativeID will fall back to RT lookup if none of the regexes registered in lookup can extract a meaningful ID or scan nr
scan_index = lookup.findByNativeID(pep.getSpectrumReference());
}
else
{
scan_index = lookup.findByRT(pep.getRT());
}
SpectrumMetaDataLookup::SpectrumMetaData meta;
lookup.getSpectrumMetaData(scan_index, meta);
scan_nr = meta.scan_number;
}
// PeptideProphet requires this format for "spectrum" attribute (otherwise TPP parsing error)
// - see also the parser code if iProphet at http://sourceforge.net/p/sashimi/code/HEAD/tree/trunk/trans_proteomic_pipeline/src/Validation/InterProphet/InterProphetParser/InterProphetParser.cxx#l180
// strictly required attributes:
// - spectrum
// - assumed_charge
// optional attributes
// - retention_time_sec
// - swath_assay
// - experiment_label
String spectrum_name = base_name + "." + scan_nr + "." + scan_nr + ".";
if (pep.metaValueExists("pepxml_spectrum_name") && keep_native_name_)
{
spectrum_name = pep.getMetaValue("pepxml_spectrum_name");
}
f << "\t<spectrum_query spectrum=\"" << spectrum_name << h.getCharge() << "\""
<< " start_scan=\"" << scan_nr << "\""
<< " end_scan=\"" << scan_nr << "\""
<< " precursor_neutral_mass=\"" << precisionWrapper(precursor_neutral_mass) << "\""
<< " assumed_charge=\"" << h.getCharge() << "\" index=\"" << scan_index << "\"";
if (pep.hasRT())
{
f << " retention_time_sec=\"" << pep.getRT() << "\" ";
}
if (!pep.getExperimentLabel().empty())
{
f << " experiment_label=\"" << pep.getExperimentLabel() << "\" ";
}
// "swath_assay" is an optional parameter used for SWATH-MS mostly and
// may be set for a PeptideIdentification
// note that according to the parsing rules of TPP, this needs to be
// "xxx:yyy" where xxx is any string and yyy is probably an integer
// indicating the Swath window
if (pep.metaValueExists("swath_assay"))
{
f << " swath_assay=\"" << pep.getMetaValue("swath_assay") << "\" ";
}
// "status" is an attribute that may be target or decoy
if (pep.metaValueExists("status"))
{
f << " status=\"" << pep.getMetaValue("status") << "\" ";
}
f << ">\n";
f << "\t<search_result>" << "\n";
vector<PeptideEvidence> pes = h.getPeptideEvidences();
// select first one if multiple are present as "leader"
PeptideEvidence pe;
if (!h.getPeptideEvidences().empty())
{
pe = pes[0];
}
f << "\t\t<search_hit hit_rank=\"" << String(h.getRank() + 1) << "\" peptide=\"" // rank in pepXML is 1-based, 0-based in OpenMS
<< seq.toUnmodifiedString() << "\" peptide_prev_aa=\""
<< pe.getAABefore() << "\" peptide_next_aa=\"" << pe.getAAAfter()
<< "\" protein=\"";
f << pe.getProteinAccession();
f << R"(" num_tot_proteins="1" num_matched_ions="0" tot_num_ions="0" calc_neutral_pep_mass=")" << precisionWrapper(precursor_neutral_mass)
<< R"(" massdiff="0.0" num_tol_term=")";
Int num_tol_term = 1;
if ((pe.getAABefore() == 'R' || pe.getAABefore() == 'K') && search_params.digestion_enzyme.getName() == "Trypsin")
{
num_tol_term = 2;
}
f << num_tol_term;
f << R"(" num_missed_cleavages="0" is_rejected="0" protein_descr="Protein No. 1">)" << "\n";
// multiple protein hits: <alternative_protein protein="sp|P0CZ86|GLS24_STRP3" num_tol_term="2" peptide_prev_aa="K" peptide_next_aa="-"/>
if (pes.size() > 1)
{
for (Size k = 1; k != pes.size(); ++k)
{
f << "\t\t<alternative_protein protein=\"" << pes[k].getProteinAccession() << "\" num_tol_term=\"" << num_tol_term << "\"";
if (pes[k].getAABefore() != PeptideEvidence::UNKNOWN_AA)
{
f << " peptide_prev_aa=\"" << pes[k].getAABefore() << "\"";
}
if (pes[k].getAAAfter() != PeptideEvidence::UNKNOWN_AA)
{
f << " peptide_next_aa=\"" << pes[k].getAAAfter() << "\"";
}
f << "/>" << "\n";
}
}
if (seq.isModified())
{
f << "\t\t\t<modification_info modified_peptide=\""
<< seq.toBracketString() << "\"";
if (seq.hasNTerminalModification())
{
const ResidueModification* mod = seq.getNTerminalModification();
const double mod_nterm_mass = Residue::getInternalToNTerm().getMonoWeight() + mod->getDiffMonoMass();
f << " mod_nterm_mass=\"" << precisionWrapper(mod_nterm_mass) << "\"";
}
if (seq.hasCTerminalModification())
{
const ResidueModification* mod = seq.getCTerminalModification();
const double mod_cterm_mass = Residue::getInternalToCTerm().getMonoWeight() + mod->getDiffMonoMass();
f << " mod_cterm_mass=\"" << precisionWrapper(mod_cterm_mass) << "\"";
}
f << ">" << "\n";
for (Size i = 0; i != seq.size(); ++i)
{
if (seq[i].isModified())
{
const ResidueModification* mod = seq[i].getModification();
// the modification position is 1-based
f << "\t\t\t\t<mod_aminoacid_mass position=\"" << (i + 1)
<< "\" mass=\"" <<
precisionWrapper(mod->getMonoMass() + seq[i].getMonoWeight(Residue::Internal)) << "\"/>" << "\n";
}
}
f << "\t\t\t</modification_info>" << "\n";
}
// write out the (optional) search_score_summary that may be associated with peptide prophet results
bool peptideprophet_written = false;
if (!h.getAnalysisResults().empty())
{
// <analysis_result analysis="peptideprophet">
// <peptideprophet_result probability="0.0660" all_ntt_prob="(0.0000,0.0000,0.0660)">
// <search_score_summary>
// <parameter name="fval" value="0.7114"/>
// <parameter name="ntt" value="2"/>
// <parameter name="nmc" value="0"/>
// <parameter name="massd" value="-0.027"/>
// <parameter name="isomassd" value="0"/>
// </search_score_summary>
// </peptideprophet_result>
// </analysis_result>
for (const PeptideHit::PepXMLAnalysisResult& ar_it : h.getAnalysisResults())
{
f << "\t\t\t<analysis_result analysis=\"" << ar_it.score_type << "\">" << "\n";
// get name of next tag
String tagname = "peptideprophet_result";
if (ar_it.score_type == "peptideprophet")
{
peptideprophet_written = true; // remember that we have now already written peptide prophet results
tagname = "peptideprophet_result";
}
else if (ar_it.score_type == "interprophet")
{
tagname = "interprophet_result";
}
else
{
peptideprophet_written = true; // remember that we have now already written peptide prophet results
warning(STORE, "Analysis type " + ar_it.score_type + " not supported, will use peptideprophet_result.");
}
f << "\t\t\t\t<" << tagname << " probability=\"" << ar_it.main_score;
// TODO
f << "\" all_ntt_prob=\"(" << ar_it.main_score << "," << ar_it.main_score
<< "," << ar_it.main_score << ")\">" << "\n";
if (!ar_it.sub_scores.empty())
{
f << "\t\t\t\t\t<search_score_summary>" << "\n";
for (std::map<String, double>::const_iterator subscore_it = ar_it.sub_scores.begin();
subscore_it != ar_it.sub_scores.end(); ++subscore_it)
{
f << "\t\t\t\t\t\t<parameter name=\""<< subscore_it->first << "\" value=\"" << subscore_it->second << "\"/>\n";
}
f << "\t\t\t\t\t</search_score_summary>" << "\n";
}
f << "\t\t\t\t</" << tagname << ">" << "\n";
f << "\t\t\t</analysis_result>" << "\n";
}
}
// deprecated way of writing out peptide prophet results (only if
// requested explicitly and if we have not already written out the
// peptide prophet results above through AnalysisResults
if (peptideprophet_analyzed && !peptideprophet_written)
{
// if (!h.getAnalysisResults().empty()) { WARNING / }
f << "\t\t\t<analysis_result analysis=\"peptideprophet\">" << "\n";
f << "\t\t\t<peptideprophet_result probability=\"" << h.getScore()
<< "\" all_ntt_prob=\"(" << h.getScore() << "," << h.getScore()
<< "," << h.getScore() << ")\">" << "\n";
f << "\t\t\t</peptideprophet_result>" << "\n";
f << "\t\t\t</analysis_result>" << "\n";
}
else
{
bool haspep = pep.getScoreType() == "Posterior Error Probability" || pep.getScoreType() == "pep";
bool percolator = false;
if (search_engine_name == "X! Tandem")
{
// check if score type is XTandem or qvalue/fdr
if (pep.getScoreType() == "XTandem")
{
f << "\t\t\t<search_score" << R"( name="hyperscore" value=")" << h.getScore() << "\"" << "/>\n";
f << "\t\t\t<search_score" << R"( name="nextscore" value=")";
if (h.metaValueExists("nextscore"))
{
f << h.getMetaValue("nextscore") << "\"" << "/>\n";
}
else
{
f << h.getScore() << "\"" << "/>\n";
}
}
else if (h.metaValueExists("XTandem_score"))
{
f << "\t\t\t<search_score" << R"( name="hyperscore" value=")" << h.getMetaValue("XTandem_score") << "\"" << "/>\n";
f << "\t\t\t<search_score" << R"( name="nextscore" value=")";
if (h.metaValueExists("nextscore"))
{
f << h.getMetaValue("nextscore") << "\"" << "/>\n";
}
else
{
f << h.getMetaValue("XTandem_score") << "\"" << "/>\n";
}
}
f << "\t\t\t<search_score" << R"( name="expect" value=")" << h.getMetaValue("E-Value") << "\"" << "/>\n";
}
else if (search_engine_name == "Comet")
{
f << "\t\t\t<search_score" << R"( name="xcorr" value=")" << h.getMetaValue("MS:1002252") << "\"" << "/>\n"; // name: Comet:xcorr
f << "\t\t\t<search_score" << R"( name="deltacn" value=")" << h.getMetaValue("MS:1002253") << "\"" << "/>\n"; // name: Comet:deltacn
f << "\t\t\t<search_score" << R"( name="deltacnstar" value=")" << h.getMetaValue("MS:1002254") << "\"" << "/>\n"; // name: Comet:deltacnstar
f << "\t\t\t<search_score" << R"( name="spscore" value=")" << h.getMetaValue("MS:1002255") << "\"" << "/>\n"; // name: Comet:spscore
f << "\t\t\t<search_score" << R"( name="sprank" value=")" << h.getMetaValue("MS:1002256") << "\"" << "/>\n"; // name: Comet:sprank
f << "\t\t\t<search_score" << R"( name="expect" value=")" << h.getMetaValue("MS:1002257") << "\"" << "/>\n"; // name: Comet:expect
}
else if (search_engine_name == "MASCOT")
{
f << "\t\t\t<search_score" << R"( name="expect" value=")" << h.getMetaValue("EValue") << "\"" << "/>\n";
f << "\t\t\t<search_score" << R"( name="ionscore" value=")" << h.getScore() << "\"" << "/>\n";
}
else if (search_engine_name == "OMSSA")
{
f << "\t\t\t<search_score" << R"( name="expect" value=")" << h.getScore() << "\"" << "/>\n";
}
else if (search_engine_name == "MSGFPlus")
{
f << "\t\t\t<search_score" << R"( name="expect" value=")" << h.getScore() << "\"" << "/>\n";
}
else if (search_engine_name == "Percolator")
{
double svm_score = 0.0;
if (h.metaValueExists("MS:1001492"))
{
svm_score = static_cast<double>(h.getMetaValue("MS:1001492"));
f << "\t\t\t<search_score" << R"( name="Percolator_score" value=")" << svm_score << "\"" << "/>\n";
}
else if (h.metaValueExists("Percolator_score"))
{
svm_score = static_cast<double>(h.getMetaValue("Percolator_score"));
f << "\t\t\t<search_score" << R"( name="Percolator_score" value=")" << svm_score << "\"" << "/>\n";
}
double qval_score = 0.0;
if (h.metaValueExists("MS:1001491"))
{
qval_score = static_cast<double>(h.getMetaValue("MS:1001491"));
f << "\t\t\t<search_score" << R"( name="Percolator_qvalue" value=")" << qval_score << "\"" << "/>\n";
}
else if (h.metaValueExists("Percolator_qvalue"))
{
qval_score = static_cast<double>(h.getMetaValue("Percolator_qvalue"));
f << "\t\t\t<search_score" << R"( name="Percolator_qvalue" value=")" << qval_score << "\"" << "/>\n";
}
double pep_score = 0.0;
if (h.metaValueExists("MS:1001493"))
{
pep_score = static_cast<double>(h.getMetaValue("MS:1001493"));
}
else if (h.metaValueExists("Percolator_PEP"))
{
pep_score = static_cast<double>(h.getMetaValue("Percolator_PEP"));
}
else
{
if (!haspep)
{
// will be written later
throw Exception::MissingInformation(__FILE__,__LINE__,OPENMS_PRETTY_FUNCTION,"Percolator PEP score missing for pepXML export of Percolator results.");
}
}
f << "\t\t\t<search_score" << R"( name="Percolator_PEP" value=")" << pep_score << "\"" << "/>\n";
f << "\t\t\t<analysis_result" << " analysis=\"peptideprophet\">\n";
f << "\t\t\t\t<peptideprophet_result" << " probability=\"" << 1. - pep_score << "\"";
f << " all_ntt_prob=\"(0.0000,0.0000," << 1. - pep_score << ")\"/>\n";
f << "\t\t\t</analysis_result>" << "\n";
percolator = true;
} // Anything else
else
{
f << "\t\t\t<search_score" << " name=\"" << pep.getScoreType() << "\" value=\"" << h.getScore() << "\"" << "/>\n";
}
// Any search engine with a PEP (e.g. also our IDPEP) except Percolator which has
// written that part already
if (haspep && !percolator)
{
f << "\t\t\t<search_score" << " name=\"" << pep.getScoreType() << "\" value=\"" << h.getScore() << "\"" << "/>\n";
double probability = 1.0 - h.getScore();
f << "\t\t\t<analysis_result" << " analysis=\"peptideprophet\">\n";
f << "\t\t\t\t<peptideprophet_result" << " probability=\"" << probability << "\"";
f << " all_ntt_prob=\"(0.0000,0.0000," << probability << ")\"/>\n";
f << "\t\t\t</analysis_result>" << "\n";
}
}
f << "\t\t</search_hit>" << "\n";
f << "\t</search_result>" << "\n";
f << "\t</spectrum_query>" << "\n";
}
++count;
}
f << "</msms_run_summary>" << "\n";
f << "</msms_pipeline_analysis>" << "\n";
f.close();
}
void PepXMLFile::readRTMZCharge_(const xercesc::Attributes& attributes)
{
double mass = attributeAsDouble_(attributes, "precursor_neutral_mass");
charge_ = attributeAsInt_(attributes, "assumed_charge");
mz_ = (mass + hydrogen_mass_ * charge_) / charge_;
rt_ = 0;
// assume only one scan, i.e. ignore "end_scan":
// "start and end_scan" are 1-based. "index" is 0-based
scannr_ = attributeAsInt_(attributes, "start_scan");
Size endscan = attributeAsInt_(attributes, "start_scan");
if (scannr_ != endscan)
{
error(LOAD, "endscan not equal to startscan. Merged spectrum queries not supported. Parsing start scan nr. only.");
}
bool rt_present = optionalAttributeAsDouble_(rt_, attributes, "retention_time_sec");
if (!rt_present) // get RT from experiment
{
if (lookup_ == nullptr || lookup_->empty())
{
// no lookup given, report non-fatal error
error(LOAD, "Cannot get RT information - no spectra given");
return;
}
Size index = (scannr_ != 0) ? lookup_->findByScanNumber(scannr_) :
lookup_->findByReference(attributeAsString_(attributes, "spectrum"));
SpectrumMetaDataLookup::SpectrumMetaData meta;
lookup_->getSpectrumMetaData(index, meta);
if (meta.ms_level == 2)
{
rt_ = meta.rt;
}
else
{
error(LOAD, "Cannot get RT information - scan mapping is incorrect");
}
}
}
void PepXMLFile::setParseUnknownScores(bool parse_unknown_scores)
{
this->parse_unknown_scores_ = parse_unknown_scores;
}
void PepXMLFile::load(const String& filename, vector<ProteinIdentification>&
proteins, PeptideIdentificationList& peptides,
const String& experiment_name
)
{
SpectrumMetaDataLookup lookup;
load(filename, proteins, peptides, experiment_name, lookup);
}
void PepXMLFile::load(const String& filename, vector<ProteinIdentification>&
proteins, PeptideIdentificationList& peptides,
const String& experiment_name,
const SpectrumMetaDataLookup& lookup)
{
// initialize here, since "load" could be called several times:
exp_name_ = "";
prot_id_ = "";
charge_ = 0;
peptides.clear();
peptides_ = &peptides;
proteins.clear();
proteins_ = &proteins;
// assume mass type "average" (in case element "search_summary" is missing):
hydrogen_mass_ = hydrogen_.getAverageWeight();
file_ = filename; // filename for error messages in XMLHandler
if (!experiment_name.empty())
{
exp_name_ = FileHandler::stripExtension(experiment_name);
lookup_ = &lookup;
}
analysis_summary_ = false;
wrong_experiment_ = false;
// without experiment name, don't care about these two:
seen_experiment_ = exp_name_.empty();
checked_base_name_ = exp_name_.empty();
parse_(filename, this);
if (!seen_experiment_)
{
fatalError(LOAD, "Found no experiment with name '" + experiment_name + "'");
}
// clean up duplicate ProteinHits in each ProteinIdentification separately:
// (can't use "sort" and "unique" because no "op<" defined for ProteinHit)
for (ProteinIdentification& prot_it : proteins)
{
set<String> accessions;
// modeled after "remove_if" in STL header "algorithm":
vector<ProteinHit>::iterator first = prot_it.getHits().begin();
vector<ProteinHit>::iterator result = first;
for (; first != prot_it.getHits().end(); ++first)
{
String accession = first->getAccession();
bool new_element = accessions.insert(accession).second;
if (new_element) // don't remove
{
*result++ = *first;
}
}
prot_it.getHits().erase(result, first);
}
// reset members
exp_name_.clear();
prot_id_.clear();
date_.clear();
proteins_ = nullptr;
peptides_ = nullptr;
lookup_ = nullptr;
scan_map_.clear();
}
/*
NOTE: numbering schemes for multiple searches
---------------------------------------------
pepXML can contain search results for multiple files and for multiple
searches of those files. We have seen two different variants (both seem to
be valid pepXML):
1. One "msms_run_summary" per searched file, containing multiple
"search_summary" elements (for each search); counting starts at "1" in each
"msms_run_summary"; produced e.g. by the TPP:
<msms_run_summary basename="File1">
<search_summary search_engine="A" search_id="1">
<search_summary search_engine="B" search_id="2">
...
<msms_run_summary basename="File2">
<search_summary search_engine="A" search_id="1">
<search_summary search_engine="B" search_id="2">
...
2. One "msms_run_summary" per search of a file, containing one
"search_summary" element; counting is sequential across "msms_run_summary"
sections; produced e.g. by ProteomeDiscoverer:
<msms_run_summary basename="File1">
<search_summary search_engine="A" search_id="1">
...
<msms_run_summary basename="File1">
<search_summary search_engine="B" search_id="2">
...
The "search_id" numbers are necessary to associate search hits with the
correct search runs. In the parser, we keep track of the search runs per
"msms_run_summary" in the "current_proteins_" vector. Importantly, this
means that for variant 2 of the numbering, the "search_id" number may be
higher than the number of elements in the vector! However, in this case we
know that the last - and only - element should be the correct one.
*/
void PepXMLFile::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";
if (element == "msms_run_summary") // parent: "msms_pipeline_analysis"
{
String ms_run_path;
if (!exp_name_.empty())
{
String base_name = attributeAsString_(attributes, "base_name");
if (!base_name.empty())
{
wrong_experiment_ = !base_name.hasSuffix(exp_name_);
seen_experiment_ = seen_experiment_ || !wrong_experiment_;
checked_base_name_ = true;
}
else // really shouldn't happen, but does for Mascot export to pepXML
{
error(LOAD, "'base_name' attribute of 'msms_run_summary' element is empty");
// continue for now, but check later in 'search_summary':
wrong_experiment_ = false;
checked_base_name_ = false;
}
String raw_data = attributeAsString_(attributes, "raw_data");
if (!base_name.empty() && !raw_data.empty())
{
ms_run_path = base_name + "." + raw_data;
}
}
if (wrong_experiment_) return;
// create a ProteinIdentification in case "search_summary" is missing:
ProteinIdentification protein;
protein.setDateTime(date_);
prot_id_ = "unknown_" + date_.getDate();
enzyme_ = "unknown_enzyme";
// "prot_id_" will be overwritten if elem. "search_summary" is present
protein.setIdentifier(prot_id_);
proteins_->push_back(protein);
if (!ms_run_path.empty())
{
protein.setPrimaryMSRunPath(StringList(1, ms_run_path));
}
current_proteins_.clear();
current_proteins_.push_back(--proteins_->end());
}
else if (element == "analysis_summary") // parent: "msms_pipeline_analysis"
{
// this element can contain "search summary" elements, which we only
// expect as subelements of "msms_run_summary", so skip the whole thing
analysis_summary_ = true;
}
else if (wrong_experiment_ || analysis_summary_)
{
// do nothing here (this case exists to prevent parsing of elements for
// experiments we're not interested in or for analysis summaries)
}
// now, elements occurring more frequently are generally closer to the top
else if (element == "search_score") // parent: "search_hit"
{
String name = attributeAsString_(attributes, "name");
double value;
// TODO: deal with different scores
if (name == "expect") // X!Tandem, Mascot or MSFragger E-value
{
value = attributeAsDouble_(attributes, "value");
peptide_hit_.setScore(value);
current_peptide_.setScoreType(name);
current_peptide_.setHigherScoreBetter(false);
if (search_engine_ == "Comet")
{
peptide_hit_.setMetaValue("MS:1002257", value); // name: Comet:expectation value
}
else if (search_engine_ == "X! Tandem" || search_engine_ == "MSFragger") // TODO check if there are separate CVs?
{
peptide_hit_.setMetaValue("MS:1001330", value); // name: X\!Tandem:expect
}
else if (search_engine_ == "Mascot")
{
peptide_hit_.setMetaValue("MS:1001172", value); // name: Mascot:expectation value
}
//TODO: there is no (generic) umbrella term for expect val in the CV right now
}
else if (name == "mvh") // MyriMatch score
{
value = attributeAsDouble_(attributes, "value");
peptide_hit_.setScore(value);
current_peptide_.setScoreType(name);
current_peptide_.setHigherScoreBetter(true);
}
// if (name == "hyperscore")
// { // X!Tandem score
// value = attributeAsDouble_(attributes, "value");
// peptide_hit_.setScore(value);
// current_peptide_.setScoreType(name); // add "X!Tandem" to name?
// current_peptide_.setHigherScoreBetter(true);
// }
else if (name == "xcorr") // Sequest score
{ // and use the mvh
value = attributeAsDouble_(attributes, "value");
if (search_engine_ != "MyriMatch") //MyriMatch has also an xcorr, but we want to ignore it
{
peptide_hit_.setScore(value);
current_peptide_.setScoreType(name); // add "Sequest" to name?
current_peptide_.setHigherScoreBetter(true);
}
if (search_engine_ == "Comet")
{
peptide_hit_.setMetaValue("MS:1002252", value); // name: Comet:xcorr
peptide_hit_.setMetaValue("COMET:xcorr", value); // name: COMET:xcorr
}
else
{
peptide_hit_.setMetaValue("MS:1001155", value); // name: SEQUEST:xcorr
}
//TODO: no other xcorr or generic xcorr in the CV right now, use SEQUEST:xcorr
}
else if (name == "fval") // SpectraST score
{
value = attributeAsDouble_(attributes, "value");
peptide_hit_.setScore(value);
current_peptide_.setScoreType(name);
current_peptide_.setHigherScoreBetter(true);
peptide_hit_.setMetaValue("MS:1001419", value); // def: "SpectraST spectrum score.
}
else if (name == "hyperscore")
{
value = attributeAsDouble_(attributes, "value");
peptide_hit_.setMetaValue("hyperscore", value);
}
else if (name == "nextscore")
{
value = attributeAsDouble_(attributes, "value");
peptide_hit_.setMetaValue("nextscore", value);
}
else if (search_engine_ == "Comet")
{
if (name == "deltacn")
{
value = attributeAsDouble_(attributes, "value");
peptide_hit_.setMetaValue("MS:1002253", value); // name: Comet:deltacn
peptide_hit_.setMetaValue("COMET:deltaCn", value);
}
else if (name == "spscore")
{
value = attributeAsDouble_(attributes, "value");
peptide_hit_.setMetaValue("MS:1002255", value); // name: Comet:spscore
peptide_hit_.setMetaValue("COMET:spscore", value); // name: Comet:spscore
}
else if (name == "sprank")
{
value = attributeAsDouble_(attributes, "value");
peptide_hit_.setMetaValue("MS:1002256", value); // name: Comet:sprank
peptide_hit_.setMetaValue("COMET:sprank", value); // name: Comet:sprank
}
else if (name == "deltacnstar")
{
value = attributeAsDouble_(attributes, "value");
peptide_hit_.setMetaValue("MS:1002254", value); // name: Comet:deltacnstar
peptide_hit_.setMetaValue("COMET:deltacnstar", value); // name: Comet:deltacnstar
}
else if (name == "lnrSp")
{
value = attributeAsDouble_(attributes, "value");
peptide_hit_.setMetaValue("Comet:lnrSp", value); // name: Comet:lnrSp
peptide_hit_.setMetaValue("COMET:lnRankSP", value); // name: COMET:lnRankSP
}
else if (name == "deltLCn")
{
value = attributeAsDouble_(attributes, "value");
peptide_hit_.setMetaValue("COMET:deltaLCn", value); // name: Comet:deltLCn
}
else if (name == "lnExpect")
{
value = attributeAsDouble_(attributes, "value");
peptide_hit_.setMetaValue("COMET:lnExpect", value); // name: Comet:lnExpect
}
else if (name == "IonFrac")
{
value = attributeAsDouble_(attributes, "value");
peptide_hit_.setMetaValue("Comet:IonFrac", value); // name: Comet:IonFrac
peptide_hit_.setMetaValue("COMET:IonFrac", value); // matched_ions / total_ions
}
else if (name == "lnNumSP")
{
value = attributeAsDouble_(attributes, "value");
peptide_hit_.setMetaValue("COMET:lnNumSP", value); // name: Comet:lnNumSP
}
}
else if (parse_unknown_scores_)
{
String strvval = attributeAsString_(attributes, "value");
if(name.hasSuffix("_ions")) //TODO create a dictionary of which known scores are which type?
{
peptide_hit_.setMetaValue(name, attributeAsInt_(attributes, "value")); // e.g. name: Comet:matched_b1_ions
}
else
{
try
{
peptide_hit_.setMetaValue(name, attributeAsDouble_(attributes, "value")); // Any other generic score
}
catch (Exception::ConversionError&)
{
//TODO warn about non-numeric score? Or even do not catch the conversion error?
peptide_hit_.setMetaValue(name, attributeAsString_(attributes, "value")); // Any other generic score (fallback String)
}
}
}
}
else if (element == "search_hit") // parent: "search_result"
{ // creates a new PeptideHit
current_sequence_ = attributeAsString_(attributes, "peptide");
current_modifications_.clear();
PeptideEvidence pe;
peptide_hit_ = PeptideHit();
int rank = attributeAsInt_(attributes, "hit_rank");
peptide_hit_.setRank(rank - 1); // rank is 1-based in pepXML and 0-based in OpenMS
peptide_hit_.setCharge(charge_); // from parent "spectrum_query" tag
String prev_aa, next_aa;
if (optionalAttributeAsString_(prev_aa, attributes, "peptide_prev_aa"))
{
pe.setAABefore(prev_aa[0]);
}
if (optionalAttributeAsString_(next_aa, attributes, "peptide_next_aa"))
{
pe.setAAAfter(next_aa[0]);
}
if (search_engine_ == "Comet")
{
String value;
if (optionalAttributeAsString_(value, attributes, "num_matched_ions"))
{
peptide_hit_.setMetaValue("MS:1002258", value); // name: Comet:matched ions
}
if (optionalAttributeAsString_(value, attributes, "tot_num_ions"))
{
peptide_hit_.setMetaValue("MS:1002259", value); // name: Comet:total ions
}
if (optionalAttributeAsString_(value, attributes, "num_matched_peptides"))
{
peptide_hit_.setMetaValue("num_matched_peptides", value);
}
}
double pepmassdiff = attributeAsDouble_(attributes, "massdiff");
peptide_hit_.setMetaValue(Constants::UserParam::ISOTOPE_ERROR, std::lrint(pepmassdiff/Constants::C13C12_MASSDIFF_U));
String protein = attributeAsString_(attributes, "protein");
protein.trim();
pe.setProteinAccession(protein);
ProteinHit hit;
hit.setAccession(protein);
if (has_decoys_)
{
bool current_prot_is_decoy = protein.hasPrefix(decoy_prefix_);
auto current_type = peptide_hit_.getTargetDecoyType();
if (current_type == PeptideHit::TargetDecoyType::UNKNOWN)
{
// No annotation yet, set based on current protein
peptide_hit_.setTargetDecoyType(current_prot_is_decoy ?
PeptideHit::TargetDecoyType::DECOY :
PeptideHit::TargetDecoyType::TARGET);
}
else if ((current_type == PeptideHit::TargetDecoyType::TARGET && current_prot_is_decoy) ||
(current_type == PeptideHit::TargetDecoyType::DECOY && !current_prot_is_decoy))
{
// Peptide matches both target and decoy proteins
peptide_hit_.setTargetDecoyType(PeptideHit::TargetDecoyType::TARGET_DECOY);
}
hit.setMetaValue("target_decoy", current_prot_is_decoy ? "decoy" : "target");
}
peptide_hit_.addPeptideEvidence(pe);
// depending on the numbering scheme used in the pepXML, "search_id_"
// may appear to be "out of bounds" - see NOTE above:
current_proteins_[min(UInt(current_proteins_.size()), search_id_) - 1]->insertHit(hit);
}
else if (element == "search_result") // parent: "spectrum_query"
{
// creates a new PeptideIdentification
current_peptide_ = PeptideIdentification();
current_peptide_.setRT(rt_);
current_peptide_.setMZ(mz_);
current_peptide_.setBaseName(current_base_name_);
search_id_ = 1; // default if attr. is missing (ref. to "search_summary")
optionalAttributeAsUInt_(search_id_, attributes, "search_id");
// depending on the numbering scheme used in the pepXML, "search_id_"
// may appear to be "out of bounds" - see NOTE above:
String identifier = current_proteins_[min(UInt(current_proteins_.size()), search_id_) - 1]->getIdentifier();
current_peptide_.setIdentifier(identifier);
// set optional attributes
if (!native_spectrum_name_.empty() && keep_native_name_)
{
current_peptide_.setMetaValue("pepxml_spectrum_name", native_spectrum_name_);
}
//TODO: we really need something uniform here, like scan number - and not in metainfointerface
if (SpectrumLookup::isNativeID(native_spectrum_name_))
{
current_peptide_.setSpectrumReference( native_spectrum_name_);
}
else if (scannr_ != 0)
{
current_peptide_.setSpectrumReference( String("scan=") + String(scannr_));
}
//TODO else error?
if (!experiment_label_.empty())
{
current_peptide_.setExperimentLabel(experiment_label_);
}
if (!swath_assay_.empty())
{
current_peptide_.setMetaValue("swath_assay", swath_assay_);
}
if (!status_.empty())
{
current_peptide_.setMetaValue("status", status_);
}
}
else if (element == "spectrum_query") // parent: "msms_run_summary"
{
// sample:
// <spectrum_query spectrum="foobar.02552.02552.2" start_scan="2552"
// end_scan="2552" precursor_neutral_mass="1168.6176" assumed_charge="2"
// index="10" retention_time_sec="488.652" experiment_label="urine"
// swath_assay="EIVLTQSPGTL2:9" status="target">
readRTMZCharge_(attributes); // sets "rt_", "mz_", "charge_"
// retrieve optional attributes
native_spectrum_name_ = "";
experiment_label_ = "";
swath_assay_ = "";
status_ = "";
optionalAttributeAsString_(native_spectrum_name_, attributes, "spectrum"); //TODO store separately? Do we ever need the pepXML internal ref?
optionalAttributeAsString_(native_spectrum_name_, attributes, "spectrumNativeID"); //some engines write that optional attribute - is preferred to spectrum
optionalAttributeAsString_(native_spectrum_name_, attributes, "native_id"); //MSFragger specific native ID
optionalAttributeAsString_(experiment_label_, attributes, "experiment_label");
optionalAttributeAsString_(swath_assay_, attributes, "swath_assay");
optionalAttributeAsString_(status_, attributes, "status");
}
else if (element == "analysis_result") // parent: "search_hit"
{
current_analysis_result_ = PeptideHit::PepXMLAnalysisResult();
current_analysis_result_.score_type = attributeAsString_(attributes, "analysis");
}
else if (element == "search_score_summary")
{
search_score_summary_ = true;
}
else if (element == "parameter") // parent: "search_score_summary"
{
// If we are within a search_score_summary, add the read in values to the current AnalysisResult
if (search_score_summary_)
{
String name = attributeAsString_(attributes, "name");
double value = attributeAsDouble_(attributes, "value");
current_analysis_result_.sub_scores[name] = value;
}
else if (search_summary_)
{
String name = attributeAsString_(attributes, "name");
if (name == "fragment_bin_tol")
{
double value = attributeAsDouble_(attributes, "value");
params_.fragment_mass_tolerance = value/2.0;
params_.fragment_mass_tolerance_ppm = false;
}
else if (name == "peptide_mass_tolerance")
{
double value = attributeAsDouble_(attributes, "value");
params_.precursor_mass_tolerance = value;
}
// this is quite comet specific, but so is parameter name peptide_mass_units, see comet configuration file documentation
else if (name == "peptide_mass_units")
{
int value = attributeAsInt_(attributes, "value");
switch (value) {
case 0: // comet value 0 type amu
params_.precursor_mass_tolerance_ppm = false;
break;
case 1: // comet value 1 type mmu
params_.precursor_mass_tolerance_ppm = false;
break;
case 2: // comet value 1 type ppm
params_.precursor_mass_tolerance_ppm = true;
break;
default:
break;
}
}
else if (name == "decoy_search")
{
has_decoys_ = attributeAsInt_(attributes, "value");
}
else if (name == "decoy_prefix")
{
decoy_prefix_ = attributeAsString_(attributes, "value");
}
}
else
{
// currently not handled
}
}
else if (element == "peptideprophet_result") // parent: "analysis_result" (in "search_hit")
{
// PeptideProphet probability overwrites original search score
// maybe TODO: deal with meta data associated with PeptideProphet search
double value = attributeAsDouble_(attributes, "probability");
if (current_peptide_.getScoreType() != "InterProphet probability")
{
peptide_hit_.setScore(value);
current_peptide_.setScoreType("PeptideProphet probability");
current_peptide_.setHigherScoreBetter(true);
}
current_analysis_result_.main_score = value;
current_analysis_result_.higher_is_better = true;
}
else if (element == "interprophet_result") // parent: "analysis_result" (in "search_hit")
{
// InterProphet probability overwrites PeptideProphet probability and
// original search score
double value = attributeAsDouble_(attributes, "probability");
peptide_hit_.setScore(value);
current_peptide_.setScoreType("InterProphet probability");
current_peptide_.setHigherScoreBetter(true);
current_analysis_result_.main_score = value;
current_analysis_result_.higher_is_better = true;
}
else if (element == "modification_info") // parent: "search_hit" (in "search result")
{
// Has N-Term Modification
double mod_nterm_mass;
if (optionalAttributeAsDouble_(mod_nterm_mass, attributes, "mod_nterm_mass")) // this specifies a terminal modification
{
// look up the modification in the search_summary by mass
bool found = false;
for (const AminoAcidModification& it : variable_modifications_)
{
if ((fabs(mod_nterm_mass - it.getMass()) < mod_tol_) && it.getTerminus() == "n")
{
current_modifications_.emplace_back(it.getRegisteredMod(), Size(-1)); // position not needed for terminus
found = true;
break; // only one modification should match, so we can stop the loop here
}
}
if (!found)
{
for (const AminoAcidModification& it : fixed_modifications_)
{
if ((fabs(mod_nterm_mass - it.getMass()) < mod_tol_) && it.getTerminus() == "n")
{
current_modifications_.emplace_back(it.getRegisteredMod(), Size(-1)); // position not needed for terminus
found = true;
break; // only one modification should match, so we can stop the loop here
}
}
}
if (!found)
{
// It was not registered in the pepXML header. Search it in DB by massdiff = mod_nterm_mass - orig_nterm_mass.
std::vector<const ResidueModification*> mods;
try
{
ModificationsDB::getInstance()->searchModificationsByDiffMonoMass(mods, mod_nterm_mass - Residue::getInternalToNTerm().getMonoWeight(), mod_tol_, "", ResidueModification::N_TERM);
}
catch(...)
{
ModificationsDB::getInstance()->searchModificationsByDiffMonoMass(mods, mod_nterm_mass - Residue::getInternalToNTerm().getMonoWeight(), mod_tol_, "", ResidueModification::PROTEIN_N_TERM);
}
if (!mods.empty())
{
current_modifications_.emplace_back(mods[0], Size(-1)); // -1, because position does not matter
}
else
{
error(LOAD, String("Cannot find N-terminal modification with mass " + String(mod_nterm_mass) + "."));
}
//TODO we should create and register a mod here
}
}
// Has C-Term Modification
double mod_cterm_mass;
if (optionalAttributeAsDouble_(mod_cterm_mass, attributes, "mod_cterm_mass")) // this specifies a terminal modification
{
// look up the modification in the search_summary by mass
bool found = false;
for (const AminoAcidModification& amino : variable_modifications_)
{
if ((fabs(mod_cterm_mass - amino.getMass()) < mod_tol_) && amino.getTerminus() == "c")
{
current_modifications_.emplace_back(amino.getRegisteredMod(), Size(-1)); // position not needed for terminus
found = true;
break; // only one modification should match, so we can stop the loop here
}
}
if (!found)
{
for (const AminoAcidModification& amino : fixed_modifications_)
{
if ((fabs(mod_cterm_mass - amino.getMass()) < mod_tol_) && amino.getTerminus() == "c")
{
current_modifications_.emplace_back(amino.getRegisteredMod(), Size(-1)); // position not needed for terminus
found = true;
break; // only one modification should match, so we can stop the loop here
}
}
}
if (!found)
{
// It was not registered in the pepXML header. Search it in DB.
std::vector<const ResidueModification*> mods;
try
{
ModificationsDB::getInstance()->searchModificationsByDiffMonoMass(mods, mod_cterm_mass - Residue::getInternalToCTerm().getMonoWeight(), mod_tol_, "", ResidueModification::C_TERM);
}
catch(...)
{
ModificationsDB::getInstance()->searchModificationsByDiffMonoMass(mods, mod_cterm_mass - Residue::getInternalToCTerm().getMonoWeight(), mod_tol_, "", ResidueModification::PROTEIN_C_TERM);
}
if (!mods.empty())
{
current_modifications_.emplace_back(mods[0], Size(-1)); // -1, because position does not matter
}
else
{
error(LOAD, String("Cannot find N-terminal modification with mass " + String(mod_nterm_mass) + "."));
}
//TODO we should create and register a mod here
}
}
}
else if (element == "alternative_protein") // parent: "search_hit"
{
String protein = attributeAsString_(attributes, "protein");
PeptideEvidence pe;
pe.setProteinAccession(protein);
ProteinHit hit;
hit.setAccession(protein);
if (has_decoys_)
{
bool current_prot_is_decoy = protein.hasPrefix(decoy_prefix_);
auto current_type = peptide_hit_.getTargetDecoyType();
if (current_type == PeptideHit::TargetDecoyType::UNKNOWN)
{
// No annotation yet, set based on current protein
peptide_hit_.setTargetDecoyType(current_prot_is_decoy ?
PeptideHit::TargetDecoyType::DECOY :
PeptideHit::TargetDecoyType::TARGET);
}
else if ((current_type == PeptideHit::TargetDecoyType::TARGET && current_prot_is_decoy) ||
(current_type == PeptideHit::TargetDecoyType::DECOY && !current_prot_is_decoy))
{
// Peptide matches both target and decoy proteins
peptide_hit_.setTargetDecoyType(PeptideHit::TargetDecoyType::TARGET_DECOY);
}
hit.setTargetDecoyType(current_prot_is_decoy ?
ProteinHit::TargetDecoyType::DECOY :
ProteinHit::TargetDecoyType::TARGET);
}
peptide_hit_.addPeptideEvidence(pe);
// depending on the numbering scheme used in the pepXML, "search_id_"
// may appear to be "out of bounds" - see NOTE above:
current_proteins_[min(UInt(current_proteins_.size()), search_id_) - 1]->
insertHit(hit);
}
else if (element == "mod_aminoacid_mass") // parent: "modification_info" (in "search_hit")
{
// this element should only be used for internal AA mods OR Terminal mods at a specific
// amino acid (pepXML limitation)
double modification_mass = attributeAsDouble_(attributes, "mass");
Size modification_position = attributeAsInt_(attributes, "position");
// the modification position is 1-based
String origin = String(current_sequence_[modification_position - 1]);
String temp_description = "";
//TODO can we infer fixed/variable from the static/variable (diffmass) attributes in pepXML?
// Only in some cases probably, since it is an optional attribute
bool found = lookupAddFromHeader_(modification_mass, modification_position - 1, fixed_modifications_);
if (!found)
{
found = lookupAddFromHeader_(modification_mass, modification_position - 1, variable_modifications_);
}
if (!found)
{
// try by PSI mod ID if present
String psimod_id;
optionalAttributeAsString_(psimod_id, attributes, "id");
if (!psimod_id.empty())
{
try
{
current_modifications_.emplace_back(ModificationsDB::getInstance()->getModification(psimod_id, origin), modification_position - 1);
found = true;
}
catch (...) {}
}
if (!found)
{
// Lookup in our DB
//TODO also here, maybe the static/variable attribute is better for diffmass if present?
double diffmass = modification_mass - ResidueDB::getInstance()->getResidue(origin)->getMonoWeight(Residue::Internal);
vector<const ResidueModification*> mods;
// try least specific search first:
ModificationsDB::getInstance()->searchModificationsByDiffMonoMass(mods, diffmass, mod_tol_, origin, ResidueModification::ANYWHERE);
if (mods.empty())
{
if (modification_position == 1)
{
ModificationsDB::getInstance()->searchModificationsByDiffMonoMass(mods, diffmass, mod_tol_, origin, ResidueModification::N_TERM);
if (mods.empty()) ModificationsDB::getInstance()->searchModificationsByDiffMonoMass(mods, diffmass, mod_tol_, origin, ResidueModification::PROTEIN_N_TERM);
}
else if (modification_position == current_sequence_.length())
{
ModificationsDB::getInstance()->searchModificationsByDiffMonoMass(mods, diffmass, mod_tol_, origin, ResidueModification::C_TERM);
if (mods.empty()) ModificationsDB::getInstance()->searchModificationsByDiffMonoMass(mods, diffmass, mod_tol_, origin, ResidueModification::PROTEIN_C_TERM);
}
}
if (!mods.empty())
{
if (mods.size() > 1)
{
warning(LOAD, String("Modification '") + String(modification_mass) + "' of residue " + String(origin) + " at position "
+ String(modification_position) + " in '" + current_sequence_ + "' not registered in pepXML header nor uniquely defined in DB." +
" Using " + mods[0]->getFullId());
current_modifications_.emplace_back(mods[0], modification_position - 1);
}
}
else
{
// still nothing found, register as unknown as last resort
current_modifications_.emplace_back(
ResidueModification::createUnknownFromMassString(
String(modification_mass),
modification_mass,
false,
ResidueModification::ANYWHERE, // since it is at an amino acid it is probably NOT a terminal mod
ResidueDB::getInstance()->getResidue(current_sequence_[modification_position - 1])),
modification_position - 1
);
}
}
}
}
else if (element == "aminoacid_modification" || element == "terminal_modification") // parent: "search_summary"
{
String description;
optionalAttributeAsString_(description, attributes, "description");
String massdiff = attributeAsString_(attributes, "massdiff");
String mass = attributeAsDouble_(attributes, "mass");
String protein_terminus_entry;
String aminoacid;
String terminus;
String is_variable = attributeAsString_(attributes, "variable");
if (element == "aminoacid_modification")
{
aminoacid = attributeAsString_(attributes, "aminoacid");
optionalAttributeAsString_(terminus, attributes, "peptide_terminus");
optionalAttributeAsString_(protein_terminus_entry, attributes, "protein_terminus");
// can't set term_spec to "ANYWHERE", because terminal mods. may not be registered as such
// (this is an issue especially with Comet)!
}
else //terminal_modification
{
// Somehow very small fixed modifications (electron mass?) get annotated by X!Tandem. Don't add them as they interfere with other mods.
if (fabs(massdiff.toDouble()) < xtandem_artificial_mod_tol_)
{
return;
}
optionalAttributeAsString_(aminoacid, attributes, "aminoacid");
terminus = attributeAsString_(attributes, "terminus");
// WARNING: Many search engines annotate this wrong! This is supposed to be empty or "n" or "c".
// But many SEs annotate it as "Y" and "N" for Yes and No. We handle this in the AAMod ctor
protein_terminus_entry = attributeAsString_(attributes, "protein_terminus");
}
AminoAcidModification aa_mod{
aminoacid, massdiff, mass, is_variable, description, terminus, protein_terminus_entry,
preferred_fixed_modifications_, preferred_variable_modifications_, mod_tol_
};
const vector<String>& errs = aa_mod.getErrors();
if (!errs.empty())
{
error(LOAD, "Errors during parsing of aminoacid/terminal modification element:");
for (const auto& e : errs)
{
error(LOAD, e);
}
}
if (aa_mod.getRegisteredMod() != nullptr)
{
if (aa_mod.isVariable())
{
variable_modifications_.push_back(aa_mod);
params_.variable_modifications.push_back(aa_mod.getDescription());
}
else
{
fixed_modifications_.push_back(aa_mod);
params_.fixed_modifications.push_back(aa_mod.getDescription());
}
}
}
else if (element == "search_summary") // parent: "msms_run_summary"
{ // creates a new ProteinIdentification (usually)
search_summary_ = true;
current_base_name_ = "";
optionalAttributeAsString_(current_base_name_, attributes, "base_name");
if (!checked_base_name_) // work-around for files exported by Mascot
{
if (current_base_name_.hasSuffix(exp_name_))
{
seen_experiment_ = true;
}
else // wrong experiment after all - roll back changes that were made
{
proteins_->pop_back();
current_proteins_.clear();
wrong_experiment_ = true;
return;
}
}
fixed_modifications_.clear();
variable_modifications_.clear();
params_ = ProteinIdentification::SearchParameters();
params_.digestion_enzyme = *(ProteaseDB::getInstance()->getEnzyme(enzyme_));
String mass_type = attributeAsString_(attributes, "precursor_mass_type");
if (mass_type == "monoisotopic")
{
hydrogen_mass_ = hydrogen_.getMonoWeight();
}
else
{
hydrogen_mass_ = hydrogen_.getAverageWeight();
if (mass_type != "average")
{
error(LOAD, "'precursor_mass_type' attribute of 'search_summary' tag should be 'monoisotopic' or 'average', not '" + mass_type + "' (assuming 'average')");
}
}
// assuming "SearchParameters::mass_type" refers to the fragment mass
mass_type = attributeAsString_(attributes, "fragment_mass_type");
if (mass_type == "monoisotopic")
{
params_.mass_type = ProteinIdentification::PeakMassType::MONOISOTOPIC;
}
else
{
if (mass_type == "average")
{
params_.mass_type = ProteinIdentification::PeakMassType::AVERAGE;
}
else
{
error(LOAD, "'fragment_mass_type' attribute of 'search_summary' tag should be 'monoisotopic' or 'average', not '" + mass_type + "'");
}
}
search_engine_ = attributeAsString_(attributes, "search_engine");
//TODO why do we not store versions?
if (search_engine_ == "X! Tandem")
{
String ver;
optionalAttributeAsString_(ver, attributes, "search_engine_version");
if (ver.hasPrefix("MSFragger"))
{
search_engine_ = "MSFragger";
}
}
// generate a unique identifier for every search engine run.
prot_id_ = search_engine_ + "_" + date_.getDate() + "_" + date_.getTime();
search_id_ = 1;
optionalAttributeAsUInt_(search_id_, attributes, "search_id");
vector<ProteinIdentification>::iterator prot_it;
if (search_id_ <= proteins_->size()) // ProteinIdent. was already created for "msms_run_summary" -> add to it
{
prot_it = current_proteins_.back();
}
else // create a new ProteinIdentification
{
ProteinIdentification protein;
protein.setDateTime(date_);
proteins_->push_back(protein);
prot_it = --proteins_->end();
prot_id_ = prot_id_ + "_" + search_id_; // make sure the ID is unique
}
prot_it->setSearchEngine(search_engine_);
prot_it->setIdentifier(prot_id_);
}
else if (element == "sample_enzyme") // parent: "msms_run_summary"
{ // special case: search parameter that occurs *before* "search_summary"!
enzyme_ = attributeAsString_(attributes, "name");
if (enzyme_ == "stricttrypsin") enzyme_ = "Trypsin/P"; // MSFragger synonyme
if (ProteaseDB::getInstance()->hasEnzyme(enzyme_.toLower()))
{
params_.digestion_enzyme = *(ProteaseDB::getInstance()->getEnzyme(enzyme_));
}
}
else if (element == "specificity" && params_.digestion_enzyme.getName() == "unknown_enzyme") // parent: "sample_enzyme"
{ // special case: search parameter that occurs *before* "search_summary"!
String cut_before = attributeAsString_(attributes, "cut");
String no_cut_after = attributeAsString_(attributes, "no_cut");
String sense = attributeAsString_(attributes, "sense");
params_.digestion_enzyme = DigestionEnzymeProtein(DigestionEnzyme(
"user-defined," + enzyme_ + "," + cut_before + "," + no_cut_after + "," + sense,
cut_before, no_cut_after, sense));
}
else if (element == "enzymatic_search_constraint") // parent: "search_summary"
{
//TODO we should not overwrite the enzyme here! Luckily in most files it is the same
// enzyme as in sample_enzyme or something useless like "default".
///<enzymatic_search_constraint enzyme="nonspecific" max_num_internal_cleavages="1" min_number_termini="2"/>
enzyme_ = attributeAsString_(attributes, "enzyme");
if (enzyme_ == "stricttrypsin") enzyme_ = "Trypsin/P"; // MSFragger synonyme
if (ProteaseDB::getInstance()->hasEnzyme(enzyme_))
{
DigestionEnzymeProtein enzyme_to_set = *(ProteaseDB::getInstance()->getEnzyme(enzyme_.toLower()));
if (params_.digestion_enzyme.getName() != "unknown_enzyme" && enzyme_to_set != params_.digestion_enzyme)
{
error(LOAD, "More than one enzyme found. This is currently not supported. Proceeding with last encountered only.");
}
params_.digestion_enzyme = enzyme_to_set;
}
// Always add the additional infos (e.g. for enzymatic_search_constraint enzyme="default" like in MSFragger)
//TODO maybe check for keyword names like "default"?
//TODO the question is, what to do with the following infos if the enzymes do not match?
// We always parse and set it for now, to be
// a) backwards-compatible
// b) it's the only info we have
int mc = attributeAsInt_(attributes, "max_num_internal_cleavages");
params_.missed_cleavages = mc;
int min_num_termini = attributeAsInt_(attributes, "min_number_termini");
if (min_num_termini >= 0 && min_num_termini <= 2)
{
params_.enzyme_term_specificity = EnzymaticDigestion::Specificity(min_num_termini);
}
}
else if (element == "search_database") // parent: "search_summary"
{
params_.db = attributeAsString_(attributes, "local_path");
if (params_.db.empty())
{
optionalAttributeAsString_(params_.db, attributes, "database_name");
}
}
else if (element == "msms_pipeline_analysis") // root
{
String date = attributeAsString_(attributes, "date");
// fix for corrupted xs:dateTime format:
if ((date[4] == ':') && (date[7] == ':') && (date[10] == ':'))
{
error(LOAD, "Format of attribute 'date' in tag 'msms_pipeline_analysis' does not comply with standard 'xs:dateTime'");
date[4] = '-';
date[7] = '-';
date[10] = 'T';
}
date_ = asDateTime_(date);
}
}
bool PepXMLFile::lookupAddFromHeader_(double modification_mass,
Size modification_position,
vector<AminoAcidModification> const& header_mods)
{
bool found = false;
for (const auto& m : header_mods)
{
//TODO do we really want to allow another tolerance to the masses in the header?
if (fabs(modification_mass - m.getMass()) < mod_tol_)
{
if (m.getAminoAcid().hasSubstring(current_sequence_[modification_position]))
{
current_modifications_
.emplace_back(m.getRegisteredMod(), modification_position); // position not needed for terminus
found = true;
break; // only one modification should match, so we can stop the loop here
}
}
}
return found;
}
void PepXMLFile::endElement(const XMLCh* const /*uri*/,
const XMLCh* const /*local_name*/,
const XMLCh* const qname)
{
String element = sm_.convert(qname);
// cout << "End: " << element << "\n";
if (element == "analysis_summary")
{
analysis_summary_ = false;
}
else if (element == "search_score_summary")
{
search_score_summary_ = false;
}
else if (element == "analysis_result") // parent: "search_hit"
{
peptide_hit_.addAnalysisResults(current_analysis_result_);
}
else if (wrong_experiment_ || analysis_summary_)
{
// do nothing here (skip all elements that belong to the wrong experiment
// or to an analysis summary)
}
else if (element == "spectrum_query")
{
// clear optional attributes
native_spectrum_name_ = "";
experiment_label_ = "";
swath_assay_ = "";
status_ = "";
}
else if (element == "search_hit")
{
AASequence temp_aa_sequence = AASequence::fromString(current_sequence_);
//Note: using our AASequence::fromString on the modified_sequence of
// the modification_info element is probably not possible since modifications may have special
// symbols that we would need to save and lookup additionally
//TODO one might argue that mods from XML attributes are better specified and should be preferred
// Modifications explicitly annotated at the current search_hit take preference over
// implicit fixed mods
//TODO use peptide_hit_.getPeptideEvidences().back().getAAAfter()/Before() to see if Protein term is applicable at all
// But: Leave it out for now since I bet there is software out there, not adhering to the specification
for (const auto& mod : current_modifications_)
{
if (mod.first->getTermSpecificity() == ResidueModification::N_TERM ||
mod.first->getTermSpecificity() == ResidueModification::PROTEIN_N_TERM)
{
if (!temp_aa_sequence.hasNTerminalModification())
{
temp_aa_sequence.setNTerminalModification(mod.first);
}
else
{
warning(LOAD, "Multiple N-term mods specified for search_hit with sequence " + current_sequence_
+ " proceeding with first.");
}
}
else if (mod.first->getTermSpecificity() == ResidueModification::C_TERM ||
mod.first->getTermSpecificity() == ResidueModification::PROTEIN_C_TERM)
{
if (!temp_aa_sequence.hasCTerminalModification())
{
temp_aa_sequence.setCTerminalModification(mod.first);
}
else
{
warning(LOAD, "Multiple C-term mods specified for search_hit with sequence " + current_sequence_
+ " proceeding with first.");
}
}
else // internal
{
if (!temp_aa_sequence[mod.second].isModified())
{
temp_aa_sequence.setModification(mod.second, mod.first->getFullId());
}
else
{
warning(LOAD, "Multiple mods for position " + String(mod.second)
+ " specified for search_hit with sequence " + current_sequence_ + " proceeding with first.");
}
}
}
// Now apply implicit fixed modifications at positions where there is no modification yet.
for (const auto& mod : fixed_modifications_)
{
if (mod.getRegisteredMod()->getTermSpecificity() == ResidueModification::N_TERM ||
mod.getRegisteredMod()->getTermSpecificity() == ResidueModification::PROTEIN_N_TERM)
{
if (!temp_aa_sequence.hasNTerminalModification())
{
temp_aa_sequence.setNTerminalModification(mod.getRegisteredMod());
}
}
else if (mod.getRegisteredMod()->getTermSpecificity() == ResidueModification::C_TERM ||
mod.getRegisteredMod()->getTermSpecificity() == ResidueModification::PROTEIN_N_TERM)
{
if (!temp_aa_sequence.hasCTerminalModification())
{
temp_aa_sequence.setCTerminalModification(mod.getRegisteredMod());
}
else
{
warning(LOAD, "Trying to add a fixed C-term modification from the search_summary to an already"
" annotated and modified N-terminus of " + current_sequence_
+ " ... skipping.");
}
}
else // go through the sequence and look for unmodified residues that match:
{
for (Size s = 0; s < temp_aa_sequence.size(); s++)
{
Residue const* r = &temp_aa_sequence[s];
if (!r->isModified())
{
if (mod.getAminoAcid().hasSubstring(r->getOneLetterCode()))
{
// Note: this calls setModification_ on a new Residue which changes its
// weight to the weight of the modification (set above)
temp_aa_sequence.setModification(s,
ResidueDB::getInstance()->getModifiedResidue(r, mod.getRegisteredMod()->getFullId()));
}
}
//TODO else warn as well? Skip for now.
}
}
}
peptide_hit_.setSequence(temp_aa_sequence);
current_peptide_.insertHit(peptide_hit_);
}
else if (element == "search_result")
{
peptides_->push_back(current_peptide_);
}
else if (element == "search_summary")
{
// In idXML we only store search engine and date as identifier, but to distinguish two identification runs these values must be unique.
// As a workaround to support multiple runs, we make the date unique by adding one second for every additional identification run.
UInt hour, minute, second;
date_.getTime(hour, minute, second);
hour = (hour + (minute + (second + 1) / 60) / 60) % 24;
minute = (minute + (second + 1) / 60) % 60;
second = (second + 1) % 60;
date_.setTime(hour, minute, second);
current_proteins_.back()->setSearchParameters(params_);
search_summary_ = false;
}
}
void PepXMLFile::setPreferredFixedModifications(const std::vector<const ResidueModification*>& mods)
{
preferred_fixed_modifications_ = mods;
}
void PepXMLFile::setPreferredVariableModifications(const std::vector<const ResidueModification*>& mods)
{
preferred_variable_modifications_ = mods;
}
/*std::vector<int> PepXMLFile::getIsotopeErrorsFromIntSetting_(int intSetting)
{
static std::vector<std::vector<int>> cometIsoLists_{{},{1},{1,2},{1,2,3},{-8,-4,4,8},{-1,1,2,3}};
return cometIsoLists_[intSetting];
}
*/
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/MzTabFile.cpp | .cpp | 125,556 | 3,339 | // 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/MzTabFile.h>
#include <OpenMS/FORMAT/FileHandler.h>
#include <OpenMS/SYSTEM/File.h>
#include <OpenMS/FORMAT/TextFile.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <algorithm>
#include <QtCore/QString>
#include <boost/regex.hpp>
#include <boost/math/special_functions/fpclassify.hpp>
using namespace std;
// TODO fix all the shadowed "String s"
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wshadow"
#endif
namespace OpenMS
{
MzTabFile::MzTabFile():
store_protein_reliability_(false),
store_peptide_reliability_(false),
store_psm_reliability_(false),
store_smallmolecule_reliability_(false),
store_protein_uri_(false),
store_peptide_uri_(false),
store_psm_uri_(false),
store_smallmolecule_uri_(false),
store_protein_goterms_(false),
store_nucleic_acid_reliability_(false),
store_oligonucleotide_reliability_(false),
store_osm_reliability_(false),
store_nucleic_acid_uri_(false),
store_oligonucleotide_uri_(false),
store_osm_uri_(false),
store_nucleic_acid_goterms_(false)
{
}
MzTabFile::~MzTabFile() = default;
std::pair<int, int> MzTabFile::extractIndexPairsFromBrackets_(const String & s)
{
std::pair<Int, Int> pair(0,0);
// ^ # Match the start of the line
// .*? # Non-greedy match anything
// \[ # Upto the first opening bracket (escaped)
// (\d+) # Match a digit string (one or more)
// \] # Match closing bracket
// .* # Match the rest of the line
// $ # Match the end of the line
boost::sregex_token_iterator end;
boost::regex rx_first_number(R"(^.*?\[(\d+)\].*$)");
boost::sregex_token_iterator it1(s.begin(), s.end(), rx_first_number, 1);
if (it1 != end)
{
pair.first = String(*it1++).toInt();
}
boost::regex rx_second_number(R"(^.*?\[\d+\].*?\[(\d+)\].*$)");
boost::sregex_token_iterator it2(s.begin(), s.end(), rx_second_number, 1);
if (it2 != end)
{
pair.second = String(*it2++).toInt();
}
return pair;
}
void MzTabFile::load(const String& filename, MzTab& mz_tab)
{
TextFile tf(filename, true);
MzTabMetaData mz_tab_metadata;
MzTabProteinSectionRows mz_tab_protein_section_data;
MzTabPeptideSectionRows mz_tab_peptide_section_data;
MzTabPSMSectionRows mz_tab_psm_section_data;
MzTabSmallMoleculeSectionRows mz_tab_small_molecule_section_data;
map<Size, String> comment_rows;
vector<Size> empty_rows;
map<String, Size> protein_custom_opt_columns; // map column name to original column index
map<String, Size> peptide_custom_opt_columns;
map<String, Size> psm_custom_opt_columns;
map<String, Size> smallmolecule_custom_opt_columns;
Size count_study_variable_description = 0;
Size count_ms_run_location = 0;
// protein section column information
Size protein_accession_index = 0;
Size protein_description_index = 0;
Size protein_taxid_index = 0;
Size protein_species_index = 0;
Size protein_database_index = 0;
Size protein_database_version_index = 0;
Size protein_search_engine_index = 0;
map<Size, Size> protein_best_search_engine_score_to_column_index; // score number to column index
map<Size, std::pair<Size, Size> > protein_column_index_to_score_runs_pair; // map column of the protein section to a search_engine_score[index1]_ms_run[index] index pair
Size protein_reliability_index = 0;
map<Size, Size> protein_num_psms_ms_run_indices;
map<Size, Size> protein_num_peptides_distinct_ms_run_indices;
map<Size, Size> protein_num_peptides_unique_ms_run_indices;
Size protein_ambiguity_members_index = 0;
Size protein_modifications_index = 0;
Size protein_uri_index = 0;
Size protein_go_terms_index = 0;
Size protein_coverage_index = 0;
map<Size, Size> protein_abundance_assay_indices;
map<Size, Size> protein_abundance_study_variable_to_column_indices;
map<Size, Size> protein_abundance_stdev_study_variable_to_column_indices;
map<Size, Size> protein_abundance_std_error_study_variable_to_column_indices;
// peptide section column information
Size peptide_sequence_index = 0;
Size peptide_accession_index = 0;
Size peptide_unique_index = 0;
Size peptide_database_index = 0;
Size peptide_database_version_index = 0;
Size peptide_search_engine_index = 0;
map<Size, Size> peptide_best_search_engine_score_to_column_index;
map<Size, std::pair<Size, Size> > peptide_column_index_to_score_runs_pair; // map column of the peptide section to a search_engine_score[index1]_ms_run[index] index pair
Size peptide_reliability_index = 0;
Size peptide_modifications_index = 0;
Size peptide_retention_time_index = 0;
Size peptide_retention_time_window_index = 0;
Size peptide_charge_index = 0;
Size peptide_mass_to_charge_index = 0;
// Size peptide_uri_index = 0;
Size peptide_spectra_ref_index = 0;
map<Size, Size> peptide_abundance_assay_indices;
map<Size, Size> peptide_abundance_study_variable_to_column_indices;
map<Size, Size> peptide_abundance_study_variable_stdev_to_column_indices;
map<Size, Size> peptide_abundance_study_variable_std_error_to_column_indices;
// psm section column information
Size psm_sequence_index = 0;
Size psm_psm_id_index = 0;
Size psm_accession_index = 0;
Size psm_unique_index = 0;
Size psm_database_index = 0;
Size psm_database_version_index = 0;
Size psm_search_engine_index = 0;
map<Size, Size> psm_search_engine_score_to_column_index;
Size psm_reliability_index = 0;
Size psm_modifications_index = 0;
Size psm_retention_time_index = 0;
Size psm_charge_index = 0;
Size psm_exp_mass_to_charge_index = 0;
Size psm_calc_mass_to_charge_index = 0;
// Size psm_uri_index = 0;
Size psm_spectra_ref_index = 0;
Size psm_pre_index = 0;
Size psm_post_index = 0;
Size psm_start_index = 0;
Size psm_end_index = 0;
// small molecule column information
Size smallmolecule_identifier_index = 0;
Size smallmolecule_chemical_formula_index = 0;
Size smallmolecule_smiles_index = 0;
Size smallmolecule_inchi_key_index = 0;
Size smallmolecule_description_index = 0;
Size smallmolecule_exp_mass_to_charge_index = 0;
Size smallmolecule_calc_mass_to_charge_index = 0;
Size smallmolecule_charge_index = 0;
Size smallmolecule_retention_time_index = 0;
Size smallmolecule_taxid_index = 0;
Size smallmolecule_species_index = 0;
Size smallmolecule_database_index = 0;
Size smallmolecule_database_version_index = 0;
Size smallmolecule_reliability_index = 0;
Size smallmolecule_uri_index = 0;
Size smallmolecule_spectra_ref_index = 0;
Size smallmolecule_search_engine_index = 0;
map<Size, Size> smallmolecule_best_search_engine_score_to_column_index;
map<Size, std::pair<Size, Size> > smallmolecule_column_index_to_score_runs_pair; // map column of the small molecule section to a search_engine_score[index1]_ms_run[index] index pair
Size smallmolecule_modifications_index = 0;
map<Size, Size> smallmolecule_abundance_assay_indices;
map<Size, Size> smallmolecule_abundance_study_variable_indices;
map<Size, Size> smallmolecule_abundance_stdev_study_variable_indices;
map<Size, Size> smallmolecule_abundance_std_error_study_variable_indices;
// potentially mandatory meta values (depending on mzTab type, mode and sections that are present)
set<String> mandatory_meta_values;
// mzTab sections present in the file. Influences compulsoriness of meta-values.
set<String> sections_present;
Size count_protein_search_engine_score = 0;
Size count_peptide_search_engine_score = 0;
Size count_psm_search_engine_score = 0;
Size count_smallmolecule_search_engine_score = 0;
Size line_number = 0;
for (TextFile::ConstIterator sit = tf.begin(); sit != tf.end(); ++sit, ++line_number)
{
// std::cout << *sit << std::endl;
String s = *sit;
// skip empty lines or lines that are too short
if (s.trim().size() < 3)
{
empty_rows.push_back(line_number); // preserve empty lines to map comments to correct position
continue;
}
const String section = s.prefix(3);
// discard comments
if (section == "COM")
{
comment_rows[line_number] = s;
continue;
}
StringList cells;
s.split("\t", cells);
if (cells.size() < 3)
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename, "Error parsing MzTab line: " + String(s) + ". Did you forget to use tabulator as separator?");
}
// parse metadata section
if (section == "MTD")
{
sections_present.insert("MTD");
StringList meta_key_fields; // the "-" separated fields of the metavalue key
cells[1].split("-", meta_key_fields);
String meta_key = meta_key_fields[0];
if (cells[1].hasPrefix("mzTab-version"))
{
mz_tab_metadata.mz_tab_version.fromCellString(cells[2]);
mandatory_meta_values.insert("mzTab-version");
}
else if (cells[1].hasPrefix("mzTab-mode"))
{
mz_tab_metadata.mz_tab_mode.fromCellString(cells[2]);
mandatory_meta_values.insert("mzTab-mode");
}
else if (cells[1].hasPrefix("mzTab-type"))
{
mz_tab_metadata.mz_tab_type.fromCellString(cells[2]);
mandatory_meta_values.insert("mzTab-type");
}
else if (cells[1].hasPrefix("mzTab-ID"))
{
mz_tab_metadata.mz_tab_id.fromCellString(cells[2]);
}
else if (meta_key == "title")
{
mz_tab_metadata.title.set(cells[2]);
}
else if (meta_key == "description")
{
mz_tab_metadata.description.set(cells[2]);
mandatory_meta_values.insert("description");
}
else if (meta_key.hasPrefix("sample_processing["))
{
Int n = meta_key.substitute("sample_processing[", "").substitute("]","").trim().toInt();
MzTabParameterList pl;
pl.fromCellString(cells[2]);
mz_tab_metadata.sample_processing[n] = pl;
}
else if (meta_key.hasPrefix("instrument[") && meta_key_fields[1] == "name")
{
Int n = meta_key_fields[0].substitute("instrument[", "").substitute("]","").trim().toInt();
MzTabParameter p;
p.fromCellString(cells[2]);
mz_tab_metadata.instrument[n].name = p;
}
else if (meta_key.hasPrefix("instrument[") && meta_key_fields[1] == "source")
{
Int n = meta_key_fields[0].substitute("instrument[", "").substitute("]","").trim().toInt();
MzTabParameter p;
p.fromCellString(cells[2]);
mz_tab_metadata.instrument[n].source = p;
}
else if (meta_key.hasPrefix("instrument[") && meta_key_fields.size() == 2 && meta_key_fields[1].hasPrefix("analyzer["))
{
Int n = meta_key_fields[0].substitute("instrument[", "").substitute("]","").trim().toInt();
Int m = meta_key_fields[1].substitute("analyzer[", "").substitute("]","").trim().toInt();
MzTabParameter p;
p.fromCellString(cells[2]);
mz_tab_metadata.instrument[n].analyzer[m] = p;
}
else if (meta_key.hasPrefix("instrument[") && meta_key_fields[1] == "detector")
{
Int n = meta_key_fields[0].substitute("instrument[", "").substitute("]","").trim().toInt();
MzTabParameter p;
p.fromCellString(cells[2]);
mz_tab_metadata.instrument[n].detector = p;
}
else if (meta_key.hasPrefix("software[") && meta_key_fields.size() == 1)
{
Int n = meta_key.substitute("software[", "").substitute("]","").trim().toInt();
MzTabParameter p;
p.fromCellString(cells[2]);
mz_tab_metadata.software[n].software = p;
}
else if (meta_key.hasPrefix("software[") && meta_key_fields.size() == 2 && meta_key_fields[1].hasPrefix("setting["))
{
Int n = meta_key_fields[0].substitute("software[", "").substitute("]","").trim().toInt();
Int m = meta_key_fields[1].substitute("setting[", "").substitute("]","").trim().toInt();
MzTabString p;
p.fromCellString(cells[2]);
mz_tab_metadata.software[n].setting[m] = p;
}
else if (meta_key.hasPrefix("protein_search_engine_score["))
{
Size n = (Size)meta_key_fields[0].substitute("protein_search_engine_score[", "").substitute("]","").trim().toInt();
MzTabParameter p;
p.fromCellString(cells[2]);
mz_tab_metadata.protein_search_engine_score[n] = p;
count_protein_search_engine_score = std::max(n, count_protein_search_engine_score); // will be checked to match number of entries in map to detect skipped entries or wrong numbering
}
else if (meta_key.hasPrefix("peptide_search_engine_score["))
{
Size n = (Size)meta_key_fields[0].substitute("peptide_search_engine_score[", "").substitute("]","").trim().toInt();
MzTabParameter p;
p.fromCellString(cells[2]);
mz_tab_metadata.peptide_search_engine_score[n] = p;
count_peptide_search_engine_score = std::max(n, count_peptide_search_engine_score); // will be checked to match number of entries in map to detect skipped entries or wrong numbering
}
else if (meta_key.hasPrefix("psm_search_engine_score["))
{
Size n = (Size)meta_key_fields[0].substitute("psm_search_engine_score[", "").substitute("]","").trim().toInt();
MzTabParameter p;
p.fromCellString(cells[2]);
mz_tab_metadata.psm_search_engine_score[n] = p;
count_psm_search_engine_score = std::max(n, count_psm_search_engine_score); // will be checked to match number of entries in map to detect skipped entries or wrong numbering
}
else if (meta_key.hasPrefix("smallmolecule_search_engine_score["))
{
Size n = (Size)meta_key_fields[0].substitute("smallmolecule_search_engine_score[", "").substitute("]","").trim().toInt();
MzTabParameter p;
p.fromCellString(cells[2]);
mz_tab_metadata.smallmolecule_search_engine_score[n] = p;
count_smallmolecule_search_engine_score = std::max(n, count_smallmolecule_search_engine_score); // will be checked to match number of entries in map to detect skipped entries or wrong numbering
}
else if (meta_key == "false_discovery_rate")
{
MzTabParameterList pl;
pl.fromCellString(cells[2]);
mz_tab_metadata.false_discovery_rate = pl;
}
else if (meta_key.hasPrefix("publication["))
{
Int n = meta_key.substitute("publication[", "").substitute("]","").trim().toInt();
MzTabString sl;
sl.fromCellString(cells[2]);
mz_tab_metadata.publication[n] = sl;
}
else if (meta_key.hasPrefix("contact") && meta_key_fields[1] == "name")
{
Int n = meta_key_fields[0].substitute("contact[", "").substitute("]","").trim().toInt();
MzTabString s;
s.fromCellString(cells[2]);
mz_tab_metadata.contact[n].name = s;
}
else if (meta_key.hasPrefix("contact") && meta_key_fields[1] == "affiliation")
{
Int n = meta_key_fields[0].substitute("contact[", "").substitute("]","").trim().toInt();
MzTabString s;
s.fromCellString(cells[2]);
mz_tab_metadata.contact[n].affiliation = s;
}
else if (meta_key.hasPrefix("contact") && meta_key_fields[1] == "email")
{
Int n = meta_key_fields[0].substitute("contact[", "").substitute("]","").trim().toInt();
MzTabString s;
s.fromCellString(cells[2]);
mz_tab_metadata.contact[n].email = s;
}
else if (meta_key.hasPrefix("uri["))
{
Int n = meta_key_fields[0].substitute("uri[", "").substitute("]","").trim().toInt();
MzTabString s;
s.fromCellString(cells[2]);
mz_tab_metadata.uri[n] = s;
}
//TODO: add mandatory check
else if (meta_key.hasPrefix("variable_mod[") && meta_key_fields.size() == 1)
{
Int n = meta_key.substitute("variable_mod[", "").substitute("]","").trim().toInt();
MzTabParameter pl;
pl.fromCellString(cells[2]);
mz_tab_metadata.variable_mod[n].modification = pl;
}
else if (meta_key.hasPrefix("variable_mod[") && meta_key_fields[1] == "site") // variable_mod[1-n]-site
{
Int n = meta_key.substitute("variable_mod[", "").substitute("]","").trim().toInt();
MzTabString pl;
pl.fromCellString(cells[2]);
mz_tab_metadata.variable_mod[n].site = pl;
}
else if (meta_key.hasPrefix("variable_mod[") && meta_key_fields[1] == "position") // variable_mod[1-n]-position
{
Int n = meta_key.substitute("variable_mod[", "").substitute("]","").trim().toInt();
MzTabString pl;
pl.fromCellString(cells[2]);
mz_tab_metadata.variable_mod[n].position = pl;
}
//TODO: add mandatory check
else if (meta_key.hasPrefix("fixed_mod[") && meta_key_fields.size() == 1) // fixed_mod[1-n]
{
Int n = meta_key.substitute("fixed_mod[", "").substitute("]","").trim().toInt();
MzTabParameter pl;
pl.fromCellString(cells[2]);
mz_tab_metadata.fixed_mod[n].modification = pl;
}
else if (meta_key.hasPrefix("fixed_mod[") && meta_key_fields[1] == "site") // fixed_mod[1-n]-site
{
Int n = meta_key.substitute("fixed_mod[", "").substitute("]","").trim().toInt();
MzTabString pl;
pl.fromCellString(cells[2]);
mz_tab_metadata.fixed_mod[n].site = pl;
}
else if (meta_key.hasPrefix("fixed_mod[") && meta_key_fields[1] == "position") // fixed_mod[1-n]-position
{
Int n = meta_key.substitute("fixed_mod[", "").substitute("]","").trim().toInt();
MzTabString pl;
pl.fromCellString(cells[2]);
mz_tab_metadata.fixed_mod[n].position = pl;
}
else if (meta_key == "quantification_method")
{
MzTabParameter p;
p.fromCellString(cells[2]);
mz_tab_metadata.quantification_method = p;
}
else if (meta_key == "protein" && meta_key_fields[1] == "quantification_unit")
{
MzTabParameter p;
p.fromCellString(cells[2]);
mz_tab_metadata.protein_quantification_unit = p;
mandatory_meta_values.insert("protein-quantification_unit");
}
else if (meta_key == "peptide" && meta_key_fields[1] == "quantification_unit")
{
MzTabParameter p;
p.fromCellString(cells[2]);
mz_tab_metadata.peptide_quantification_unit = p;
mandatory_meta_values.insert("peptide-quantification_unit");
}
else if (meta_key == "small_molecule" && meta_key_fields[1] == "quantification_unit")
{
MzTabParameter p;
p.fromCellString(cells[2]);
mz_tab_metadata.small_molecule_quantification_unit = p;
mandatory_meta_values.insert("small_molecule-quantification_unit");
}
else if (meta_key.hasPrefix("ms_run[") && meta_key_fields[1] == "format")
{
Int n = meta_key_fields[0].substitute("ms_run[", "").substitute("]","").trim().toInt();
MzTabParameter p;
p.fromCellString(cells[2]);
mz_tab_metadata.ms_run[n].format = p;
}
else if (meta_key.hasPrefix("ms_run[") && meta_key_fields[1] == "location")
{
Int n = meta_key_fields[0].substitute("ms_run[", "").substitute("]","").trim().toInt();
MzTabString p;
p.fromCellString(cells[2]);
mz_tab_metadata.ms_run[n].location = p;
count_ms_run_location = std::max((Size)n, (Size)count_ms_run_location); // will be checked to match number of entries in map to detect skipped entries or wrong numbering
}
else if (meta_key.hasPrefix("ms_run[") && meta_key_fields[1] == "id_format")
{
Int n = meta_key_fields[0].substitute("ms_run[", "").substitute("]","").trim().toInt();
MzTabParameter p;
p.fromCellString(cells[2]);
mz_tab_metadata.ms_run[n].id_format = p;
}
else if (meta_key.hasPrefix("ms_run[") && meta_key_fields[1] == "fragmentation_method")
{
Int n = meta_key_fields[0].substitute("ms_run[", "").substitute("]","").trim().toInt();
MzTabParameterList p;
p.fromCellString(cells[2]);
mz_tab_metadata.ms_run[n].fragmentation_method = p;
}
else if (meta_key.hasPrefix("custom["))
{
Int n = meta_key.substitute("custom[", "").substitute("]","").trim().toInt();
MzTabParameter p;
p.fromCellString(cells[2]);
mz_tab_metadata.custom[n] = p;
}
else if (meta_key.hasPrefix("sample[") && meta_key_fields[1].hasPrefix("species["))
{
Int n = meta_key_fields[0].substitute("sample[", "").substitute("]","").trim().toInt();
Int m = meta_key_fields[1].substitute("species[", "").substitute("]","").trim().toInt();
MzTabParameter p;
p.fromCellString(cells[2]);
mz_tab_metadata.sample[n].species[m] = p;
}
else if (meta_key.hasPrefix("sample[") && meta_key_fields[1].hasPrefix("tissue["))
{
Int n = meta_key_fields[0].substitute("sample[", "").substitute("]","").trim().toInt();
Int m = meta_key_fields[1].substitute("tissue[", "").substitute("]","").trim().toInt();
MzTabParameter p;
p.fromCellString(cells[2]);
mz_tab_metadata.sample[n].tissue[m] = p;
}
else if (meta_key.hasPrefix("sample[") && meta_key_fields[1].hasPrefix("cell_type["))
{
Int n = meta_key_fields[0].substitute("sample[", "").substitute("]","").trim().toInt();
Int m = meta_key_fields[1].substitute("cell_type[", "").substitute("]","").trim().toInt();
MzTabParameter p;
p.fromCellString(cells[2]);
mz_tab_metadata.sample[n].cell_type[m] = p;
}
else if (meta_key.hasPrefix("sample[") && meta_key_fields[1].hasPrefix("disease["))
{
Int n = meta_key_fields[0].substitute("sample[", "").substitute("]","").trim().toInt();
Int m = meta_key_fields[1].substitute("disease[", "").substitute("]","").trim().toInt();
MzTabParameter p;
p.fromCellString(cells[2]);
mz_tab_metadata.sample[n].disease[m] = p;
}
else if (meta_key.hasPrefix("sample[") && meta_key_fields[1] == "description")
{
Int n = meta_key_fields[0].substitute("sample[", "").substitute("]","").trim().toInt();
MzTabString p;
p.fromCellString(cells[2]);
mz_tab_metadata.sample[n].description = p;
}
else if (meta_key.hasPrefix("sample[") && meta_key_fields[1].hasPrefix("custom["))
{
Int n = meta_key_fields[0].substitute("sample[", "").substitute("]","").trim().toInt();
Int m = meta_key_fields[1].substitute("custom[", "").substitute("]","").trim().toInt();
MzTabParameter p;
p.fromCellString(cells[2]);
mz_tab_metadata.sample[n].custom[m] = p;
}
else if (meta_key.hasPrefix("assay[") && meta_key_fields[1] == "quantification_reagent")
{
Int n = meta_key_fields[0].substitute("assay[", "").substitute("]","").trim().toInt();
MzTabParameter p;
p.fromCellString(cells[2]);
mz_tab_metadata.assay[n].quantification_reagent = p;
}
else if (meta_key.hasPrefix("assay[") && meta_key_fields[1].hasPrefix("quantification_mod[") && meta_key_fields.size() == 2) // assay[]-quantification_mod[]
{
Int n = meta_key_fields[0].substitute("assay[", "").substitute("]","").trim().toInt();
Int m = meta_key_fields[1].substitute("quantification_mod[", "").substitute("]","").trim().toInt();
MzTabParameter p;
p.fromCellString(cells[2]);
mz_tab_metadata.assay[n].quantification_mod[m].modification = p;
}
else if (meta_key.hasPrefix("assay[") && meta_key_fields[1].hasPrefix("quantification_mod[") && meta_key_fields[2] == "site")
{
Int n = meta_key_fields[0].substitute("assay[", "").substitute("]","").trim().toInt();
Int m = meta_key_fields[1].substitute("quantification_mod[", "").substitute("]","").trim().toInt();
MzTabString s;
s.fromCellString(cells[2]);
mz_tab_metadata.assay[n].quantification_mod[m].site = s;
}
else if (meta_key.hasPrefix("assay[") && meta_key_fields[1].hasPrefix("quantification_mod[") && meta_key_fields[2] == "position")
{
Int n = meta_key_fields[0].substitute("assay[", "").substitute("]","").trim().toInt();
Int m = meta_key_fields[1].substitute("quantification_mod[", "").substitute("]","").trim().toInt();
MzTabString s;
s.fromCellString(cells[2]);
mz_tab_metadata.assay[n].quantification_mod[m].position = s;
}
else if (meta_key.hasPrefix("assay[") && meta_key_fields[1] == "sample_ref")
{
Int n = meta_key_fields[0].substitute("assay[", "").substitute("]","").trim().toInt();
MzTabString p;
p.fromCellString(cells[2]);
mz_tab_metadata.assay[n].sample_ref = p;
}
else if (meta_key.hasPrefix("cv[") && meta_key_fields[1] == "label")
{
Int n = meta_key_fields[0].substitute("cv[", "").substitute("]","").trim().toInt();
MzTabString p;
p.fromCellString(cells[2]);
mz_tab_metadata.cv[n].label = p;
}
else if (meta_key.hasPrefix("cv[") && meta_key_fields[1] == "full_name")
{
Int n = meta_key_fields[0].substitute("cv[", "").substitute("]","").trim().toInt();
MzTabString p;
p.fromCellString(cells[2]);
mz_tab_metadata.cv[n].full_name = p;
}
else if (meta_key.hasPrefix("cv[") && meta_key_fields[1] == "version")
{
Int n = meta_key_fields[0].substitute("cv[", "").substitute("]","").trim().toInt();
MzTabString p;
p.fromCellString(cells[2]);
mz_tab_metadata.cv[n].version = p;
}
else if (meta_key.hasPrefix("cv[") && meta_key_fields[1] == "url")
{
Int n = meta_key_fields[0].substitute("cv[", "").substitute("]","").trim().toInt();
MzTabString p;
p.fromCellString(cells[2]);
mz_tab_metadata.cv[n].url = p;
}
else if (meta_key.hasPrefix("assay[") && meta_key_fields[1] == "ms_run_ref")
{
Int n = meta_key_fields[0].substitute("assay[", "").substitute("]","").trim().toInt();
String s = cells[2];
s.substitute("ms_run[","").substitute("]","");
vector<String> ms_run;
s.split(',', ms_run);
for (auto& a : ms_run)
{
a.trim();
mz_tab_metadata.assay[n].ms_run_ref.push_back(a.toInt());
}
}
else if (meta_key.hasPrefix("study_variable[") && meta_key_fields[1] == "assay_refs")
{
Int n = meta_key_fields[0].substitute("study_variable[", "").substitute("]","").trim().toInt();
String s = cells[2];
s.substitute("assay[","").substitute("]","");
vector<String> assays;
s.split(',', assays);
for (auto& a : assays)
{
a.trim();
mz_tab_metadata.study_variable[n].assay_refs.push_back(a.toInt());
}
}
else if (meta_key.hasPrefix("study_variable[") && meta_key_fields[1] == "sample_refs")
{
Int n = meta_key_fields[0].substitute("study_variable[", "").substitute("]","").trim().toInt();
String s = cells[2];
s.substitute("sample[","").substitute("]","");
vector<String> assays;
s.split(',', assays);
for (auto& a : assays)
{
a.trim();
mz_tab_metadata.study_variable[n].sample_refs.push_back(a.toInt());
}
}
else if (meta_key.hasPrefix("study_variable[") && meta_key_fields[1] == "description")
{
Int n = meta_key_fields[0].substitute("study_variable[", "").substitute("]","").trim().toInt();
MzTabString p;
p.fromCellString(cells[2]);
mz_tab_metadata.study_variable[n].description = p;
count_study_variable_description = std::max((Size)n, count_study_variable_description);
}
else if (meta_key.hasPrefix("colunit") && meta_key_fields[1] == "protein")
{
Int n = meta_key_fields[0].substitute("colunit[", "").substitute("]","").trim().toInt();
String s = cells[2];
mz_tab_metadata.colunit_protein[n] = s;
}
else if (meta_key.hasPrefix("colunit") && meta_key_fields[1] == "peptide")
{
Int n = meta_key_fields[0].substitute("colunit[", "").substitute("]","").trim().toInt();
String s = cells[2];
mz_tab_metadata.colunit_peptide[n] = s;
}
else if (meta_key.hasPrefix("colunit") && meta_key_fields[1] == "psm")
{
Int n = meta_key_fields[0].substitute("colunit[", "").substitute("]","").trim().toInt();
String s = cells[2];
mz_tab_metadata.colunit_psm[n] = s;
}
else if (meta_key.hasPrefix("colunit") && meta_key_fields[1] == "small_molecule")
{
Int n = meta_key_fields[0].substitute("colunit[", "").substitute("]","").trim().toInt();
String s = cells[2];
mz_tab_metadata.colunit_small_molecule[n] = s;
}
}
// parse protein header section
if (section == "PRH")
{
for (Size i = 0; i != cells.size(); ++i)
{
if (cells[i] == "accession")
{
protein_accession_index = i;
}
else if (cells[i] == "description")
{
protein_description_index = i;
}
else if (cells[i] == "taxid")
{
protein_taxid_index = i;
}
else if (cells[i] == "species")
{
protein_species_index = i;
}
else if (cells[i] == "database")
{
protein_database_index = i;
}
else if (cells[i] == "database_version")
{
protein_database_version_index = i;
}
else if (cells[i] =="search_engine")
{
protein_search_engine_index = i;
}
else if (cells[i].hasPrefix("best_search_engine_score["))
{
String s = cells[i];
Size n = (Size)s.substitute("best_search_engine_score[", "").substitute("]","").trim().toInt();
protein_best_search_engine_score_to_column_index[n] = i;
}
else if (cells[i].hasPrefix("search_engine_score["))
{
std::pair<Size, Size> pair = extractIndexPairsFromBrackets_(cells[i]);
protein_column_index_to_score_runs_pair[i] = pair;
}
else if (cells[i] == "reliability")
{
protein_reliability_index = i;
}
else if (cells[i].hasPrefix("num_psms_ms_run["))
{
String s = cells[i];
Size n = (Size)s.substitute("num_psms_ms_run[", "").substitute("]","").trim().toInt();
protein_num_psms_ms_run_indices[n] = i;
}
else if (cells[i].hasPrefix("num_peptides_distinct_ms_run["))
{
String s = cells[i];
Size n = (Size)s.substitute("num_peptides_distinct_ms_run[", "").substitute("]","").trim().toInt();
protein_num_peptides_distinct_ms_run_indices[n] = i;
}
else if (cells[i].hasPrefix("num_peptides_unique_ms_run["))
{
String s = cells[i];
Size n = (Size)s.substitute("num_peptides_unique_ms_run[", "").substitute("]","").trim().toInt();
protein_num_peptides_unique_ms_run_indices[n] = i;
}
else if (cells[i] == "ambiguity_members")
{
protein_ambiguity_members_index = i;
}
else if (cells[i] == "modifications")
{
protein_modifications_index = i;
}
else if (cells[i] == "uri")
{
protein_uri_index = i;
}
else if (cells[i] == "go_terms")
{
protein_go_terms_index = i;
}
else if (cells[i] == "protein_coverage")
{
protein_coverage_index = i;
}
else if (cells[i].hasPrefix("protein_abundance_assay["))
{
String s = cells[i];
Size n = (Size)s.substitute("protein_abundance_assay[", "").substitute("]","").trim().toInt();
protein_abundance_assay_indices[n] = i;
}
else if (cells[i].hasPrefix("protein_abundance_study_variable["))
{
String s = cells[i];
Size n = (Size)s.substitute("protein_abundance_study_variable[", "").substitute("]","").trim().toInt();
protein_abundance_study_variable_to_column_indices[n] = i;
}
else if (cells[i].hasPrefix("protein_abundance_stdev_study_variable["))
{
String s = cells[i];
Size n = (Size)s.substitute("protein_abundance_stdev_study_variable[", "").substitute("]","").trim().toInt();
protein_abundance_stdev_study_variable_to_column_indices[n] = i;
}
else if (cells[i].hasPrefix("protein_abundance_std_error_study_variable["))
{
String s = cells[i];
Size n = (Size)s.substitute("protein_abundance_std_error_study_variable[", "").substitute("]","").trim().toInt();
protein_abundance_std_error_study_variable_to_column_indices[n] = i;
}
else if (cells[i].hasPrefix("opt_"))
{
protein_custom_opt_columns[cells[i]] = i;
}
}
continue;
}
// parse protein section
if (section == "PRT")
{
sections_present.insert("PRT");
// check if all mandatory columns are present
if (protein_accession_index == 0)
{
cout << "Error: mandatory protein accession column missing" << endl;
}
if (protein_description_index == 0)
{
cout << "Error: mandatory protein description column missing" << endl;
}
if (protein_taxid_index == 0)
{
cout << "Error: mandatory protein taxid column missing" << endl;
}
if (protein_species_index == 0)
{
cout << "Error: mandatory protein species column missing" << endl;
}
if (protein_database_index == 0)
{
cout << "Error: mandatory protein database column missing" << endl;
}
if (protein_database_version_index == 0)
{
cout << "Error: mandatory protein database_version column missing" << endl;
}
if (protein_search_engine_index == 0)
{
cout << "Error: mandatory protein search_engine column missing" << endl;
}
if (protein_best_search_engine_score_to_column_index.empty())
{
cout << "Error: mandatory protein best_search_engine_score[1-n] column missing" << endl;
}
if (mz_tab_metadata.mz_tab_mode.toCellString() == "Complete")
{
if (protein_column_index_to_score_runs_pair.size() != mz_tab_metadata.ms_run.size())
{
cout << "Error: mandatory protein search_engine_score_ms_run column(s) missing. Expected "
<< mz_tab_metadata.ms_run.size() << " ms_runs (meta data section) but only " << protein_column_index_to_score_runs_pair.size()
<< " ms_runs provide score columns (protein section)." << endl;
}
}
if (protein_num_psms_ms_run_indices.empty() && mz_tab_metadata.mz_tab_mode.toCellString() == "Complete"
&& mz_tab_metadata.mz_tab_type.toCellString() == "Identification")
{
cout << "Error: mandatory protein num_psms_ms_run column(s) missing" << endl;
}
if (protein_num_peptides_distinct_ms_run_indices.empty() && mz_tab_metadata.mz_tab_mode.toCellString() == "Complete"
&& mz_tab_metadata.mz_tab_type.toCellString() == "Identification")
{
cout << "Error: mandatory protein num_peptides_distinct_ms_run column(s) missing" << endl;
}
if (protein_num_peptides_unique_ms_run_indices.empty() && mz_tab_metadata.mz_tab_mode.toCellString() == "Complete"
&& mz_tab_metadata.mz_tab_type.toCellString() == "Identification")
{
cout << "Error: mandatory protein num_peptides_unique_ms_run column(s) missing" << endl;
}
if (protein_ambiguity_members_index == 0)
{
cout << "Error: mandatory protein ambiguity_members column missing" << endl;
}
if (protein_modifications_index == 0)
{
cout << "Error: mandatory protein modifications column missing" << endl;
}
if (protein_coverage_index == 0)
{
cout << "Error: mandatory protein coverage column missing" << endl;
}
if (protein_abundance_assay_indices.empty()&& mz_tab_metadata.mz_tab_mode.toCellString() == "Complete"
&& mz_tab_metadata.mz_tab_type.toCellString() == "Quantification")
{
cout << "Error: mandatory protein protein_abundance_assay column(s) missing" << endl;
}
if (protein_abundance_study_variable_to_column_indices.empty() && mz_tab_metadata.mz_tab_type.toCellString() == "Quantification")
{
cout << "Error: mandatory protein_abundance_study_variable column(s) missing" << endl;
}
if (protein_abundance_stdev_study_variable_to_column_indices.empty() && mz_tab_metadata.mz_tab_type.toCellString() == "Quantification")
{
cout << "Error: mandatory protein_abundance_stdev_study_variable column(s) missing" << endl;
}
if (protein_abundance_std_error_study_variable_to_column_indices.empty() && mz_tab_metadata.mz_tab_type.toCellString() == "Quantification")
{
cout << "Error: mandatory protein_abundance_stderr_study_variable column(s) missing" << endl;
}
MzTabProteinSectionRow row;
row.accession.fromCellString(cells[protein_accession_index]);
row.description.fromCellString(cells[protein_description_index]);
row.taxid.fromCellString(cells[protein_taxid_index]);
row.species.fromCellString(cells[protein_species_index]);
row.database.fromCellString(cells[protein_database_index]);
row.database_version.fromCellString(cells[protein_database_version_index]);
row.search_engine.fromCellString(cells[protein_search_engine_index]);
for (map<Size, Size>::const_iterator it = protein_best_search_engine_score_to_column_index.begin(); it != protein_best_search_engine_score_to_column_index.end(); ++it)
{
row.best_search_engine_score[it->first].fromCellString(cells[it->second]);
}
for (map<Size, std::pair<Size, Size> >::const_iterator it = protein_column_index_to_score_runs_pair.begin(); it != protein_column_index_to_score_runs_pair.end(); ++it)
{
row.search_engine_score_ms_run[it->second.first][it->second.second].fromCellString(cells[it->first]);
}
if (protein_reliability_index != 0)
{
row.reliability.fromCellString(cells[protein_reliability_index]);
}
for (map<Size, Size>::const_iterator it = protein_num_psms_ms_run_indices.begin(); it != protein_num_psms_ms_run_indices.end(); ++it)
{
row.num_psms_ms_run[it->first].fromCellString(cells[it->second]);
}
for (map<Size, Size>::const_iterator it = protein_num_peptides_distinct_ms_run_indices.begin(); it != protein_num_peptides_distinct_ms_run_indices.end(); ++it)
{
row.num_peptides_distinct_ms_run[it->first].fromCellString(cells[it->second]);
}
for (map<Size, Size>::const_iterator it = protein_num_peptides_unique_ms_run_indices.begin(); it != protein_num_peptides_unique_ms_run_indices.end(); ++it)
{
row.num_peptides_unique_ms_run[it->first].fromCellString(cells[it->second]);
}
row.ambiguity_members.fromCellString(cells[protein_ambiguity_members_index]);
row.modifications.fromCellString(cells[protein_modifications_index]);
if (protein_uri_index != 0)
{
row.uri.fromCellString(cells[protein_uri_index]);
}
if (protein_go_terms_index != 0)
{
row.go_terms.fromCellString(cells[protein_go_terms_index]);
}
row.coverage.fromCellString(cells[protein_coverage_index]);
// quantification data
for (map<Size, Size>::const_iterator it = protein_abundance_assay_indices.begin(); it != protein_abundance_assay_indices.end(); ++it)
{
row.protein_abundance_assay[it->first].fromCellString(cells[it->second]);
}
for (map<Size, Size>::const_iterator it = protein_abundance_study_variable_to_column_indices.begin(); it != protein_abundance_study_variable_to_column_indices.end(); ++it)
{
row.protein_abundance_study_variable[it->first].fromCellString(cells[it->second]);
}
for (map<Size, Size>::const_iterator it = protein_abundance_stdev_study_variable_to_column_indices.begin(); it != protein_abundance_stdev_study_variable_to_column_indices.end(); ++it)
{
row.protein_abundance_stdev_study_variable[it->first].fromCellString(cells[it->second]);
}
for (map<Size, Size>::const_iterator it = protein_abundance_std_error_study_variable_to_column_indices.begin(); it != protein_abundance_std_error_study_variable_to_column_indices.end(); ++it)
{
row.protein_abundance_std_error_study_variable[it->first].fromCellString(cells[it->second]);
}
for (map<String, Size>::const_iterator it = protein_custom_opt_columns.begin(); it != protein_custom_opt_columns.end(); ++it)
{
MzTabString s;
s.fromCellString(cells[it->second]);
MzTabOptionalColumnEntry e(it->first, s);
row.opt_.push_back(e);
}
mz_tab_protein_section_data.push_back(row);
continue;
}
// parse peptide header section
if (section == "PEH")
{
for (Size i = 0; i != cells.size(); ++i)
{
if (cells[i] == "sequence")
{
peptide_sequence_index = i;
}
else if (cells[i] == "accession")
{
peptide_accession_index = i;
}
else if (cells[i] == "unique")
{
peptide_unique_index = i;
}
else if (cells[i] == "database")
{
peptide_database_index = i;
}
else if (cells[i] == "database_version")
{
peptide_database_version_index = i;
}
else if (cells[i] == "search_engine")
{
peptide_search_engine_index = i;
}
else if (cells[i].hasPrefix("best_search_engine_score["))
{
String s = cells[i];
Size n = (Size)s.substitute("best_search_engine_score[", "").substitute("]","").trim().toInt();
peptide_best_search_engine_score_to_column_index[n] = i;
}
else if (cells[i].hasPrefix("search_engine_score["))
{
std::pair<Size, Size> pair = extractIndexPairsFromBrackets_(cells[i].toQString());
peptide_column_index_to_score_runs_pair[i] = pair;
}
else if (cells[i] == "reliability")
{
peptide_reliability_index = i;
}
else if (cells[i] == "modifications")
{
peptide_modifications_index = i;
}
else if (cells[i] == "retention_time")
{
peptide_retention_time_index = i;
}
else if (cells[i] == "retention_time_window")
{
peptide_retention_time_window_index = i;
}
else if (cells[i] == "charge")
{
peptide_charge_index = i;
}
else if (cells[i] == "mass_to_charge")
{
peptide_mass_to_charge_index = i;
}
else if (cells[i] == "uri")
{
protein_uri_index = i;
}
else if (cells[i] == "spectra_ref")
{
peptide_spectra_ref_index = i;
}
else if (cells[i].hasPrefix("peptide_abundance_assay["))
{
String s = cells[i];
Size n = (Size)s.substitute("peptide_abundance_assay[", "").substitute("]","").trim().toInt();
peptide_abundance_assay_indices[n] = i;
}
else if (cells[i].hasPrefix("peptide_abundance_study_variable["))
{
String s = cells[i];
Size n = (Size)s.substitute("peptide_abundance_study_variable[", "").substitute("]","").trim().toInt();
peptide_abundance_study_variable_to_column_indices[n] = i;
}
else if (cells[i].hasPrefix("peptide_abundance_stdev_study_variable["))
{
String s = cells[i];
Size n = (Size)s.substitute("peptide_abundance_stdev_study_variable[", "").substitute("]","").trim().toInt();
peptide_abundance_study_variable_stdev_to_column_indices[n] = i;
}
else if (cells[i].hasPrefix("peptide_abundance_std_error_study_variable["))
{
String s = cells[i];
Size n = (Size)s.substitute("peptide_abundance_std_error_study_variable[", "").substitute("]","").trim().toInt();
peptide_abundance_study_variable_std_error_to_column_indices[n] = i;
}
else if (cells[i].hasPrefix("opt_"))
{
peptide_custom_opt_columns[cells[i]] = i;
}
}
continue;
}
// parse peptide section
if (section == "PEP")
{
sections_present.insert("PRT");
MzTabPeptideSectionRow row;
row.sequence.fromCellString(cells[peptide_sequence_index]);
row.accession.fromCellString(cells[peptide_accession_index]);
row.unique.fromCellString(cells[peptide_unique_index]);
row.database.fromCellString(cells[peptide_database_index]);
row.database_version.fromCellString(cells[peptide_database_version_index]);
row.search_engine.fromCellString(cells[peptide_search_engine_index]);
for (map<Size, Size>::const_iterator it = peptide_best_search_engine_score_to_column_index.begin(); it != peptide_best_search_engine_score_to_column_index.end(); ++it)
{
row.best_search_engine_score[it->first].fromCellString(cells[it->second]);
}
for (auto it = peptide_column_index_to_score_runs_pair.begin(); it != peptide_column_index_to_score_runs_pair.end(); ++it)
{
row.search_engine_score_ms_run[it->second.first][it->second.second].fromCellString(cells[it->first]);
}
if (peptide_reliability_index != 0)
{
row.reliability.fromCellString(cells[peptide_reliability_index]);
}
row.modifications.fromCellString(cells[peptide_modifications_index]);
row.retention_time.fromCellString(cells[peptide_retention_time_index]);
row.retention_time_window.fromCellString(cells[peptide_retention_time_window_index]);
row.charge.fromCellString(cells[peptide_charge_index]);
row.mass_to_charge.fromCellString(cells[peptide_mass_to_charge_index]);
// if (peptide_uri_index != 0) // always false
// {
// row.uri.fromCellString(cells[peptide_uri_index]);
// }
row.spectra_ref.fromCellString(cells[peptide_spectra_ref_index]);
// quantification data
for (map<Size, Size>::const_iterator it = peptide_abundance_assay_indices.begin(); it != peptide_abundance_assay_indices.end(); ++it)
{
row.peptide_abundance_assay[it->first].fromCellString(cells[it->second]);
}
for (map<Size, Size>::const_iterator it = peptide_abundance_study_variable_to_column_indices.begin(); it != peptide_abundance_study_variable_to_column_indices.end(); ++it)
{
row.peptide_abundance_study_variable[it->first].fromCellString(cells[it->second]);
}
for (map<Size, Size>::const_iterator it = peptide_abundance_study_variable_stdev_to_column_indices.begin(); it != peptide_abundance_study_variable_stdev_to_column_indices.end(); ++it)
{
row.peptide_abundance_stdev_study_variable[it->first].fromCellString(cells[it->second]);
}
for (map<Size, Size>::const_iterator it = peptide_abundance_study_variable_std_error_to_column_indices.begin(); it != peptide_abundance_study_variable_std_error_to_column_indices.end(); ++it)
{
row.peptide_abundance_std_error_study_variable[it->first].fromCellString(cells[it->second]);
}
for (map<String, Size>::const_iterator it = peptide_custom_opt_columns.begin(); it != peptide_custom_opt_columns.end(); ++it)
{
MzTabString s;
s.fromCellString(cells[it->second]);
MzTabOptionalColumnEntry e(it->first, s);
row.opt_.push_back(e);
}
mz_tab_peptide_section_data.push_back(row);
continue;
}
// parse PSM header section
if (section == "PSH")
{
for (Size i = 0; i != cells.size(); ++i)
{
if (cells[i] == "sequence")
{
psm_sequence_index = i;
}
else if (cells[i] == "PSM_ID")
{
psm_psm_id_index = i;
}
else if (cells[i] == "accession")
{
psm_accession_index = i;
}
else if (cells[i] == "unique")
{
psm_unique_index = i;
}
else if (cells[i] == "database")
{
psm_database_index = i;
}
else if (cells[i] == "database_version")
{
psm_database_version_index = i;
}
else if (cells[i] == "search_engine")
{
psm_search_engine_index = i;
}
else if (cells[i].hasPrefix("search_engine_score["))
{
String s = cells[i];
Size n = (Size)s.substitute("search_engine_score[", "").substitute("]","").trim().toInt();
psm_search_engine_score_to_column_index[n] = i;
}
else if (cells[i].hasPrefix("reliability"))
{
psm_reliability_index = i;
}
else if (cells[i] == "modifications")
{
psm_modifications_index = i;
}
else if (cells[i] == "retention_time")
{
psm_retention_time_index = i;
}
else if (cells[i] == "charge")
{
psm_charge_index = i;
}
else if (cells[i] == "exp_mass_to_charge")
{
psm_exp_mass_to_charge_index = i;
}
else if (cells[i] == "calc_mass_to_charge")
{
psm_calc_mass_to_charge_index = i;
}
else if (cells[i] == "uri")
{
protein_uri_index = i;
}
else if (cells[i] == "spectra_ref")
{
psm_spectra_ref_index = i;
}
else if (cells[i] == "pre")
{
psm_pre_index = i;
}
else if (cells[i] == "post")
{
psm_post_index = i;
}
else if (cells[i] == "start")
{
psm_start_index = i;
}
else if (cells[i] == "end")
{
psm_end_index = i;
}
else if (cells[i] == "opt_")
{
psm_custom_opt_columns[cells[i]] = i;
}
}
continue;
}
// parse peptide section
if (section == "PSM")
{
MzTabPSMSectionRow row;
row.sequence.fromCellString(cells[psm_sequence_index]);
row.PSM_ID.fromCellString(cells[psm_psm_id_index]);
row.accession.fromCellString(cells[psm_accession_index]);
row.unique.fromCellString(cells[psm_unique_index]);
row.database.fromCellString(cells[psm_database_index]);
row.database_version.fromCellString(cells[psm_database_version_index]);
row.search_engine.fromCellString(cells[psm_search_engine_index]);
for (map<Size, Size>::const_iterator it = psm_search_engine_score_to_column_index.begin(); it != psm_search_engine_score_to_column_index.end(); ++it)
{
row.search_engine_score[it->first].fromCellString(cells[it->second]);
}
if (psm_reliability_index != 0)
{
row.reliability.fromCellString(cells[psm_reliability_index]);
}
row.modifications.fromCellString(cells[psm_modifications_index]);
row.retention_time.fromCellString(cells[psm_retention_time_index]);
row.charge.fromCellString(cells[psm_charge_index]);
row.exp_mass_to_charge.fromCellString(cells[psm_exp_mass_to_charge_index]);
row.calc_mass_to_charge.fromCellString(cells[psm_calc_mass_to_charge_index]);
// always false
// if (psm_uri_index != 0)
// {
// row.uri.fromCellString(cells[psm_uri_index]);
// }
row.spectra_ref.fromCellString(cells[psm_spectra_ref_index]);
row.pre.fromCellString(cells[psm_pre_index]);
row.post.fromCellString(cells[psm_post_index]);
row.start.fromCellString(cells[psm_start_index]);
row.end.fromCellString(cells[psm_end_index]);
for (map<String, Size>::const_iterator it = psm_custom_opt_columns.begin(); it != psm_custom_opt_columns.end(); ++it)
{
MzTabString s;
s.fromCellString(cells[it->second]);
MzTabOptionalColumnEntry e(it->first, s);
row.opt_.push_back(e);
}
mz_tab_psm_section_data.push_back(row);
continue;
}
// parse small molecule header section
if (section == "SMH")
{
for (Size i = 0; i != cells.size(); ++i)
{
if (cells[i] == "identifier")
{
smallmolecule_identifier_index = i;
}
else if (cells[i] == "chemical_formula")
{
smallmolecule_chemical_formula_index = i;
}
else if (cells[i] == "smiles")
{
smallmolecule_smiles_index = i;
}
else if (cells[i] == "inchi_key")
{
smallmolecule_inchi_key_index = i;
}
else if (cells[i] == "description")
{
smallmolecule_description_index = i;
}
else if (cells[i] == "exp_mass_to_charge")
{
smallmolecule_exp_mass_to_charge_index = i;
}
else if (cells[i] == "calc_mass_to_charge")
{
smallmolecule_calc_mass_to_charge_index = i;
}
else if (cells[i] == "charge")
{
smallmolecule_charge_index = i;
}
else if (cells[i] == "retention_time")
{
smallmolecule_retention_time_index = i;
}
else if (cells[i] == "taxid")
{
smallmolecule_taxid_index = i;
}
else if (cells[i] == "species")
{
smallmolecule_species_index = i;
}
else if (cells[i] == "database")
{
smallmolecule_database_index = i;
}
else if (cells[i] == "database_version")
{
smallmolecule_database_version_index = i;
}
else if (cells[i] == "reliability")
{
smallmolecule_reliability_index = i;
}
else if (cells[i] == "uri")
{
smallmolecule_uri_index = i;
}
else if (cells[i] == "spectra_ref")
{
smallmolecule_spectra_ref_index = i;
}
else if (cells[i] == "search_engine")
{
smallmolecule_search_engine_index = i;
}
else if (cells[i].hasPrefix("best_search_engine_score["))
{
String s = cells[i];
Size n = (Size)s.substitute("best_search_engine_score[", "").substitute("]","").trim().toInt();
smallmolecule_best_search_engine_score_to_column_index[n] = i;
}
else if (cells[i].hasPrefix("search_engine_score["))
{
std::pair<Size, Size> pair = extractIndexPairsFromBrackets_(cells[i].toQString());
smallmolecule_column_index_to_score_runs_pair[i] = pair;
}
else if (cells[i] == "modifications")
{
smallmolecule_modifications_index = i;
}
else if (cells[i].hasPrefix("smallmolecule_abundance_assay["))
{
String s = cells[i];
Size n = (Size)s.substitute("smallmolecule_abundance_assay[", "").substitute("]","").trim().toInt();
smallmolecule_abundance_assay_indices[n] = i;
}
else if (cells[i].hasPrefix("smallmolecule_abundance_study_variable["))
{
String s = cells[i];
Size n = (Size)s.substitute("smallmolecule_abundance_study_variable[", "").substitute("]","").trim().toInt();
smallmolecule_abundance_study_variable_indices[n] = i;
}
else if (cells[i].hasPrefix("smallmolecule_abundance_stdev_study_variable["))
{
String s = cells[i];
Size n = (Size)s.substitute("smallmolecule_abundance_stdev_study_variable[", "").substitute("]","").trim().toInt();
smallmolecule_abundance_stdev_study_variable_indices[n] = i;
}
else if (cells[i].hasPrefix("smallmolecule_abundance_std_error_study_variable["))
{
String s = cells[i];
Size n = (Size)s.substitute("smallmolecule_abundance_std_error_study_variable[", "").substitute("]","").trim().toInt();
smallmolecule_abundance_std_error_study_variable_indices[n] = i;
}
else if (cells[i].hasPrefix("opt_"))
{
smallmolecule_custom_opt_columns[cells[i]] = i;
}
}
continue;
}
// parse small molecule section
if (section == "SML")
{
sections_present.insert("SML");
MzTabSmallMoleculeSectionRow row;
row.identifier.fromCellString(cells[smallmolecule_identifier_index]);
row.chemical_formula.fromCellString(cells[smallmolecule_chemical_formula_index]);
row.smiles.fromCellString(cells[smallmolecule_smiles_index]);
row.inchi_key.fromCellString(cells[smallmolecule_inchi_key_index]);
row.description.fromCellString(cells[smallmolecule_description_index]);
row.exp_mass_to_charge.fromCellString(cells[smallmolecule_exp_mass_to_charge_index]);
row.calc_mass_to_charge.fromCellString(cells[smallmolecule_calc_mass_to_charge_index]);
row.charge.fromCellString(cells[smallmolecule_charge_index]);
row.retention_time.fromCellString(cells[smallmolecule_retention_time_index]);
row.taxid.fromCellString(cells[smallmolecule_taxid_index]);
row.species.fromCellString(cells[smallmolecule_species_index]);
row.database.fromCellString(cells[smallmolecule_database_index]);
row.database_version.fromCellString(cells[smallmolecule_database_version_index]);
if (smallmolecule_reliability_index != 0)
{
row.reliability.fromCellString(cells[smallmolecule_reliability_index]);
}
if (smallmolecule_uri_index != 0)
{
row.uri.fromCellString(cells[smallmolecule_uri_index]);
}
row.spectra_ref.fromCellString(cells[smallmolecule_spectra_ref_index]);
row.search_engine.fromCellString(cells[smallmolecule_search_engine_index]);
for (map<Size, Size>::const_iterator it = smallmolecule_best_search_engine_score_to_column_index.begin(); it != smallmolecule_best_search_engine_score_to_column_index.end(); ++it)
{
row.best_search_engine_score[it->first].fromCellString(cells[it->second]);
}
for (map<Size, std::pair<Size, Size> >::const_iterator it = smallmolecule_column_index_to_score_runs_pair.begin(); it != smallmolecule_column_index_to_score_runs_pair.end(); ++it)
{
row.search_engine_score_ms_run[it->second.first][it->second.second].fromCellString(cells[it->first]);
}
row.modifications.fromCellString(cells[smallmolecule_modifications_index]);
// quantification data
for (map<Size, Size>::const_iterator it = smallmolecule_abundance_assay_indices.begin(); it != smallmolecule_abundance_assay_indices.end(); ++it)
{
row.smallmolecule_abundance_assay[it->first].fromCellString(cells[it->second]);
}
for (map<Size, Size>::const_iterator it = smallmolecule_abundance_study_variable_indices.begin(); it != smallmolecule_abundance_study_variable_indices.end(); ++it)
{
row.smallmolecule_abundance_study_variable[it->first].fromCellString(cells[it->second]);
}
for (map<Size, Size>::const_iterator it = smallmolecule_abundance_stdev_study_variable_indices.begin(); it != smallmolecule_abundance_stdev_study_variable_indices.end(); ++it)
{
row.smallmolecule_abundance_stdev_study_variable[it->first].fromCellString(cells[it->second]);
}
for (map<Size, Size>::const_iterator it = smallmolecule_abundance_std_error_study_variable_indices.begin(); it != smallmolecule_abundance_std_error_study_variable_indices.end(); ++it)
{
row.smallmolecule_abundance_std_error_study_variable[it->first].fromCellString(cells[it->second]);
}
for (map<String, Size>::const_iterator it = smallmolecule_custom_opt_columns.begin(); it != smallmolecule_custom_opt_columns.end(); ++it)
{
MzTabString s;
s.fromCellString(cells[it->second]);
MzTabOptionalColumnEntry e(it->first, s);
row.opt_.push_back(e);
}
mz_tab_small_molecule_section_data.push_back(row);
continue;
}
}
// TODO: check compulsoriness
//hasMandatoryMetaDataKeys_(mandatory_meta_values, sections_present, mz_tab_metadata);
mz_tab.setMetaData(mz_tab_metadata);
mz_tab.setProteinSectionRows(mz_tab_protein_section_data);
mz_tab.setPeptideSectionRows(mz_tab_peptide_section_data);
mz_tab.setPSMSectionRows(mz_tab_psm_section_data);
mz_tab.setSmallMoleculeSectionRows(mz_tab_small_molecule_section_data);
mz_tab.setEmptyRows(empty_rows);
mz_tab.setCommentRows(comment_rows);
}
void MzTabFile::generateMzTabMetaDataSection_(const MzTabMetaData& md, StringList& sl) const
{
sl.push_back(String("MTD\tmzTab-version\t") + md.mz_tab_version.toCellString());
sl.push_back(String("MTD\tmzTab-mode\t") + md.mz_tab_mode.toCellString());
sl.push_back(String("MTD\tmzTab-type\t") + md.mz_tab_type.toCellString());
if (!md.title.isNull())
{
String s = String("MTD\ttitle\t") + md.title.toCellString();
sl.push_back(s);
}
if (!md.mz_tab_id.isNull())
{
String s = String("MTD\tmzTab-ID\t") + md.mz_tab_id.toCellString();
sl.push_back(s);
}
sl.push_back(String("MTD\tdescription\t") + md.description.toCellString());
for (map<Size, MzTabParameterList>::const_iterator it = md.sample_processing.begin(); it != md.sample_processing.end(); ++it)
{
String s = "MTD\tsample_processing[" + String(it->first) + "]\t" + it->second.toCellString();
sl.push_back(s);
}
for (map<Size, MzTabParameter>::const_iterator it = md.protein_search_engine_score.begin(); it != md.protein_search_engine_score.end(); ++it)
{
String s = "MTD\tprotein_search_engine_score[" + String(it->first) + "]\t" + it->second.toCellString();
sl.push_back(s);
}
for (map<Size, MzTabParameter>::const_iterator it = md.peptide_search_engine_score.begin(); it != md.peptide_search_engine_score.end(); ++it)
{
String s = "MTD\tpeptide_search_engine_score[" + String(it->first) + "]\t" + it->second.toCellString();
sl.push_back(s);
}
for (map<Size, MzTabParameter>::const_iterator it = md.psm_search_engine_score.begin(); it != md.psm_search_engine_score.end(); ++it)
{
String s = "MTD\tpsm_search_engine_score[" + String(it->first) + "]\t" + it->second.toCellString();
sl.push_back(s);
}
for (map<Size, MzTabParameter>::const_iterator it = md.smallmolecule_search_engine_score.begin(); it != md.smallmolecule_search_engine_score.end(); ++it)
{
String s = "MTD\tsmallmolecule_search_engine_score[" + String(it->first) + "]\t" + it->second.toCellString();
sl.push_back(s);
}
for (map<Size, MzTabParameter>::const_iterator it = md.nucleic_acid_search_engine_score.begin(); it != md.nucleic_acid_search_engine_score.end(); ++it)
{
String s = "MTD\tnucleic_acid_search_engine_score[" + String(it->first) + "]\t" + it->second.toCellString();
sl.push_back(s);
}
for (map<Size, MzTabParameter>::const_iterator it = md.oligonucleotide_search_engine_score.begin(); it != md.oligonucleotide_search_engine_score.end(); ++it)
{
String s = "MTD\toligonucleotide_search_engine_score[" + String(it->first) + "]\t" + it->second.toCellString();
sl.push_back(s);
}
for (map<Size, MzTabParameter>::const_iterator it = md.osm_search_engine_score.begin(); it != md.osm_search_engine_score.end(); ++it)
{
String s = "MTD\tosm_search_engine_score[" + String(it->first) + "]\t" + it->second.toCellString();
sl.push_back(s);
}
for (map<Size, MzTabInstrumentMetaData>::const_iterator it = md.instrument.begin(); it != md.instrument.end(); ++it)
{
const MzTabInstrumentMetaData & imd = it->second;
if (!imd.name.isNull())
{
String s = "MTD\tinstrument[" + String(it->first) + "]-name\t" + imd.name.toCellString();
sl.push_back(s);
}
if (!imd.source.isNull())
{
String s = "MTD\tinstrument[" + String(it->first) + "]-source\t" + imd.source.toCellString();
sl.push_back(s);
}
for (map<Size, MzTabParameter>::const_iterator mit = imd.analyzer.begin(); mit != imd.analyzer.end(); ++mit)
{
if (!mit->second.isNull())
{
String s = "MTD\tinstrument[" + String(it->first) + "]-analyzer[" + String(mit->first) + "]\t" + mit->second.toCellString();
sl.push_back(s);
}
}
if (!imd.detector.isNull())
{
String s = "MTD\tinstrument[" + String(it->first) + "]-detector\t" + imd.detector.toCellString();
sl.push_back(s);
}
}
for (map<Size, MzTabSoftwareMetaData>::const_iterator it = md.software.begin(); it != md.software.end(); ++it)
{
String s = "MTD\tsoftware[" + String(it->first) + "]\t" + it->second.software.toCellString();
sl.push_back(s);
for (map<Size, MzTabString>::const_iterator jt = it->second.setting.begin(); jt != it->second.setting.end(); ++jt)
{
String s = "MTD\tsoftware[" + String(it->first) + "]-setting[" + String(jt->first) + String("]\t") + jt->second.toCellString();
sl.push_back(s);
}
}
if (!md.false_discovery_rate.isNull())
{
String s = "MTD\tfalse_discovery_rate\t" + md.false_discovery_rate.toCellString();
sl.push_back(s);
}
for (map<Size, MzTabString>::const_iterator it = md.publication.begin(); it != md.publication.end(); ++it)
{
String s = "MTD\tpublication[" + String(it->first) + "]\t" + it->second.toCellString();
sl.push_back(s);
}
for (map<Size, MzTabContactMetaData>::const_iterator it = md.contact.begin(); it != md.contact.end(); ++it)
{
const MzTabContactMetaData & mdc = it->second;
if (!mdc.name.isNull())
{
String s = "MTD\tcontact[" + String(it->first) + "]-name\t" + mdc.name.toCellString();
sl.push_back(s);
}
if (!mdc.affiliation.isNull())
{
String s = "MTD\tcontact[" + String(it->first) + "]-affiliation\t" + mdc.affiliation.toCellString();
sl.push_back(s);
}
if (!mdc.email.isNull())
{
String s = "MTD\tcontact[" + String(it->first) + "]-email\t" + mdc.email.toCellString();
sl.push_back(s);
}
}
for (map<Size, MzTabString>::const_iterator it = md.uri.begin(); it != md.uri.end(); ++it)
{
String s = "MTD\turi[" + String(it->first) + String("]\t") + it->second.toCellString();
sl.push_back(s);
}
for (map<Size, MzTabModificationMetaData>::const_iterator it = md.fixed_mod.begin(); it != md.fixed_mod.end(); ++it)
{
const MzTabModificationMetaData & mod_md = it->second;
if (!mod_md.modification.isNull())
{
String s = "MTD\tfixed_mod[" + String(it->first) + String("]\t")+ mod_md.modification.toCellString();
sl.push_back(s);
}
else
{
//TODO: add CV for no fixed modification searched when it is available
}
if (!mod_md.site.isNull())
{
String s = "MTD\tfixed_mod[" + String(it->first) + String("]-site\t") + mod_md.site.toCellString();
sl.push_back(s);
}
if (!mod_md.position.isNull())
{
String s = "MTD\tfixed_mod[" + String(it->first) + String("]-position\t") + mod_md.position.toCellString();
sl.push_back(s);
}
}
for (map<Size, MzTabModificationMetaData>::const_iterator it = md.variable_mod.begin(); it != md.variable_mod.end(); ++it)
{
const MzTabModificationMetaData & mod_md = it->second;
if (!mod_md.modification.isNull())
{
String s = "MTD\tvariable_mod[" + String(it->first) + String("]\t") + mod_md.modification.toCellString();
sl.push_back(s);
}
else
{
//TODO: add CV for no variable modification searched when it is available
}
if (!mod_md.site.isNull())
{
String s = "MTD\tvariable_mod[" + String(it->first) + String("]-site\t") + mod_md.site.toCellString();
sl.push_back(s);
}
if (!mod_md.position.isNull())
{
String s = "MTD\tvariable_mod[" + String(it->first) + String("]-position\t")+ mod_md.position.toCellString();
sl.push_back(s);
}
}
// quantification_method
if (!md.quantification_method.isNull())
{
String s = "MTD\tquantification_method\t" + md.quantification_method.toCellString();
sl.push_back(s);
}
// protein-quantification_unit
if (!md.protein_quantification_unit.isNull())
{
String s = "MTD\tprotein-quantification_unit\t" + md.protein_quantification_unit.toCellString();
sl.push_back(s);
}
// peptide-quantification_unit
if (!md.peptide_quantification_unit.isNull())
{
String s = "MTD\tpeptide-quantification_unit\t" + md.peptide_quantification_unit.toCellString();
sl.push_back(s);
}
// small_molecule-quantification_unit
if (!md.small_molecule_quantification_unit.isNull())
{
String s = "MTD\tsmall_molecule-quantification_unit\t" + md.small_molecule_quantification_unit.toCellString();
sl.push_back(s);
}
for (map<Size, MzTabMSRunMetaData>::const_iterator it = md.ms_run.begin(); it != md.ms_run.end(); ++it)
{
const MzTabMSRunMetaData & msmd = it->second;
if (!msmd.format.isNull())
{
String s = "MTD\tms_run[" + String(it->first) + "]-format\t" + msmd.format.toCellString();
sl.push_back(s);
}
if (!msmd.location.isNull())
{
String s = "MTD\tms_run[" + String(it->first) + "]-location\t" + msmd.location.toCellString();
sl.push_back(s);
}
if (!msmd.id_format.isNull())
{
String s = "MTD\tms_run[" + String(it->first) + "]-id_format\t" + msmd.id_format.toCellString();
sl.push_back(s);
}
if (!msmd.fragmentation_method.isNull())
{
String s = "MTD\tms_run[" + String(it->first) + "]-fragmentation_method\t" + msmd.fragmentation_method.toCellString();
sl.push_back(s);
}
}
// custom
for (map<Size, MzTabParameter>::const_iterator it = md.custom.begin(); it != md.custom.end(); ++it)
{
String s = "MTD\tcustom[" + String(it->first) + "]\t" + it->second.toCellString();
sl.push_back(s);
}
for (map<Size, MzTabSampleMetaData>::const_iterator it = md.sample.begin(); it != md.sample.end(); ++it)
{
for (map<Size, MzTabParameter>::const_iterator sit = it->second.species.begin(); sit != it->second.species.end(); ++sit)
{
String s = "MTD\tsample[" + String(it->first) + "]-species[" + String(sit->first) + "]\t" + sit->second.toCellString();
sl.push_back(s);
}
for (map<Size, MzTabParameter>::const_iterator sit = it->second.tissue.begin(); sit != it->second.tissue.end(); ++sit)
{
String s = "MTD\tsample[" + String(it->first) + "]-tissue[" + String(sit->first) + "]\t" + sit->second.toCellString();
sl.push_back(s);
}
for (map<Size, MzTabParameter>::const_iterator sit = it->second.cell_type.begin(); sit != it->second.cell_type.end(); ++sit)
{
String s = "MTD\tsample[" + String(it->first) + "]-cell_type[" + String(sit->first) + "]\t" + sit->second.toCellString();
sl.push_back(s);
}
for (map<Size, MzTabParameter>::const_iterator sit = it->second.disease.begin(); sit != it->second.disease.end(); ++sit)
{
String s = "MTD\tsample[" + String(it->first) + "]-disease[" + String(sit->first) + "]\t" + sit->second.toCellString();
sl.push_back(s);
}
for (map<Size, MzTabParameter>::const_iterator sit = it->second.custom.begin(); sit != it->second.custom.end(); ++sit)
{
String s = "MTD\tsample[" + String(it->first) + "]-custom[" + String(sit->first) + "]\t" + sit->second.toCellString();
sl.push_back(s);
}
if (!it->second.description.isNull())
{
String s = "MTD\tsample[" + String(it->first) + String("]-description\t") + it->second.description.toCellString();
sl.push_back(s);
}
}
for (map<Size, MzTabAssayMetaData>::const_iterator it = md.assay.begin(); it != md.assay.end(); ++it)
{
const MzTabAssayMetaData & amd = it->second;
if (!amd.quantification_reagent.isNull())
{
String s = "MTD\tassay[" + String(it->first) + "]-quantification_reagent\t" + amd.quantification_reagent.toCellString();
sl.push_back(s);
}
for (map<Size, MzTabModificationMetaData>::const_iterator mit = amd.quantification_mod.begin(); mit != amd.quantification_mod.end(); ++mit)
{
const MzTabModificationMetaData & mod = mit->second;
if (!mod.modification.isNull())
{
String s = "MTD\tassay[" + String(it->first) + String("]-quantification_mod[") + String(mit->first) + String("]\t") + mod.modification.toCellString();
sl.push_back(s);
}
if (!mod.site.isNull())
{
String s = "MTD\tassay[" + String(it->first) + String("]-quantification_mod[") + String(mit->first) + String("]-site\t") + mod.site.toCellString();
sl.push_back(s);
}
if (!mod.position.isNull())
{
String s = "MTD\tassay[" + String(it->first) + String("]-quantification_mod[") + String(mit->first) + String("]-position\t") + mod.position.toCellString();
sl.push_back(s);
}
}
if (!amd.sample_ref.isNull())
{
String s = "MTD\tassay[" + String(it->first) + String("]-sample_ref\t") + amd.sample_ref.toCellString();
sl.push_back(s);
}
if (!amd.ms_run_ref.empty())
{
String s = "MTD\tassay[" + String(it->first) + "]-ms_run_ref\t";
bool first(true);
for (auto const & a : amd.ms_run_ref)
{
if (!first) { s += ","; } else { first = false; }
s += "ms_run[" + String(a) + "]";
}
sl.push_back(s);
}
}
for (map<Size, MzTabStudyVariableMetaData>::const_iterator it = md.study_variable.begin(); it != md.study_variable.end(); ++it)
{
const MzTabStudyVariableMetaData & smd = it->second;
if (!smd.assay_refs.empty())
{
String s = "MTD\tstudy_variable[" + String(it->first) + "]-assay_refs\t";
bool first(true);
for (auto const & a : smd.assay_refs)
{
if (!first) { s += ","; } else { first = false; }
s += "assay[" + String(a) + "]";
}
sl.push_back(s);
}
if (!smd.sample_refs.empty())
{
String s = "MTD\tstudy_variable[" + String(it->first) + String("]-sample_refs\t");
bool first(true);
for (auto const & a : smd.sample_refs)
{
if (!first) { s += ","; } else { first = false; }
s += "sample[" + String(a) + "]";
}
sl.push_back(s);
}
if (!smd.description.isNull())
{
String s = "MTD\tstudy_variable[" + String(it->first) + String("]-description\t") + smd.description.toCellString();
sl.push_back(s);
}
}
for (map<Size, MzTabCVMetaData>::const_iterator it = md.cv.begin(); it != md.cv.end(); ++it)
{
const MzTabCVMetaData & mdcv = it->second;
if (!mdcv.label.isNull())
{
String s = "MTD\tcv[" + String(it->first) + String("]-label\t") + mdcv.label.toCellString();
sl.push_back(s);
}
if (!mdcv.full_name.isNull())
{
String s = "MTD\tcv[" + String(it->first) + String("]-full_name\t") + mdcv.full_name.toCellString();
sl.push_back(s);
}
if (!mdcv.version.isNull())
{
String s = "MTD\tcv[" + String(it->first) + String("]-version\t") + mdcv.version.toCellString();
sl.push_back(s);
}
if (!mdcv.url.isNull())
{
String s = "MTD\tcv[" + String(it->first) + String("]-url\t") + mdcv.url.toCellString();
sl.push_back(s);
}
}
// colunit-protein
for (Size i = 0; i != md.colunit_protein.size(); ++i)
{
String s = String("MTD\tcolunit-protein") + md.colunit_protein[i];
sl.push_back(s);
}
// colunit-peptide
for (Size i = 0; i != md.colunit_peptide.size(); ++i)
{
String s = String("MTD\tcolunit-peptide") + md.colunit_peptide[i];
sl.push_back(s);
}
// colunit-PSM
for (Size i = 0; i != md.colunit_psm.size(); ++i)
{
String s = String("MTD\tcolunit-PSM") + md.colunit_psm[i];
sl.push_back(s);
}
// colunit-small_molecule
for (Size i = 0; i != md.colunit_small_molecule.size(); ++i)
{
String s = String("MTD\tcolunit-small_molecule") + md.colunit_small_molecule[i];
sl.push_back(s);
}
}
String MzTabFile::generateMzTabProteinHeader_(
const MzTabProteinSectionRow& reference_row,
const Size n_best_search_engine_scores,
const std::vector<String>& optional_columns,
const MzTabMetaData& meta,
size_t& n_columns) const
{
Size n_search_engine_scores = reference_row.search_engine_score_ms_run.size();
StringList header;
header.push_back("PRH");
header.push_back("accession");
header.push_back("description");
header.push_back("taxid");
header.push_back("species");
header.push_back("database");
header.push_back("database_version");
header.push_back("search_engine");
for (Size i = 0; i != n_best_search_engine_scores; ++i)
{
header.push_back(String("best_search_engine_score[") + String(i + 1) + String("]"));
}
if (n_search_engine_scores != 0)
{
// get number of runs for the first search score type (should be the same for every score)
for (Size i = 0; i != reference_row.search_engine_score_ms_run.begin()->second.size(); ++i)
{
for (std::map<Size, std::map<Size, MzTabDouble> >::const_iterator search_it = reference_row.search_engine_score_ms_run.begin(); search_it != reference_row.search_engine_score_ms_run.end(); ++search_it)
{
header.push_back(String("search_engine_score[" + String(search_it->first) + "]_ms_run[") + String(i + 1) + String("]"));
}
}
}
if (store_protein_reliability_)
{
header.push_back("reliability");
}
for (std::map<Size, MzTabInteger>::const_iterator it = reference_row.num_psms_ms_run.begin(); it != reference_row.num_psms_ms_run.end(); ++it)
{
header.push_back(String("num_psms_ms_run[") + String(it->first) + String("]"));
}
for (std::map<Size, MzTabInteger>::const_iterator it = reference_row.num_peptides_distinct_ms_run.begin(); it != reference_row.num_peptides_distinct_ms_run.end(); ++it)
{
header.push_back(String("num_peptides_distinct_ms_run[") + String(it->first) + String("]"));
}
for (std::map<Size, MzTabInteger>::const_iterator it = reference_row.num_peptides_unique_ms_run.begin(); it != reference_row.num_peptides_unique_ms_run.end(); ++it)
{
header.push_back(String("num_peptides_unique_ms_run[") + String(it->first) + String("]"));
}
header.push_back("ambiguity_members");
header.push_back("modifications");
if (store_protein_uri_)
{
header.push_back("uri");
}
if (store_protein_goterms_)
{
header.push_back("go_terms");
}
header.push_back("protein_coverage");
for (const auto& a : meta.assay)
{
header.push_back(String("protein_abundance_assay[") + String(a.first) + String("]"));
}
for (const auto& s : meta.study_variable)
{
header.push_back(String("protein_abundance_study_variable[") + String(s.first) + String("]"));
header.push_back(String("protein_abundance_stdev_study_variable[") + String(s.first) + String("]"));
header.push_back(String("protein_abundance_std_error_study_variable[") + String(s.first) + String("]"));
}
std::copy(optional_columns.begin(), optional_columns.end(), std::back_inserter(header));
n_columns = header.size();
return ListUtils::concatenate(header, "\t");
}
String MzTabFile::generateMzTabSectionRow_(
const MzTabProteinSectionRow& row,
const vector<String>& optional_columns,
const MzTabMetaData& meta,
size_t& n_columns) const
{
StringList s;
s.push_back("PRT");
s.push_back(row.accession.toCellString());
s.push_back(row.description.toCellString());
s.push_back(row.taxid.toCellString());
s.push_back(row.species.toCellString());
s.push_back(row.database.toCellString());
s.push_back(row.database_version.toCellString());
s.push_back(row.search_engine.toCellString());
for (map<Size, MzTabDouble>::const_iterator it = row.best_search_engine_score.begin(); it != row.best_search_engine_score.end(); ++it)
{
s.push_back(it->second.toCellString());
}
for (std::map<Size, std::map<Size, MzTabDouble> >::const_iterator it = row.search_engine_score_ms_run.begin(); it != row.search_engine_score_ms_run.end(); ++it)
{
for (std::map<Size, MzTabDouble>::const_iterator sit = it->second.begin(); sit != it->second.end(); ++sit)
{
s.push_back(sit->second.toCellString());
}
}
if (store_protein_reliability_)
{
s.push_back(row.reliability.toCellString());
}
for (std::map<Size, MzTabInteger>::const_iterator it = row.num_psms_ms_run.begin(); it != row.num_psms_ms_run.end(); ++it)
{
s.push_back(it->second.toCellString());
}
for (std::map<Size, MzTabInteger>::const_iterator it = row.num_peptides_distinct_ms_run.begin(); it != row.num_peptides_distinct_ms_run.end(); ++it)
{
s.push_back(it->second.toCellString());
}
for (std::map<Size, MzTabInteger>::const_iterator it = row.num_peptides_unique_ms_run.begin(); it != row.num_peptides_unique_ms_run.end(); ++it)
{
s.push_back(it->second.toCellString());
}
s.push_back(row.ambiguity_members.toCellString());
s.push_back(row.modifications.toCellString());
if (store_protein_uri_)
{
s.push_back(row.uri.toCellString());
}
if (store_protein_goterms_)
{
s.push_back(row.go_terms.toCellString());
}
s.push_back(row.coverage.toCellString());
// Quantification columns:
// Assays
for (const auto& kv : meta.assay)
{
const auto& k = kv.first;
const auto& ity = row.protein_abundance_assay.find(k);
// make sure that everything is set for this SV
if (ity != row.protein_abundance_assay.end())
{
s.emplace_back(ity->second.toCellString());
}
else
{
// putting "null" directly would be a little faster, but with this we can keep consistency
s.emplace_back(MzTabString().toCellString());
}
}
// Study variables
// go over all study variables that should be present and fill with either values
// or uninitialized MzTabDouble()
for (const auto& kv : meta.study_variable)
{
const auto& k = kv.first;
const auto& ity = row.protein_abundance_study_variable.find(k);
const auto& sd = row.protein_abundance_stdev_study_variable.find(k);
const auto& err = row.protein_abundance_std_error_study_variable.find(k);
// make sure that everything is set for this SV
if (ity != row.protein_abundance_study_variable.end() &&
sd != row.protein_abundance_stdev_study_variable.end() &&
err != row.protein_abundance_std_error_study_variable.end())
{
s.emplace_back(ity->second.toCellString());
s.emplace_back(sd->second.toCellString());
s.emplace_back(err->second.toCellString());
}
else
{
// putting "null" directly would be a little faster, but with this we can keep consistency
s.emplace_back(MzTabString().toCellString());
s.emplace_back(MzTabString().toCellString());
s.emplace_back(MzTabString().toCellString());
}
}
addOptionalColumnsToSectionRow_(optional_columns, row.opt_, s);
n_columns = s.size();
return ListUtils::concatenate(s, "\t");
}
String MzTabFile::generateMzTabPeptideHeader_(Size search_ms_runs, Size n_best_search_engine_scores, Size n_search_engine_scores, Size assays, Size study_variables, const vector<String>& optional_columns,
size_t& n_columns) const
{
StringList header;
header.push_back("PEH");
header.push_back("sequence");
header.push_back("accession");
header.push_back("unique");
header.push_back("database");
header.push_back("database_version");
header.push_back("search_engine");
for (Size i = 0; i != n_best_search_engine_scores; ++i)
{
header.push_back(String("best_search_engine_score[") + String(i + 1) + String("]"));
}
for (Size i = 0; i != search_ms_runs; ++i)
{
for (Size j = 0; j != n_search_engine_scores; ++j)
{
header.push_back(String("search_engine_score[" + String(j + 1) + "]_ms_run[") + String(i + 1) + String("]"));
}
}
if (store_peptide_reliability_)
{
header.push_back("reliability");
}
header.push_back("modifications");
header.push_back("retention_time");
header.push_back("retention_time_window");
header.push_back("charge");
header.push_back("mass_to_charge");
if (store_peptide_uri_)
{
header.push_back("uri");
}
header.push_back("spectra_ref");
for (Size i = 0; i != assays; ++i)
{
header.push_back(String("peptide_abundance_assay[") + String(i + 1) + String("]"));
}
for (Size i = 0; i != study_variables; ++i)
{
header.push_back(String("peptide_abundance_study_variable[") + String(i + 1) + String("]"));
header.push_back(String("peptide_abundance_stdev_study_variable[") + String(i + 1) + String("]"));
header.push_back(String("peptide_abundance_std_error_study_variable[") + String(i + 1) + String("]"));
}
std::copy(optional_columns.begin(), optional_columns.end(), std::back_inserter(header));
n_columns = header.size();
return ListUtils::concatenate(header, "\t");
}
String MzTabFile::generateMzTabPSMHeader_(Size n_search_engine_scores, const vector<String>& optional_columns, size_t& n_columns) const
{
StringList header;
header.push_back("PSH");
header.push_back("sequence");
header.push_back("PSM_ID");
header.push_back("accession");
header.push_back("unique");
header.push_back("database");
header.push_back("database_version");
header.push_back("search_engine");
for (Size i = 0; i != n_search_engine_scores; ++i)
{
header.push_back("search_engine_score[" + String(i + 1) + "]");
}
if (store_psm_reliability_)
{
header.push_back("reliability");
}
header.push_back("modifications");
header.push_back("retention_time");
header.push_back("charge");
header.push_back("exp_mass_to_charge");
header.push_back("calc_mass_to_charge");
if (store_psm_uri_)
{
header.push_back("uri");
}
header.push_back("spectra_ref");
header.push_back("pre");
header.push_back("post");
header.push_back("start");
header.push_back("end");
std::copy(optional_columns.begin(), optional_columns.end(), std::back_inserter(header));
n_columns = header.size();
return ListUtils::concatenate(header, "\t");
}
String MzTabFile::generateMzTabSectionRow_(const MzTabPeptideSectionRow& row, const vector<String>& optional_columns,
const MzTabMetaData& /*meta*/, size_t& n_columns) const
{
StringList s;
s.push_back("PEP");
s.push_back(row.sequence.toCellString());
s.push_back(row.accession.toCellString());
s.push_back(row.unique.toCellString());
s.push_back(row.database.toCellString());
s.push_back(row.database_version.toCellString());
s.push_back(row.search_engine.toCellString());
// best score(s)
for (auto const & bs : row.best_search_engine_score) { s.push_back(bs.second.toCellString()); }
// run-level best score(s)
for (auto const & bsrun : row.search_engine_score_ms_run)
{
for (auto const & bs : bsrun.second) { s.push_back(bs.second.toCellString()); }
}
if (store_peptide_reliability_)
{
s.push_back(row.reliability.toCellString());
}
s.push_back(row.modifications.toCellString());
s.push_back(row.retention_time.toCellString());
s.push_back(row.retention_time_window.toCellString());
s.push_back(row.charge.toCellString());
s.push_back(row.mass_to_charge.toCellString());
if (store_peptide_uri_)
{
s.push_back(row.uri.toCellString());
}
s.push_back(row.spectra_ref.toCellString());
// quantification columns
for (std::map<Size, MzTabDouble>::const_iterator it = row.peptide_abundance_assay.begin(); it != row.peptide_abundance_assay.end(); ++it)
{
s.push_back(it->second.toCellString());
}
std::map<Size, MzTabDouble>::const_iterator sv_it = row.peptide_abundance_study_variable.begin();
std::map<Size, MzTabDouble>::const_iterator sv_stdev_it = row.peptide_abundance_stdev_study_variable.begin();
std::map<Size, MzTabDouble>::const_iterator sv_error_it = row.peptide_abundance_std_error_study_variable.begin();
for (;
sv_it != row.peptide_abundance_study_variable.end()
&& sv_stdev_it != row.peptide_abundance_stdev_study_variable.end()
&& sv_error_it != row.peptide_abundance_std_error_study_variable.end();
++sv_it, ++sv_stdev_it, ++sv_error_it)
{
s.push_back(sv_it->second.toCellString());
s.push_back(sv_stdev_it->second.toCellString());
s.push_back(sv_error_it->second.toCellString());
}
addOptionalColumnsToSectionRow_(optional_columns, row.opt_, s);
n_columns = s.size();
return ListUtils::concatenate(s, "\t");
}
String MzTabFile::generateMzTabSectionRow_(const MzTabPSMSectionRow& row, const vector<String>& optional_columns,
const MzTabMetaData& /*meta*/, size_t& n_columns) const
{
StringList s;
s.push_back("PSM");
s.push_back(row.sequence.toCellString());
s.push_back(row.PSM_ID.toCellString());
s.push_back(row.accession.toCellString());
s.push_back(row.unique.toCellString());
s.push_back(row.database.toCellString());
s.push_back(row.database_version.toCellString());
s.push_back(row.search_engine.toCellString());
if (row.search_engine_score.empty())
{ // workaround for PeptideIDs without hits (QC export)
s.push_back("null");
}
else
{
for (map<Size, MzTabDouble>::const_iterator it = row.search_engine_score.begin(); it != row.search_engine_score.end(); ++it)
{
s.push_back(it->second.toCellString());
}
}
if (store_psm_reliability_)
{
s.push_back(row.reliability.toCellString());
}
s.push_back(row.modifications.toCellString());
s.push_back(row.retention_time.toCellString());
s.push_back(row.charge.toCellString());
s.push_back(row.exp_mass_to_charge.toCellString());
s.push_back(row.calc_mass_to_charge.toCellString());
if (store_psm_uri_)
{
s.push_back(row.uri.toCellString());
}
s.push_back(row.spectra_ref.toCellString());
s.push_back(row.pre.toCellString());
s.push_back(row.post.toCellString());
s.push_back(row.start.toCellString());
s.push_back(row.end.toCellString());
addOptionalColumnsToSectionRow_(optional_columns, row.opt_, s);
n_columns = s.size();
return ListUtils::concatenate(s, "\t");
}
String MzTabFile::generateMzTabSmallMoleculeHeader_(Size ms_runs, Size n_best_search_engine_scores, Size n_search_engine_scores, Size assays, Size study_variables, const vector<String>& optional_smallmolecule_columns, size_t& n_columns) const
{
StringList header;
header.push_back("SMH");
header.push_back("identifier");
header.push_back("chemical_formula");
header.push_back("smiles");
header.push_back("inchi_key");
header.push_back("description");
header.push_back("exp_mass_to_charge");
header.push_back("calc_mass_to_charge");
header.push_back("charge");
header.push_back("retention_time");
header.push_back("taxid");
header.push_back("species");
header.push_back("database");
header.push_back("database_version");
if (store_smallmolecule_reliability_)
{
header.push_back("reliability");
}
if (store_smallmolecule_uri_)
{
header.push_back("uri");
}
header.push_back("spectra_ref");
header.push_back("search_engine");
for (Size i = 0; i != n_best_search_engine_scores; ++i)
{
header.push_back(String("best_search_engine_score[") + String(i + 1) + String("]"));
}
for (Size i = 0; i != ms_runs; ++i)
{
for (Size j = 0; j != n_search_engine_scores; ++j)
{
header.push_back(String("search_engine_score[" + String(j + 1) + "]_ms_run[") + String(i + 1) + String("]"));
}
}
header.push_back("modifications");
for (Size i = 0; i != assays; ++i)
{
header.push_back(String("smallmolecule_abundance_assay[") + String(i + 1) + String("]"));
}
for (Size i = 0; i != study_variables; ++i)
{
header.push_back(String("smallmolecule_abundance_study_variable[") + String(i + 1) + String("]"));
header.push_back(String("smallmolecule_abundance_stdev_study_variable[") + String(i + 1) + String("]"));
header.push_back(String("smallmolecule_abundance_std_error_study_variable[") + String(i + 1) + String("]"));
}
// copy optional column names to header
std::copy(optional_smallmolecule_columns.begin(), optional_smallmolecule_columns.end(), std::back_inserter(header));
n_columns = header.size();
return ListUtils::concatenate(header, "\t");
}
String MzTabFile::generateMzTabSectionRow_(
const MzTabSmallMoleculeSectionRow& row,
const std::vector<String>& optional_columns,
const MzTabMetaData& /*meta*/, size_t& n_columns) const
{
StringList s;
s.push_back("SML");
s.push_back(row.identifier.toCellString());
s.push_back(row.chemical_formula.toCellString());
s.push_back(row.smiles.toCellString());
s.push_back(row.inchi_key.toCellString());
s.push_back(row.description.toCellString());
s.push_back(row.exp_mass_to_charge.toCellString());
s.push_back(row.calc_mass_to_charge.toCellString());
s.push_back(row.charge.toCellString());
s.push_back(row.retention_time.toCellString());
s.push_back(row.taxid.toCellString());
s.push_back(row.species.toCellString());
s.push_back(row.database.toCellString());
s.push_back(row.database_version.toCellString());
if (store_smallmolecule_reliability_)
{
s.push_back(row.reliability.toCellString());
}
if (store_smallmolecule_uri_)
{
s.push_back(row.uri.toCellString());
}
s.push_back(row.spectra_ref.toCellString());
s.push_back(row.search_engine.toCellString());
for (map<Size, MzTabDouble>::const_iterator it = row.best_search_engine_score.begin(); it != row.best_search_engine_score.end(); ++it)
{
s.push_back(it->second.toCellString());
}
for (auto it = row.search_engine_score_ms_run.begin(); it != row.search_engine_score_ms_run.end(); ++it)
{
for (auto sit = it->second.begin(); sit != it->second.end(); ++sit)
{
s.push_back(sit->second.toCellString());
}
}
s.push_back(row.modifications.toCellString());
// quantification columns
std::map<Size, MzTabDouble>::const_iterator sv_it = row.smallmolecule_abundance_study_variable.begin();
std::map<Size, MzTabDouble>::const_iterator sv_stdev_it = row.smallmolecule_abundance_stdev_study_variable.begin();
std::map<Size, MzTabDouble>::const_iterator sv_error_it = row.smallmolecule_abundance_std_error_study_variable.begin();
for (;
sv_it != row.smallmolecule_abundance_study_variable.end()
&& sv_stdev_it != row.smallmolecule_abundance_stdev_study_variable.end()
&& sv_error_it != row.smallmolecule_abundance_std_error_study_variable.end();
++sv_it, ++sv_stdev_it, ++sv_error_it)
{
s.push_back(sv_it->second.toCellString());
s.push_back(sv_stdev_it->second.toCellString());
s.push_back(sv_error_it->second.toCellString());
}
addOptionalColumnsToSectionRow_(optional_columns, row.opt_, s);
n_columns = s.size();
return ListUtils::concatenate(s, "\t");
}
String MzTabFile::generateMzTabNucleicAcidHeader_(Size search_ms_runs, Size n_best_search_engine_scores, Size n_search_engine_scores, const std::vector<String>& optional_columns, size_t& n_columns) const
{
StringList header;
header.push_back("NUH");
header.push_back("accession");
header.push_back("description");
header.push_back("taxid");
header.push_back("species");
header.push_back("database");
header.push_back("database_version");
header.push_back("search_engine");
for (Size i = 0; i != n_best_search_engine_scores; ++i)
{
header.push_back(String("best_search_engine_score[") + String(i + 1) + String("]"));
}
for (Size i = 0; i != search_ms_runs; ++i)
{
for (Size j = 0; j != n_search_engine_scores; ++j)
{
header.push_back(String("search_engine_score[" + String(j + 1) + "]_ms_run[") + String(i + 1) + String("]"));
}
}
if (store_nucleic_acid_reliability_)
{
header.push_back("reliability");
}
for (Size i = 0; i != search_ms_runs; ++i)
{
header.push_back(String("num_osms_ms_run[") + String(i) + String("]"));
}
for (Size i = 0; i != search_ms_runs; ++i)
{
header.push_back(String("num_oligos_distinct_ms_run[") + String(i) + String("]"));
}
for (Size i = 0; i != search_ms_runs; ++i)
{
header.push_back(String("num_oligos_unique_ms_run[") + String(i) + String("]"));
}
header.push_back("ambiguity_members");
header.push_back("modifications");
if (store_nucleic_acid_uri_)
{
header.push_back("uri");
}
if (store_nucleic_acid_goterms_)
{
header.push_back("go_terms");
}
header.push_back("sequence_coverage");
std::copy(optional_columns.begin(), optional_columns.end(), std::back_inserter(header));
n_columns = header.size();
return ListUtils::concatenate(header, "\t");
}
String MzTabFile::generateMzTabSectionRow_(
const MzTabNucleicAcidSectionRow& row,
const vector<String>& optional_columns,
const MzTabMetaData& /*meta*/, size_t& n_columns) const
{
StringList s;
s.push_back("NUC");
s.push_back(row.accession.toCellString());
s.push_back(row.description.toCellString());
s.push_back(row.taxid.toCellString());
s.push_back(row.species.toCellString());
s.push_back(row.database.toCellString());
s.push_back(row.database_version.toCellString());
s.push_back(row.search_engine.toCellString());
for (map<Size, MzTabDouble>::const_iterator it = row.best_search_engine_score.begin(); it != row.best_search_engine_score.end(); ++it)
{
s.push_back(it->second.toCellString());
}
for (std::map<Size, std::map<Size, MzTabDouble> >::const_iterator it = row.search_engine_score_ms_run.begin(); it != row.search_engine_score_ms_run.end(); ++it)
{
for (std::map<Size, MzTabDouble>::const_iterator sit = it->second.begin(); sit != it->second.end(); ++sit)
{
s.push_back(sit->second.toCellString());
}
}
if (store_nucleic_acid_reliability_)
{
s.push_back(row.reliability.toCellString());
}
for (std::map<Size, MzTabInteger>::const_iterator it = row.num_osms_ms_run.begin(); it != row.num_osms_ms_run.end(); ++it)
{
s.push_back(it->second.toCellString());
}
for (std::map<Size, MzTabInteger>::const_iterator it = row.num_oligos_distinct_ms_run.begin(); it != row.num_oligos_distinct_ms_run.end(); ++it)
{
s.push_back(it->second.toCellString());
}
for (std::map<Size, MzTabInteger>::const_iterator it = row.num_oligos_unique_ms_run.begin(); it != row.num_oligos_unique_ms_run.end(); ++it)
{
s.push_back(it->second.toCellString());
}
s.push_back(row.ambiguity_members.toCellString());
s.push_back(row.modifications.toCellString());
if (store_nucleic_acid_uri_)
{
s.push_back(row.uri.toCellString());
}
if (store_nucleic_acid_goterms_)
{
s.push_back(row.go_terms.toCellString());
}
s.push_back(row.coverage.toCellString());
addOptionalColumnsToSectionRow_(optional_columns, row.opt_, s);
n_columns = s.size();
return ListUtils::concatenate(s, "\t");
}
String MzTabFile::generateMzTabOligonucleotideHeader_(Size search_ms_runs, Size n_best_search_engine_scores, Size n_search_engine_scores, const vector<String>& optional_columns, size_t& n_columns) const
{
StringList header;
header.push_back("OLH");
header.push_back("sequence");
header.push_back("accession");
header.push_back("unique");
header.push_back("search_engine");
for (Size i = 0; i != n_best_search_engine_scores; ++i)
{
header.push_back(String("best_search_engine_score[") + String(i + 1) + String("]"));
}
for (Size i = 0; i != search_ms_runs; ++i)
{
for (Size j = 0; j != n_search_engine_scores; ++j)
{
header.push_back(String("search_engine_score[" + String(j + 1) + "]_ms_run[") + String(i + 1) + String("]"));
}
}
if (store_oligonucleotide_reliability_)
{
header.push_back("reliability");
}
header.push_back("modifications");
header.push_back("retention_time");
header.push_back("retention_time_window");
if (store_oligonucleotide_uri_)
{
header.push_back("uri");
}
header.push_back("pre");
header.push_back("post");
header.push_back("start");
header.push_back("end");
std::copy(optional_columns.begin(), optional_columns.end(), std::back_inserter(header));
n_columns = header.size();
return ListUtils::concatenate(header, "\t");
}
String MzTabFile::generateMzTabSectionRow_(
const MzTabOligonucleotideSectionRow& row,
const vector<String>& optional_columns,
const MzTabMetaData& /*meta*/, size_t& n_columns) const
{
StringList s;
s.push_back("OLI");
s.push_back(row.sequence.toCellString());
s.push_back(row.accession.toCellString());
s.push_back(row.unique.toCellString());
s.push_back(row.search_engine.toCellString());
for (map<Size, MzTabDouble>::const_iterator it = row.best_search_engine_score.begin(); it != row.best_search_engine_score.end(); ++it)
{
s.push_back(it->second.toCellString());
}
for (map<Size, map<Size, MzTabDouble> >::const_iterator it = row.search_engine_score_ms_run.begin(); it != row.search_engine_score_ms_run.end(); ++it)
{
for (map<Size, MzTabDouble>::const_iterator sit = it->second.begin(); sit != it->second.end(); ++sit)
{
s.push_back(sit->second.toCellString());
}
}
if (store_oligonucleotide_reliability_)
{
s.push_back(row.reliability.toCellString());
}
s.push_back(row.modifications.toCellString());
s.push_back(row.retention_time.toCellString());
s.push_back(row.retention_time_window.toCellString());
if (store_oligonucleotide_uri_)
{
s.push_back(row.uri.toCellString());
}
s.push_back(row.pre.toCellString());
s.push_back(row.post.toCellString());
s.push_back(row.start.toCellString());
s.push_back(row.end.toCellString());
addOptionalColumnsToSectionRow_(optional_columns, row.opt_, s);
n_columns = s.size();
return ListUtils::concatenate(s, "\t");
}
String MzTabFile::generateMzTabOSMHeader_(Size n_search_engine_scores, const vector<String>& optional_columns, size_t& n_columns) const
{
StringList header;
header.push_back("OSH");
header.push_back("sequence");
header.push_back("search_engine");
for (Size i = 0; i != n_search_engine_scores; ++i)
{
header.push_back("search_engine_score[" + String(i + 1) + "]");
}
if (store_osm_reliability_)
{
header.push_back("reliability");
}
header.push_back("modifications");
header.push_back("retention_time");
header.push_back("charge");
header.push_back("exp_mass_to_charge");
header.push_back("calc_mass_to_charge");
if (store_osm_uri_)
{
header.push_back("uri");
}
header.push_back("spectra_ref");
std::copy(optional_columns.begin(), optional_columns.end(), std::back_inserter(header));
n_columns = header.size();
return ListUtils::concatenate(header, "\t");
}
String MzTabFile::generateMzTabSectionRow_(
const MzTabOSMSectionRow& row,
const vector<String>& optional_columns,
const MzTabMetaData& /*meta*/, size_t& n_columns) const
{
StringList s;
s.push_back("OSM");
s.push_back(row.sequence.toCellString());
s.push_back(row.search_engine.toCellString());
for (map<Size, MzTabDouble>::const_iterator it = row.search_engine_score.begin(); it != row.search_engine_score.end(); ++it)
{
s.push_back(it->second.toCellString());
}
if (store_osm_reliability_)
{
s.push_back(row.reliability.toCellString());
}
s.push_back(row.modifications.toCellString());
s.push_back(row.retention_time.toCellString());
s.push_back(row.charge.toCellString());
s.push_back(row.exp_mass_to_charge.toCellString());
s.push_back(row.calc_mass_to_charge.toCellString());
if (store_osm_uri_)
{
s.push_back(row.uri.toCellString());
}
s.push_back(row.spectra_ref.toCellString());
addOptionalColumnsToSectionRow_(optional_columns, row.opt_, s);
n_columns = s.size();
return ListUtils::concatenate(s, "\t");
}
void MzTabFile::addOptionalColumnsToSectionRow_(const vector<String>& column_names, const vector<MzTabOptionalColumnEntry>& column_entries, StringList& output)
{
for (vector<String>::const_iterator it = column_names.begin(); it != column_names.end(); ++it)
{
bool found = false;
for (Size i = 0; i != column_entries.size(); ++i)
{
if (column_entries[i].first == *it)
{
output.push_back(column_entries[i].second.toCellString());
found = true;
break;
}
}
if (!found)
{
output.push_back(MzTabString("null").toCellString());
}
}
}
// stream IDs to file
void MzTabFile::store(
const String& filename,
const std::vector<ProteinIdentification>& protein_identifications,
const PeptideIdentificationList& peptide_identifications,
bool first_run_inference_only,
bool export_empty_pep_ids,
bool export_all_psms,
const String& title)
{
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) + "'");
}
vector<const PeptideIdentification*> pep_ids_ptr;
pep_ids_ptr.reserve(peptide_identifications.size());
for (const PeptideIdentification& pi : peptide_identifications) { pep_ids_ptr.push_back(&pi); }
vector<const ProteinIdentification*> prot_ids_ptr;
prot_ids_ptr.reserve(protein_identifications.size());
for (const ProteinIdentification& pi : protein_identifications) { prot_ids_ptr.push_back(&pi); }
ofstream tab_file;
tab_file.open(filename, ios::out | ios::trunc);
MzTab::IDMzTabStream s(
prot_ids_ptr,
pep_ids_ptr,
filename,
first_run_inference_only,
export_empty_pep_ids,
export_all_psms,
title);
// generate full meta data section and write to file
MzTabMetaData meta_data = s.getMetaData();
{
StringList out;
generateMzTabMetaDataSection_(meta_data, out);
for (const String & line : out) { tab_file << line << "\n"; }
}
Size n_best_search_engine_score = meta_data.protein_search_engine_score.size();
{
MzTabProteinSectionRow row;
bool first = true;
size_t n_header_columns = 0;
while (s.nextPRTRow(row))
{
if (first)
{ // add header
tab_file << "\n" << generateMzTabProteinHeader_(
row,
n_best_search_engine_score,
s.getProteinOptionalColumnNames(),
meta_data,
n_header_columns) + "\n";
first = false;
}
size_t n_section_columns = 0;
tab_file << generateMzTabSectionRow_(row, s.getProteinOptionalColumnNames(), meta_data, n_section_columns) + "\n";
if (n_header_columns != n_section_columns) throw Exception::Postcondition(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Protein header and content differs in columns. Please report this bug to the OpenMS developers.");
}
}
Size n_search_engine_scores = meta_data.psm_search_engine_score.size();
if (n_search_engine_scores == 0)
{
OPENMS_LOG_WARN << "No search engine scores given. Please check your input data." << endl;
}
{
MzTabPSMSectionRow row;
bool first = true;
size_t n_header_columns = 0;
while (s.nextPSMRow(row))
{
// TODO better return a State enum instead of relying on some uninitialized
// parts of a row.. at least it is a mandatory field and therefore it would not make
// sense writing that row anyway
if (!row.sequence.isNull())
{
if (first)
{ // add header
tab_file << "\n" << generateMzTabPSMHeader_(n_search_engine_scores, s.getPSMOptionalColumnNames(), n_header_columns) + "\n";
first = false;
}
size_t n_section_columns = 0;
tab_file << generateMzTabSectionRow_(row, s.getPSMOptionalColumnNames(), meta_data, n_section_columns) + "\n";
if (n_header_columns != n_section_columns) throw Exception::Postcondition(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "PSM header and content differs in columns. Please report this bug to the OpenMS developers.");
}
}
}
tab_file.close();
}
void MzTabFile::store(
const String& filename,
const ConsensusMap& cmap,
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
{
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) + "'");
}
ofstream tab_file;
tab_file.open(filename, ios::out | ios::trunc);
MzTab::CMMzTabStream s(
cmap,
filename,
first_run_inference_only,
export_unidentified_features,
export_unassigned_ids,
export_subfeatures,
export_empty_pep_ids,
export_all_psms,
"ConsensusMap export from OpenMS");
// generate full meta data section and write to file
MzTabMetaData meta_data = s.getMetaData();
{
StringList out;
generateMzTabMetaDataSection_(meta_data, out);
for (const String & line : out) { tab_file << line << "\n"; }
}
Size n_best_search_engine_score = meta_data.protein_search_engine_score.size();
// TODO: we currently only store one search engine score per PSM so we need to limit the number to the main score
n_best_search_engine_score = std::min(n_best_search_engine_score, Size(1));
{
MzTabProteinSectionRow row;
bool first = true;
size_t n_header_columns = 0;
while (s.nextPRTRow(row))
{
if (first)
{ // add header
tab_file << "\n" << generateMzTabProteinHeader_(
row,
n_best_search_engine_score,
s.getProteinOptionalColumnNames(),
meta_data,
n_header_columns) + "\n";
first = false;
}
size_t n_section_columns = 0;
tab_file << generateMzTabSectionRow_(row, s.getProteinOptionalColumnNames(), meta_data, n_section_columns) + "\n";
if (n_header_columns != n_section_columns) throw Exception::Postcondition(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Protein header and content differs in columns. Please report this bug to the OpenMS developers.");
}
}
Size assays(0);
Size study_variables(0);
{
MzTabPeptideSectionRow row;
bool first = true;
size_t n_header_columns = 0;
while (s.nextPEPRow(row))
{
if (first)
{
assays = row.peptide_abundance_assay.size();
study_variables = row.peptide_abundance_study_variable.size();
Size n_search_engine_score = row.search_engine_score_ms_run.size(); // scores to runs
Size search_ms_runs = n_search_engine_score != 0 ? row.search_engine_score_ms_run.at(1).size() : 0; // take number of searched MS runs from first score. TODO: handle this more generic
OPENMS_LOG_DEBUG << "Exporting assays: " << assays << endl;
OPENMS_LOG_DEBUG << "Exporting study variables: " << study_variables << endl;
OPENMS_LOG_DEBUG << "Exporting search engines scores: " << n_search_engine_score << endl;
Size n_best_search_engine_score = row.best_search_engine_score.size();
tab_file << "\n" << generateMzTabPeptideHeader_(search_ms_runs, n_best_search_engine_score, n_search_engine_score, assays, study_variables, s.getPeptideOptionalColumnNames(), n_header_columns) + "\n";
first = false;
}
size_t n_section_columns = 0;
tab_file << generateMzTabSectionRow_(row, s.getPeptideOptionalColumnNames(), meta_data, n_section_columns) + "\n";
if (n_header_columns != n_section_columns)
{
OPENMS_LOG_ERROR << "Number of columns in header/section: " << n_header_columns << "/" << n_section_columns << endl;
throw Exception::Postcondition(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Peptide header and content differs in columns. Please report this bug to the OpenMS developers.");
}
}
}
Size n_search_engine_scores = meta_data.psm_search_engine_score.size();
if (n_search_engine_scores == 0)
{
OPENMS_LOG_WARN << "No search engine scores given. Please check your input data." << endl;
}
{
MzTabPSMSectionRow row;
bool first = true;
// TODO: we currently only store one search engine score per PSM so we need to limit the number to the main score
n_search_engine_scores = 1;
size_t n_header_columns = 0;
while (s.nextPSMRow(row))
{
// TODO better return a State enum instead of relying on some uninitialized
// parts of a row.. at least it is a mandatory field and therefore it would not make
// sense writing that row anyway
if (!row.sequence.isNull())
{
if (first)
{ // add header
tab_file << "\n" << generateMzTabPSMHeader_(n_search_engine_scores, s.getPSMOptionalColumnNames(), n_header_columns) + "\n";
first = false;
}
size_t n_section_columns = 0;
tab_file << generateMzTabSectionRow_(row, s.getPSMOptionalColumnNames(), meta_data, n_section_columns) + "\n";
if (n_header_columns != n_section_columns) throw Exception::Postcondition(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "PSM header and content differs in columns. Please report this bug to the OpenMS developers.");
}
}
}
tab_file.close();
}
void MzTabFile::store(const String& filename, const MzTab& mz_tab) const
{
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;
generateMzTabMetaDataSection_(mz_tab.getMetaData(), out);
bool complete = (mz_tab.getMetaData().mz_tab_mode.toCellString() == "Complete");
Size ms_runs = mz_tab.getMetaData().ms_run.size();
const MzTabProteinSectionRows& protein_section = mz_tab.getProteinSectionRows();
const MzTabPeptideSectionRows& peptide_section = mz_tab.getPeptideSectionRows();
const MzTabPSMSectionRows& psm_section = mz_tab.getPSMSectionRows();
const MzTabSmallMoleculeSectionRows& smallmolecule_section = mz_tab.getSmallMoleculeSectionRows();
if (!protein_section.empty())
{
Size n_best_search_engine_score = mz_tab.getMetaData().protein_search_engine_score.size();
// add header
// use the first row as a reference row to get the optional cols from meta values
out.push_back("");
size_t n_header_columns = 0;
out.push_back(generateMzTabProteinHeader_(protein_section[0],
n_best_search_engine_score,
mz_tab.getProteinOptionalColumnNames(),
mz_tab.getMetaData(),
n_header_columns));
// add section content
generateMzTabSection_(protein_section, mz_tab.getProteinOptionalColumnNames(), mz_tab.getMetaData(), out, n_header_columns);
}
if (!peptide_section.empty())
{
Size assays = peptide_section[0].peptide_abundance_assay.size();
Size study_variables = peptide_section[0].peptide_abundance_study_variable.size();
Size search_ms_runs = 0;
if (complete)
{
// all ms_runs mandatory
search_ms_runs = ms_runs;
}
else // only report all scores if user provided at least one
{
const MzTabPeptideSectionRows& psr = mz_tab.getPeptideSectionRows();
bool has_ms_run_level_scores = false;
for (Size i = 0; i != psr.size(); ++i)
{
if (!psr[i].search_engine_score_ms_run.empty())
{
has_ms_run_level_scores = true;
}
}
if (has_ms_run_level_scores) { search_ms_runs = ms_runs; }
}
Size n_search_engine_score = peptide_section[0].search_engine_score_ms_run.size();
Size n_best_search_engine_score = peptide_section[0].best_search_engine_score.size();
out.push_back("");
size_t n_header_columns = 0;
out.push_back(generateMzTabPeptideHeader_(search_ms_runs, n_best_search_engine_score, n_search_engine_score, assays, study_variables, mz_tab.getPeptideOptionalColumnNames(), n_header_columns));
generateMzTabSection_(mz_tab.getPeptideSectionRows(), mz_tab.getPeptideOptionalColumnNames(), mz_tab.getMetaData(), out, n_header_columns);
}
if (!psm_section.empty())
{
//Size n_search_engine_scores = mz_tab.getMetaData().psm_search_engine_score.size();
//TODO since we currently only support getting the main score for psms, maximally reserve one column
Size n_search_engine_scores = std::min(mz_tab.getMetaData().psm_search_engine_score.size(), Size(1));
if (n_search_engine_scores == 0)
{
// TODO warn
}
out.push_back("");
size_t n_header_columns = 0;
out.push_back(generateMzTabPSMHeader_(n_search_engine_scores, mz_tab.getPSMOptionalColumnNames(), n_header_columns));
generateMzTabSection_(mz_tab.getPSMSectionRows(), mz_tab.getPSMOptionalColumnNames(), mz_tab.getMetaData(), out, n_header_columns);
}
if (!smallmolecule_section.empty())
{
Size assays = smallmolecule_section[0].smallmolecule_abundance_assay.size();
Size study_variables = smallmolecule_section[0].smallmolecule_abundance_study_variable.size();
Size n_search_engine_score = smallmolecule_section[0].search_engine_score_ms_run.size();
Size n_best_search_engine_score = mz_tab.getMetaData().smallmolecule_search_engine_score.size();
out.push_back("");
size_t n_header_columns = 0;
out.push_back(generateMzTabSmallMoleculeHeader_(ms_runs, n_best_search_engine_score, n_search_engine_score, assays, study_variables, mz_tab.getSmallMoleculeOptionalColumnNames(), n_header_columns));
generateMzTabSection_(smallmolecule_section, mz_tab.getSmallMoleculeOptionalColumnNames(), mz_tab.getMetaData(), out, n_header_columns);
}
const MzTabNucleicAcidSectionRows& nucleic_acid_section = mz_tab.getNucleicAcidSectionRows();
const MzTabOligonucleotideSectionRows& oligonucleotide_section = mz_tab.getOligonucleotideSectionRows();
const MzTabOSMSectionRows& osm_section = mz_tab.getOSMSectionRows();
if (!nucleic_acid_section.empty())
{
Size search_ms_runs = 0;
if (complete)
{
// all ms_runs mandatory
search_ms_runs = ms_runs;
}
else // only report all scores if user provided at least one
{
bool has_ms_run_level_scores = false;
for (Size i = 0; i != nucleic_acid_section.size(); ++i)
{
if (!nucleic_acid_section[i].search_engine_score_ms_run.empty())
{
has_ms_run_level_scores = true;
}
}
if (has_ms_run_level_scores)
{
search_ms_runs = ms_runs;
}
}
Size n_search_engine_score = nucleic_acid_section[0].search_engine_score_ms_run.size();
Size n_best_search_engine_score = mz_tab.getMetaData().nucleic_acid_search_engine_score.size();
// add header
out.push_back("");
size_t n_header_columns = 0;
out.push_back(generateMzTabNucleicAcidHeader_(search_ms_runs, n_search_engine_score, n_best_search_engine_score, mz_tab.getNucleicAcidOptionalColumnNames(), n_header_columns));
// add section
generateMzTabSection_(nucleic_acid_section, mz_tab.getNucleicAcidOptionalColumnNames(), mz_tab.getMetaData(), out, n_header_columns);
}
if (!oligonucleotide_section.empty())
{
Size search_ms_runs = 0;
if (complete)
{
// all ms_runs mandatory
search_ms_runs = ms_runs;
}
else // only report all scores if user provided at least one
{
bool has_ms_run_level_scores = false;
for (Size i = 0; i != oligonucleotide_section.size(); ++i)
{
if (!oligonucleotide_section[i].search_engine_score_ms_run.empty())
{
has_ms_run_level_scores = true;
}
}
if (has_ms_run_level_scores)
{
search_ms_runs = ms_runs;
}
}
Size n_search_engine_score = oligonucleotide_section[0].search_engine_score_ms_run.size();
Size n_best_search_engine_score = mz_tab.getMetaData().oligonucleotide_search_engine_score.size();
out.push_back("");
size_t n_columns = 0;
out.push_back(generateMzTabOligonucleotideHeader_(search_ms_runs, n_best_search_engine_score, n_search_engine_score, mz_tab.getOligonucleotideOptionalColumnNames(), n_columns));
generateMzTabSection_(mz_tab.getOligonucleotideSectionRows(), mz_tab.getOligonucleotideOptionalColumnNames(), mz_tab.getMetaData(), out, n_columns);
}
if (!osm_section.empty())
{
Size n_search_engine_scores = mz_tab.getMetaData().osm_search_engine_score.size();
if (n_search_engine_scores == 0)
{
// TODO warn
}
out.push_back("");
size_t n_columns = 0;
out.push_back(generateMzTabOSMHeader_(n_search_engine_scores, mz_tab.getOSMOptionalColumnNames(), n_columns));
generateMzTabSection_(mz_tab.getOSMSectionRows(), mz_tab.getOSMOptionalColumnNames(), mz_tab.getMetaData(), out, n_columns);
}
// insert comments (might provide critical cues for human reader) and empty lines
Size line = 0;
vector<Size> empty_rows = mz_tab.getEmptyRows();
map<Size, String> comment_rows = mz_tab.getCommentRows();
if (empty_rows.empty() && comment_rows.empty())
{
TextFile tmp_out;
for (TextFile::ConstIterator it = out.begin(); it != out.end(); ++it)
{
tmp_out.addLine(*it);
}
tmp_out.store(filename);
}
else
{
TextFile tmp_out;
for (TextFile::ConstIterator it = out.begin(); it != out.end(); )
{
if (std::binary_search(empty_rows.begin(), empty_rows.end(), line)) // check if current line was originally an empty line
{
tmp_out.addLine("\n");
++line;
}
else if (comment_rows.find(line) != comment_rows.end()) // check if current line was originally a comment line
{
tmp_out.addLine(comment_rows[line]);
++line;
}
else // no empty line, no comment => add row
{
tmp_out.addLine(*it);
++line;
++it;
}
}
tmp_out.store(filename);
}
}
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif | C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/SequestOutfile.cpp | .cpp | 40,795 | 1,240 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Martin Langwisch $
// --------------------------------------------------------------------------
#include <OpenMS/FORMAT/SequestOutfile.h>
#include <OpenMS/SYSTEM/File.h>
#include <OpenMS/DATASTRUCTURES/DateTime.h>
#include <OpenMS/METADATA/ProteinIdentification.h>
#include <fstream>
#include <sstream>
using namespace std;
namespace OpenMS
{
#if 0 // useful for debugging
template <typename ContainerType>
void printContainer(std::ostream& os, ContainerType rhs, const String& separator = " ", const String& suffix = "\n", const String& prefix = "\n")
{
os << prefix;
for (typename ContainerType::const_iterator cit = rhs.begin();; )
{
os << *cit;
++cit;
if (cit == rhs.end())
{
break;
}
os << separator;
}
os << suffix;
}
#endif
SequestOutfile::SequestOutfile() = default;
SequestOutfile::SequestOutfile(const SequestOutfile&) = default;
SequestOutfile::~SequestOutfile() = default;
SequestOutfile& SequestOutfile::operator=(const SequestOutfile& sequest_outfile)
{
if (this == &sequest_outfile)
return *this;
return *this;
}
bool SequestOutfile::operator==(const SequestOutfile&) const
{
return true;
}
void SequestOutfile::load(const String& result_filename,
PeptideIdentificationList& peptide_identifications,
ProteinIdentification& protein_identification,
const double p_value_threshold,
vector<double>& pvalues,
const String& database,
const bool ignore_proteins_per_peptide
)
{
// check whether the p_value is correct
if ((p_value_threshold < 0) || (p_value_threshold > 1))
{
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "the parameters 'p_value_threshold' must be >= 0 and <=1 !");
}
// if no p_values were computed take all peptides
bool no_pvalues = pvalues.empty();
if (no_pvalues)
{
pvalues.push_back(0.0); // to make sure pvalues.end() is never reached
}
// generally used variables
String
line,
buffer,
sequest,
sequest_version,
database_type,
identifier;
vector<String> substrings;
// map the protein hits according to their accession number in the result file
map<String, Size> ac_position_map;
// get the protein hits that have already been found in another out-file
vector<ProteinHit> protein_hits = protein_identification.getHits();
// and insert them Into the map
for (const ProteinHit& phit_i : protein_hits)
{
ac_position_map.insert(make_pair(phit_i.getAccession(), ac_position_map.size()));
}
String accession, accession_type, score_type;
DateTime datetime;
double precursor_mz_value(0.0);
Size
precursor_mass_type(0),
ion_mass_type(0),
number_of_columns(0),
displayed_peptides(0),
proteins_per_peptide(0),
line_number(0);
Int
charge(-1),
number_column(-1),
rank_sp_column(-1),
id_column(-1),
mh_column(-1),
delta_cn_column(-1),
xcorr_column(-1),
sp_column(-1),
sf_column(-1),
ions_column(-1),
reference_column(-1),
peptide_column(-1),
score_column(-1);
String::size_type
start(0),
end(0);
readOutHeader(result_filename, datetime, precursor_mz_value, charge,
precursor_mass_type, ion_mass_type, displayed_peptides, sequest,
sequest_version, database_type, number_column, rank_sp_column,
id_column, mh_column, delta_cn_column, xcorr_column, sp_column,
sf_column, ions_column, reference_column, peptide_column, score_column,
number_of_columns);
identifier = sequest + "_" + datetime.getDate();
// set the search engine and its version and the score type
protein_identification.setSearchEngine(sequest);
protein_identification.setSearchEngineVersion(sequest_version);
protein_identification.setIdentifier(identifier);
// protein_identification.setScoreType("SEQUEST");
// open the result
ifstream result_file(result_filename.c_str());
if (!result_file)
{
if (!File::exists(result_filename))
{
throw Exception::FileNotFound(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, result_filename);
}
else if (!File::readable(result_filename))
{
throw Exception::FileNotReadable(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, result_filename);
}
else
{
throw Exception::IOException(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, result_filename);
}
}
while (getline(result_file, line)) // skip all lines until the one with '---'
{
if (!line.empty() && (line[line.length() - 1] < 33))
{
line.resize(line.length() - 1);
}
line.trim();
++line_number;
if (line.hasPrefix("---"))
{
break;
}
}
PeptideIdentification peptide_identification;
peptide_identification.setMZ(precursor_mz_value);
peptide_identification.setIdentifier(identifier);
peptide_identification.setSignificanceThreshold(p_value_threshold);
vector<String> databases;
databases.push_back(database);
score_type = (sf_column == -1) ? "SEQUEST prelim." : "SEQUEST";
peptide_identification.setScoreType(score_type);
if (no_pvalues)
{
pvalues.insert(pvalues.end(), displayed_peptides, 0.0);
}
vector<double>::const_iterator p_value = pvalues.begin();
for (Size viewed_peptides = 0; viewed_peptides < displayed_peptides; )
{
PeptideEvidence peptide_evidence;
PeptideHit peptide_hit;
ProteinHit protein_hit;
++line_number;
// if less peptides were found than may be displayed, break
if (!getline(result_file, line))
{
break;
}
if (!line.empty() && (line[line.length() - 1] < 33))
{
line.resize(line.length() - 1);
}
line.trim();
if (line.empty())
{
continue; // skip empty lines
}
++viewed_peptides;
getColumns(line, substrings, number_of_columns, reference_column);
// check whether the line has enough columns
if (substrings.size() != number_of_columns)
{
stringstream error_message;
error_message << "Wrong number of columns in line " << line_number << "! (" << substrings.size() << " present, should be " << number_of_columns << ")";
result_file.close();
result_file.clear();
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, error_message.str().c_str(), result_filename);
}
// check whether there are multiple proteins that belong to this peptide
if (substrings[reference_column].find_last_of('+') != String::npos)
{
// save the number of multiple proteins
proteins_per_peptide = substrings[reference_column].substr(substrings[reference_column].find_last_of('+')).toInt();
// and remove this number from the String
substrings[reference_column].resize(substrings[reference_column].find_last_of('+'));
}
else
{
proteins_per_peptide = 0;
}
// get the peptide information and insert it
if (p_value != pvalues.end() && (*p_value) <= p_value_threshold)
{
peptide_hit.setScore(String(substrings[score_column].c_str()).toDouble());
{
if (rank_sp_column != (-1))
{
peptide_hit.setMetaValue("RankSp", substrings[rank_sp_column]);
}
if (id_column != (-1))
{
peptide_hit.setMetaValue("SequestId", atoi(substrings[id_column].c_str()));
}
if (mh_column != (-1))
{
peptide_hit.setMetaValue("MH", String(substrings[mh_column].c_str()).toDouble());
}
if (delta_cn_column != (-1))
{
peptide_hit.setMetaValue("DeltCn", String(substrings[delta_cn_column].c_str()).toDouble());
}
if (xcorr_column != (-1))
{
peptide_hit.setMetaValue("XCorr", String(substrings[xcorr_column].c_str()).toDouble());
}
if (sp_column != (-1))
{
peptide_hit.setMetaValue("Sp", String(substrings[sp_column].c_str()).toDouble());
}
if (sf_column != (-1))
{
peptide_hit.setMetaValue("Sf", String(substrings[sf_column].c_str()).toDouble());
}
if (ions_column != (-1))
{
peptide_hit.setMetaValue("Ions", substrings[ions_column]);
}
}
peptide_hit.setCharge(charge);
String sequence_with_mods = substrings[peptide_column];
start = sequence_with_mods.find('.') + 1;
end = sequence_with_mods.find_last_of('.');
if (start >= 2)
{
peptide_evidence.setAABefore(sequence_with_mods[start - 2]);
}
if (end < sequence_with_mods.length() + 1)
{
peptide_evidence.setAAAfter(sequence_with_mods[end + 1]);
}
//remove modifications (small characters and everything that's not in the alphabet)
String sequence;
sequence_with_mods = substrings[peptide_column].substr(start, end - start);
for (String::ConstIterator c_i = sequence_with_mods.begin(); c_i != sequence_with_mods.end(); ++c_i)
{
if ((bool) isalpha(*c_i) && (bool) isupper(*c_i))
{
sequence.append(1, *c_i);
}
}
peptide_hit.setSequence(AASequence::fromString(sequence));
peptide_hit.setRank(substrings[rank_sp_column].substr(0, substrings[rank_sp_column].find('/')).toInt());
// get the protein information
getACAndACType(substrings[reference_column], accession, accession_type);
protein_hit.setAccession(accession);
// protein_hit.setRank(ac_position_map.size());
/// @todo simply sum up score? (Martin)
if (ac_position_map.insert(make_pair(accession, protein_hits.size())).second)
{
protein_hits.push_back(protein_hit);
}
peptide_evidence.setProteinAccession(accession);
peptide_hit.addPeptideEvidence(peptide_evidence);
if (!ignore_proteins_per_peptide)
{
for (Size i = 0; i < proteins_per_peptide; ++i)
{
getline(result_file, line);
if (!line.empty() && (line[line.length() - 1] < 33))
{
line.resize(line.length() - 1);
}
line.trim();
// all these lines look like '0 accession', e.g. '0 gi|1584947|prf||2123446B gamma sar'
/*if (!line.hasPrefix("0 ")) // if the line doesn't look like that
{
stringstream error_message;
error_message << "Line " << line_number << " doesn't look like a line with additional found proteins! (Should look like this: 0 gi|1584947|prf||2123446B gamma sar)";
result_file.close();
result_file.clear();
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, error_message.str().c_str() , result_filename);
}*/
line.erase(0, 3);
getACAndACType(line, accession, accession_type);
protein_hit.setAccession(accession);
// protein_hit.setRank(ac_position_map.size());
// @todo simply add up score
// Simply sum up score? (Martin)
// protein_hit.setScore(0.0);
if (ac_position_map.insert(make_pair(accession, protein_hits.size())).second)
{
protein_hits.push_back(protein_hit);
}
PeptideEvidence pe;
pe.setProteinAccession(accession);
peptide_hit.addPeptideEvidence(pe);
}
}
peptide_identification.insertHit(peptide_hit);
}
else // if the pvalue is higher than allowed
{
if (!ignore_proteins_per_peptide)
{
for (Size i = 0; i < proteins_per_peptide; ++i)
{
getline(result_file, line);
}
}
}
++p_value;
}
result_file.close();
result_file.clear();
if (no_pvalues)
{
pvalues.clear();
}
if (!peptide_identification.getHits().empty())
{
peptide_identifications.push_back(peptide_identification);
}
protein_identification.setHits(protein_hits);
protein_identification.setDateTime(datetime);
ac_position_map.clear();
}
// get the columns from a line
bool
SequestOutfile::getColumns(
const String& line,
vector<String>& substrings,
Size number_of_columns,
Size reference_column)
{
String buffer;
if (line.empty())
{
return false;
}
line.split(' ', substrings);
// remove any empty strings
substrings.erase(remove(substrings.begin(), substrings.end(), ""), substrings.end());
for (vector<String>::iterator s_i = substrings.begin(); s_i != substrings.end(); )
{
// if there are three columns, the middle one being a '/', they are merged
if (s_i + 1 != substrings.end())
{
if (((*(s_i + 1)) == "/") && (s_i + 2 != substrings.end()))
{
s_i->append(*(s_i + 1));
s_i->append(*(s_i + 2));
substrings.erase(s_i + 2);
substrings.erase(s_i + 1);
}
// if there are two columns, and the first ends with, or the second starts with a '/', they are merged
else if ((*(s_i + 1))[0] == '/')
{
s_i->append(*(s_i + 1));
substrings.erase(s_i + 1);
}
else if ((*(s_i))[s_i->length() - 1] == '/')
{
s_i->append(*(s_i + 1));
substrings.erase(s_i + 1);
}
// if there are two columns and the second is a number preceded by a '+', they are merged
else if ((*(s_i + 1))[0] == '+')
{
bool is_digit(true);
for (Size i = 1; i < (s_i + 1)->length(); ++i)
{
is_digit &= (bool)isdigit((*(s_i + 1))[i]);
}
if (is_digit && ((s_i + 1)->length() - 1))
{
s_i->append(*(s_i + 1));
substrings.erase(s_i + 1);
}
else
{
++s_i;
}
}
else
{
++s_i;
}
}
else
{
++s_i;
}
}
// if there are more columns than should be, there were spaces in the protein column
for (vector<String>::iterator s_i = substrings.begin() + reference_column; substrings.size() > number_of_columns; )
{
s_i->append(" ");
s_i->append(*(s_i + 1));
substrings.erase(s_i + 1);
}
return true;
}
// retrieve the sequences
void
SequestOutfile::getSequences(
const String& database_filename,
const map<String, Size>& ac_position_map,
vector<String>& sequences,
vector<pair<String, Size> >& found,
map<String, Size>& not_found)
{
ifstream database_file(database_filename.c_str());
if (!database_file)
{
if (!File::exists(database_filename))
{
throw Exception::FileNotFound(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, database_filename);
}
else if (!File::readable(database_filename))
{
throw Exception::FileNotReadable(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, database_filename);
}
else
{
throw Exception::IOException(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, database_filename);
}
}
String line, accession, accession_type, sequence;
not_found = ac_position_map;
map<String, Size>::iterator nf_i = not_found.end();
while (getline(database_file, line) && !not_found.empty())
{
if (!line.empty() && (line[line.length() - 1] < 33))
{
line.resize(line.length() - 1);
}
line.trim();
// empty and comment lines are skipped
if (line.empty() || line.hasPrefix(";"))
{
continue;
}
// the sequence belonging to the predecessing protein ('>') is stored, so
// when a new protein ('>') is found, save the sequence of the old
// protein
if (line.hasPrefix(">"))
{
getACAndACType(line, accession, accession_type);
if (nf_i != not_found.end())
{
sequences.push_back(sequence);
found.emplace_back(*nf_i);
not_found.erase(nf_i);
}
nf_i = not_found.find(accession); // for the first protein in the database, there's no predecessing protein
sequence.clear();
}
else if (nf_i != not_found.end())
{
sequence.append(line);
}
}
if (nf_i != not_found.end())
{
sequences.push_back(sequence);
found.emplace_back(*nf_i);
not_found.erase(nf_i);
}
database_file.close();
database_file.clear();
}
void SequestOutfile::getACAndACType(String line, String& accession, String& accession_type)
{
String swissprot_prefixes = "JLOPQUX";
/// @todo replace this by general FastA implementation? (Martin)
accession.clear();
accession_type.clear();
// if it's a FASTA line
if (line.hasPrefix(">"))
{
line.erase(0, 1);
}
if (!line.empty() && (line[line.length() - 1] < 33))
{
line.resize(line.length() - 1);
}
line.trim();
// if it's a swissprot accession
if (line.hasPrefix("tr") || line.hasPrefix("sp"))
{
accession = line.substr(3, line.find('|', 3) - 3);
accession_type = "SwissProt";
}
else if (line.hasPrefix("gi"))
{
String::size_type snd(line.find('|', 3));
String::size_type third(0);
if (snd != String::npos)
{
third = line.find('|', ++snd) + 1;
accession = line.substr(third, line.find('|', third) - third);
accession_type = line.substr(snd, third - 1 - snd);
}
if (accession_type == "gb")
{
accession_type = "GenBank";
}
else if (accession_type == "emb")
{
accession_type = "EMBL";
}
else if (accession_type == "dbj")
{
accession_type = "DDBJ";
}
else if (accession_type == "ref")
{
accession_type = "NCBI";
}
else if ((accession_type == "sp") || (accession_type == "tr"))
{
accession_type = "SwissProt";
}
else if (accession_type == "gnl")
{
accession_type = accession;
snd = line.find('|', third);
third = line.find('|', ++snd);
if (third != String::npos)
{
accession = line.substr(snd, third - snd);
}
else
{
third = line.find(' ', snd);
if (third != String::npos)
{
accession = line.substr(snd, third - snd);
}
else
{
accession = line.substr(snd);
}
}
}
else
{
String::size_type pos1(line.find('(', 0));
String::size_type pos2(0);
if (pos1 != String::npos)
{
pos2 = line.find(')', ++pos1);
if (pos2 != String::npos)
{
accession = line.substr(pos1, pos2 - pos1);
if ((accession.size() == 6) && (String(swissprot_prefixes).find(accession[0], 0) != String::npos))
{
accession_type = "SwissProt";
}
else
{
accession.clear();
}
}
}
if (accession.empty())
{
accession_type = "gi";
if (snd != String::npos)
{
accession = line.substr(3, snd - 4);
}
else
{
snd = line.find(' ', 3);
if (snd != String::npos)
{
accession = line.substr(3, snd - 3);
}
else
{
accession = line.substr(3);
}
}
}
}
}
else if (line.hasPrefix("ref"))
{
accession = line.substr(4, line.find('|', 4) - 4);
accession_type = "NCBI";
}
else if (line.hasPrefix("gnl"))
{
line.erase(0, 3);
accession_type = line.substr(0, line.find('|', 0));
accession = line.substr(accession_type.length() + 1);
}
else if (line.hasPrefix("lcl"))
{
line.erase(0, 4);
accession_type = "lcl";
accession = line;
}
else
{
String::size_type pos1(line.find('(', 0));
String::size_type pos2(0);
if (pos1 != String::npos)
{
pos2 = line.find(')', ++pos1);
if (pos2 != String::npos)
{
accession = line.substr(pos1, pos2 - pos1);
if ((accession.size() == 6) && (String(swissprot_prefixes).find(accession[0], 0) != String::npos))
{
accession_type = "SwissProt";
}
else
{
accession.clear();
}
}
}
if (accession.empty())
{
pos1 = line.find('|');
accession = line.substr(0, pos1);
if ((accession.size() == 6) && (String(swissprot_prefixes).find(accession[0], 0) != String::npos))
{
accession_type = "SwissProt";
}
else
{
pos1 = line.find(' ');
accession = line.substr(0, pos1);
if ((accession.size() == 6) && (String(swissprot_prefixes).find(accession[0], 0) != String::npos))
{
accession_type = "SwissProt";
}
else
{
accession = line.substr(0, 6);
if (String(swissprot_prefixes).find(accession[0], 0) != String::npos)
{
accession_type = "SwissProt";
}
else
{
accession.clear();
}
}
}
}
}
if (accession.empty())
{
accession = line.trim();
accession_type = "unknown";
}
}
void SequestOutfile::readOutHeader(
const String& result_filename,
DateTime& datetime,
double& precursor_mz_value,
Int& charge,
Size& precursor_mass_type,
Size& ion_mass_type,
Size& displayed_peptides,
String& sequest,
String& sequest_version,
String& database_type,
Int& number_column,
Int& rank_sp_column,
Int& id_column,
Int& mh_column,
Int& delta_cn_column,
Int& xcorr_column,
Int& sp_column,
Int& sf_column,
// Int& P_column,
Int& ions_column,
Int& reference_column,
Int& peptide_column,
Int& score_column,
Size& number_of_columns)
{
charge = 0;
precursor_mz_value = 0.0;
precursor_mass_type = ion_mass_type = 0;
// open the result
ifstream result_file(result_filename.c_str());
if (!result_file)
{
if (!File::exists(result_filename))
{
throw Exception::FileNotFound(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, result_filename);
}
else if (!File::readable(result_filename))
{
throw Exception::FileNotReadable(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, result_filename);
}
else
{
throw Exception::IOException(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, result_filename);
}
}
String line, buffer;
vector<String> substrings;
// get the date and time
DateTime datetime_empty;
datetime.clear();
datetime_empty.clear();
while (getline(result_file, line))
{
if (!line.empty() && (line[line.length() - 1] < 33))
{
line.resize(line.length() - 1);
}
line.trim();
line.split(',', substrings);
if (line.hasSuffix(".out")) // next line is the sequest version
{
// \\bude\langwisc\temp\Inspect_Sequest.mzXML.13.1.d.out
// TurboSEQUEST v.27 (rev. 12), (c) 1998-2005
if (!getline(result_file, line))
{
result_file.close();
result_file.clear();
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "No Sequest version found!", result_filename);
}
if (!line.empty() && (line[line.length() - 1] < 33))
{
line.resize(line.length() - 1);
}
line.trim();
if (line.hasSubstring(","))
{
line = line.substr(0, line.find(',', 0));
}
buffer = line;
buffer.toUpper();
if (!buffer.hasSubstring("SEQUEST"))
{
result_file.close();
result_file.clear();
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "No Sequest version found!", result_filename);
}
// the search engine
String::size_type pos(0), pos1(0);
pos1 = buffer.find("SEQUEST", 0) + strlen("SEQUEST");
pos = line.find(' ', 0);
if (pos == String::npos || pos >= pos1)
{
sequest = line.substr(0, pos1);
pos = 0;
}
else
sequest = line.substr(pos, pos1 - pos);
// the version
pos = line.find(' ', pos1);
if (pos != String::npos)
{
pos1 = line.find(',', ++pos);
if (pos1 == String::npos)
{
sequest_version = line.substr(pos);
}
else
{
sequest_version = line.substr(pos, pos1 - pos);
}
} // else no version was found
}
else if (line.hasPrefix("(M+H)+ mass = "))
{
line.erase(0, strlen("(M+H)+ mass = "));
line.split(' ', substrings);
precursor_mz_value = substrings[0].toFloat();
charge = substrings[3].substr(1, 2).toInt();
line = *(--substrings.end());
line.split('/', substrings);
substrings[0].toUpper();
substrings[1].toUpper();
precursor_mass_type = (substrings[0] == "MONO") ? 1 : 0;
ion_mass_type = (substrings[1] == "MONO") ? 1 : 0;
}
else if ((!substrings.empty()) && (substrings[0].size() == 10) && (substrings[0][2] == '/') && (substrings[0][5] == '/'))
{
datetime.setDate(substrings[0]);
buffer = substrings[1];
buffer.trim();
buffer.split(' ', substrings);
// 12:00 = 12:00 PM; 24:00 = 12:00 AM
Int hour = substrings[0].substr(0, 2).toInt();
if ((hour == 12) && (substrings[1] == "AM"))
{
substrings[0].replace(0, 2, "00");
}
else if ((hour != 12) && (substrings[1] == "PM"))
{
hour += 12;
substrings[0].replace(0, 2, String(hour));
}
substrings[0].append(":00");
datetime.setTime(substrings[0]);
}
else if (line.hasPrefix("# bases"))
{
database_type = "bases";
}
else if (line.hasPrefix("# amino acids"))
{
database_type = "amino acids";
}
else if (line.hasPrefix("display top") && substrings[0].hasPrefix("display top")) // get the number of peptides displayed
{
displayed_peptides = strlen("display top ");
displayed_peptides = substrings[0].substr(displayed_peptides, substrings[0].find('/', displayed_peptides) - displayed_peptides).toInt();
}
else if (line.hasPrefix("#"))
{
break; // the header is read
}
}
if (datetime == datetime_empty)
{
result_file.close();
result_file.clear();
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "No time found!", result_filename);
}
if (sequest.empty())
{
result_file.close();
result_file.clear();
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "No Sequest version found!", result_filename);
}
if (sequest_version.empty())
{
result_file.close();
result_file.clear();
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "No Sequest version found!", result_filename);
}
if (!precursor_mz_value)
{
result_file.close();
result_file.clear();
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "No precursor mass found found!", result_filename);
}
if (!charge)
{
result_file.close();
result_file.clear();
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "No charge found!", result_filename);
}
if (!line.hasPrefix("#")) // check whether the header line was found
{
result_file.close();
result_file.clear();
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Not enough lines in file (no table header found)!", result_filename);
}
// retrieve the number of lines and get the needed column numbers
number_column = -1;
rank_sp_column = -1;
id_column = -1;
mh_column = -1;
delta_cn_column = -1;
xcorr_column = -1;
sp_column = -1;
sf_column = -1;
// P_column = -1;
ions_column = -1;
reference_column = -1;
peptide_column = -1;
// get the single columns
line.split(' ', substrings);
// remove the empty strings
for (vector<String>::iterator i = substrings.begin(); i != substrings.end(); )
{
i->trim();
if (i->empty())
{
i = substrings.erase(i);
}
else
{
++i;
}
}
number_of_columns = substrings.size();
// get the numbers of the columns
for (vector<String>::const_iterator iter = substrings.begin(); iter != substrings.end(); ++iter)
{
if (!iter->compare("#"))
{
number_column = (iter - substrings.begin());
}
else if (!iter->compare("Rank/Sp"))
{
rank_sp_column = (iter - substrings.begin());
}
else if (!iter->compare("Id#"))
{
id_column = (iter - substrings.begin());
}
else if (!iter->compare("(M+H)+"))
{
mh_column = (iter - substrings.begin());
}
else if (!iter->compare("deltCn"))
{
delta_cn_column = (iter - substrings.begin());
}
else if (!iter->compare("XCorr"))
{
xcorr_column = (iter - substrings.begin());
}
else if (!iter->compare("Sp"))
{
sp_column = (iter - substrings.begin());
}
else if (!iter->compare("Sf"))
{
sf_column = (iter - substrings.begin());
}
else if (!iter->compare("Ions"))
{
ions_column = (iter - substrings.begin());
}
else if (!iter->compare("Reference"))
{
reference_column = (iter - substrings.begin());
}
else if (!iter->compare("Peptide"))
{
peptide_column = (iter - substrings.begin());
}
}
// check whether the columns are available in the table header
if ((number_column == -1) || (rank_sp_column == -1) || /* (id_column == -1) ||*/ (mh_column == -1) || (delta_cn_column == -1) || (xcorr_column == -1) || (sp_column == -1) || (ions_column == -1) || (reference_column == -1) || (peptide_column == -1))
{
result_file.close();
result_file.clear();
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "at least one of the columns '#', 'Rank/Sp', 'Id#', '(M+H)+', 'deltCn', 'XCorr', 'Sp', 'Ions', 'Reference' or 'Peptide' is missing!", result_filename);
}
score_column = (sf_column == -1) ? sp_column : sf_column;
result_file.close();
result_file.clear();
}
// void SequestOutfile::getPValuesFromOutFiles(vector< pair < String, vector< double > > >& out_filenames_and_pvalues)
// throw (Exception::FileNotFound&, Exception::ParseError)
// {
// DateTime datetime;
// double
// precursor_mz_value(0),
// discriminant_score,
// xcorr,
// rank_sp,
// delta_mass;
//
// Size
// precursor_mass_type(0),
// ion_mass_type(0),
// number_of_columns(0),
// displayed_peptides(0),
// line_number(0),
// proteins_per_peptide(0),
// peptide_length(0);
//
// Int
// charge(0),
// number_column(0),
// rank_sp_column(0),
// id_column(0),
// mh_column(0),
// delta_cn_column(0),
// xcorr_column(0),
// sp_column(0),
// sf_column(0),
// ions_column(0),
// reference_column(0),
// peptide_column(0),
// score_column(0);
//
// String
// line,
// sequence,
// buffer,
// out_filename,
// database_type;
//
// vector< String > substrings;
// vector< double >
// delta_cns,
// current_discriminant_scores,
// pvalues;
//
// // map< String, vector< double > > out_filenames_and_discriminant_scores;
// vector< vector< double > > discriminant_scores;
// map< double, Size > discriminant_scores_histogram;
//
// for ( vector< pair < String, vector< double > > >::const_iterator fp_i = out_filenames_and_pvalues.begin(); fp_i != out_filenames_and_pvalues.end(); ++fp_i )
// {
// current_discriminant_scores.clear();
// readOutHeader(fp_i->first, datetime, precursor_mz_value, charge, precursor_mass_type, ion_mass_type, displayed_peptides, line, line, database_type, number_column, rank_sp_column, id_column, mh_column, delta_cn_column, xcorr_column, sp_column, sf_column, ions_column, reference_column, peptide_column, score_column, number_of_columns);
//
// // the charge is allowed from 1 to 3 only
// if ( charge < 0 ) charge *= -1;
// if ( charge > 3 ) charge = 3;
//
// // reopen the result file
// ifstream out_file(out_filename.c_str());
// if ( !out_file )
// {
// throw Exception::FileNotFound(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, out_filename);
// }
//
// while ( getline(out_file, line) ) // skip all lines until the one with '---'
// {
// if ( !line.empty() && (line[line.length()-1] < 33) ) line.resize(line.length()-1);
// line.trim();
// ++line_number;
// if ( line.hasPrefix("---") ) break;
// }
//
// // needed: XCorr, peptide length, delta Cn, rankSp, delta Mass
// for ( Size viewed_peptides = 0 ; viewed_peptides < displayed_peptides; )
// {
// if ( !getline(out_file, line) ) break; // if fewer peptides were found than may be displayed, break
// ++line_number;
// if ( !line.empty() && (line[line.length()-1] < 33) ) line.resize(line.length()-1);
// line.trim();
// if ( line.empty() ) continue;
//
// getColumns(line, substrings, number_of_columns, reference_column);
// ++viewed_peptides;
//
// // check whether the line has enough columns
// if (substrings.size() < number_of_columns )
// {
// stringstream error_message;
// error_message << "Wrong number of columns in line " << line_number << "! (" << substrings.size() << " present, should be " << number_of_columns << ")";
// throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, error_message.str().c_str() , out_filename);
// }
// delta_cns.push_back(substrings[delta_cn_column].toFloat());
// xcorr = substrings[xcorr_column].toFloat();
// rank_sp = substrings[rank_sp_column].toFloat();
// delta_mass = precursor_mz_value - substrings[mh_column].toFloat();
// buffer = substrings[peptide_column].substr(2, substrings[peptide_column].length() - 4);
// // remove all ptms
// for ( String::ConstIterator c_i = buffer.begin(); c_i != buffer.end(); ++c_i )
// {
// if ( (bool) isalpha(*c_i) && (bool) isupper(*c_i) ) sequence.append(1, *c_i);
// }
//
// // compute the discriminant score
// peptide_length = min(max_pep_lens_[charge], sequence.length());
// discriminant_score = xcorr_weights_[charge] * (log(xcorr) / log(peptide_length * num_frags_[charge]));
// discriminant_score += rank_sp_weights_[charge] * log(rank_sp);
// discriminant_score += delta_mass_weights_[charge] * abs(delta_mass);
// discriminant_score += const_weights_[charge];
// current_discriminant_scores.push_back(discriminant_score);
//
// // if there are multiple proteins that belong to this peptide, skip these lines
// if ( substrings[reference_column].find_last_of('+') != String::npos )
// {
// proteins_per_peptide = substrings[reference_column].substr(substrings[reference_column].find_last_of('+')).toInt();
// for ( Size prot = 0; prot < proteins_per_peptide; ++prot ) getline(out_file, line);
// line_number += proteins_per_peptide;
// }
// }
//
// // close and clear the stream for further use
// out_file.close();
// out_file.clear();
//
// // if only one delta cn is found, it is set to 1
//
// if ( delta_cns.size() == 1 ) current_discriminant_scores.back() += delta_cn_weights_[charge];
// else if ( delta_cns.size() > 1 )
// {
// // the delta cns are recalculated and the discriminant scores are calculated correspondingly and added to the histogram
// vector< double >::iterator ds_i = current_discriminant_scores.begin();
// for ( vector< double >::const_iterator dcn_i = delta_cns.begin(); dcn_i != delta_cns.end(); ++dcn_i, ++ds_i )
// {
// (*ds_i) += delta_cn_weights_[charge] * (delta_cns.back() - (*dcn_i));
// ++discriminant_scores_histogram[*ds_i]; // bucketing; not yet finished
// }
// }
// // append the discriminant scores
// discriminant_scores.push_back(current_discriminant_scores);
// // out_filenames_and_discriminant_scores[out_filename] = current_discriminant_scores;
// }
//
// // now the p-values can be computed
// // fit two normal distributions to the data
// Math::BasicStatistics< >
// correct,
// incorrect;
// // unfinished;
// correct.setMean();
// correct.setVariance();
// incorrect.setMean();
// incorrect.setVariance();
//
// // for ( map< String, vector< double > >::const_iterator fnds_i = out_filenames_and_discriminant_scores.begin(); fnds_i != out_filenames_and_discriminant_scores.end(); ++fnds_i )
// vector< vector< double >::const_iterator dss_i = discriminant_scores.begin();
// for ( vector< pair < String, vector< double > > >::iterator fp_i = out_filenames_and_pvalues.begin(); fp_i != out_filenames_and_pvalues.end(); ++fp_i, ++dss_i )
// {
// pvalues.clear();
// // for ( vector< double >::const_iterator ds_i = fnds_i->second.begin(); ds_i != fnds_i->second.begin(); ++ds_i )
// for ( vector< double >::const_iterator ds_i = dss_i->begin(); ds_i != dss_i->end(); ++ds_i )
// {
// pvalues.push_back(correct.normalDensity(*ds_i) / (correct.normalDensity(*ds_i) + incorrect.normalDensity(*ds_i)));
// // p_correct = exp(-0.5 * pow((*ds_i - mean_correct) / sd, 2)) / (sd_correct * sqrt(2 * pi) );
// // p_incorrect = exp(-0.5 * pow((*ds_i - mean_incorrect) / sd, 2)) / (sd_incorrect * sqrt(2 * pi) );
// // pvalues.push_back();
// }
// fp_i->second = pvalues;
// }
// }
double SequestOutfile::const_weights_[] = {0.646f, -0.959f, -1.460f};
double SequestOutfile::xcorr_weights_[] = {5.49f, 8.362f, 9.933f};
double SequestOutfile::delta_cn_weights_[] = {4.643f, 7.386f, 11.149f};
double SequestOutfile::rank_sp_weights_[] = {-0.455f, -0.194f, -0.201f};
double SequestOutfile::delta_mass_weights_[] = {-0.84f, -0.314f, -0.277f};
Size SequestOutfile::max_pep_lens_[] = {100, 15, 25};
Size SequestOutfile::num_frags_[] = {2, 2, 4};
} //namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/InspectOutfile.cpp | .cpp | 43,387 | 1,306 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Martin Langwisch $
// --------------------------------------------------------------------------
#if defined OPENMS_BIG_ENDIAN
#define OPENMS_IS_BIG_ENDIAN true
#else
#define OPENMS_IS_BIG_ENDIAN false
#endif
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/FORMAT/InspectOutfile.h>
#include <OpenMS/SYSTEM/File.h>
#include <QtCore/QRegularExpression>
#include <fstream>
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunreachable-code"
#endif
using namespace std;
namespace OpenMS
{
InspectOutfile::InspectOutfile() = default;
/// copy constructor
InspectOutfile::InspectOutfile(const InspectOutfile&) = default;
/// destructor
InspectOutfile::~InspectOutfile() = default;
/// assignment operator
InspectOutfile& InspectOutfile::operator=(const InspectOutfile& inspect_outfile)
{
if (this == &inspect_outfile)
{
return *this;
}
return *this;
}
/// equality operator
bool InspectOutfile::operator==(const InspectOutfile&) const
{
return true;
}
vector<Size> InspectOutfile::load(const String& result_filename, PeptideIdentificationList& peptide_identifications,
ProteinIdentification& protein_identification, const double p_value_threshold, const String& database_filename)
{
// check whether the p_value is correct
if ((p_value_threshold < 0) || (p_value_threshold > 1))
{
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "The parameters 'p_value_threshold' must be >= 0 and <=1 !");
}
ifstream result_file(result_filename.c_str());
if (!result_file)
{
if (!File::exists(result_filename))
{
throw Exception::FileNotFound(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, result_filename);
}
else if (!File::readable(result_filename))
{
throw Exception::FileNotReadable(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, result_filename);
}
else
{
throw Exception::IOException(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, result_filename);
}
}
String
line,
accession,
accession_type,
spectrum_file,
identifier;
Size
record_number(0),
scan_number(0),
line_number(0),
number_of_columns(0);
vector<String> substrings;
vector<Size> corrupted_lines;
PeptideIdentification peptide_identification;
if (!getline(result_file, line)) // the header is read in a special function, so it can be skipped
{
result_file.close();
result_file.clear();
throw Exception::FileEmpty(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, result_filename);
}
if (!line.empty() && (line[line.length() - 1] < 33))
line.resize(line.length() - 1);
line.trim();
++line_number;
DateTime datetime = DateTime::now();
if (protein_identification.getSearchEngine().empty())
{
identifier = "InsPecT_" + datetime.getDate();
}
else
{
protein_identification.getSearchEngine() + "_" + datetime.getDate();
}
// to get the precursor retention time and mz values later, save the filename and the numbers of the scans
vector<pair<String, vector<pair<Size, Size> > > > files_and_peptide_identification_with_scan_number;
// the record number is mapped to the position in the protein hits, to retrieve their sequences
map<Size, Size> rn_position_map;
// get the header
Int
spectrum_file_column(-1),
scan_column(-1),
peptide_column(-1),
protein_column(-1),
charge_column(-1),
MQ_score_column(-1),
p_value_column(-1),
record_number_column(-1),
DB_file_pos_column(-1),
spec_file_pos_column(-1);
String::size_type start(0), end(0);
try
{
readOutHeader(result_filename, line, spectrum_file_column, scan_column, peptide_column, protein_column, charge_column, MQ_score_column, p_value_column, record_number_column, DB_file_pos_column, spec_file_pos_column, number_of_columns);
}
catch (Exception::ParseError& p_e)
{
result_file.close();
result_file.clear();
OPENMS_LOG_WARN << "ParseError (" << p_e.what() << ") caught in " << __FILE__ << "\n";
throw;
}
while (getline(result_file, line))
{
++line_number;
if (!line.empty() && (line[line.length() - 1] < 33))
line.resize(line.length() - 1);
line.trim();
if (line.empty())
continue;
// check whether the line has enough columns
line.split('\t', substrings);
if (substrings.size() != number_of_columns)
{
corrupted_lines.push_back(line_number);
continue;
}
// if the pvalue is too small, skip the line
if (substrings[p_value_column].toFloat() > p_value_threshold)
{
continue;
}
// the protein
ProteinHit protein_hit;
// get accession number and type
getACAndACType(substrings[protein_column], accession, accession_type);
protein_hit.setAccession(accession);
// protein_hit.setScore(0.0);
// the database position of the protein (the i-th protein)
record_number = substrings[record_number_column].toInt();
// map the database position of the protein to its position in the
// protein hits and insert it, if it's a new protein
if (rn_position_map.find(record_number) == rn_position_map.end())
{
rn_position_map[record_number] = protein_identification.getHits().size();
protein_identification.insertHit(protein_hit);
}
// if a new scan is found (new file or new scan), insert it into the
// vector (the first time the condition is fulfilled because
// spectrum_file is "")
if ((substrings[spectrum_file_column] != spectrum_file) || ((Size) substrings[scan_column].toInt() != scan_number))
{
// if it's a new file, insert it into the vector (used to retrieve RT and MT later)
if (substrings[spectrum_file_column] != spectrum_file)
{
// if it's the first file or if hits have been found in the file before, insert a new file
if (files_and_peptide_identification_with_scan_number.empty() ||
!files_and_peptide_identification_with_scan_number.back().second.empty())
{
files_and_peptide_identification_with_scan_number.emplace_back(substrings[spectrum_file_column],
vector<pair<Size, Size> >());
}
// otherwise change the name of the last file entry (the one without hits)
else
files_and_peptide_identification_with_scan_number.back().first = substrings[spectrum_file_column];
}
spectrum_file = substrings[spectrum_file_column];
scan_number = substrings[scan_column].toInt();
// if it's not the first scan and if hits have been found, insert the peptide identification
if (!peptide_identification.empty() && !peptide_identification.getHits().empty())
{
files_and_peptide_identification_with_scan_number.back().second.emplace_back(peptide_identifications.size(), scan_number);
peptide_identifications.push_back(peptide_identification);
}
peptide_identification = PeptideIdentification();
peptide_identification.setIdentifier(identifier);
peptide_identification.setSignificanceThreshold(p_value_threshold);
peptide_identification.setScoreType(score_type_);
}
// get the peptide infos from the new peptide and insert it
PeptideHit peptide_hit;
peptide_hit.setCharge(substrings[charge_column].toInt());
peptide_hit.setScore(substrings[MQ_score_column].toFloat());
peptide_hit.setRank(0); // all ranks are set to zero and assigned later
// get the sequence and the amino acid before and after
String sequence, sequence_with_mods;
sequence_with_mods = substrings[peptide_column];
start = sequence_with_mods.find('.') + 1;
end = sequence_with_mods.find_last_of('.');
PeptideEvidence pe;
if (start >= 2)
{
pe.setAABefore(sequence_with_mods[start - 2]);
}
if (end < sequence_with_mods.length() + 1)
{
pe.setAAAfter(sequence_with_mods[end + 1]);
}
//remove modifications (small characters and anything that's not in the alphabet)
sequence_with_mods = substrings[peptide_column].substr(start, end - start);
for (String::ConstIterator c_i = sequence_with_mods.begin(); c_i != sequence_with_mods.end(); ++c_i)
{
if ((bool) isalpha(*c_i) && (bool) isupper(*c_i))
sequence.append(1, *c_i);
}
peptide_hit.setSequence(AASequence::fromString(sequence));
pe.setProteinAccession(accession);
peptide_hit.addPeptideEvidence(pe);
peptide_identification.insertHit(peptide_hit);
}
// result file read
result_file.close();
result_file.clear();
// if it's not the first scan and if hits have been found, insert the peptide identification
if (!peptide_identification.empty() && !peptide_identification.getHits().empty())
{
files_and_peptide_identification_with_scan_number.back().second.emplace_back(peptide_identifications.size(), scan_number);
peptide_identifications.push_back(peptide_identification);
}
// if the last file had no hits, delete it
if (!files_and_peptide_identification_with_scan_number.empty() && files_and_peptide_identification_with_scan_number.back().second.empty())
{
files_and_peptide_identification_with_scan_number.pop_back();
}
if (!peptide_identifications.empty())
peptide_identifications.back().sort();
// search the sequence of the proteins
if (!protein_identification.getHits().empty() && !database_filename.empty())
{
vector<ProteinHit> protein_hits = protein_identification.getHits();
vector<String> sequences;
getSequences(database_filename, rn_position_map, sequences);
// set the retrieved sequences
vector<String>::const_iterator s_i = sequences.begin();
for (map<Size, Size>::const_iterator rn_i = rn_position_map.begin(); rn_i != rn_position_map.end(); ++rn_i, ++s_i)
protein_hits[rn_i->second].setSequence(*s_i);
sequences.clear();
rn_position_map.clear();
protein_identification.setHits(protein_hits);
protein_hits.clear();
}
// get the precursor retention times and mz values
getPrecursorRTandMZ(files_and_peptide_identification_with_scan_number, peptide_identifications);
protein_identification.setDateTime(datetime);
protein_identification.setIdentifier(identifier);
return corrupted_lines;
}
// < record number, number of protein in a vector >
vector<Size>
InspectOutfile::getSequences(
const String& database_filename,
const map<Size, Size>& wanted_records,
vector<String>& sequences)
{
ifstream database(database_filename.c_str());
if (!database)
{
if (!File::exists(database_filename))
{
throw Exception::FileNotFound(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, database_filename);
}
else if (!File::readable(database_filename))
{
throw Exception::FileNotReadable(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, database_filename);
}
else
{
throw Exception::IOException(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, database_filename);
}
}
vector<Size> not_found;
Size seen_records(0);
stringbuf sequence;
database.seekg(0, ios::end);
streampos sp = database.tellg();
database.seekg(0, ios::beg);
for (map<Size, Size>::const_iterator wr_i = wanted_records.begin(); wr_i != wanted_records.end(); ++wr_i)
{
for (; seen_records < wr_i->first; ++seen_records)
{
database.ignore(sp, trie_delimiter_);
}
database.get(sequence, trie_delimiter_);
sequences.emplace_back(sequence.str());
if (sequences.back().empty())
{
not_found.push_back(wr_i->first);
}
sequence.str("");
}
// close the filestreams
database.close();
database.clear();
return not_found;
}
void
InspectOutfile::getACAndACType(
String line,
String& accession,
String& accession_type)
{
String swissprot_prefixes = "JLOPQUX";
/// @todo replace this by general FastA implementation? (Martin)
accession.clear();
accession_type.clear();
// if it's a FASTA line
if (line.hasPrefix(">"))
{
line.erase(0, 1);
}
if (!line.empty() && (line[line.length() - 1] < 33))
{
line.resize(line.length() - 1);
}
line.trim();
// if it's a swissprot accession
if (line.hasPrefix("tr") || line.hasPrefix("sp"))
{
accession = line.substr(3, line.find('|', 3) - 3);
accession_type = "SwissProt";
}
else if (line.hasPrefix("gi"))
{
String::size_type snd(line.find('|', 3));
String::size_type third(0);
if (snd != String::npos)
{
third = line.find('|', ++snd) + 1;
accession = line.substr(third, line.find('|', third) - third);
accession_type = line.substr(snd, third - 1 - snd);
}
if (accession_type == "gb")
{
accession_type = "GenBank";
}
else if (accession_type == "emb")
{
accession_type = "EMBL";
}
else if (accession_type == "dbj")
{
accession_type = "DDBJ";
}
else if (accession_type == "ref")
{
accession_type = "NCBI";
}
else if ((accession_type == "sp") || (accession_type == "tr"))
{
accession_type = "SwissProt";
}
else if (accession_type == "gnl")
{
accession_type = accession;
snd = line.find('|', third);
third = line.find('|', ++snd);
if (third != String::npos)
{
accession = line.substr(snd, third - snd);
}
else
{
third = line.find(' ', snd);
if (third != String::npos)
{
accession = line.substr(snd, third - snd);
}
else
{
accession = line.substr(snd);
}
}
}
else
{
String::size_type pos1(line.find('(', 0));
String::size_type pos2(0);
if (pos1 != String::npos)
{
pos2 = line.find(')', ++pos1);
if (pos2 != String::npos)
{
accession = line.substr(pos1, pos2 - pos1);
if ((accession.size() == 6) && (String(swissprot_prefixes).find(accession[0], 0) != String::npos))
{
accession_type = "SwissProt";
}
else
{
accession.clear();
}
}
}
if (accession.empty())
{
accession_type = "gi";
if (snd != String::npos)
{
accession = line.substr(3, snd - 4);
}
else
{
snd = line.find(' ', 3);
if (snd != String::npos)
{
accession = line.substr(3, snd - 3);
}
else
{
accession = line.substr(3);
}
}
}
}
}
else if (line.hasPrefix("ref"))
{
accession = line.substr(4, line.find('|', 4) - 4);
accession_type = "NCBI";
}
else if (line.hasPrefix("gnl"))
{
line.erase(0, 3);
accession_type = line.substr(0, line.find('|', 0));
accession = line.substr(accession_type.length() + 1);
}
else if (line.hasPrefix("lcl"))
{
line.erase(0, 4);
accession_type = "lcl";
accession = line;
}
else
{
String::size_type pos1(line.find('(', 0));
String::size_type pos2(0);
if (pos1 != String::npos)
{
pos2 = line.find(')', ++pos1);
if (pos2 != String::npos)
{
accession = line.substr(pos1, pos2 - pos1);
if ((accession.size() == 6) && (String(swissprot_prefixes).find(accession[0], 0) != String::npos))
{
accession_type = "SwissProt";
}
else
{
accession.clear();
}
}
}
if (accession.empty())
{
pos1 = line.find('|');
accession = line.substr(0, pos1);
if ((accession.size() == 6) && (String(swissprot_prefixes).find(accession[0], 0) != String::npos))
accession_type = "SwissProt";
else
{
pos1 = line.find(' ');
accession = line.substr(0, pos1);
if ((accession.size() == 6) && (String(swissprot_prefixes).find(accession[0], 0) != String::npos))
{
accession_type = "SwissProt";
}
else
{
accession = line.substr(0, 6);
if (String(swissprot_prefixes).find(accession[0], 0) != String::npos)
{
accession_type = "SwissProt";
}
else
{
accession.clear();
}
}
}
}
}
if (accession.empty())
{
accession = line.trim();
accession_type = "unknown";
}
}
void
InspectOutfile::getPrecursorRTandMZ(
const vector<pair<String, vector<pair<Size, Size> > > >& files_and_peptide_identification_with_scan_number,
PeptideIdentificationList& ids)
{
PeakMap experiment;
String type;
for (vector<pair<String, vector<pair<Size, Size> > > >::const_iterator fs_i = files_and_peptide_identification_with_scan_number.begin(); fs_i != files_and_peptide_identification_with_scan_number.end(); ++fs_i)
{
getExperiment(experiment, type, fs_i->first); // may throw an exception if the filetype could not be determined
if (experiment.size() < fs_i->second.back().second)
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Not enough scans in file! (" + String(experiment.size()) + " available, should be at least " + String(fs_i->second.back().second) + ")", fs_i->first);
}
for (vector<pair<Size, Size> >::const_iterator pi_scan_i = fs_i->second.begin(); pi_scan_i != fs_i->second.end(); ++pi_scan_i)
{
ids[pi_scan_i->first].setMZ(experiment[pi_scan_i->second - 1].getPrecursors()[0].getMZ());
ids[pi_scan_i->first].setRT(experiment[pi_scan_i->second - 1].getRT());
}
}
}
void
InspectOutfile::compressTrieDB(
const String& database_filename,
const String& index_filename,
vector<Size>& wanted_records,
const String& snd_database_filename,
const String& snd_index_filename,
bool append)
{
if (database_filename == snd_database_filename)
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Same filename can not be used for original and second database!", database_filename);
}
if (index_filename == snd_index_filename)
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Same filename can not be used for original and second database!", index_filename);
}
ifstream database(database_filename.c_str());
if (!database)
{
if (!File::exists(database_filename))
{
throw Exception::FileNotFound(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, database_filename);
}
else if (!File::readable(database_filename))
{
throw Exception::FileNotReadable(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, database_filename);
}
else
{
throw Exception::IOException(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, database_filename);
}
}
ifstream index(index_filename.c_str(), ios::in | ios::binary);
if (!index)
{
database.close();
database.clear();
if (!File::exists(index_filename))
{
throw Exception::FileNotFound(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, index_filename);
}
else if (!File::readable(index_filename))
{
throw Exception::FileNotReadable(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, index_filename);
}
else
{
throw Exception::IOException(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, index_filename);
}
}
// determine the length of the index file
index.seekg(0, ios::end);
streampos index_length = index.tellg();
index.seekg(0, ios::beg);
bool empty_records = wanted_records.empty();
if (wanted_records.empty())
{
for (Size i = 0; i < index_length / record_length_; ++i)
wanted_records.push_back(i);
}
// take the wanted records, copy their sequences to the new db and write the index file accordingly
ofstream snd_database;
if (append)
{
snd_database.open(snd_database_filename.c_str(), std::ios::out | std::ios::app);
}
else
{
snd_database.open(snd_database_filename.c_str(), std::ios::out | std::ios::trunc);
}
if (!snd_database)
{
database.close();
database.clear();
index.close();
index.clear();
throw Exception::UnableToCreateFile(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, snd_database_filename);
}
ofstream snd_index;
if (append)
{
snd_index.open(snd_index_filename.c_str(), std::ios::out | std::ios::binary | std::ios::app);
}
else
{
snd_index.open(snd_index_filename.c_str(), std::ios::out | std::ios::binary | std::ios::trunc);
}
if (!snd_index)
{
database.close();
database.clear();
index.close();
index.clear();
snd_database.close();
snd_database.clear();
throw Exception::UnableToCreateFile(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, snd_index_filename);
}
char* index_record = new char[record_length_]; // to copy one record from the index file
Size database_pos(0), snd_database_pos(0); // their sizes HAVE TO BE 4 bytes
stringbuf sequence;
for (vector<Size>::const_iterator wr_i = wanted_records.begin(); wr_i != wanted_records.end(); ++wr_i)
{
// get the according record in the index file
if (index_length < Int((*wr_i + 1) * record_length_)) // if the file is too short
{
delete[] index_record;
database.close();
database.clear();
index.close();
index.clear();
snd_database.close();
snd_database.clear();
snd_index.close();
snd_index.clear();
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "index file is too short!", index_filename);
}
index.seekg((*wr_i) * record_length_);
index.read(index_record, record_length_);
// all but the first sequence are preceded by an asterisk
if (append)
{
snd_database.put(trie_delimiter_);
}
append = true;
// check if we have to reverse the database_pos part (which is saved in little endian)
if (OPENMS_IS_BIG_ENDIAN)
{
for (Size i = 0; i < trie_db_pos_length_ / 2; i++)
{
char tmp = index_record[db_pos_length_ + i];
index_record[db_pos_length_ + i] = index_record[db_pos_length_ + trie_db_pos_length_ - 1 - i];
index_record[db_pos_length_ + trie_db_pos_length_ - 1 - i] = tmp;
}
}
// go to the beginning of the sequence
// whoever wrote this code - please don't ever do this again.
// x86 does *not* have a monopoly, nor does little endian.
memcpy(&database_pos, index_record + db_pos_length_, trie_db_pos_length_);
database.seekg(database_pos);
// store the corresponding index for the second database
snd_database_pos = snd_database.tellp(); // get the position in the second database
memcpy(index_record + db_pos_length_, &snd_database_pos, trie_db_pos_length_); // and copy to its place in the index record
// fixing the above "suboptimal" code
if (OPENMS_IS_BIG_ENDIAN)
{
for (Size i = 0; i < trie_db_pos_length_ / 2; i++)
{
char tmp = index_record[db_pos_length_ + i];
index_record[db_pos_length_ + i] = index_record[db_pos_length_ + trie_db_pos_length_ - 1 - i];
index_record[db_pos_length_ + trie_db_pos_length_ - 1 - i] = tmp;
}
}
snd_index.write((char*) index_record, record_length_); // because only the trie-db position changed, not the position in the original database, nor the protein name
// store the sequence
database.get(sequence, trie_delimiter_);
snd_database << sequence.str();
sequence.str("");
}
if (empty_records)
{
wanted_records.clear();
}
delete[] index_record;
database.close();
database.clear();
index.close();
index.clear();
snd_database.close();
snd_database.clear();
snd_index.close();
snd_index.clear();
}
void InspectOutfile::generateTrieDB(
const String& source_database_filename,
const String& database_filename,
const String& index_filename,
bool append,
const String& species)
{
ifstream source_database(source_database_filename.c_str());
if (!source_database)
{
if (!File::exists(source_database_filename))
{
throw Exception::FileNotFound(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, source_database_filename);
}
else if (!File::readable(source_database_filename))
{
throw Exception::FileNotReadable(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, source_database_filename);
}
else
{
throw Exception::IOException(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, source_database_filename);
}
}
// get the labels
String ac_label, sequence_start_label, sequence_end_label, comment_label, species_label;
getLabels(source_database_filename, ac_label, sequence_start_label, sequence_end_label, comment_label, species_label);
ofstream database;
if (append)
{
database.open(database_filename.c_str(), ios::app | ios::out);
}
else
{
database.open(database_filename.c_str());
}
if (!database)
{
source_database.close();
source_database.clear();
throw Exception::UnableToCreateFile(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, database_filename);
}
ofstream index;
if (append)
{
index.open(index_filename.c_str(), ios::app | ios::out | ios::binary);
}
else
{
index.open(index_filename.c_str(), ios::out | ios::binary);
}
if (!index)
{
source_database.close();
source_database.clear();
database.close();
database.clear();
throw Exception::UnableToCreateFile(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, index_filename);
}
// using flags to mark what has already been read
// the flags
unsigned char ac_flag = 1;
unsigned char species_flag = !species.empty() * 2; // if no species is given, take all proteins
unsigned char sequence_flag = 4;
// the value
unsigned char record_flags = 0;
String::size_type pos(0); // the position in a line
unsigned long long source_database_pos = source_database.tellg(); // the start of a protein in the source database
unsigned long long source_database_pos_buffer = 0; // because you don't know whether a new protein starts unless the line is read, the actual position is buffered before any new getline
Size database_pos(0);
String line, sequence, protein_name;
char* record = new char[record_length_]; // a record in the index file
char* protein_name_pos = record + db_pos_length_ + trie_db_pos_length_;
while (getline(source_database, line))
{
if (!line.empty() && (line[line.length() - 1] < 33))
{
line.resize(line.length() - 1);
}
line.trim();
// empty and comment lines are skipped
if (line.empty() || line.hasPrefix(comment_label))
{
source_database_pos_buffer = source_database.tellg();
continue;
}
// read the sequence if the accession and the species have been read already
if (record_flags == (ac_flag | species_flag | sequence_flag))
{
if (!line.hasPrefix(sequence_end_label)) // if it is still the same protein, append the sequence
{
line.trim(); // erase all whitespaces from the sequence
line.remove(trie_delimiter_);
// save this part of the sequence
sequence.append(line);
}
else // if a new protein is found, write down the old one
{
// if the sequence is not empty, the record has the correct form
if (!sequence.empty())
{
// all but the first record in the database are preceded by an asterisk (if in append mode an asterisk has to be put at any time)
if (append)
{
database.put('*');
}
database_pos = database.tellp();
// write the record
memcpy(record, &source_database_pos, db_pos_length_); // source database position
if (OPENMS_IS_BIG_ENDIAN)
{
for (Size i = 0; i < db_pos_length_ / 2; i++)
{
char tmp = record[i];
record[i] = record[db_pos_length_ - 1 - i];
record[db_pos_length_ - 1 - i] = tmp;
}
}
// whoever wrote this code - please don't ever do this again.
// x86 does *not* have a monopoly, nor does little endian.
memcpy(record + db_pos_length_, &database_pos, trie_db_pos_length_); // database position
// fix the above "suboptimal" code
if (OPENMS_IS_BIG_ENDIAN)
{
for (Size i = 0; i < trie_db_pos_length_ / 2; i++)
{
char tmp = record[db_pos_length_ + i];
record[db_pos_length_ + i] = record[db_pos_length_ + trie_db_pos_length_ - 1 - i];
record[db_pos_length_ + trie_db_pos_length_ - 1 - i] = tmp;
}
}
index.write(record, record_length_);
// protein name / accession has already been written
database << sequence;
source_database_pos = source_database_pos_buffer; // the position of the start of the new protein
append = true;
}
sequence.clear();
// set back the record flags for a new record
record_flags = 0;
}
}
// if not reading the sequence
if (!(record_flags & sequence_flag))
{
if (line.hasPrefix(ac_label))
{
pos = ac_label.length(); // find the beginning of the accession
while ((line.length() > pos) && (line[pos] < 33))
++pos; // discard the whitespaces after the label
if (pos != line.length()) // if no accession is found, skip this protein
{
memset(protein_name_pos, 0, protein_name_length_); // clear the protein name
// read at most protein_name_length_ characters from the record name and write them to the record
protein_name = line.substr(pos, protein_name_length_);
protein_name.substitute('>', '}');
// cppcheck produces a false positive warning here -> ignore
// cppcheck-suppress redundant copy
memcpy(protein_name_pos, protein_name.c_str(), protein_name.length());
record_flags |= ac_flag; // set the ac flag
}
else
record_flags = 0;
}
// if a species line is found and an accession has already been found, check whether this record is from the wanted species, if not, skip it
if (species_flag && line.hasPrefix(species_label) && (record_flags == ac_flag))
{
pos = species_label.length();
if (line.find(species, pos) != String::npos)
{
record_flags |= species_flag;
}
else
{
record_flags = 0;
}
}
// if the beginning of the sequence is found and accession and correct species have been found
if (line.hasPrefix(sequence_start_label) && ((record_flags & (ac_flag | species_flag)) == (ac_flag | species_flag)))
{
record_flags |= sequence_flag;
}
}
source_database_pos_buffer = source_database.tellg();
}
// source file read
source_database.close();
source_database.clear();
// if the last record has no sequence end label, the sequence has to be appended nevertheless (e.g. FASTA)
if (record_flags == (ac_flag | species_flag | sequence_flag) && !sequence.empty())
{
// all but the first record in the database are preceded by an asterisk (if in append mode an asterisk has to be put at any time)
if (append)
{
database.put('*');
}
database_pos = database.tellp();
// write the record
// whoever wrote this code - please don't ever do this again.
// x86 does *not* have a monopoly, nor does little endian.
memcpy(record, &source_database_pos, db_pos_length_); // source database position
if (OPENMS_IS_BIG_ENDIAN)
{
for (Size i = 0; i < db_pos_length_ / 2; i++)
{
char tmp = record[i];
record[i] = record[db_pos_length_ - 1 - i];
record[db_pos_length_ - 1 - i] = tmp;
}
}
memcpy(record + db_pos_length_, &database_pos, trie_db_pos_length_); // database position
// fix the above "suboptimal" code
if (OPENMS_IS_BIG_ENDIAN)
{
for (Size i = 0; i < trie_db_pos_length_ / 2; i++)
{
char tmp = record[db_pos_length_ + i];
record[db_pos_length_ + i] = record[db_pos_length_ + trie_db_pos_length_ - 1 - i];
record[db_pos_length_ + trie_db_pos_length_ - 1 - i] = tmp;
}
}
index.write(record, record_length_);
// protein name / accession has already been written
database << sequence;
append = true;
}
delete[] record;
// close the filestreams
database.close();
database.clear();
index.close();
index.clear();
}
void InspectOutfile::getLabels(
const String& source_database_filename,
String& ac_label,
String& sequence_start_label,
String& sequence_end_label,
String& comment_label,
String& species_label)
{
ac_label = sequence_start_label = sequence_end_label = comment_label = species_label = "";
ifstream source_database(source_database_filename.c_str());
if (!source_database)
{
if (!File::exists(source_database_filename))
{
throw Exception::FileNotFound(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, source_database_filename);
}
else if (!File::readable(source_database_filename))
{
throw Exception::FileNotReadable(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, source_database_filename);
}
else
{
throw Exception::IOException(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, source_database_filename);
}
}
String line;
while (getline(source_database, line) && (sequence_start_label.empty()))
{
if (!line.empty() && (line[line.length() - 1] < 33))
{
line.resize(line.length() - 1);
}
if (line.trim().empty())
{
continue;
}
else if (line.hasPrefix(">"))
{
ac_label = ">";
sequence_start_label = ">";
sequence_end_label = ">";
comment_label = ";";
species_label = ">";
}
else if (line.hasPrefix("SQ"))
{
ac_label = "AC";
sequence_start_label = "SQ";
sequence_end_label = "//";
comment_label = "CC";
species_label = "OS";
}
}
source_database.close();
source_database.clear();
// if no known start separator is found
if (sequence_start_label.empty())
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "database has unknown file format (neither trie nor FASTA nor swissprot)", source_database_filename);
}
}
vector<Size> InspectOutfile::getWantedRecords(const String& result_filename, double p_value_threshold)
{
// check whether the p_value is correct
if ((p_value_threshold < 0) || (p_value_threshold > 1))
{
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "the parameters 'p_value_threshold' must be >= 0 and <=1 !");
}
ifstream result_file(result_filename.c_str());
if (!result_file)
{
if (!File::exists(result_filename))
{
throw Exception::FileNotFound(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, result_filename);
}
else if (!File::readable(result_filename))
{
throw Exception::FileNotReadable(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, result_filename);
}
else
{
throw Exception::IOException(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, result_filename);
}
}
String line;
vector<String> substrings;
set<Size> wanted_records_set;
vector<Size>
wanted_records,
corrupted_lines;
Size line_number(0);
// get the header
Int
spectrum_file_column(-1),
scan_column(-1),
peptide_column(-1),
protein_column(-1),
charge_column(-1),
MQ_score_column(-1),
p_value_column(-1),
record_number_column(-1),
DB_file_pos_column(-1),
spec_file_pos_column(-1);
Size number_of_columns(0);
if (!getline(result_file, line))
{
result_file.close();
result_file.clear();
throw Exception::FileEmpty(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, result_filename);
}
++line_number;
readOutHeader(result_filename, line, spectrum_file_column, scan_column, peptide_column, protein_column, charge_column, MQ_score_column, p_value_column, record_number_column, DB_file_pos_column, spec_file_pos_column, number_of_columns);
while (getline(result_file, line))
{
++line_number;
if (!line.empty() && (line[line.length() - 1] < 33))
{
line.resize(line.length() - 1);
}
line.trim();
if (line.empty())
{
continue;
}
line.split('\t', substrings);
// check whether the line has enough columns
if (substrings.size() != number_of_columns)
{
corrupted_lines.push_back(line_number);
continue;
}
// check whether the line has enough columns
if (substrings.size() != number_of_columns)
{
continue;
}
// take only those peptides whose p-value is less or equal the given threshold
if (substrings[p_value_column].toFloat() > p_value_threshold)
{
continue;
}
wanted_records_set.insert(substrings[record_number_column].toInt());
}
result_file.close();
result_file.clear();
for (set<Size>::const_iterator rn_i = wanted_records_set.begin(); rn_i != wanted_records_set.end(); ++rn_i)
{
wanted_records.push_back(*rn_i);
}
return wanted_records;
}
bool
InspectOutfile::getSearchEngineAndVersion(
const String& cmd_output,
ProteinIdentification& protein_identification)
{
protein_identification.setSearchEngine("InsPecT");
protein_identification.setSearchEngineVersion("unknown");
// searching for something like this: InsPecT version 20060907, InsPecT version 20100331
QString response(cmd_output.toQString());
QRegularExpression rx("InsPecT (version|vesrion) (\\d+)"); // older versions of InsPecT have typo...
auto match = rx.match(response);
if (!match.hasMatch())
{
return false;
}
protein_identification.setSearchEngineVersion(match.captured(2));
return true;
}
void
InspectOutfile::readOutHeader(
const String& filename,
const String& header_line,
Int& spectrum_file_column,
Int& scan_column,
Int& peptide_column,
Int& protein_column,
Int& charge_column,
Int& MQ_score_column,
Int& p_value_column,
Int& record_number_column,
Int& DB_file_pos_column,
Int& spec_file_pos_column,
Size& number_of_columns)
{
spectrum_file_column = scan_column = peptide_column = protein_column = charge_column = MQ_score_column = p_value_column = record_number_column = DB_file_pos_column = spec_file_pos_column = -1;
vector<String> substrings;
header_line.split('\t', substrings);
// #SpectrumFile Scan# Annotation Protein Charge MQScore Length TotalPRMScore MedianPRMScore FractionY FractionB Intensity NTT p-value F-Score DeltaScore DeltaScoreOther RecordNumber DBFilePos SpecFilePos
for (vector<String>::const_iterator s_i = substrings.begin(); s_i != substrings.end(); ++s_i)
{
if ((*s_i) == "#SpectrumFile")
{
spectrum_file_column = s_i - substrings.begin();
}
else if ((*s_i) == "Scan#")
{
scan_column = s_i - substrings.begin();
}
else if ((*s_i) == "Annotation")
{
peptide_column = s_i - substrings.begin();
}
else if ((*s_i) == "Protein")
{
protein_column = s_i - substrings.begin();
}
else if ((*s_i) == "Charge")
{
charge_column = s_i - substrings.begin();
}
else if ((*s_i) == "MQScore")
{
MQ_score_column = s_i - substrings.begin();
}
else if ((*s_i) == "p-value")
{
p_value_column = s_i - substrings.begin();
}
else if ((*s_i) == "RecordNumber")
{
record_number_column = s_i - substrings.begin();
}
else if ((*s_i) == "DBFilePos")
{
DB_file_pos_column = s_i - substrings.begin();
}
else if ((*s_i) == "SpecFilePos")
{
spec_file_pos_column = s_i - substrings.begin();
}
}
if ((spectrum_file_column == -1) || (scan_column == -1) || (peptide_column == -1) || (protein_column == -1) || (charge_column == -1) || (MQ_score_column == -1) || (p_value_column == -1) || (record_number_column == -1) || (DB_file_pos_column == -1) || (spec_file_pos_column == -1))
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "at least one of the columns '#SpectrumFile', 'Scan#', 'Annotation', 'Protein', 'Charge', 'MQScore', 'p-value', 'RecordNumber', 'DBFilePos' or 'SpecFilePos' is missing!", filename);
}
number_of_columns = substrings.size();
}
const Size InspectOutfile::db_pos_length_ = 8;
const Size InspectOutfile::trie_db_pos_length_ = 4;
const Size InspectOutfile::protein_name_length_ = 80;
const Size InspectOutfile::record_length_ = db_pos_length_ + trie_db_pos_length_ + protein_name_length_;
const char InspectOutfile::trie_delimiter_ = '*';
const String InspectOutfile::score_type_ = "Inspect";
} //namespace OpenMS
#ifdef __clang__
#pragma clang diagnostic pop
#endif
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/OSWFile.cpp | .cpp | 23,936 | 659 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: George Rosenberger $
// $Authors: George Rosenberger $
// --------------------------------------------------------------------------
#include <OpenMS/FORMAT/OSWFile.h>
#include <OpenMS/DATASTRUCTURES/StringListUtils.h>
#include <sqlite3.h>
#include <cstring> // for strcmp
#include <sstream>
#include <utility> // for std::move
namespace OpenMS
{
namespace Sql = Internal::SqliteHelper;
using namespace std;
const std::array<std::string, (Size)OSWFile::OSWLevel::SIZE_OF_OSWLEVEL> OSWFile::names_of_oswlevel = { "ms1", "ms2", "transition" };
void OSWFile::readToPIN(const std::string& in_osw,
const OSWLevel osw_level,
std::ostream& pin_output,
const double ipf_max_peakgroup_pep,
const double ipf_max_transition_isotope_overlap,
const double ipf_min_transition_sn)
{
sqlite3_stmt * stmt;
std::string select_sql;
// Open database
SqliteConnector conn(in_osw);
if (osw_level == OSWLevel::MS1)
{
select_sql = "SELECT *, RUN_ID || '_' || PRECURSOR.ID AS GROUP_ID " \
"FROM FEATURE_MS1 "\
"INNER JOIN (SELECT ID, PRECURSOR_ID, RUN_ID FROM FEATURE) AS FEATURE ON FEATURE_ID = FEATURE.ID "\
"INNER JOIN (SELECT ID, DECOY FROM PRECURSOR) AS PRECURSOR ON FEATURE.PRECURSOR_ID = PRECURSOR.ID "\
"INNER JOIN PRECURSOR_PEPTIDE_MAPPING ON PRECURSOR.ID = PRECURSOR_PEPTIDE_MAPPING.PRECURSOR_ID "\
"INNER JOIN (SELECT ID, MODIFIED_SEQUENCE FROM PEPTIDE) AS PEPTIDE ON "\
"PRECURSOR_PEPTIDE_MAPPING.PEPTIDE_ID = PEPTIDE.ID;";
}
else if (osw_level == OSWLevel::TRANSITION)
{
select_sql = "SELECT TRANSITION.DECOY AS DECOY, FEATURE_TRANSITION.*, "\
"RUN_ID || '_' || FEATURE_TRANSITION.FEATURE_ID || '_' || PRECURSOR_ID || '_' || TRANSITION_ID AS GROUP_ID, "\
"FEATURE_TRANSITION.FEATURE_ID || '_' || FEATURE_TRANSITION.TRANSITION_ID AS FEATURE_ID, "\
"'PEPTIDE' AS MODIFIED_SEQUENCE FROM FEATURE_TRANSITION "\
"INNER JOIN (SELECT RUN_ID, ID, PRECURSOR_ID FROM FEATURE) AS FEATURE ON FEATURE_TRANSITION.FEATURE_ID = FEATURE.ID " \
"INNER JOIN PRECURSOR ON FEATURE.PRECURSOR_ID = PRECURSOR.ID "\
"INNER JOIN SCORE_MS2 ON FEATURE.ID = SCORE_MS2.FEATURE_ID "\
"INNER JOIN (SELECT ID, DECOY FROM TRANSITION) AS TRANSITION ON FEATURE_TRANSITION.TRANSITION_ID = TRANSITION.ID "\
"WHERE PEP <= " + OpenMS::String(ipf_max_peakgroup_pep) +
" AND VAR_ISOTOPE_OVERLAP_SCORE <= " + OpenMS::String(ipf_max_transition_isotope_overlap) +
" AND VAR_LOG_SN_SCORE > " + OpenMS::String(ipf_min_transition_sn) +
" AND PRECURSOR.DECOY == 0 ORDER BY FEATURE_ID, PRECURSOR_ID, TRANSITION_ID;";
}
else
{
// Peak group-level query including peptide sequence
select_sql = "SELECT *, RUN_ID || '_' || PRECURSOR.ID AS GROUP_ID "\
"FROM FEATURE_MS2 "\
"INNER JOIN (SELECT ID, PRECURSOR_ID, RUN_ID FROM FEATURE) AS FEATURE ON FEATURE_ID = FEATURE.ID "\
"INNER JOIN (SELECT ID, DECOY FROM PRECURSOR) AS PRECURSOR ON FEATURE.PRECURSOR_ID = PRECURSOR.ID "\
"INNER JOIN PRECURSOR_PEPTIDE_MAPPING ON PRECURSOR.ID = PRECURSOR_PEPTIDE_MAPPING.PRECURSOR_ID "\
"INNER JOIN (SELECT ID, MODIFIED_SEQUENCE FROM PEPTIDE) AS PEPTIDE ON PRECURSOR_PEPTIDE_MAPPING.PEPTIDE_ID = PEPTIDE.ID;";
}
// Execute SQL select statement
conn.prepareStatement(&stmt, select_sql);
sqlite3_step(stmt);
int cols = sqlite3_column_count(stmt);
// Generate features
int k = 0;
std::vector<std::string> group_id_index;
OpenMS::String tmp;
while (sqlite3_column_type( stmt, 0 ) != SQLITE_NULL)
{
std::string psm_id;
size_t scan_id = 0;
int label = 0;
std::string peptide;
std::map<std::string, double> features;
for (int i = 0; i < cols; i++)
{
if (strcmp(sqlite3_column_name(stmt, i), "FEATURE_ID") == 0)
{
Sql::extractValue<string>(&psm_id, stmt, i);
}
if (strcmp(sqlite3_column_name(stmt, i), "GROUP_ID") == 0)
{
std::string group_id(reinterpret_cast<const char*>(sqlite3_column_text(stmt, i)));
auto it = std::find(group_id_index.begin(), group_id_index.end(), group_id);
if (it != group_id_index.end())
{
scan_id = it - group_id_index.begin();
}
else
{
scan_id = group_id_index.size();
group_id_index.emplace_back(group_id);
}
}
if (strcmp(sqlite3_column_name(stmt, i), "DECOY") == 0)
{
if (sqlite3_column_int( stmt, i ) == 1)
{
label = -1;
}
else
{
label = 1;
}
}
if (strcmp(sqlite3_column_name( stmt, i ), "MODIFIED_SEQUENCE") == 0)
{
Sql::extractValue<string>(&peptide, stmt, i);
}
if (strncmp(sqlite3_column_name( stmt, i ), "VAR_", 4) == 0)
{
features[OpenMS::String(sqlite3_column_name( stmt, i ))] = sqlite3_column_double( stmt, i );
}
}
// Write output
if (k == 0)
{
pin_output << "PSMId\tLabel\tScanNr";
for (auto const &feat : features)
{
pin_output << "\t" << feat.first;
}
pin_output << "\tPeptide\tProteins\n";
}
pin_output << psm_id << "\t" << label << "\t" << scan_id;
for (auto const &feat : features)
{
pin_output << "\t" << feat.second;
}
pin_output << "\t." << peptide << ".\tProt1" << "\n";
sqlite3_step( stmt );
k++;
}
sqlite3_finalize(stmt);
if (k==0)
{
if (osw_level == OSWLevel::TRANSITION)
{
throw Exception::Precondition(__FILE__, __LINE__, __FUNCTION__,
OpenMS::String("PercolatorAdapter needs to be applied on MS1 & MS2 levels before conducting transition-level scoring."));
}
else
{
throw Exception::FileEmpty(__FILE__, __LINE__, __FUNCTION__, in_osw);
}
}
}
void OSWFile::writeFromPercolator(const std::string& in_osw,
const OSWFile::OSWLevel osw_level,
const std::map< std::string, PercolatorFeature >& features)
{
std::string table;
std::string create_sql;
if (osw_level == OSWLevel::MS1)
{
table = "SCORE_MS1";
create_sql = "DROP TABLE IF EXISTS " + table + "; " \
"CREATE TABLE " + table + "(" \
"FEATURE_ID INT NOT NULL," \
"SCORE DOUBLE NOT NULL," \
"QVALUE DOUBLE NOT NULL," \
"PEP DOUBLE NOT NULL);";
}
else if (osw_level == OSWLevel::TRANSITION)
{
table = "SCORE_TRANSITION";
create_sql = "DROP TABLE IF EXISTS " + table + "; " \
"CREATE TABLE " + table + "(" \
"FEATURE_ID INT NOT NULL," \
"TRANSITION_ID INT NOT NULL," \
"SCORE DOUBLE NOT NULL," \
"QVALUE DOUBLE NOT NULL," \
"PEP DOUBLE NOT NULL);";
}
else
{
table = "SCORE_MS2";
create_sql = "DROP TABLE IF EXISTS " + table + "; " \
"CREATE TABLE " + table + "(" \
"FEATURE_ID INT NOT NULL," \
"SCORE DOUBLE NOT NULL," \
"QVALUE DOUBLE NOT NULL," \
"PEP DOUBLE NOT NULL);";
}
std::vector<std::string> insert_sqls;
for (auto const &feat : features)
{
std::stringstream insert_sql;
insert_sql << "INSERT INTO " << table;
if (osw_level == OSWLevel::TRANSITION)
{
std::vector<String> ids;
String(feat.first).split("_", ids);
insert_sql << " (FEATURE_ID, TRANSITION_ID, SCORE, QVALUE, PEP) VALUES (";
insert_sql << ids[0] << ",";
insert_sql << ids[1] << ",";
}
else
{
insert_sql << " (FEATURE_ID, SCORE, QVALUE, PEP) VALUES (";
insert_sql << feat.first << ",";
}
insert_sql << feat.second.score << ",";
insert_sql << feat.second.qvalue << ",";
insert_sql << feat.second.posterior_error_prob << "); ";
insert_sqls.push_back(insert_sql.str());
}
// Write to Sqlite database
SqliteConnector conn(in_osw);
conn.executeStatement(create_sql);
conn.executeStatement("BEGIN TRANSACTION");
for (size_t i = 0; i < insert_sqls.size(); i++)
{
conn.executeStatement(insert_sqls[i]);
}
conn.executeStatement("END TRANSACTION");
}
OSWFile::OSWFile(const String& filename)
: filename_(filename),
conn_(filename, SqliteConnector::SqlOpenMode::READONLY)
{
has_SCOREMS2_ = conn_.tableExists("SCORE_MS2");
}
void OSWFile::readMinimal(OSWData& swath_result)
{
readMeta_(swath_result);
readTransitions_(swath_result);
String select_sql = "select PROTEIN.ID as prot_id, PROTEIN_ACCESSION as prot_accession from PROTEIN order by prot_id";
sqlite3_stmt* stmt;
conn_.prepareStatement(&stmt, select_sql);
enum CBIG
{ // indices of respective columns in the query above
I_PROTID,
I_ACCESSION,
SIZE_OF_CBIG
};
Sql::SqlState rc = Sql::nextRow(stmt);
if (sqlite3_column_count(stmt) != SIZE_OF_CBIG)
{
throw Exception::SqlOperationFailed(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Query was changed! Please report this bug!");
}
String accession;
// protein loop
while (rc == Sql::SqlState::SQL_ROW)
{
int id = Sql::extractInt(stmt, I_PROTID);
accession = Sql::extractString(stmt, I_ACCESSION);
swath_result.addProtein(OSWProtein(std::move(accession), id, {}));
rc = Sql::nextRow(stmt, rc); // next row
}
sqlite3_finalize(stmt);
}
/**
@brief populates the @p index'th protein with Peptides, unless the protein already has peptides
Internally uses the proteins ID to search for cross referencing peptides and transitions in the OSW file.
@throws Exception::InvalidValue if the ID is unknown
*/
void OSWFile::readProtein(OSWData& swath_result, const Size index)
{
if (!swath_result.getProteins()[index].getPeptidePrecursors().empty())
{ // already populated
return;
}
getFullProteins_(swath_result, index);
if (swath_result.getProteins()[index].getPeptidePrecursors().empty())
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "ID is not known in OSWFile " + filename_, String(swath_result.getProteins()[index].getID()));
}
}
void OSWFile::read(OSWData& swath_result)
{
readMeta_(swath_result);
readTransitions_(swath_result);
getFullProteins_(swath_result);
}
enum ColProteinSelect
{ // indices of respective columns in the query below
I_PROTID,
I_ACCESSION,
I_DECOY,
I_MODSEQ,
I_PRECID,
I_PRECMZ,
I_PRECQ,
I_FEATID,
I_EXPRT,
I_DELTART,
I_RTLEFT,
I_RTRIGHT,
I_TRID,
I_QVALUE,
SIZE_OF_ColProteinSelect
};
/// represents the state of an SQL row, which is
/// updated partially whenever nested structures change
struct LineState
{
// Layers of information. Whenever the id changes, we know a new item has begun
// ... PROTEIN
int prot_id;
String accession;
bool decoy;
void setProt(sqlite3_stmt* stmt)
{
prot_id = Sql::extractInt(stmt, I_PROTID);
accession = Sql::extractString(stmt, I_ACCESSION);
decoy = Sql::extractBool(stmt, I_DECOY);
}
void updateProt(LineState& new_line)
{
prot_id = new_line.prot_id;
accession = std::move(new_line.accession);
decoy = new_line.decoy;
}
// ... PRECURSOR
int prec_id;
String seq;
short chargePC;
float precmz;
void setPC(sqlite3_stmt* stmt)
{
prec_id = Sql::extractInt(stmt, I_PRECID);
seq = Sql::extractString(stmt, I_MODSEQ);
chargePC = (short)Sql::extractInt(stmt, I_PRECQ);
precmz = Sql::extractFloat(stmt, I_PRECMZ);
}
void updatePC(LineState& new_line)
{
prec_id = new_line.prec_id;
seq = std::move(new_line.seq);
chargePC = new_line.chargePC;
precmz = new_line.precmz;
}
// ... FEATURE
Int64 feat_id; // in SQL, feature_id is a 63-bit integer...
float rt_exp;
float rt_lw;
float rt_rw;
float rt_delta;
float qvalue;
void setFeature(sqlite3_stmt* stmt)
{
feat_id = Sql::extractInt64(stmt, I_FEATID);
rt_exp = Sql::extractFloat(stmt, I_EXPRT);
rt_lw = Sql::extractFloat(stmt, I_RTLEFT);
rt_rw = Sql::extractFloat(stmt, I_RTRIGHT);
rt_delta = Sql::extractFloat(stmt, I_DELTART);
qvalue = Sql::extractFloat(stmt, I_QVALUE);
}
void updateFeat(const LineState& new_line)
{
feat_id = new_line.feat_id;
rt_exp = new_line.rt_exp;
rt_lw = new_line.rt_lw;
rt_rw = new_line.rt_rw;
rt_delta = new_line.rt_delta;
qvalue = new_line.qvalue;
}
};
void initLine(LineState& current, sqlite3_stmt* stmt)
{
current.setProt(stmt);
current.setPC(stmt);
current.setFeature(stmt);
}
bool nextProtein(OSWProtein& prot, sqlite3_stmt* stmt, Sql::SqlState& rc, LineState& old_line)
{
LineState new_line;
// PROTEIN
std::vector<OSWPeptidePrecursor> precursors;
OSWPeptidePrecursor new_pc;
auto check_add_protein = [&](bool add_force = false)
{
precursors.push_back(new_pc); // the last PC already belonged to the old protein
if (old_line.prot_id != new_line.prot_id || add_force)
{
prot = OSWProtein(old_line.accession, old_line.prot_id, std::move(precursors));
old_line.updateProt(new_line);
precursors.clear();
return true;
}
return false;
};
// ... PRECURSOR
std::vector<OSWPeakGroup> features;
OSWPeakGroup new_feature;
auto check_add_pc = [&](bool add_force = false)
{
features.push_back(std::move(new_feature)); // the last feature belonged to the old PC
if (old_line.prec_id != new_line.prec_id || add_force)
{
new_pc = OSWPeptidePrecursor(old_line.seq, old_line.chargePC, old_line.decoy, old_line.precmz, std::move(features));
old_line.updatePC(new_line);
features.clear();
return true;
}
return false;
};
// ... FEATURE
std::vector<UInt32> transition_ids;
UInt32 new_transition;
auto check_add_feat = [&](bool add_force = false)
{
if (old_line.feat_id != new_line.feat_id || add_force)
{
new_feature = OSWPeakGroup(old_line.rt_exp, old_line.rt_lw, old_line.rt_rw, old_line.rt_delta, std::move(transition_ids), old_line.qvalue);
old_line.updateFeat(new_line);
transition_ids.clear();
return true;
}
else
{ // if we enter the above block, we will parse the same sql row in the next iteration, so only add the tr-ID if its not a new block
transition_ids.push_back(new_transition); // the current transition belongs to the current feature...
}
return false;
};
// protein loop
while (rc == Sql::SqlState::SQL_ROW)
{
// precursor loop (peptide with charge)
while (rc == Sql::SqlState::SQL_ROW)
{
// feature loop
while (rc == Sql::SqlState::SQL_ROW)
{
new_transition = Sql::extractInt(stmt, I_TRID);
new_line.setFeature(stmt);
if (check_add_feat())
{
break; // new feature just started?--> check if new PC started as well.
}
rc = Sql::nextRow(stmt, rc); // next row
}
if (rc != Sql::SqlState::SQL_ROW) {
// we are beyond last row; new feature is not yet made; so we forcibly do it now
check_add_feat(true); // add last feature
check_add_pc(true); // add last precursor
check_add_protein(true); // add last protein
return false; // this was the last protein
}
new_line.setPC(stmt);
if (check_add_pc())
{
break; // new PC just started?--> check if if new protein started as well.
}
}
new_line.setProt(stmt);
if (check_add_protein())
{
return true; // current protein ended... but there are more..
}
}
// we did not even enter the while-loops... so no data was there (but should have been)
throw Exception::SqlOperationFailed(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "No rows available. Please report this as a bug!");
}
void OSWFile::getFullProteins_(OSWData& swath_result, Size index)
{
String protein_subselect;
if (index == ALL_PROTEINS)
{
swath_result.clearProteins();
protein_subselect = "PROTEIN";
}
else
{ // do not use accession to filter -- its as slow as full query
protein_subselect = "(select * from PROTEIN where ID = " + String(swath_result.getProteins().at(index).getID()) + ") as PROTEIN";
}
// check of SCORE_MS2 table is available (for OSW files which underwent pyProphet)
// set q_value to -1 if missing
String MS2_select = (has_SCOREMS2_ ? "SCORE_MS2.QVALUE as qvalue" : "-1 as qvalue");
String MS2_join = (has_SCOREMS2_ ? "inner join(select * from SCORE_MS2) as SCORE_MS2 on SCORE_MS2.FEATURE_ID = FEATURE.ID" : "");
// assemble the protein-PeptidePrecursor-Feature hierarchy
// note: when changing the query, make sure to keep the indices in ColProteinSelect in sync!!!
String select_sql = "select PROTEIN.ID as prot_id, PROTEIN_ACCESSION as prot_accession, PROTEIN.DECOY as decoy, "
" PEPTIDE.MODIFIED_SEQUENCE as modified_sequence,"
" PRECURSOR.ID as prec_id, PRECURSOR.PRECURSOR_MZ as pc_mz, PRECURSOR.CHARGE as pc_charge,"
" FEATURE.ID as feat_id, FEATURE.EXP_RT as rt_experimental, FEATURE.DELTA_RT as rt_delta, FEATURE.LEFT_WIDTH as rt_left_width, FEATURE.RIGHT_WIDTH as rt_right_width,"
" FeatTrMap.TRANSITION_ID as tr_id, " +
MS2_select +
" FROM " + protein_subselect +
" inner join(select* FROM PEPTIDE_PROTEIN_MAPPING) as PepProtMap on PepProtMap.PROTEIN_ID = PROTEIN.ID "
" inner join(select ID, MODIFIED_SEQUENCE FROM PEPTIDE) as PEPTIDE on PEPTIDE.ID = PepProtMap.PEPTIDE_ID "
" inner join(select * FROM PRECURSOR_PEPTIDE_MAPPING) as PrePepMap on PrePepMap.PEPTIDE_ID = PEPTIDE.ID "
" inner join(select * from PRECURSOR) as PRECURSOR on PRECURSOR.ID = PrePepMap.PRECURSOR_ID "
" inner join(select * from FEATURE) as FEATURE on FEATURE.PRECURSOR_ID = PRECURSOR.ID "
" inner join(select * from FEATURE_TRANSITION) as FeatTrMap on FeatTrMap.FEATURE_ID = FEATURE.ID " +
MS2_join +
" order by prot_id, prec_id, feat_id, qvalue, tr_id ";
sqlite3_stmt* stmt;
conn_.prepareStatement(&stmt, select_sql);
Sql::SqlState rc = Sql::nextRow(stmt);
if (sqlite3_column_count(stmt) != SIZE_OF_ColProteinSelect)
{
throw Exception::SqlOperationFailed(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Query was changed! Please report this bug!");
}
if (rc == Sql::SqlState::SQL_DONE)
{ // no data
return;
}
LineState current_line;
initLine(current_line, stmt);
OSWProtein prot;
if (index == ALL_PROTEINS)
{
bool has_more;
do
{
has_more = nextProtein(prot, stmt, rc, current_line);
swath_result.addProtein(std::move(prot));
} while (has_more);
}
else // single protein
{
nextProtein(prot, stmt, rc, current_line);
swath_result.setProtein(index, std::move(prot));
}
sqlite3_finalize(stmt);
}
void OSWFile::readMeta_(OSWData& data)
{
data.setSqlSourceFile(filename_);
data.setRunID(getRunID());
}
UInt64 OSWFile::getRunID() const
{
SqliteConnector conn(filename_);
Size nr_results = 0;
std::string select_sql = "SELECT RUN.ID FROM RUN;";
sqlite3_stmt* stmt;
conn.prepareStatement(&stmt, select_sql);
Sql::SqlState state = Sql::SqlState::SQL_ROW;
UInt64 id;
while ((state = Sql::nextRow(stmt, state)) == Sql::SqlState::SQL_ROW)
{
++nr_results;
id = Sql::extractInt64(stmt, 0);
}
// free memory
sqlite3_finalize(stmt);
if (nr_results != 1)
{
throw Exception::SqlOperationFailed(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "File '" + filename_ + "' contains more than one run. This is currently not supported!");
}
return id;
}
void OSWFile::readTransitions_(OSWData& swath_result)
{
swath_result.clear();
Size count = conn_.countTableRows("RUN");
if (count != 1)
{
throw Exception::Precondition(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Database '" + filename_ + "' contains more than one RUN. This is currently not supported!");
}
// Grab transitions first
// We do this separately, because the full sql query below will show transitions in duplicates, because many features might use the same XIC at different positions
const StringList colnames_tr = { "ID", "PRODUCT_MZ", "TYPE", "DECOY", "ANNOTATION" };
enum COLIDs
{
ID,
PRODUCT_MZ,
TYPE,
DECOY,
ANNOTATION
};
// does not make the query below any faster...
//conn.executeStatement("ANALYZE");
String select_transitions = "SELECT " + ListUtils::concatenate(colnames_tr, ",") + " FROM TRANSITION ORDER BY ID;";
sqlite3_stmt* stmt;
conn_.prepareStatement(&stmt, select_transitions);
Sql::SqlState rc = Sql::nextRow(stmt);
while (rc == Sql::SqlState::SQL_ROW)
{
OSWTransition tr(Sql::extractString(stmt, COLIDs::ANNOTATION),
Sql::extractInt(stmt, COLIDs::ID),
Sql::extractFloat(stmt, COLIDs::PRODUCT_MZ),
Sql::extractChar(stmt, COLIDs::TYPE),
Sql::extractInt(stmt, COLIDs::DECOY));
swath_result.addTransition(std::move(tr));
rc = Sql::nextRow(stmt);
}
sqlite3_finalize(stmt);
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/MSPFile.cpp | .cpp | 17,921 | 491 | // 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/MSPFile.h>
#include <OpenMS/FORMAT/FileHandler.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/METADATA/AnnotatedMSRun.h>
#include <OpenMS/SYSTEM/File.h>
#include <fstream>
#include <regex>
#include <map>
using namespace std;
namespace OpenMS
{
MSPFile::MSPFile() :
DefaultParamHandler("MSPFile")
{
defaults_.setValue("parse_headers", "false", "Flag whether header information should be parsed an stored for each spectrum");
vector<std::string> parse_strings{"true","false"};
defaults_.setValidStrings("parse_headers", parse_strings);
defaults_.setValue("parse_peakinfo", "true", "Flag whether the peak annotation information should be parsed and stored for each peak");
defaults_.setValidStrings("parse_peakinfo", parse_strings);
defaults_.setValue("parse_firstpeakinfo_only", "true", "Flag whether only the first or all peak annotation information should be parsed and stored for each peak.");
defaults_.setValidStrings("parse_firstpeakinfo_only", parse_strings);
defaults_.setValue("instrument", "", "If instrument given, only spectra of these type of instrument (Inst= in header) are parsed");
defaults_.setValidStrings("instrument", {"","it","qtof","toftof"});
defaultsToParam_();
}
MSPFile::MSPFile(const MSPFile & rhs) = default;
MSPFile & MSPFile::operator=(const MSPFile & rhs)
{
if (this != &rhs)
{
DefaultParamHandler::operator=(rhs);
}
return *this;
}
MSPFile::~MSPFile() = default;
void MSPFile::load(const String & filename, PeptideIdentificationList & ids, PeakMap & exp)
{
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);
}
// groups everything inside the shortest pair of parentheses
const std::regex rex(R"(\((.*?)\))");
// matches 2+ whitespaces or tabs or returns " ", "\t", "\r"
// Note: this is a hack because one of the encountered formats has single whitespaces in quotes.
// TODO choose a format during construction of the class. If we actually knew how to call and define them.
const std::regex ws_rex(R"(\s{2,}|\t|\r)");
exp.reset();
//set DocumentIdentifier
exp.setLoadedFileType(filename);
exp.setLoadedFilePath(filename);
String line;
ifstream is(filename.c_str());
std::map<String, String> modname_to_unimod;
modname_to_unimod["Pyro-glu"] = "Gln->pyro-Glu";
modname_to_unimod["CAM"] = "Carbamidomethyl";
modname_to_unimod["AB_old_ICATd8"] = "ICAT-D:2H(8)";
modname_to_unimod["AB_old_ICATd0"] = "ICAT-D";
bool parse_headers(param_.getValue("parse_headers").toBool());
bool parse_peakinfo(param_.getValue("parse_peakinfo").toBool());
bool parse_firstpeakinfo_only(param_.getValue("parse_firstpeakinfo_only").toBool());
std::string instrument((std::string)param_.getValue("instrument"));
bool inst_type_correct(true);
[[maybe_unused]] bool spectrast_format(false); // TODO: implement usage
Size spectrum_number = 0;
PeakSpectrum spec;
// line number counter
Size line_number = 0;
while (getline(is, line))
{
++line_number;
if (line.hasPrefix("Name:"))
{
vector<String> split, split2;
line.split(' ', split);
split[1].split('/', split2);
String peptide = split2[0];
// in newer NIST versions, the charge is followed by the modification(s) e.g. "_1(0,A,Acetyl)"
vector<String> split3;
split2[1].split('_', split3);
Int charge = split3[0].toInt();
// remove modifications inside the peptide string, since it is also defined in 'Mods=' comment
peptide = std::regex_replace(peptide, rex, "");
PeptideIdentification id;
id.insertHit(PeptideHit(0, 0, charge, AASequence::fromString(peptide)));
ids.push_back(id);
inst_type_correct = true;
}
else if (line.hasPrefix("MW:"))
{
vector<String> split;
line.split(' ', split);
if (split.size() == 2)
{
UInt charge = ids.back().getHits().begin()->getCharge();
spec.getPrecursors().resize(1);
spec.getPrecursors()[0].setMZ((split[1].toDouble() + (double)charge * Constants::PROTON_MASS_U) / (double)charge);
}
}
else if (line.hasPrefix("Comment:"))
{
// slow, but we need the modifications from the header and the instrument type
vector<String> split;
line.split(' ', split);
for (vector<String>::const_iterator it = split.begin(); it != split.end(); ++it)
{
if (!inst_type_correct)
{
break;
}
if (!instrument.empty() && it->hasPrefix("Inst="))
{
String inst_type = it->suffix('=');
if (instrument != inst_type)
{
inst_type_correct = false;
ids.erase(--ids.end());
}
break;
}
if (it->hasPrefix("Mods=") && *it != "Mods=0")
{
String mods = it->suffix('=');
// e.g. Mods=2/7,K,Carbamyl/22,K,Carbamyl
vector<String> mod_split;
mods.split('/', mod_split);
if (mod_split.size() <= 1) // e.g. Mods=2(0,A,Acetyl)(11,M,Oxidation)
{
mod_split.clear();
mod_split.emplace_back(mods.prefix('('));
Size sz = mod_split[0].toInt();
std::smatch sm;
std::string::const_iterator cit = mods.cbegin();
// go through all pairs of parentheses
while (std::regex_search(cit, mods.cend(), sm, rex) && mod_split.size()-1 <= sz)
{
if (sm.size() == 2) // 2 = match
{
mod_split.emplace_back(sm[1].str());
}
// set cit to after match
cit = sm[0].second;
}
}
AASequence peptide = ids.back().getHits().begin()->getSequence();
for (Size i = 1; i <= (UInt)mod_split[0].toInt(); ++i)
{
vector<String> single_mod;
mod_split[i].split(',', single_mod);
String mod_name = single_mod[2];
if (modname_to_unimod.find(mod_name) != modname_to_unimod.end())
{
mod_name = modname_to_unimod[mod_name];
}
String origin = single_mod[1];
Size position = single_mod[0].toInt();
//cerr << "MSP modification: " << origin << " " << mod_name << " " << position << "\n";
if (position > 0 && position < peptide.size() - 1)
{
peptide.setModification(position, mod_name);
}
else if (position == 0)
{
// we must decide whether this can be a terminal mod
try
{
peptide.setNTerminalModification(mod_name);
}
catch (Exception::ElementNotFound& /*e*/)
{
peptide.setModification(position, mod_name);
}
}
else if (position == peptide.size() - 1)
{
// we must decide whether this can be a terminal mod
try
{
peptide.setCTerminalModification(mod_name);
}
catch (Exception::ElementNotFound& /*e*/)
{
peptide.setModification(position, mod_name);
}
}
else
{
cerr << "MSPFile: Error: ignoring modification: '" << line << "' in line " << line_number << "\n";
}
}
vector<PeptideHit> hits(ids.back().getHits());
hits.begin()->setSequence(peptide);
ids.back().setHits(hits);
}
}
if (parse_headers && inst_type_correct)
{
parseHeader_(line, spec);
}
}
else if (line.hasPrefix("Num peaks:") || line.hasPrefix("NumPeaks:"))
{
if (line.hasPrefix("NumPeaks:"))
{
spectrast_format = true;
}
if (!inst_type_correct)
{
while (getline(is, line) && ++line_number && !line.empty() && isdigit(line[0]))
{
}
}
else
{
PeptideHit& hitToAnnotate = ids.back().getHits()[0];
vector<PeptideHit::PeakAnnotation> annots;
while (getline(is, line) && ++line_number && !line.empty() && isdigit(line[0]))
{
std::sregex_token_iterator iter(line.begin(),
line.end(),
ws_rex,
-1);
std::sregex_token_iterator end;
if (iter == end)
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
line, R"(not <mz><tab/spaces><intensity><tab/spaces>"<annotation>"<tab/spaces>"<comment>" in line )" + String(line_number));
}
Peak1D peak;
float mz = String(iter->str()).toFloat();
peak.setMZ(mz);
++iter;
if (iter == end)
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
line, R"(not <mz><tab/spaces><intensity><tab/spaces>"<annotation>"<tab/spaces>"<comment>" in line )" + String(line_number));
}
float ity = String(iter->str()).toFloat();
peak.setIntensity(ity);
++iter;
if (parse_peakinfo && iter != end)
{
//e.g. "b32-H2O^3/0.11,y19-H2O^2/0.26"
String annot = iter->str();
annot = annot.unquote();
if (annot.hasPrefix("?")) //"? 2/2 0.6" or "?i 2/2 0.6" whatever i means, it will be lost here
{
annots.push_back(PeptideHit::PeakAnnotation{"?", 0, mz, ity});
}
else
{
if (annot.has(' ')) annot = annot.prefix(' '); // in case of different format "b8/-0.07,y9-46/-0.01 2/2 32.4" we only need the first part
StringList splitstr;
annot.split(',',splitstr);
for (auto& str : splitstr)
{
String splitstrprefix = str.prefix('/');
int charge = 1;
StringList splitstr2;
splitstrprefix.split('^', splitstr2);
if (splitstr2.size() > 1)
{
charge = splitstr2[1].toInt();
}
annots.push_back(PeptideHit::PeakAnnotation{splitstr2[0], charge, mz, ity});
if (parse_firstpeakinfo_only) break;
}
}
}
else if (parse_peakinfo)
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
line, "Requested reading peak info but no annotation found for line " + String(line_number));
}
spec.push_back(peak);
}
hitToAnnotate.setPeakAnnotations(annots);
spec.setNativeID(String("index=") + spectrum_number);
exp.addSpectrum(spec);
// clear spectrum
spec.clear(true);
}
spectrum_number++;
}
}
}
void MSPFile::load(const String & filename, AnnotatedMSRun & annot_exp)
{
// use existing load function
PeptideIdentificationList ids;
MSExperiment exp;
this->load(filename, ids, exp);
// Convert to the new data structure (one PeptideIdentification per spectrum)
annot_exp.setPeptideIdentifications(std::move(ids));
annot_exp.getMSExperiment() = std::move(exp);
}
void MSPFile::parseHeader_(const String & header, PeakSpectrum & spec)
{
// first header from std_protein of NIST spectra DB
// Spec=Consensus Pep=Tryptic Fullname=R.AAANFFSASCVPCADQSSFPK.L/2 Mods=0 Parent=1074.480 Inst=it Mz_diff=0.500 Mz_exact=1074.4805 Mz_av=1075.204 Protein="TRFE_BOVIN" Organism="Protein Standard" Se=2^X23:ex=3.1e-008/1.934e-005,td=5.14e+007/2.552e+019,sd=0/0,hs=45.8/5.661,bs=6.3e-021,b2=1.2e-015,bd=5.87e+020^O22:ex=3.24e-005/0.0001075,td=304500/5.909e+297,pr=3.87e-007/1.42e-006,bs=1.65e-301,b2=1.25e-008,bd=1.3e+299 Sample=1/bovine-serotransferrin_cam,23,26 Nreps=23/34 Missing=0.3308/0.0425 Parent_med=1074.88/0.23 Max2med_orig=22.1/9.5 Dotfull=0.618/0.029 Dot_cons=0.728/0.040 Unassign_all=0.161 Unassigned=0.000 Dotbest=0.70 Naa=21 DUScorr=2.3/3.8/0.61 Dottheory=0.86 Pfin=4.3e+010 Probcorr=1 Tfratio=8e+008 Specqual=0.0
vector<String> split;
header.split(' ', split);
for (vector<String>::const_iterator it = split.begin(); it != split.end(); ++it)
{
vector<String> split2;
String tmp = *it;
tmp.trim();
tmp.split('=', split2);
if (split2.size() == 2)
{
spec.setMetaValue(split2[0], split2[1]);
}
}
}
//TODO adapt store to write new? format
void MSPFile::store(const String & filename, const AnnotatedMSRun & exp) const
{
if (!FileHandler::hasValidExtension(filename, FileTypes::MSP))
{
throw Exception::UnableToCreateFile(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
filename, "invalid file extension, expected '" + FileTypes::typeToName(FileTypes::MSP) + "'");
}
if (!File::writable(filename))
{
throw Exception::FileNotWritable(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename);
}
ofstream out(filename.c_str());
for (auto [spectrum, peptide_id] : exp)
{
if (!peptide_id.getHits().empty())
{
PeptideHit hit = peptide_id.getHits()[0];
String peptide;
for (const Residue& pit : hit.getSequence())
{
if (pit.isModified() && pit.getOneLetterCode() == "M" &&
fabs(pit.getModification()->getDiffFormula().getMonoWeight() - 16.0) < 0.01)
{
peptide += "M(O)"; // TODO why are we writing specifically only oxidations?
}
else
{
peptide += pit.getOneLetterCode();
}
}
out << "Name: " << peptide << "/" << hit.getCharge() << "\n";
out << "MW: " << hit.getSequence().getMonoWeight() << "\n";
out << "Comment:";
// modifications
// e.g. 2/9,C,Carbamidomethyl/12,C,Carbamidomethyl
Size num_mods(0);
vector<String> modifications;
if (hit.getSequence().hasNTerminalModification())
{
String mod = hit.getSequence().getNTerminalModificationName();
++num_mods;
String modification = "0," + hit.getSequence().begin()->getOneLetterCode() + "," + mod;
modifications.push_back(modification);
}
// @improvement improve writing support (Andreas)
UInt pos(0);
for (AASequence::ConstIterator pit = hit.getSequence().begin(); pit != hit.getSequence().end(); ++pit, ++pos)
{
if (!pit->isModified())
{
continue;
}
String mod = pit->getModificationName();
String res = pit->getOneLetterCode();
++num_mods;
String modification = String(pos) + "," + res + "," + mod;
modifications.push_back(modification);
}
String mods;
mods.concatenate(modifications.begin(), modifications.end(), "/");
if (!mods.empty())
{
out << " Mods=" << String(num_mods) << "/" << mods;
}
else
{
out << " Mods=0";
}
out << " Inst=it\n"; // @improvement write instrument type, protein...and other information
out << "Num peaks: " << spectrum.size() << "\n";
// normalize to 10,000
PeakSpectrum rich_spec = spectrum;
double max_int(0);
for (const Peak1D& sit : rich_spec)
{
if (sit.getIntensity() > max_int)
{
max_int = sit.getIntensity();
}
}
if (max_int != 0)
{
for (Peak1D& sit : rich_spec)
{
sit.setIntensity(sit.getIntensity() / max_int * 10000.0);
}
}
else
{
cerr << "MSPFile: spectrum contains only zero intensities!" << endl;
}
int ion_name = -1;
for (Size k = 0; k < rich_spec.getStringDataArrays().size(); k++)
{
if (rich_spec.getStringDataArrays()[k].getName() == Constants::UserParam::IonNames)
{
ion_name = (int)k;
break;
}
}
Size k = 0;
for (const Peak1D& sit : rich_spec)
{
out << sit.getPosition()[0] << "\t" << sit.getIntensity() << "\t";
if (ion_name >= 0)
{
out << "\"" << rich_spec.getStringDataArrays()[ion_name][k] << "\"";
k++;
}
else
{
out << "\"?\"";
}
out << "\n";
}
out << "\n";
}
}
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/XMLFile.cpp | .cpp | 7,494 | 254 | // 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/XMLFile.h>
#include <OpenMS/CONCEPT/Macros.h>
#include <OpenMS/FORMAT/HANDLERS/XMLHandler.h>
#include <OpenMS/SYSTEM/File.h>
#include <OpenMS/FORMAT/VALIDATORS/XMLValidator.h>
#include <OpenMS/FORMAT/CompressedInputSource.h>
#include <xercesc/framework/LocalFileInputSource.hpp>
#include <xercesc/framework/MemBufInputSource.hpp>
#include <xercesc/sax2/SAX2XMLReader.hpp>
#include <xercesc/sax2/XMLReaderFactory.hpp>
#include <fstream>
#include <iomanip> // setprecision etc.
#include <memory>
using namespace std;
namespace OpenMS::Internal
{
/// This class ensures that the reset() method of the XMLHandler is called when it goes out of scope.
/// useful when used in exception handling
class XMLCleaner_
{
public:
explicit XMLCleaner_(XMLHandler * handler) :
p_(handler)
{
}
~XMLCleaner_()
{
p_->reset();
}
private:
XMLHandler * p_;
};
XMLFile::XMLFile()
= default;
XMLFile::XMLFile(const String & schema_location, const String & version) :
schema_location_(schema_location),
schema_version_(version)
{
}
XMLFile::~XMLFile()
= default;
void XMLFile::enforceEncoding_(const String& encoding)
{
enforced_encoding_ = encoding;
}
void parse(xercesc::InputSource* const source, XMLHandler* handler)
{
unique_ptr<xercesc::SAX2XMLReader> parser(xercesc::XMLReaderFactory::createXMLReader());
parser->setFeature(xercesc::XMLUni::fgSAX2CoreNameSpaces, false);
parser->setFeature(xercesc::XMLUni::fgSAX2CoreNameSpacePrefixes, false);
parser->setContentHandler(handler);
parser->setErrorHandler(handler);
// try to parse file
try
{
parser->parse(*source);
}
catch (const xercesc::XMLException& toCatch)
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "", String("XMLException: ") + StringManager().convert(toCatch.getMessage()));
}
catch (const xercesc::SAXException& toCatch)
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "", String("SAXException: ") + StringManager().convert(toCatch.getMessage()));
}
catch (const XMLHandler::EndParsingSoftly& /*toCatch*/)
{
// nothing to do here, as this exception is used to softly abort the
// parsing for whatever reason.
}
catch (...)
{
// re-throw
throw;
}
}
void XMLFile::parse_(const String & filename, XMLHandler * handler)
{
// ensure handler->reset() is called to save memory (in case the XMLFile
// reader, e.g. FeatureXMLFile, is used again)
XMLCleaner_ clean(handler);
StringManager sm;
//try to open file
if (!File::exists(filename))
{
throw Exception::FileNotFound(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename);
}
// initialize parser
try
{
xercesc::XMLPlatformUtils::Initialize();
}
catch (const xercesc::XMLException & toCatch)
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"", String("Error during initialization: ") + StringManager().convert(toCatch.getMessage()));
}
// peak ahead into the file: is it bzip2 or gzip compressed?
String bz;
{
std::ifstream file(filename.c_str());
char tmp_bz[3];
file.read(tmp_bz, 2);
tmp_bz[2] = '\0';
bz = String(tmp_bz);
}
unique_ptr<xercesc::InputSource> source;
char g1 = 0x1f;
char g2 = 0;
g2 |= 1 << 7;
g2 |= 1 << 3;
g2 |= 1 << 1;
g2 |= 1 << 0;
//g2 = static_cast<char>(0x8b); // can make troubles if it is casted to 0x7F which is the biggest number signed char can save
if ((bz[0] == 'B' && bz[1] == 'Z') || (bz[0] == g1 && bz[1] == g2))
{
source.reset(new CompressedInputSource(sm.convert(filename).c_str(), bz));
}
else
{
source.reset(new xercesc::LocalFileInputSource(sm.convert(filename).c_str()));
}
// what if no encoding given http://xerces.apache.org/xerces-c/apiDocs-3/classInputSource.html
if (!enforced_encoding_.empty())
{
static const XMLCh* s_enc = xercesc::XMLString::transcode(enforced_encoding_.c_str());
source->setEncoding(s_enc);
}
parse(source.get(), handler);
}
void XMLFile::parseBuffer_(const std::string & buffer, XMLHandler * handler)
{
// ensure handler->reset() is called to save memory (in case the XMLFile
// reader, e.g. FeatureXMLFile, is used again)
XMLCleaner_ clean(handler);
StringManager sm;
// initialize parser
try
{
xercesc::XMLPlatformUtils::Initialize();
}
catch (const xercesc::XMLException & toCatch)
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"", String("Error during initialization: ") + StringManager().convert(toCatch.getMessage()));
}
// TODO: handle non-plain text
// peak ahead into the file: is it bzip2 or gzip compressed?
// String bz = buffer.substr(0, 2);
unique_ptr<xercesc::InputSource> source;
{
auto fake_id = sm.convert("inMemory");
source.reset(new xercesc::MemBufInputSource(reinterpret_cast<const unsigned char *>(buffer.c_str()), buffer.size(), fake_id.c_str()));
}
// what if no encoding given http://xerces.apache.org/xerces-c/apiDocs-3/classInputSource.html
if (!enforced_encoding_.empty())
{
static const XMLCh* s_enc = xercesc::XMLString::transcode(enforced_encoding_.c_str());
source->setEncoding(s_enc);
}
parse(source.get(), handler);
}
void XMLFile::save_(const String & filename, XMLHandler * handler) const
{
// open file in binary mode to avoid any line ending conversions
std::ofstream os(filename.c_str(), std::ios::out | std::ios::binary);
//set high precision for writing of floating point numbers
os.precision(writtenDigits(double()));
if (!os)
{
throw Exception::UnableToCreateFile(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename);
}
// write data and close stream
handler->writeTo(os);
os.close();
}
String encodeTab(const String& to_encode)
{
if (!to_encode.has('\t'))
{
return to_encode;
}
else
{
return String(to_encode).substitute("\t", "	");
}
}
bool XMLFile::isValid(const String & filename, std::ostream & os)
{
if (schema_location_.empty())
{
throw Exception::NotImplemented(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
String current_location = File::find(schema_location_);
return XMLValidator().isValid(filename, current_location, os);
}
const String & XMLFile::getVersion() const
{
return schema_version_;
}
} // namespace OpenMS // namespace Internal
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/KroenikFile.cpp | .cpp | 3,362 | 103 | // 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/KroenikFile.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/CONCEPT/Constants.h>
#include <OpenMS/FORMAT/TextFile.h>
namespace OpenMS
{
KroenikFile::KroenikFile() = default;
KroenikFile::~KroenikFile() = default;
void KroenikFile::load(const String& filename, FeatureMap& feature_map)
{
// load input
TextFile input(filename);
// reset map
FeatureMap fmap;
feature_map = fmap;
TextFile::ConstIterator it = input.begin();
if (it == input.end())
{
return; // no data to load
}
// skip header line
++it;
// process content
for (; it != input.end(); ++it)
{
String line = *it;
//split lines: 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
std::vector<String> parts;
line.split('\t', parts);
if (parts.size() != 14)
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "",
String("Failed parsing in line ")
+ String((it - input.begin()) + 1)
+ ": missing 14 tab-separated entries (got "
+ String(parts.size())
+ ")\nLine was: '"
+ line
+ "'");
}
//create feature
Feature f;
f.setCharge(parts[4].toInt());
f.setMZ(parts[5].toDouble() / f.getCharge() + Constants::PROTON_MASS_U);
f.setRT(parts[11].toDouble());
f.setOverallQuality(parts[12].toDouble());
f.setIntensity(parts[8].toDouble());
ConvexHull2D hull;
ConvexHull2D::PointType point;
point.setX(parts[9].toDouble());
point.setY(f.getMZ());
hull.addPoint(point);
point.setX(parts[9].toDouble());
point.setY(f.getMZ() + 3.0 / static_cast<double>(f.getCharge()));
hull.addPoint(point);
point.setX(parts[10].toDouble());
point.setY(f.getMZ() + 3.0 / static_cast<double>(f.getCharge()));
hull.addPoint(point);
point.setX(parts[10].toDouble());
point.setY(f.getMZ());
hull.addPoint(point);
point.setX(parts[9].toDouble());
point.setY(f.getMZ());
hull.addPoint(point);
std::vector<ConvexHull2D> hulls;
hulls.push_back(hull);
f.setConvexHulls(hulls);
f.setMetaValue("Mass", parts[5].toDouble());
f.setMetaValue("FirstScan", parts[1].toDouble());
f.setMetaValue("LastScan", parts[2].toInt());
f.setMetaValue("NumOfScans", parts[3].toDouble());
f.setMetaValue("AveragineModifications", parts[13]);
feature_map.push_back(f);
}
OPENMS_LOG_INFO << "Hint: The convex hulls are approximated in m/z dimension (Kroenik lacks this information)!\n";
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/ParamCTDFile.cpp | .cpp | 12,426 | 369 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Ruben Grünberg $
// $Authors: Ruben Grünberg $
// --------------------------------------------------------------------------
#include <OpenMS/FORMAT/ParamCTDFile.h>
#include <OpenMS/APPLICATIONS/TOPPBase.h>
#include <cstdint>
#include <fstream>
#include <iostream>
#include <limits>
namespace OpenMS
{
void ParamCTDFile::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;
}
writeCTDToStream(os_ptr, param, tool_info);
}
void ParamCTDFile::writeCTDToStream(std::ostream* os_ptr, const Param& param, const ToolInfo& tool_info) const
{
std::ostream& os = *os_ptr;
os.precision(std::numeric_limits<double>::digits10);
// write ctd specific stuff
os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
os << R"(<tool ctdVersion="1.8" version=")" << tool_info.version_ << R"(" name=")" << tool_info.name_ << R"(" docurl=")" << tool_info.docurl_ << R"(" category=")" << tool_info.category_
<< "\" >\n";
os << "<description><![CDATA[" << tool_info.description_ << "]]></description>\n";
os << "<manual><![CDATA[" << tool_info.description_ << "]]></manual>\n";
os << "<citations>\n";
for (auto& doi : tool_info.citations_)
{
os << " <citation doi=\"" << doi << "\" url=\"\" />\n";
}
os << "</citations>\n";
os << "<PARAMETERS version=\"" << schema_version_ << R"(" xsi:noNamespaceSchemaLocation="https://raw.githubusercontent.com/OpenMS/OpenMS/develop/share/OpenMS)" << schema_location_
<< "\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n";
// Write the xml stuff
uint32_t indentations = 2;
auto param_it = param.begin();
for (auto last = param.end(); param_it != last; ++param_it)
{
for (auto& trace : param_it.getTrace())
{
if (trace.opened)
{
std::string d = trace.description;
replace(d, '\n', "#br#");
os << std::string(indentations, ' ') << "<NODE name=\"" << escapeXML(trace.name) << "\" description=\"" << escapeXML(d) << "\">\n";
indentations += 2;
}
else
{
indentations -= 2;
os << std::string(indentations, ' ') << "</NODE>\n";
}
}
if (param_it->value.valueType() != ParamValue::EMPTY_VALUE)
{
// we create a temporary copy of the tag list, since we remove certain tags while writing,
// that will be represented differently in the xml
std::set<std::string> tag_list = param_it->tags;
ParamValue::ValueType value_type = param_it->value.valueType();
bool stringParamIsFlag = false;
if (value_type < ParamValue::STRING_LIST)
{
os << std::string(indentations, ' ') << "<ITEM name=\"" << escapeXML(param_it->name) << R"(" value=")";
}
else
{
os << std::string(indentations, ' ') << "<ITEMLIST name=\"" << escapeXML(param_it->name);
}
switch (value_type)
{
case ParamValue::INT_VALUE:
os << param_it->value.toString() << R"(" type="int")";
break;
case ParamValue::DOUBLE_VALUE:
os << param_it->value.toString() << R"(" type="double")";
break;
case ParamValue::STRING_VALUE:
if (tag_list.find(TOPPBase::TAG_INPUT_FILE) != tag_list.end())
{
os << escapeXML(param_it->value.toString()) << R"(" type="input-file")";
tag_list.erase(TOPPBase::TAG_INPUT_FILE);
}
else if (tag_list.find(TOPPBase::TAG_OUTPUT_FILE) != tag_list.end())
{
os << escapeXML(param_it->value.toString()) << R"(" type="output-file")";
tag_list.erase(TOPPBase::TAG_OUTPUT_FILE);
}
else if (tag_list.find(TOPPBase::TAG_OUTPUT_DIR) != tag_list.end())
{
os << escapeXML(param_it->value.toString()) << R"(" type="output-dir")";
tag_list.erase(TOPPBase::TAG_OUTPUT_DIR);
}
else if (tag_list.find(TOPPBase::TAG_OUTPUT_PREFIX) != tag_list.end())
{
os << escapeXML(param_it->value.toString()) << R"(" type="output-prefix")";
tag_list.erase(TOPPBase::TAG_OUTPUT_PREFIX);
}
else if (param_it->valid_strings.size() == 2 && param_it->valid_strings[0] == "true" && param_it->valid_strings[1] == "false" && param_it->value == "false")
{
stringParamIsFlag = true;
os << param_it->value.toString() << R"(" type="bool")";
}
else
{
std::string value = param_it->value.toString();
if (value.find('\t') != std::string::npos)
{
replace(value, '\t', "	");
}
os << escapeXML(value) << R"(" type="string")";
}
break;
case ParamValue::STRING_LIST:
if (tag_list.find(TOPPBase::TAG_INPUT_FILE) != tag_list.end())
{
os << R"(" type="input-file")";
tag_list.erase(TOPPBase::TAG_INPUT_FILE);
}
else if (tag_list.find(TOPPBase::TAG_OUTPUT_FILE) != tag_list.end())
{
os << R"(" type="output-file")";
tag_list.erase(TOPPBase::TAG_OUTPUT_FILE);
}
else
{
os << R"(" type="string")";
}
break;
case ParamValue::INT_LIST:
os << R"(" type="int")";
break;
case ParamValue::DOUBLE_LIST:
os << R"(" type="double")";
break;
default:
break;
}
std::string description = param_it->description;
replace(description, '\n', "#br#");
os << " description=\"" << escapeXML(description) << "\"";
if (tag_list.find("required") != tag_list.end())
{
os << R"( required="true")";
tag_list.erase("required");
}
else
{
os << R"( required="false")";
}
if (tag_list.find("advanced") != tag_list.end())
{
os << R"( advanced="true")";
tag_list.erase("advanced");
}
else
{
os << R"( advanced="false")";
}
if (!tag_list.empty())
{
std::string list;
for (auto& tag : tag_list)
{
if (!list.empty())
list += ",";
list += tag;
}
os << " tags=\"" << escapeXML(list) << "\"";
}
if (!stringParamIsFlag)
{
std::string restrictions;
switch (value_type)
{
case ParamValue::INT_VALUE:
case ParamValue::INT_LIST: {
bool min_set = (param_it->min_int != -std::numeric_limits<int>::max());
bool max_set = (param_it->max_int != std::numeric_limits<int>::max());
if (max_set || min_set)
{
if (min_set)
{
restrictions += std::to_string(param_it->min_int);
}
restrictions += ':';
if (max_set)
{
restrictions += std::to_string(param_it->max_int);
}
}
}
break;
case ParamValue::DOUBLE_VALUE:
case ParamValue::DOUBLE_LIST: {
bool min_set = (param_it->min_float != -std::numeric_limits<double>::max());
bool max_set = (param_it->max_float != std::numeric_limits<double>::max());
if (max_set || min_set)
{
if (min_set)
{
restrictions += std::to_string(param_it->min_float);
}
restrictions += ':';
if (max_set)
{
restrictions += std::to_string(param_it->max_float);
}
}
}
break;
case ParamValue::STRING_VALUE:
case ParamValue::STRING_LIST:
if (!param_it->valid_strings.empty())
{
restrictions = param_it->valid_strings.front();
for (auto it = param_it->valid_strings.begin() + 1, end = param_it->valid_strings.end(); it != end; ++it)
{
restrictions += ",";
restrictions += *it;
}
}
break;
default:
break;
}
if (!restrictions.empty())
{
if (param_it->tags.find("input file") != param_it->tags.end() || param_it->tags.find("output file") != param_it->tags.end() || param_it->tags.find("output prefix") != param_it->tags.end())
{
os << " supported_formats=\"" << escapeXML(restrictions) << "\"";
}
else
{
os << " restrictions=\"" << escapeXML(restrictions) << "\"";
}
}
}
if (value_type < ParamValue::STRING_LIST)
{
os << " />\n";
}
else
{
os << " >\n";
}
switch (value_type)
{
case ParamValue::STRING_LIST:
for (auto item : static_cast<const std::vector<std::string>&>(param_it->value))
{
if (item.find('\t') != std::string::npos)
{
replace(item, '\t', "	");
}
os << std::string(indentations + 2, ' ') << "<LISTITEM value=\"" << escapeXML(item) << "\"/>\n";
}
break;
case ParamValue::INT_LIST:
for (int item : static_cast<const std::vector<int>&>(param_it->value))
{
os << std::string(indentations + 2, ' ') << "<LISTITEM value=\"" << item << "\"/>\n";
}
break;
case ParamValue::DOUBLE_LIST:
for (double item : static_cast<const std::vector<double>&>(param_it->value))
{
os << std::string(indentations + 2, ' ') << "<LISTITEM value=\"" << item << "\"/>\n";
}
break;
default:
break;
}
if (value_type > ParamValue::DOUBLE_VALUE && value_type)
{
os << std::string(indentations, ' ') << "</ITEMLIST>\n";
}
}
}
if (param.begin() != param.end())
{
for ([[maybe_unused]] auto& trace : param_it.getTrace())
{
indentations -= 2;
os << std::string(indentations, ' ') << "</NODE>\n";
}
}
os << "</PARAMETERS>\n";
os << "</tool>" << std::endl; // forces a flush
}
std::string ParamCTDFile::escapeXML(const std::string& to_escape)
{
std::string copy = to_escape;
if (copy.find('&') != std::string::npos)
replace(copy, '&', "&");
if (copy.find('>') != std::string::npos)
replace(copy, '>', ">");
if (copy.find('"') != std::string::npos)
replace(copy, '"', """);
if (copy.find('<') != std::string::npos)
replace(copy, '<', "<");
if (copy.find('\'') != std::string::npos)
replace(copy, '\'', "'");
return copy;
}
void ParamCTDFile::replace(std::string& replace_in, char to_replace, const std::string& replace_with)
{
for (size_t i = 0; i < replace_in.size(); ++i)
{
if (replace_in[i] == to_replace)
{
replace_in = replace_in.substr(0, i) + replace_with + replace_in.substr(i + 1);
i += replace_with.size();
}
}
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/CVMappingFile.cpp | .cpp | 6,016 | 220 | // 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/CVMappingFile.h>
#include <OpenMS/DATASTRUCTURES/CVReference.h>
#include <OpenMS/DATASTRUCTURES/CVMappingTerm.h>
#include <OpenMS/DATASTRUCTURES/DataValue.h>
#include <OpenMS/SYSTEM/File.h>
using namespace xercesc;
using namespace std;
namespace OpenMS
{
CVMappingFile::CVMappingFile() :
XMLHandler("", 0),
XMLFile()
{
}
CVMappingFile::~CVMappingFile() = default;
void CVMappingFile::load(const String& filename, CVMappings& cv_mappings, bool strip_namespaces)
{
//File name for error messages in XMLHandler
file_ = filename;
strip_namespaces_ = strip_namespaces;
parse_(filename, this);
cv_mappings.setCVReferences(cv_references_);
cv_mappings.setMappingRules(rules_);
cv_references_.clear();
rules_.clear();
return;
}
void CVMappingFile::startElement(const XMLCh* const /*uri*/, const XMLCh* const /*local_name*/, const XMLCh* const qname, const Attributes& attributes)
{
tag_ = String(sm_.convert(qname));
if (tag_ == "CvReference")
{
// CvReference cvName="PSI-PI" cvIdentifier="PSI-PI"/>
CVReference ref;
ref.setName(attributeAsString_(attributes, "cvName"));
ref.setIdentifier(attributeAsString_(attributes, "cvIdentifier"));
cv_references_.push_back(ref);
return;
}
if (tag_ == "CvMappingRule")
{
// id="R1" cvElementPath="/psi-pi:MzIdentML/psi-pi:AnalysisSoftwareList/psi-pi:AnalysisSoftware/pf:ContactRole/pf:role/pf:cvParam" requirementLevel="MUST" scopePath="" cvTermsCombinationLogic="OR
actual_rule_.setIdentifier(attributeAsString_(attributes, "id"));
String element_path = attributeAsString_(attributes, "cvElementPath");
if (strip_namespaces_)
{
vector<String> slash_split;
element_path.split('/', slash_split);
if (slash_split.empty())
{
slash_split.push_back(element_path);
}
element_path = "";
for (vector<String>::const_iterator it = slash_split.begin(); it != slash_split.end(); ++it)
{
if (it->empty())
{
continue;
}
vector<String> split;
it->split(':', split);
if (split.empty())
{
element_path += "/" + *it;
}
else
{
if (split.size() == 2)
{
element_path += "/" + split[1];
}
else
{
fatalError(LOAD, String("Cannot parse namespaces of path: '") + element_path + "'");
}
}
}
}
actual_rule_.setElementPath(element_path);
CVMappingRule::RequirementLevel level = CVMappingRule::MUST;
String lvl = attributeAsString_(attributes, "requirementLevel");
if (lvl == "MAY")
{
level = CVMappingRule::MAY;
}
else
{
if (lvl == "SHOULD")
{
level = CVMappingRule::SHOULD;
}
else
{
if (lvl == "MUST")
{
level = CVMappingRule::MUST;
}
else
{
// throw Exception
}
}
}
actual_rule_.setRequirementLevel(level);
actual_rule_.setScopePath(attributeAsString_(attributes, "scopePath"));
CVMappingRule::CombinationsLogic logic = CVMappingRule::OR;
String lgc = attributeAsString_(attributes, "cvTermsCombinationLogic");
if (lgc == "OR")
{
logic = CVMappingRule::OR;
}
else
{
if (lgc == "AND")
{
logic = CVMappingRule::AND;
}
else
{
if (lgc == "XOR")
{
logic = CVMappingRule::XOR;
}
else
{
// throw Exception;
}
}
}
actual_rule_.setCombinationsLogic(logic);
return;
}
if (tag_ == "CvTerm")
{
// termAccession="PI:00266" useTermName="false" useTerm="false" termName="role type" isRepeatable="true" allowChildren="true" cvIdentifierRef="PSI-PI"
CVMappingTerm term;
term.setAccession(attributeAsString_(attributes, "termAccession"));
term.setUseTerm(DataValue(attributeAsString_(attributes, "useTerm")).toBool());
String use_term_name;
optionalAttributeAsString_(use_term_name, attributes, "useTermName");
if (!use_term_name.empty())
{
term.setUseTermName(DataValue(use_term_name).toBool());
}
else
{
term.setUseTermName(false);
}
term.setTermName(attributeAsString_(attributes, "termName"));
String is_repeatable;
optionalAttributeAsString_(is_repeatable, attributes, "isRepeatable");
if (!is_repeatable.empty())
{
term.setIsRepeatable(DataValue(is_repeatable).toBool());
}
else
{
term.setIsRepeatable(true);
}
term.setAllowChildren(DataValue(attributeAsString_(attributes, "allowChildren")).toBool());
term.setCVIdentifierRef(attributeAsString_(attributes, "cvIdentifierRef"));
actual_rule_.addCVTerm(term);
return;
}
return;
}
void CVMappingFile::endElement(const XMLCh* const /*uri*/, const XMLCh* const /*local_name*/, const XMLCh* const qname)
{
tag_ = String(sm_.convert(qname));
if (tag_ == "CvMappingRule")
{
rules_.push_back(actual_rule_);
actual_rule_ = CVMappingRule();
return;
}
return;
}
void CVMappingFile::characters(const XMLCh* const /*chars*/, const XMLSize_t /*length*/)
{
// good XML format, nothing to do here
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/XQuestResultXMLFile.cpp | .cpp | 12,635 | 291 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Eugen Netz $
// $Authors: Lukas Zimmermann, Eugen Netz $
// --------------------------------------------------------------------------
#include <OpenMS/FORMAT/FileHandler.h>
#include <OpenMS/FORMAT/XQuestResultXMLFile.h>
#include <OpenMS/FORMAT/HANDLERS/XQuestResultXMLHandler.h>
#include <OpenMS/FORMAT/Base64.h>
#include <OpenMS/MATH/MathFunctions.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <fstream>
#include <OpenMS/ANALYSIS/XLMS/OPXLHelper.h>
namespace OpenMS
{
XQuestResultXMLFile::XQuestResultXMLFile() :
XMLFile("/SCHEMAS/xQuest_1_0.xsd", "1.0"),
n_hits_(-1)
{
}
XQuestResultXMLFile::~XQuestResultXMLFile() = default;
void XQuestResultXMLFile::load(const String & filename,
PeptideIdentificationList & pep_ids,
std::vector< ProteinIdentification > & prot_ids
)
{
Internal::XQuestResultXMLHandler handler(filename, pep_ids, prot_ids);
this->parse_(filename, &handler);
this->n_hits_ = handler.getNumberOfHits();
this->min_score_ = handler.getMinScore();
this->max_score_ = handler.getMaxScore();
// this helper function adds additional explicit "xl_target_decoy" meta values derived from parsed data
OPXLHelper::addXLTargetDecoyMV(pep_ids);
// this helper function adds beta peptide accessions
OPXLHelper::addBetaAccessions(pep_ids);
// this helper function bases the ranked lists of labeled XLMS searches on each light spectrum instead of pairs
// the second parameter here should be the maximal number of hits per spectrum,
// but using the total number of hits we will just keep everything contained in the file
// (just reassigned to single spectra and re-ranked by score)
pep_ids = OPXLHelper::combineTopRanksFromPairs(pep_ids, this->n_hits_);
OPXLHelper::removeBetaPeptideHits(pep_ids);
OPXLHelper::computeDeltaScores(pep_ids);
}
int XQuestResultXMLFile::getNumberOfHits() const
{
return this->n_hits_;
}
double XQuestResultXMLFile::getMinScore() const
{
return this->min_score_;
}
double XQuestResultXMLFile::getMaxScore() const
{
return this->max_score_;
}
void XQuestResultXMLFile::store(const String& filename, const std::vector<ProteinIdentification>& poid, const PeptideIdentificationList& peid) const
{
if (!FileHandler::hasValidExtension(filename, FileTypes::XQUESTXML))
{
throw Exception::UnableToCreateFile(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename, "invalid file extension, expected '" + FileTypes::typeToName(FileTypes::XQUESTXML) + "'");
}
Internal::XQuestResultXMLHandler handler(poid, peid, filename, schema_version_);
save_(filename, &handler);
}
// version for labeled linkers
void XQuestResultXMLFile::writeXQuestXMLSpec(const String& out_file, const String& base_name, const OPXLDataStructs::PreprocessedPairSpectra& preprocessed_pair_spectra, const std::vector< std::pair<Size, Size> >& spectrum_pairs, const std::vector< std::vector< OPXLDataStructs::CrossLinkSpectrumMatch > >& all_top_csms, const PeakMap& spectra, const bool& test_mode)
{
// XML Header
std::ofstream spec_xml_file;
OPENMS_LOG_INFO << "Writing spec.xml to " << out_file << std::endl;
spec_xml_file.open(out_file.c_str(), std::ios::trunc); // ios::app = append to file, ios::trunc = overwrites file
// TODO write actual data
spec_xml_file << R"(<?xml version="1.0" encoding="UTF-8"?><xquest_spectra author="Eugen Netz" deffile="xquest.def" >)" << '\n';
// collect indices of spectra, that need to be written out
std::vector <std::pair <Size, Size> > spectrum_indices;
for (Size i = 0; i < all_top_csms.size(); ++i)
{
if (!all_top_csms[i].empty())
{
if (all_top_csms[i][0].scan_index_light < spectra.size() && all_top_csms[i][0].scan_index_heavy < spectra.size())
{
spectrum_indices.emplace_back(all_top_csms[i][0].scan_index_light, all_top_csms[i][0].scan_index_heavy );
}
}
}
// loop over list of indices and write out spectra
for (Size i = 0; i < spectrum_indices.size(); ++i)
{
Size scan_index_light = spectrum_indices[i].first;
Size scan_index_heavy = spectrum_indices[i].second;
// TODO more correct alternative
String spectrum_light_name = base_name + ".light." + scan_index_light;
String spectrum_heavy_name = base_name + ".heavy." + scan_index_heavy;
String spectrum_name = spectrum_light_name + String("_") + spectrum_heavy_name;
if (scan_index_light < spectra.size() && scan_index_heavy < spectra.size() && i < preprocessed_pair_spectra.spectra_linear_peaks.size() && i < preprocessed_pair_spectra.spectra_xlink_peaks.size())
{
// 4 Spectra resulting from a light/heavy spectra pair. Write for each spectrum, that is written to xquest.xml (should be all considered pairs, or better only those with at least one sensible Hit, meaning a score was computed)
spec_xml_file << "<spectrum filename=\"" << spectrum_light_name << ".dta" << R"(" type="light">)" << '\n';
spec_xml_file << getxQuestBase64EncodedSpectrum_(spectra[scan_index_light], String(""), test_mode);
spec_xml_file << "</spectrum>\n";
spec_xml_file << "<spectrum filename=\"" << spectrum_heavy_name << ".dta" << R"(" type="heavy">)" << '\n';
spec_xml_file << getxQuestBase64EncodedSpectrum_(spectra[scan_index_heavy], String(""), test_mode);
spec_xml_file << "</spectrum>\n";
// the preprocessed pair spectra are sorted by another index
// because some pairs do not yield any hits worth reporting (e.g. no matching peaks), the index from the spectrum matches or spectrum_indices does not address the right pair anymore
// use find with the pair of spectrum indices to find the correct index for the preprocessed linear and cross-linked ion spectra
std::vector<std::pair <Size, Size> >::const_iterator pair_it = std::find(spectrum_pairs.begin(), spectrum_pairs.end(), spectrum_indices[i]);
Size pair_index = std::distance(spectrum_pairs.begin(), pair_it);
String spectrum_common_name = spectrum_name + String("_common.txt");
spec_xml_file << "<spectrum filename=\"" << spectrum_common_name << R"(" type="common">)" << '\n';
spec_xml_file << getxQuestBase64EncodedSpectrum_(preprocessed_pair_spectra.spectra_linear_peaks[pair_index], spectrum_light_name + ".dta," + spectrum_heavy_name + ".dta", test_mode);
spec_xml_file << "</spectrum>\n";
String spectrum_xlink_name = spectrum_name + String("_xlinker.txt");
spec_xml_file << "<spectrum filename=\"" << spectrum_xlink_name << R"(" type="xlinker">)" << '\n';
spec_xml_file << getxQuestBase64EncodedSpectrum_(preprocessed_pair_spectra.spectra_xlink_peaks[pair_index], spectrum_light_name + ".dta," + spectrum_heavy_name + ".dta", test_mode);
spec_xml_file << "</spectrum>\n";
}
}
spec_xml_file << "</xquest_spectra>\n";
spec_xml_file.close();
return;
}
// version for label-free linkers
void XQuestResultXMLFile::writeXQuestXMLSpec(const String& out_file, const String& base_name, const std::vector< std::vector< OPXLDataStructs::CrossLinkSpectrumMatch > >& all_top_csms, const PeakMap& spectra, const bool& test_mode)
{
// String spec_xml_filename = base_name + "_matched.spec.xml";
// XML Header
std::ofstream spec_xml_file;
OPENMS_LOG_INFO << "Writing spec.xml to " << out_file << std::endl;
spec_xml_file.open(out_file.c_str(), std::ios::trunc); // ios::app = append to file, ios::trunc = overwrites file
// TODO write actual data
spec_xml_file << R"(<?xml version="1.0" encoding="UTF-8"?><xquest_spectra author="Eugen Netz" deffile="xquest.def" >)" << '\n';
// collect indices of spectra, that need to be written out
std::vector <Size> spectrum_indices;
for (Size i = 0; i < all_top_csms.size(); ++i)
{
if (!all_top_csms[i].empty())
{
if (all_top_csms[i][0].scan_index_light < spectra.size())
{
spectrum_indices.push_back(all_top_csms[i][0].scan_index_light);
}
}
}
// loop over list of indices and write out spectra
for (Size i = 0; i < spectrum_indices.size(); ++i)
{
String spectrum_light_name = base_name + ".light." + spectrum_indices[i];
String spectrum_heavy_name = base_name + ".heavy." + spectrum_indices[i];
String spectrum_name = spectrum_light_name + String("_") + spectrum_heavy_name;
// 4 Spectra resulting from a light/heavy spectra pair. Write for each spectrum, that is written to xquest.xml (should be all considered pairs, or better only those with at least one sensible Hit, meaning a score was computed)
spec_xml_file << "<spectrum filename=\"" << spectrum_light_name << ".dta" << R"(" type="light">)" << '\n';
spec_xml_file << getxQuestBase64EncodedSpectrum_(spectra[spectrum_indices[i]], String(""), test_mode);
spec_xml_file << "</spectrum>\n";
spec_xml_file << "<spectrum filename=\"" << spectrum_heavy_name << ".dta" << R"(" type="heavy">)" << '\n';
spec_xml_file << getxQuestBase64EncodedSpectrum_(spectra[spectrum_indices[i]], String(""), test_mode);
spec_xml_file << "</spectrum>\n";
String spectrum_common_name = spectrum_name + String("_common.txt");
spec_xml_file << "<spectrum filename=\"" << spectrum_common_name << R"(" type="common">)" << '\n';
spec_xml_file << getxQuestBase64EncodedSpectrum_(spectra[spectrum_indices[i]], spectrum_light_name + ".dta," + spectrum_heavy_name + ".dta", test_mode);
spec_xml_file << "</spectrum>\n";
String spectrum_xlink_name = spectrum_name + String("_xlinker.txt");
spec_xml_file << "<spectrum filename=\"" << spectrum_xlink_name << R"(" type="xlinker">)" << '\n';
spec_xml_file << getxQuestBase64EncodedSpectrum_(spectra[spectrum_indices[i]], spectrum_light_name + ".dta," + spectrum_heavy_name + ".dta", test_mode);
spec_xml_file << "</spectrum>\n";
}
spec_xml_file << "</xquest_spectra>\n";
spec_xml_file.close();
return;
}
String XQuestResultXMLFile::getxQuestBase64EncodedSpectrum_(const PeakSpectrum& spec, const String& header, const bool& test_mode)
{
std::vector<String> in_strings;
StringList sl;
double precursor_mz = 0;
double precursor_z = 0;
if (!spec.getPrecursors().empty())
{
precursor_mz = Math::roundDecimal(spec.getPrecursors()[0].getMZ(), -6);
precursor_z = spec.getPrecursors()[0].getCharge();
}
// header lines
if (!header.empty()) // common or xlinker spectrum will be reported
{
sl.push_back(header + "\n"); // e.g. GUA1372-S14-A-LRRK2_DSS_1A3.03873.03873.3.dta,GUA1372-S14-A-LRRK2_DSS_1A3.03863.03863.3.dta
sl.push_back(String(precursor_mz) + "\n");
sl.push_back(String(precursor_z) + "\n");
}
else // light or heavy spectrum will be reported
{
sl.push_back(String(precursor_mz) + "\t" + String(precursor_z) + "\n");
}
PeakSpectrum::IntegerDataArray charges;
if (!spec.getIntegerDataArrays().empty())
{
charges = spec.getIntegerDataArrays()[0];
}
// write peaks
for (Size i = 0; i != spec.size(); ++i)
{
String s;
s += String(Math::roundDecimal(spec[i].getMZ(), -6)) + "\t";
s += String(Math::roundDecimal(spec[i].getIntensity(), -4)) + "\t";
if (!charges.empty())
{
s += String(charges[i]);
}
else
{
s += "0";
}
s += "\n";
sl.push_back(s);
}
String out;
out.concatenate(sl.begin(), sl.end(), "");
in_strings.push_back(out);
if (!test_mode)
{
String out_encoded;
Base64().encodeStrings(in_strings, out_encoded, false, false);
String out_wrapped;
wrap_(out_encoded, 76, out_wrapped);
return out_wrapped;
}
else // skip base64 encoding in test mode
{
return out;
}
}
void XQuestResultXMLFile::wrap_(const String& input, Size width, String & output)
{
Size start = 0;
while (start + width < input.size())
{
output += input.substr(start, width) + "\n";
start += width;
}
if (start < input.size())
{
output += input.substr(start, input.size() - start) + "\n";
}
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/MzMLFile.cpp | .cpp | 8,735 | 277 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm, Chris Bielow, Hannes Roest $
// --------------------------------------------------------------------------
#include <OpenMS/FORMAT/MzMLFile.h>
#include <OpenMS/FORMAT/HANDLERS/MzMLHandler.h>
#include <OpenMS/FORMAT/HANDLERS/XMLHandler.h>
#include <OpenMS/FORMAT/CVMappingFile.h>
#include <OpenMS/FORMAT/FileHandler.h>
#include <OpenMS/FORMAT/VALIDATORS/XMLValidator.h>
#include <OpenMS/FORMAT/VALIDATORS/MzMLValidator.h>
#include <OpenMS/FORMAT/TextFile.h>
#include <OpenMS/FORMAT/DATAACCESS/MSDataTransformingConsumer.h>
#include <OpenMS/FORMAT/HANDLERS/IndexedMzMLDecoder.h>
#include <OpenMS/SYSTEM/File.h>
#include <sstream>
namespace OpenMS
{
MzMLFile::MzMLFile() :
XMLFile("/SCHEMAS/mzML_1_10.xsd", "1.1.0"),
indexed_schema_location_("/SCHEMAS/mzML_idx_1_10.xsd")
{
}
MzMLFile::~MzMLFile() = default;
PeakFileOptions& MzMLFile::getOptions()
{
return options_;
}
const PeakFileOptions& MzMLFile::getOptions() const
{
return options_;
}
void MzMLFile::setOptions(const PeakFileOptions& options)
{
options_ = options;
}
bool MzMLFile::hasIndex(const String& filename)
{
const std::streampos NOT_FOUND {-1};
return NOT_FOUND != IndexedMzMLDecoder().findIndexListOffset(filename);
}
// reimplemented in order to handle index MzML
bool MzMLFile::isValid(const String& filename, std::ostream& os)
{
//determine if this is indexed mzML or not
bool indexed = false;
TextFile file(filename, true, 4);
String s;
s.concatenate(file.begin(), file.end());
if (s.hasSubstring("<indexedmzML"))
{
indexed = true;
}
// find the corresponding schema
String current_location;
if (indexed)
{
current_location = File::find(indexed_schema_location_);
}
else
{
current_location = File::find(schema_location_);
}
return XMLValidator().isValid(filename, current_location, os);
}
bool MzMLFile::isSemanticallyValid(const String& filename, StringList& errors, StringList& warnings)
{
// load mapping
CVMappings mapping;
CVMappingFile().load(File::find("/MAPPING/ms-mapping.xml"), mapping);
// validate
Internal::MzMLValidator v(mapping, ControlledVocabulary::getPSIMSCV());
bool result = v.validate(filename, errors, warnings);
return result;
}
void MzMLFile::loadSize(const String& filename, Size& scount, Size& ccount)
{
PeakMap dummy;
Internal::MzMLHandler handler(dummy, filename, getVersion(), *this);
handler.setOptions(options_);
if (options_.hasFilters())
{
handler.setLoadDetail(Internal::XMLHandler::LD_COUNTS_WITHOPTIONS);
}
else
{ // no filters where specified. Just take the 'counts' attributes from the mzML file and end parsing
handler.setLoadDetail(Internal::XMLHandler::LD_RAWCOUNTS);
}
safeParse_(filename, &handler);
handler.getCounts(scount, ccount);
}
void MzMLFile::safeParse_(const String& filename, Internal::XMLHandler* handler)
{
try
{
parse_(filename, handler);
}
catch (Exception::BaseException& e)
{
String expr;
expr += e.getFile();
expr += "@";
expr += e.getLine();
expr += "-";
expr += e.getFunction();
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, expr, String("- due to that error of type ") + e.getName());
}
}
void MzMLFile::loadBuffer(const std::string& buffer, PeakMap& map)
{
map.reset();
Internal::MzMLHandler handler(map, "memory", getVersion(), *this);
handler.setOptions(options_);
parseBuffer_(buffer, &handler);
map.updateRanges();
}
void MzMLFile::load(const String& filename, PeakMap& map)
{
map.reset();
//set DocumentIdentifier
map.setLoadedFileType(filename);
map.setLoadedFilePath(filename);
Internal::MzMLHandler handler(map, filename, getVersion(), *this);
handler.setOptions(options_);
safeParse_(filename, &handler);
map.updateRanges();
}
void MzMLFile::store(const String& filename, const PeakMap& map) const
{
Internal::MzMLHandler handler(map, filename, getVersion(), *this);
handler.setOptions(options_);
save_(filename, &handler);
}
void MzMLFile::storeBuffer(std::string& output, const PeakMap& map) const
{
Internal::MzMLHandler handler(map, "dummy", getVersion(), *this);
handler.setOptions(options_);
{
std::stringstream os;
//set high precision for writing of floating point numbers
os.precision(writtenDigits(double()));
// write data and close stream
handler.writeTo(os);
output = os.str();
}
}
void MzMLFile::transform(const String& filename_in, Interfaces::IMSDataConsumer* consumer, bool skip_full_count, bool skip_first_pass)
{
// 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);
// Second pass through the data, now read the spectra!
{
PeakMap dummy;
Internal::MzMLHandler handler(dummy, filename_in, getVersion(), *this);
handler.setOptions(options_);
handler.setMSDataConsumer(consumer);
safeParse_(filename_in, &handler);
}
}
void MzMLFile::transform(const String& filename_in, Interfaces::IMSDataConsumer* consumer, PeakMap& map, bool skip_full_count, bool skip_first_pass)
{
// 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);
}
// Second pass through the data, now read the spectra!
{
PeakFileOptions tmp_options(options_);
Internal::MzMLHandler handler(map, filename_in, getVersion(), *this);
tmp_options.setAlwaysAppendData(true);
handler.setOptions(tmp_options);
handler.setMSDataConsumer(consumer);
safeParse_(filename_in, &handler);
}
}
void MzMLFile::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;
PeakMap experimental_settings;
Internal::MzMLHandler 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);
safeParse_(filename_in, &handler);
// After parsing, collect information
handler.getCounts(scount, ccount);
consumer->setExpectedSize(scount, ccount);
consumer->setExperimentalSettings(experimental_settings);
}
std::map<UInt, MzMLFile::SpecInfo> MzMLFile::getCentroidInfo(const String& filename, const Size first_n_spectra_only)
{
bool oldoption = options_.getFillData();
options_.setFillData(true); // we want the data as well (to allow estimation from data if metadata is missing)
std::map<UInt, SpecInfo> ret;
Size first_n_spectra_only_remaining = first_n_spectra_only;
auto f = [&ret, &first_n_spectra_only_remaining](const MSSpectrum& s)
{
UInt lvl = s.getMSLevel();
switch (s.getType(true))
{
case (MSSpectrum::SpectrumType::CENTROID):
++ret[lvl].count_centroided;
--first_n_spectra_only_remaining;
break;
case (MSSpectrum::SpectrumType::PROFILE):
++ret[lvl].count_profile;
--first_n_spectra_only_remaining;
break;
case (MSSpectrum::SpectrumType::UNKNOWN): // this can only happen for spectra with very few peaks (or completely empty spectra)
++ret[lvl].count_unknown;
break;
default:
// make sure we did not forget a case
throw Exception::NotImplemented(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
// stop parsing after 10 or so spectra
if (first_n_spectra_only_remaining == 0)
{
throw Internal::XMLHandler::EndParsingSoftly(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
};
MSDataTransformingConsumer c;
c.setSpectraProcessingFunc(f);
transform(filename, &c, true, true); // no first pass
// restore old state
options_.setFillData(oldoption);
return ret;
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/DTA2DFile.cpp | .cpp | 686 | 31 | // 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/DTA2DFile.h>
using namespace std;
namespace OpenMS
{
DTA2DFile::DTA2DFile() = default;
DTA2DFile::~DTA2DFile() = default;
PeakFileOptions & DTA2DFile::getOptions()
{
return options_;
}
const PeakFileOptions & DTA2DFile::getOptions() const
{
return options_;
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/QuantmsIO.cpp | .cpp | 37,447 | 944 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Julianus Pfeuffer $
// $Authors: Julianus Pfeuffer $
// --------------------------------------------------------------------------
#include <OpenMS/FORMAT/QuantmsIO.h>
#include <OpenMS/CONCEPT/Exception.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/CONCEPT/Constants.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/DATASTRUCTURES/DataValue.h>
#include <OpenMS/METADATA/PeptideHit.h>
#include <OpenMS/METADATA/PeptideEvidence.h>
#include <OpenMS/ANALYSIS/ID/IDScoreSwitcherAlgorithm.h>
#include <arrow/api.h>
#include <arrow/io/api.h>
#include <parquet/arrow/writer.h>
#include <algorithm>
#include <sstream>
#include <chrono>
#include <iomanip>
#include <functional>
using namespace std;
namespace
{
// Helper functions moved to anonymous namespace to hide Arrow types from header
// Helper function to map DataValue type to Arrow field type
std::shared_ptr<arrow::DataType> dataValueTypeToArrowType(OpenMS::DataValue::DataType data_type)
{
switch (data_type)
{
case OpenMS::DataValue::STRING_VALUE:
return arrow::utf8();
case OpenMS::DataValue::INT_VALUE:
return arrow::int64(); // SignedSize maps to int64
case OpenMS::DataValue::DOUBLE_VALUE:
return arrow::float64();
case OpenMS::DataValue::STRING_LIST:
return arrow::list(arrow::utf8());
case OpenMS::DataValue::INT_LIST:
return arrow::list(arrow::int64());
case OpenMS::DataValue::DOUBLE_LIST:
return arrow::list(arrow::float64());
case OpenMS::DataValue::EMPTY_VALUE:
default:
return arrow::utf8(); // Default to string for unknown or empty types
}
}
// Helper function to determine meta value types by scanning all peptide hits
std::map<OpenMS::String, OpenMS::DataValue::DataType> determineMetaValueTypes(
const OpenMS::PeptideIdentificationList& peptide_identifications,
const std::set<OpenMS::String>& meta_value_keys,
bool export_all_psms)
{
std::map<OpenMS::String, OpenMS::DataValue::DataType> meta_value_types;
// Initialize all keys as EMPTY_VALUE
for (const auto& key : meta_value_keys)
{
meta_value_types[key] = OpenMS::DataValue::EMPTY_VALUE;
}
// Scan all peptide identifications and hits to determine types
for (const auto& peptide_id : peptide_identifications)
{
const auto& hits = peptide_id.getHits();
if (hits.empty()) continue;
size_t num_hits_to_process = export_all_psms ? hits.size() : 1;
for (size_t hit_index = 0; hit_index < num_hits_to_process; ++hit_index)
{
const OpenMS::PeptideHit& hit = hits[hit_index];
for (const auto& key : meta_value_keys)
{
if (hit.metaValueExists(key))
{
OpenMS::DataValue meta_value = hit.getMetaValue(key);
OpenMS::DataValue::DataType current_type = meta_value.valueType();
if (current_type != OpenMS::DataValue::EMPTY_VALUE)
{
if (meta_value_types[key] == OpenMS::DataValue::EMPTY_VALUE)
{
// First non-empty value found, set the type
meta_value_types[key] = current_type;
}
else if (meta_value_types[key] != current_type)
{
// Type conflict - throw an exception as requested
throw OpenMS::Exception::InvalidParameter(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Meta value type conflict for key '" + key + "': found both " +
OpenMS::DataValue::NamesOfDataType[meta_value_types[key]] + " and " +
OpenMS::DataValue::NamesOfDataType[current_type] + ". All values for a meta key must have the same type.");
}
}
}
}
}
}
// Convert any remaining EMPTY_VALUE types to STRING_VALUE
for (auto& pair : meta_value_types)
{
if (pair.second == OpenMS::DataValue::EMPTY_VALUE)
{
pair.second = OpenMS::DataValue::STRING_VALUE;
}
}
return meta_value_types;
}
// Base class for meta value builders to handle different types
class MetaValueBuilderBase
{
public:
virtual ~MetaValueBuilderBase() = default;
virtual arrow::Status AppendValue(const OpenMS::DataValue& value) = 0;
virtual arrow::Status AppendNull() = 0;
virtual arrow::Status Finish(std::shared_ptr<arrow::Array>* out) = 0;
};
// String meta value builder
class StringMetaValueBuilder : public MetaValueBuilderBase
{
private:
arrow::StringBuilder builder_;
public:
arrow::Status AppendValue(const OpenMS::DataValue& value) override
{
return builder_.Append(value.toString().c_str());
}
arrow::Status AppendNull() override
{
return builder_.AppendNull();
}
arrow::Status Finish(std::shared_ptr<arrow::Array>* out) override
{
return builder_.Finish(out);
}
};
// Integer meta value builder
class IntMetaValueBuilder : public MetaValueBuilderBase
{
private:
arrow::Int64Builder builder_;
public:
arrow::Status AppendValue(const OpenMS::DataValue& value) override
{
try
{
return builder_.Append(static_cast<int64_t>(value));
}
catch (...)
{
return builder_.AppendNull(); // Fall back to null if conversion fails
}
}
arrow::Status AppendNull() override
{
return builder_.AppendNull();
}
arrow::Status Finish(std::shared_ptr<arrow::Array>* out) override
{
return builder_.Finish(out);
}
};
// Double meta value builder
class DoubleMetaValueBuilder : public MetaValueBuilderBase
{
private:
arrow::DoubleBuilder builder_;
public:
arrow::Status AppendValue(const OpenMS::DataValue& value) override
{
try
{
return builder_.Append(static_cast<double>(value));
}
catch (...)
{
return builder_.AppendNull(); // Fall back to null if conversion fails
}
}
arrow::Status AppendNull() override
{
return builder_.AppendNull();
}
arrow::Status Finish(std::shared_ptr<arrow::Array>* out) override
{
return builder_.Finish(out);
}
};
// String list meta value builder
class StringListMetaValueBuilder : public MetaValueBuilderBase
{
private:
arrow::ListBuilder builder_;
arrow::StringBuilder value_builder_;
public:
StringListMetaValueBuilder() : builder_(arrow::default_memory_pool(), std::make_shared<arrow::StringBuilder>())
{
}
arrow::Status AppendValue(const OpenMS::DataValue& value) override
{
try
{
auto string_list = value.toStringList();
ARROW_RETURN_NOT_OK(builder_.Append());
for (const auto& str : string_list)
{
ARROW_RETURN_NOT_OK(static_cast<arrow::StringBuilder*>(builder_.value_builder())->Append(str.c_str()));
}
return arrow::Status::OK();
}
catch (...)
{
return builder_.AppendNull(); // Fall back to null if conversion fails
}
}
arrow::Status AppendNull() override
{
return builder_.AppendNull();
}
arrow::Status Finish(std::shared_ptr<arrow::Array>* out) override
{
return builder_.Finish(out);
}
};
// Integer list meta value builder
class IntListMetaValueBuilder : public MetaValueBuilderBase
{
private:
arrow::ListBuilder builder_;
public:
IntListMetaValueBuilder() : builder_(arrow::default_memory_pool(), std::make_shared<arrow::Int64Builder>())
{
}
arrow::Status AppendValue(const OpenMS::DataValue& value) override
{
try
{
auto int_list = value.toIntList();
ARROW_RETURN_NOT_OK(builder_.Append());
for (const auto& val : int_list)
{
ARROW_RETURN_NOT_OK(static_cast<arrow::Int64Builder*>(builder_.value_builder())->Append(static_cast<int64_t>(val)));
}
return arrow::Status::OK();
}
catch (...)
{
return builder_.AppendNull(); // Fall back to null if conversion fails
}
}
arrow::Status AppendNull() override
{
return builder_.AppendNull();
}
arrow::Status Finish(std::shared_ptr<arrow::Array>* out) override
{
return builder_.Finish(out);
}
};
// Double list meta value builder
class DoubleListMetaValueBuilder : public MetaValueBuilderBase
{
private:
arrow::ListBuilder builder_;
public:
DoubleListMetaValueBuilder() : builder_(arrow::default_memory_pool(), std::make_shared<arrow::DoubleBuilder>())
{
}
arrow::Status AppendValue(const OpenMS::DataValue& value) override
{
try
{
auto double_list = value.toDoubleList();
ARROW_RETURN_NOT_OK(builder_.Append());
for (const auto& val : double_list)
{
ARROW_RETURN_NOT_OK(static_cast<arrow::DoubleBuilder*>(builder_.value_builder())->Append(val));
}
return arrow::Status::OK();
}
catch (...)
{
return builder_.AppendNull(); // Fall back to null if conversion fails
}
}
arrow::Status AppendNull() override
{
return builder_.AppendNull();
}
arrow::Status Finish(std::shared_ptr<arrow::Array>* out) override
{
return builder_.Finish(out);
}
};
// Factory function to create appropriate meta value builder
std::unique_ptr<MetaValueBuilderBase> createMetaValueBuilder(OpenMS::DataValue::DataType data_type)
{
switch (data_type)
{
case OpenMS::DataValue::STRING_VALUE:
return std::make_unique<StringMetaValueBuilder>();
case OpenMS::DataValue::INT_VALUE:
return std::make_unique<IntMetaValueBuilder>();
case OpenMS::DataValue::DOUBLE_VALUE:
return std::make_unique<DoubleMetaValueBuilder>();
case OpenMS::DataValue::STRING_LIST:
return std::make_unique<StringListMetaValueBuilder>();
case OpenMS::DataValue::INT_LIST:
return std::make_unique<IntListMetaValueBuilder>();
case OpenMS::DataValue::DOUBLE_LIST:
return std::make_unique<DoubleListMetaValueBuilder>();
case OpenMS::DataValue::EMPTY_VALUE:
default:
return std::make_unique<StringMetaValueBuilder>(); // Default to string
}
}
std::shared_ptr<arrow::Schema> createPSMSchema(bool export_all_psms = false,
const std::set<OpenMS::String>& meta_value_keys = {},
const std::map<OpenMS::String, OpenMS::DataValue::DataType>& meta_value_types = {})
{
std::vector<std::shared_ptr<arrow::Field>> fields = {
arrow::field("sequence", arrow::utf8()),
arrow::field("peptidoform", arrow::utf8()),
arrow::field("modifications", arrow::null(), true), // nullable - null for now
arrow::field("precursor_charge", arrow::int32()),
arrow::field("posterior_error_probability", arrow::float32(), true), // nullable
arrow::field("is_decoy", arrow::int32()),
arrow::field("calculated_mz", arrow::float32()),
arrow::field("observed_mz", arrow::float32()),
arrow::field("additional_scores", arrow::null(), true), // nullable - null for now
arrow::field("protein_accessions", arrow::null(), true), // nullable - null for now
arrow::field("predicted_rt", arrow::float32(), true), // nullable
arrow::field("reference_file_name", arrow::utf8()),
arrow::field("cv_params", arrow::null(), true), // nullable - null for now
arrow::field("scan", arrow::utf8()),
arrow::field("rt", arrow::float32(), true), // nullable
arrow::field("ion_mobility", arrow::float32(), true), // nullable
arrow::field("number_peaks", arrow::int32(), true), // nullable
arrow::field("mz_array", arrow::null(), true), // nullable - null for now
arrow::field("intensity_array", arrow::null(), true) // nullable - null for now
};
// Add rank column if exporting all PSMs
if (export_all_psms)
{
fields.insert(fields.begin() + 4, arrow::field("rank", arrow::int32())); // Insert after precursor_charge
}
// Add meta value columns with appropriate types
for (const auto& key : meta_value_keys)
{
auto type_it = meta_value_types.find(key);
std::shared_ptr<arrow::DataType> arrow_type;
if (type_it != meta_value_types.end())
{
arrow_type = dataValueTypeToArrowType(type_it->second);
}
else
{
arrow_type = arrow::utf8(); // Default to string
}
fields.push_back(arrow::field(key.c_str(), arrow_type, true)); // nullable
}
return arrow::schema(fields);
}
void writeParquetFile(const std::shared_ptr<arrow::Table>& table,
const OpenMS::String& filename,
const std::map<std::string, std::string>& file_metadata = {})
{
std::shared_ptr<arrow::io::FileOutputStream> outfile;
auto result = arrow::io::FileOutputStream::Open(filename.c_str());
if (!result.ok()) {
throw OpenMS::Exception::UnableToCreateFile(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
filename, "Failed to open parquet file: " + OpenMS::String(result.status().ToString()));
}
outfile = result.ValueOrDie();
// Create a writer with parquet::arrow::FileWriter
auto writer_result = parquet::arrow::FileWriter::Open(*table->schema(),
arrow::default_memory_pool(),
outfile);
if (!writer_result.ok()) {
throw OpenMS::Exception::UnableToCreateFile(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
filename, "Failed to create parquet writer: " + OpenMS::String(writer_result.status().ToString()));
}
std::unique_ptr<parquet::arrow::FileWriter> writer = std::move(writer_result.ValueOrDie());
// Add metadata to the parquet file using AddKeyValueMetadata
if (!file_metadata.empty()) {
std::vector<std::string> md_keys, md_values;
for (const auto& kv : file_metadata) {
md_keys.push_back(kv.first);
md_values.push_back(kv.second);
}
const auto metadata = arrow::key_value_metadata(md_keys,md_values);
auto status = writer->AddKeyValueMetadata(metadata);
if (!status.ok()) {
throw OpenMS::Exception::UnableToCreateFile(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
filename, "Failed to add metadata: " + OpenMS::String(status.ToString()));
}
}
// Write table using the FileWriter
auto status = writer->WriteTable(*table, table->num_rows());
if (!status.ok()) {
throw OpenMS::Exception::UnableToCreateFile(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
filename, "Failed to write parquet file: " + OpenMS::String(status.ToString()));
}
// Close writer
status = writer->Close();
if (!status.ok()) {
throw OpenMS::Exception::UnableToCreateFile(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
filename, "Failed to close writer: " + OpenMS::String(status.ToString()));
}
}
std::shared_ptr<arrow::Table> convertToArrowTable(
const std::vector<OpenMS::ProteinIdentification>& protein_identifications,
const OpenMS::PeptideIdentificationList& peptide_identifications,
bool export_all_psms = false,
const std::set<OpenMS::String>& meta_value_keys = {})
{
// First, determine meta value types by scanning all data
auto meta_value_types = determineMetaValueTypes(peptide_identifications, meta_value_keys, export_all_psms);
// Create builders for each column - using simpler types for now
arrow::StringBuilder sequence_builder;
arrow::StringBuilder peptidoform_builder;
arrow::Int32Builder precursor_charge_builder;
arrow::Int32Builder rank_builder; // Only used if export_all_psms is true
arrow::FloatBuilder posterior_error_probability_builder;
arrow::Int32Builder is_decoy_builder;
arrow::FloatBuilder calculated_mz_builder;
arrow::FloatBuilder observed_mz_builder;
arrow::StringBuilder mp_accessions_builder; // Use comma-separated string for now
arrow::FloatBuilder predicted_rt_builder;
arrow::StringBuilder reference_file_name_builder;
arrow::StringBuilder scan_builder;
arrow::FloatBuilder rt_builder;
arrow::FloatBuilder ion_mobility_builder;
arrow::Int32Builder num_peaks_builder;
// Create typed builders for meta value columns
std::map<OpenMS::String, std::unique_ptr<MetaValueBuilderBase>> meta_value_builders;
for (const auto& key : meta_value_keys)
{
auto type_it = meta_value_types.find(key);
OpenMS::DataValue::DataType data_type = (type_it != meta_value_types.end()) ?
type_it->second : OpenMS::DataValue::STRING_VALUE;
meta_value_builders[key] = createMetaValueBuilder(data_type);
}
// Find associated protein identification for metadata
std::map<OpenMS::String, const OpenMS::ProteinIdentification*> protein_id_map;
for (const auto& protein_id : protein_identifications)
{
protein_id_map[protein_id.getIdentifier()] = &protein_id;
}
// Find PEP score if available using IDScoreSwitcherAlgorithm
OpenMS::String pep_score_name;
bool is_main_score_pep = false;
if (!peptide_identifications.empty())
{
OpenMS::IDScoreSwitcherAlgorithm score_switcher;
const auto& first_peptide_id = peptide_identifications[0];
auto pep_result = score_switcher.findScoreType(first_peptide_id, OpenMS::IDScoreSwitcherAlgorithm::ScoreType::PEP);
pep_score_name = pep_result.score_name;
is_main_score_pep = pep_result.is_main_score_type;
}
// Process each peptide identification
for (const auto& peptide_id : peptide_identifications)
{
const auto& hits = peptide_id.getHits();
if (hits.empty()) continue; // Skip if no hits
// Determine how many hits to process
size_t num_hits_to_process = export_all_psms ? hits.size() : 1;
for (size_t hit_index = 0; hit_index < num_hits_to_process; ++hit_index)
{
const OpenMS::PeptideHit& hit = hits[hit_index];
// Sequence
OpenMS::String sequence = hit.getSequence().toUnmodifiedString();
auto status = sequence_builder.Append(sequence.c_str());
if (!status.ok()) {
throw OpenMS::Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Failed to append sequence: " + OpenMS::String(status.ToString()));
}
// Peptidoform (sequence with modifications in ProForma format)
OpenMS::String peptidoform = hit.getSequence().toBracketString(true, false);
// Convert round brackets to square brackets for ProForma format
peptidoform.substitute("(", "[");
peptidoform.substitute(")", "]");
status = peptidoform_builder.Append(peptidoform.c_str());
if (!status.ok()) {
throw OpenMS::Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Failed to append peptidoform: " + OpenMS::String(status.ToString()));
}
// Precursor charge
status = precursor_charge_builder.Append(hit.getCharge());
if (!status.ok()) {
throw OpenMS::Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Failed to append precursor charge: " + OpenMS::String(status.ToString()));
}
// Rank (if exporting all PSMs)
if (export_all_psms)
{
status = rank_builder.Append(static_cast<int>(hit_index + 1)); // rank is 1-based
if (!status.ok()) {
throw OpenMS::Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Failed to append rank: " + OpenMS::String(status.ToString()));
}
}
// Posterior error probability
if (is_main_score_pep)
{
// Use main score as PEP value
double pep_value = hit.getScore();
status = posterior_error_probability_builder.Append(static_cast<float>(pep_value));
}
else if (!pep_score_name.empty() && hit.metaValueExists(pep_score_name))
{
double pep_value = hit.getMetaValue(pep_score_name);
status = posterior_error_probability_builder.Append(static_cast<float>(pep_value));
}
else
{
status = posterior_error_probability_builder.AppendNull();
}
if (!status.ok()) {
throw OpenMS::Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Failed to append posterior error probability: " + OpenMS::String(status.ToString()));
}
// Is decoy - use the isDecoy() method from PeptideHit
int is_decoy = hit.isDecoy() ? 1 : 0;
status = is_decoy_builder.Append(is_decoy);
if (!status.ok()) {
throw OpenMS::Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Failed to append is_decoy: " + OpenMS::String(status.ToString()));
}
// Calculated m/z (theoretical)
double theoretical_mz = hit.getSequence().getMonoWeight(OpenMS::Residue::Full, hit.getCharge());
status = calculated_mz_builder.Append(static_cast<float>(theoretical_mz));
if (!status.ok()) {
throw OpenMS::Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Failed to append calculated mz: " + OpenMS::String(status.ToString()));
}
// Observed m/z (experimental)
double observed_mz = peptide_id.getMZ();
status = observed_mz_builder.Append(static_cast<float>(observed_mz));
if (!status.ok()) {
throw OpenMS::Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Failed to append observed mz: " + OpenMS::String(status.ToString()));
}
// Protein accessions (comma-separated string for now)
OpenMS::String protein_accessions;
const auto& peptide_evidences = hit.getPeptideEvidences();
for (size_t i = 0; i < peptide_evidences.size(); ++i)
{
if (i > 0) protein_accessions += ",";
protein_accessions += peptide_evidences[i].getProteinAccession();
}
status = mp_accessions_builder.Append(protein_accessions.c_str());
if (!status.ok()) {
throw OpenMS::Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Failed to append protein accessions: " + OpenMS::String(status.ToString()));
}
// Predicted RT (null for now)
status = predicted_rt_builder.AppendNull();
if (!status.ok()) {
throw OpenMS::Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Failed to append predicted rt: " + OpenMS::String(status.ToString()));
}
// Reference file name
OpenMS::String file_name = peptide_id.getSpectrumReference();
if (file_name.empty())
{
file_name = peptide_id.getBaseName();
}
if (file_name.empty())
{
file_name = "unknown";
}
status = reference_file_name_builder.Append(file_name.c_str());
if (!status.ok()) {
throw OpenMS::Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Failed to append reference file name: " + OpenMS::String(status.ToString()));
}
// Scan
OpenMS::String scan = peptide_id.getSpectrumReference();
if (scan.empty())
{
// Generate scan from RT if available
std::ostringstream scan_stream;
scan_stream << "RT_" << peptide_id.getRT();
scan = scan_stream.str();
}
status = scan_builder.Append(scan.c_str());
if (!status.ok()) {
throw OpenMS::Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Failed to append scan: " + OpenMS::String(status.ToString()));
}
// RT (retention time)
double rt = peptide_id.getRT();
if (rt >= 0)
{
status = rt_builder.Append(static_cast<float>(rt));
}
else
{
status = rt_builder.AppendNull();
}
if (!status.ok()) {
throw OpenMS::Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Failed to append rt: " + OpenMS::String(status.ToString()));
}
// Ion mobility
if (hit.metaValueExists(OpenMS::Constants::UserParam::IM))
{
double ion_mobility = hit.getMetaValue(OpenMS::Constants::UserParam::IM);
status = ion_mobility_builder.Append(ion_mobility);
}
else
{
status = ion_mobility_builder.AppendNull();
}
if (!status.ok()) {
throw OpenMS::Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Failed to append ion mobility: " + OpenMS::String(status.ToString()));
}
// Num peaks
if (hit.metaValueExists(OpenMS::Constants::UserParam::NUM_PEAKS))
{
int num_peaks = hit.getMetaValue(OpenMS::Constants::UserParam::NUM_PEAKS);
status = num_peaks_builder.Append(num_peaks);
}
else
{
status = num_peaks_builder.AppendNull();
}
if (!status.ok()) {
throw OpenMS::Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Failed to append num peaks: " + OpenMS::String(status.ToString()));
}
// Process meta values
for (const auto& key : meta_value_keys)
{
auto& builder = meta_value_builders[key];
if (hit.metaValueExists(key))
{
OpenMS::DataValue meta_value = hit.getMetaValue(key);
status = builder->AppendValue(meta_value);
}
else
{
status = builder->AppendNull();
}
if (!status.ok()) {
throw OpenMS::Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Failed to append meta value " + key + ": " + OpenMS::String(status.ToString()));
}
}
} // End hit processing loop
} // End peptide identification loop
// Finish builders and create arrays
std::shared_ptr<arrow::Array> sequence_array;
auto status = sequence_builder.Finish(&sequence_array);
if (!status.ok()) {
throw OpenMS::Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Failed to finish sequence array: " + OpenMS::String(status.ToString()));
}
std::shared_ptr<arrow::Array> peptidoform_array;
status = peptidoform_builder.Finish(&peptidoform_array);
if (!status.ok()) {
throw OpenMS::Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Failed to finish peptidoform array: " + OpenMS::String(status.ToString()));
}
std::shared_ptr<arrow::Array> precursor_charge_array;
status = precursor_charge_builder.Finish(&precursor_charge_array);
if (!status.ok()) {
throw OpenMS::Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Failed to finish precursor charge array: " + OpenMS::String(status.ToString()));
}
std::shared_ptr<arrow::Array> posterior_error_probability_array;
status = posterior_error_probability_builder.Finish(&posterior_error_probability_array);
if (!status.ok()) {
throw OpenMS::Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Failed to finish posterior error probability array: " + OpenMS::String(status.ToString()));
}
std::shared_ptr<arrow::Array> is_decoy_array;
status = is_decoy_builder.Finish(&is_decoy_array);
if (!status.ok()) {
throw OpenMS::Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Failed to finish is_decoy array: " + OpenMS::String(status.ToString()));
}
std::shared_ptr<arrow::Array> calculated_mz_array;
status = calculated_mz_builder.Finish(&calculated_mz_array);
if (!status.ok()) {
throw OpenMS::Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Failed to finish calculated mz array: " + OpenMS::String(status.ToString()));
}
std::shared_ptr<arrow::Array> observed_mz_array;
status = observed_mz_builder.Finish(&observed_mz_array);
if (!status.ok()) {
throw OpenMS::Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Failed to finish observed mz array: " + OpenMS::String(status.ToString()));
}
std::shared_ptr<arrow::Array> mp_accessions_array;
status = mp_accessions_builder.Finish(&mp_accessions_array);
if (!status.ok()) {
throw OpenMS::Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Failed to finish mp_accessions array: " + OpenMS::String(status.ToString()));
}
std::shared_ptr<arrow::Array> predicted_rt_array;
status = predicted_rt_builder.Finish(&predicted_rt_array);
if (!status.ok()) {
throw OpenMS::Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Failed to finish predicted rt array: " + OpenMS::String(status.ToString()));
}
std::shared_ptr<arrow::Array> reference_file_name_array;
status = reference_file_name_builder.Finish(&reference_file_name_array);
if (!status.ok()) {
throw OpenMS::Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Failed to finish reference file name array: " + OpenMS::String(status.ToString()));
}
std::shared_ptr<arrow::Array> scan_array;
status = scan_builder.Finish(&scan_array);
if (!status.ok()) {
throw OpenMS::Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Failed to finish scan array: " + OpenMS::String(status.ToString()));
}
std::shared_ptr<arrow::Array> rt_array;
status = rt_builder.Finish(&rt_array);
if (!status.ok()) {
throw OpenMS::Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Failed to finish rt array: " + OpenMS::String(status.ToString()));
}
std::shared_ptr<arrow::Array> ion_mobility_array;
status = ion_mobility_builder.Finish(&ion_mobility_array);
if (!status.ok()) {
throw OpenMS::Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Failed to finish ion mobility array: " + OpenMS::String(status.ToString()));
}
std::shared_ptr<arrow::Array> num_peaks_array;
status = num_peaks_builder.Finish(&num_peaks_array);
if (!status.ok()) {
throw OpenMS::Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Failed to finish num peaks array: " + OpenMS::String(status.ToString()));
}
// Finish rank array if needed
std::shared_ptr<arrow::Array> rank_array;
if (export_all_psms)
{
status = rank_builder.Finish(&rank_array);
if (!status.ok()) {
throw OpenMS::Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Failed to finish rank array: " + OpenMS::String(status.ToString()));
}
}
// Finish meta value arrays
std::map<OpenMS::String, std::shared_ptr<arrow::Array>> meta_value_arrays;
for (const auto& key : meta_value_keys)
{
std::shared_ptr<arrow::Array> meta_array;
status = meta_value_builders[key]->Finish(&meta_array);
if (!status.ok()) {
throw OpenMS::Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Failed to finish meta value array for " + key + ": " + OpenMS::String(status.ToString()));
}
meta_value_arrays[key] = meta_array;
}
// Create simplified schema for now - will add complex nested types later
auto schema = createPSMSchema(export_all_psms, meta_value_keys, meta_value_types);
// Build the arrays vector in the correct order to match the schema
std::vector<std::shared_ptr<arrow::Array>> arrays = {
sequence_array,
peptidoform_array,
arrow::MakeArrayOfNull(arrow::null(), sequence_array->length()).ValueOrDie(), // modifications - null for now
precursor_charge_array
};
// Add rank array if exporting all PSMs (inserted after precursor_charge)
if (export_all_psms)
{
arrays.push_back(rank_array);
}
// Continue with the rest of the standard columns
arrays.insert(arrays.end(), {
posterior_error_probability_array,
is_decoy_array,
calculated_mz_array,
observed_mz_array,
arrow::MakeArrayOfNull(arrow::null(), sequence_array->length()).ValueOrDie(), // additional_scores - null for now
arrow::MakeArrayOfNull(arrow::null(), sequence_array->length()).ValueOrDie(), // protein_accessions - using mp_accessions_array would need list type
predicted_rt_array,
reference_file_name_array,
arrow::MakeArrayOfNull(arrow::null(), sequence_array->length()).ValueOrDie(), // cv_params - null for now
scan_array,
rt_array,
ion_mobility_array,
num_peaks_array,
arrow::MakeArrayOfNull(arrow::null(), sequence_array->length()).ValueOrDie(), // mz_array - null for now
arrow::MakeArrayOfNull(arrow::null(), sequence_array->length()).ValueOrDie() // intensity_array - null for now
});
// Add meta value arrays in the same order as in the schema
for (const auto& key : meta_value_keys)
{
arrays.push_back(meta_value_arrays[key]);
}
auto table = arrow::Table::Make(schema, arrays);
return table;
}
} // anonymous namespace
namespace OpenMS
{
QuantmsIO::~QuantmsIO() = default;
void QuantmsIO::store(const String& filename,
const std::vector<ProteinIdentification>& protein_identifications,
const PeptideIdentificationList& peptide_identifications)
{
store(filename, protein_identifications, peptide_identifications, false, {});
}
void QuantmsIO::store(const String& filename,
const std::vector<ProteinIdentification>& protein_identifications,
const PeptideIdentificationList& peptide_identifications,
bool export_all_psms)
{
store(filename, protein_identifications, peptide_identifications, export_all_psms, {});
}
void QuantmsIO::store(const String& filename,
const std::vector<ProteinIdentification>& protein_identifications,
const PeptideIdentificationList& peptide_identifications,
bool export_all_psms,
const std::set<String>& meta_value_keys)
{
// Generate file metadata
auto now = std::chrono::system_clock::now();
auto time_t = std::chrono::system_clock::to_time_t(now);
std::ostringstream creation_date_stream;
creation_date_stream << std::put_time(std::gmtime(&time_t), "%Y-%m-%dT%H:%M:%SZ");
std::string creation_date_str = creation_date_stream.str();
// Generate a simple UUID based on current time and process
std::ostringstream uuid_stream;
uuid_stream << std::hex << std::hash<std::string>{}(creation_date_str) << "-0000-4000-8000-"
<< std::setfill('0') << std::setw(12) << (std::hash<const void*>{}(&protein_identifications) & 0xFFFFFFFFFFFF);
std::string uuid_str = uuid_stream.str();
// Create file metadata map
std::map<std::string, std::string> file_metadata = {
{"quantmsio_version", "1.0"},
{"creator", "OpenMS"},
{"file_type", "psm"},
{"creation_date", creation_date_str},
{"uuid", uuid_str},
{"scan_format", "scan"},
{"software_provider", "OpenMS"}
};
// Convert data to Arrow table
auto table = convertToArrowTable(protein_identifications, peptide_identifications, export_all_psms, meta_value_keys);
// Write to parquet file with metadata
writeParquetFile(table, filename, file_metadata);
}
} // namespace OpenMS | C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/MzDataFile.cpp | .cpp | 2,055 | 79 | // 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/SYSTEM/File.h>
#include <OpenMS/FORMAT/MzDataFile.h>
#include <OpenMS/FORMAT/VALIDATORS/MzDataValidator.h>
#include <OpenMS/FORMAT/CVMappingFile.h>
#include <OpenMS/FORMAT/ControlledVocabulary.h>
namespace OpenMS
{
MzDataFile::MzDataFile() :
XMLFile("/SCHEMAS/mzData_1_05.xsd", "1.05"),
options_()
{
}
MzDataFile::~MzDataFile() = default;
PeakFileOptions & MzDataFile::getOptions()
{
return options_;
}
const PeakFileOptions & MzDataFile::getOptions() const
{
return options_;
}
void MzDataFile::setOptions(const PeakFileOptions & options)
{
options_ = options;
}
bool MzDataFile::isSemanticallyValid(const String & filename, StringList & errors, StringList & warnings)
{
//load mapping
CVMappings mapping;
CVMappingFile().load(File::find("/MAPPING/mzdata-mapping.xml"), mapping);
//load cvs
ControlledVocabulary cv;
cv.loadFromOBO("PSI", File::find("/CV/psi-mzdata.obo"));
//validate
Internal::MzDataValidator v(mapping, cv);
bool result = v.validate(filename, errors, warnings);
return result;
}
void MzDataFile::load(const String & filename, PeakMap & map)
{
map.reset();
//set DocumentIdentifier
map.setLoadedFileType(filename);
map.setLoadedFilePath(filename);
Internal::MzDataHandler handler(map, filename, schema_version_, *this);
handler.setOptions(options_);
parse_(filename, &handler);
}
void MzDataFile::store(const String & filename, const PeakMap & map) const
{
Internal::MzDataHandler handler(map, filename, schema_version_, *this);
handler.setOptions(options_);
save_(filename, &handler);
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/HDF5Connector.cpp | .cpp | 1,481 | 55 | // 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/HDF5Connector.h>
#include <OpenMS/CONCEPT/Exception.h>
#include "H5Cpp.h"
using namespace H5;
namespace OpenMS
{
HDF5Connector::~HDF5Connector()
{
close();
}
void HDF5Connector::close()
{
if (file_)
{
file_->flush(H5F_SCOPE_LOCAL);
file_->close();
delete file_;
file_ = nullptr;
}
}
HDF5Connector::HDF5Connector(const String& filename, bool createNewFile)
{
// H5F_ACC_TRUNC - Truncate file, if it already exists, erasing all data previously stored in the file.
// H5F_ACC_EXCL - Fail if file already exists. H5F_ACC_TRUNC and H5F_ACC_EXCL are mutually exclusive
// H5F_ACC_RDONLY - Open file as read-only, if it already exists, and fail, otherwise
// H5F_ACC_RDWR - Open file for read/write, if it already exists, and fail, otherwise
unsigned int openFlag = H5F_ACC_RDWR;
if (createNewFile)
{
openFlag = H5F_ACC_TRUNC;
}
FileCreatPropList fcparm = FileCreatPropList::DEFAULT;
FileAccPropList faparm = FileAccPropList::DEFAULT;
file_ = new H5::H5File(filename, openFlag, fcparm, faparm);
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/FileTypes.cpp | .cpp | 13,357 | 253 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Stephan Aiche, Andreas Bertsch, Marc Sturm, Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/FORMAT/FileTypes.h>
#include <OpenMS/CONCEPT/Exception.h>
#include <OpenMS/DATASTRUCTURES/ListUtils.h>
#include <array>
#include <list>
#include <utility>
#include <cassert>
namespace OpenMS
{
/// connect the type to some other information
/// We could also use paired arrays, but this way, its less likely to have mismatches if a new type is added
struct TypeNameBinding
{
FileTypes::Type type;
String name;
String description;
std::vector<FileTypes::FileProperties> features;
TypeNameBinding(FileTypes::Type ptype, String pname, String pdescription, std::vector<FileTypes::FileProperties> pfeatures)
: type(ptype), name(std::move(pname)), description(std::move(pdescription)), features(pfeatures)
{
// Check that there are no double-spaces in the description, since Qt will replace " " with " " in filters supplied to QFileDialog::getSaveFileName.
// And if you later ask for the selected filter, you will get a different string back.
assert(description.find(" ") == std::string::npos);
}
};
using PROP = FileTypes::FileProperties; // shorten our syntax a bit
/// Maps the FileType::Type to the preferred extension.
/// when adding new types, be sure to update the FileTypes_test typesWithProperties test to match the new files
static const std::array<TypeNameBinding, FileTypes::SIZE_OF_TYPE> type_with_annotation__ =
{
TypeNameBinding(FileTypes::UNKNOWN, "unknown", "unknown file extension", {}),
TypeNameBinding(FileTypes::DTA, "dta", "dta raw data file", {PROP::PROVIDES_EXPERIMENT, PROP::PROVIDES_SPECTRUM, PROP::READABLE, PROP::WRITEABLE}),
TypeNameBinding(FileTypes::DTA2D, "dta2d", "dta2d raw data file", {PROP::PROVIDES_EXPERIMENT, PROP::READABLE, PROP::WRITEABLE}),
TypeNameBinding(FileTypes::MZDATA, "mzData", "mzData raw data file", {PROP::PROVIDES_EXPERIMENT, PROP::READABLE, PROP::WRITEABLE}),
TypeNameBinding(FileTypes::MZXML, "mzXML", "mzXML raw data file", {PROP::PROVIDES_EXPERIMENT, PROP::READABLE, PROP::WRITEABLE}),
TypeNameBinding(FileTypes::FEATUREXML, "featureXML", "OpenMS feature map", {PROP::PROVIDES_FEATURES, PROP::READABLE, PROP::WRITEABLE}),
TypeNameBinding(FileTypes::IDXML, "idXML", "OpenMS peptide identification file", {PROP::PROVIDES_IDENTIFICATIONS, PROP::READABLE, PROP::WRITEABLE}),
TypeNameBinding(FileTypes::CONSENSUSXML, "consensusXML", "OpenMS consensus feature map", {PROP::PROVIDES_CONSENSUSFEATURES, PROP::READABLE, PROP::WRITEABLE}),
TypeNameBinding(FileTypes::MGF, "mgf", "mascot generic format file", {PROP::PROVIDES_EXPERIMENT, PROP::READABLE, PROP::WRITEABLE}),
TypeNameBinding(FileTypes::INI, "ini", "OpenMS parameter file", {PROP::READABLE}),
TypeNameBinding(FileTypes::TOPPAS, "toppas", "OpenMS TOPPAS pipeline", {PROP::READABLE}),
TypeNameBinding(FileTypes::TRANSFORMATIONXML, "trafoXML", "RT transformation file", {PROP::PROVIDES_TRANSFORMATIONS, PROP::READABLE, PROP::WRITEABLE}),
TypeNameBinding(FileTypes::MZML, "mzML", "mzML raw data file", {PROP::PROVIDES_EXPERIMENT, PROP::READABLE, PROP::WRITEABLE}),
//TODO: Add support for cachedMZML as a first class file type
TypeNameBinding(FileTypes::CACHEDMZML, "cachedMzML", "cachedMzML raw data file", {PROP::READABLE, PROP::WRITEABLE}),
TypeNameBinding(FileTypes::MS2, "ms2", "ms2 file", {PROP::PROVIDES_EXPERIMENT, PROP::READABLE}),
TypeNameBinding(FileTypes::PEPXML, "pepXML", "pepXML file", {PROP::READABLE, PROP::WRITEABLE}), //Supported for loading and storing identifications but TODO integrate this into fileHandler
TypeNameBinding(FileTypes::PROTXML, "protXML", "protXML file", {PROP::PROVIDES_IDENTIFICATIONS, PROP::READABLE}),
TypeNameBinding(FileTypes::MZIDENTML, "mzid", "mzIdentML file", {PROP::PROVIDES_IDENTIFICATIONS, PROP::READABLE, PROP::WRITEABLE}),
TypeNameBinding(FileTypes::QCML, "qcml", "quality control file", {PROP::PROVIDES_QC, PROP::WRITEABLE}), //TODO add load functions for QC
TypeNameBinding(FileTypes::MZQC, "mzqc", "quality control file in json format", {PROP::PROVIDES_QC, PROP::WRITEABLE}),
TypeNameBinding(FileTypes::GELML, "gelML", "gelML file", {}),
TypeNameBinding(FileTypes::TRAML, "traML", "transition file", {PROP::PROVIDES_TRANSITIONS, PROP::READABLE, PROP::WRITEABLE}),
TypeNameBinding(FileTypes::MSP, "msp", "NIST spectra library file format", {PROP::PROVIDES_EXPERIMENT, PROP::READABLE, PROP::WRITEABLE}),
TypeNameBinding(FileTypes::OMSSAXML, "omssaXML", "omssaXML file", {PROP::PROVIDES_IDENTIFICATIONS, PROP::READABLE}),
TypeNameBinding(FileTypes::MASCOTXML, "mascotXML", "mascotXML file", {}),
TypeNameBinding(FileTypes::PNG, "png", "portable network graphics file", {}),
TypeNameBinding(FileTypes::XMASS, "fid", "XMass analysis file", {PROP::PROVIDES_EXPERIMENT, PROP::PROVIDES_SPECTRUM, PROP::READABLE, PROP::WRITEABLE}),
TypeNameBinding(FileTypes::TSV, "tsv", "tab-separated file", {PROP::PROVIDES_FEATURES, PROP::READABLE, PROP::WRITEABLE}),
TypeNameBinding(FileTypes::MZTAB, "mzTab", "mzTab file", {}), //TODO add filehandler support for MZTAB
TypeNameBinding(FileTypes::PEPLIST, "peplist", "SpecArray file", {PROP::PROVIDES_FEATURES, PROP::READABLE, PROP::WRITEABLE}),
TypeNameBinding(FileTypes::HARDKLOER, "hardkloer", "hardkloer file", {}),
TypeNameBinding(FileTypes::KROENIK, "kroenik", "kroenik file", {PROP::PROVIDES_FEATURES, PROP::READABLE, PROP::WRITEABLE}),
TypeNameBinding(FileTypes::FASTA, "fasta", "FASTA file", {PROP::READABLE, PROP::WRITEABLE}),
TypeNameBinding(FileTypes::EDTA, "edta", "enhanced dta file", {PROP::PROVIDES_FEATURES, PROP::PROVIDES_CONSENSUSFEATURES, PROP::READABLE, PROP::WRITEABLE}),
TypeNameBinding(FileTypes::CSV, "csv", "comma-separated values file", {PROP::READABLE, PROP::WRITEABLE}),
TypeNameBinding(FileTypes::TXT, "txt", "generic text file", {}),
TypeNameBinding(FileTypes::OBO, "obo", "controlled vocabulary file", {}),
TypeNameBinding(FileTypes::HTML, "html", "any HTML file", {}),
TypeNameBinding(FileTypes::ANALYSISXML, "analysisXML", "analysisXML file", {}),
TypeNameBinding(FileTypes::XSD, "xsd", "XSD schema format", {}),
TypeNameBinding(FileTypes::PSQ, "psq", "NCBI binary blast db", {}),
TypeNameBinding(FileTypes::MRM, "mrm", "SpectraST MRM list", {PROP::READABLE}),
TypeNameBinding(FileTypes::SQMASS, "sqMass", "SQLite format for mass and chromatograms", {PROP::READABLE, PROP::WRITEABLE}),
TypeNameBinding(FileTypes::PQP, "pqp", "pqp file", {PROP::READABLE, PROP::WRITEABLE}),
TypeNameBinding(FileTypes::MS, "ms", "SIRIUS file", {}),
TypeNameBinding(FileTypes::OSW, "osw", "OpenSwath output files", {PROP::READABLE, PROP::WRITEABLE}),
TypeNameBinding(FileTypes::PSMS, "psms", "Percolator tab-delimited output (PSM level)", {PROP::READABLE}),
TypeNameBinding(FileTypes::PIN, "pin", "Percolator tab-delimited input (PSM level)", {}),
TypeNameBinding(FileTypes::PARAMXML, "paramXML", "OpenMS internal XML file", {}),
TypeNameBinding(FileTypes::SPLIB, "splib", "SpectraST binary spectral library file", {}),
TypeNameBinding(FileTypes::NOVOR, "novor", "Novor custom parameter file", {}),
TypeNameBinding(FileTypes::XQUESTXML, "xquest.xml", "xquest.xml file", {PROP::PROVIDES_IDENTIFICATIONS, PROP::READABLE, PROP::WRITEABLE}),
TypeNameBinding(FileTypes::SPECXML, "spec.xml", "spec.xml file", {}),
TypeNameBinding(FileTypes::JSON, "json", "JavaScript Object Notation file", {PROP::READABLE, PROP::WRITEABLE}),
TypeNameBinding(FileTypes::RAW, "raw", "(Thermo) Raw data file", {}),
TypeNameBinding(FileTypes::OMS, "oms", "OpenMS SQLite file", {PROP::PROVIDES_IDENTIFICATIONS, PROP::PROVIDES_FEATURES, PROP::PROVIDES_CONSENSUSFEATURES}),
TypeNameBinding(FileTypes::EXE, "exe", "Windows executable", {}),
TypeNameBinding(FileTypes::BZ2, "bz2", "bzip2 compressed file", {PROP::READABLE}),
TypeNameBinding(FileTypes::GZ, "gz", "gzip compressed file", {PROP::READABLE}),
TypeNameBinding(FileTypes::PARQUET, "parquet", "Apache Parquet file", {PROP::READABLE, PROP::WRITEABLE}),
TypeNameBinding(FileTypes::XML, "xml", "any XML file", {PROP::READABLE}), // make sure this comes last, since the name is a suffix of other formats and should only be matched last
};
FileTypeList::FileTypeList(const std::vector<FileTypes::Type>& types)
: type_list_(types)
{
}
bool FileTypeList::contains(const FileTypes::Type& type) const
{
for (const auto& t : type_list_)
{
if (t == type)
{
return true;
}
}
return false;
}
String FileTypeList::toFileDialogFilter(const FilterLayout style, bool add_all_filter) const
{
return ListUtils::concatenate(asFilterElements_(style, add_all_filter).items, ";;");
}
FileTypes::Type FileTypeList::fromFileDialogFilter(const String& filter, const FileTypes::Type fallback) const
{
auto candidates = asFilterElements_(FilterLayout::BOTH, true); // may add more filters than needed, but that's fine
auto where = std::find(candidates.items.begin(), candidates.items.end(), filter);
if (where == candidates.items.end())
{
throw Exception::ElementNotFound(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filter);
}
const FileTypes::Type r = candidates.types[where - candidates.items.begin()];
return r == FileTypes::Type::UNKNOWN ? fallback : r;
}
std::vector<FileTypes::Type> FileTypeList::typesWithProperties(std::vector<FileTypes::FileProperties> haveFeatures)
{
std::vector<FileTypes::Type> compatible;
std::vector<TypeNameBinding> good_types(type_with_annotation__.begin(), type_with_annotation__.end());
// for each feature we are looking for
for (auto i : haveFeatures)
{
// Remove any types that lack the feature
good_types.erase(std::remove_if(good_types.begin(), good_types.end(),[i](auto j) { return (std::find(j.features.begin(),j.features.end(),i) == j.features.end()); }), good_types.end());
}
for (auto t : good_types)
{
compatible.push_back(t.type);
}
return compatible;
}
FileTypeList::FilterElements_ FileTypeList::asFilterElements_(const FilterLayout style, bool add_all_filter) const
{
FilterElements_ result;
if (style == FilterLayout::COMPACT || style == FilterLayout::BOTH)
{
StringList items;
for (const auto& t : type_list_)
{
items.push_back("*." + FileTypes::typeToName(t));
}
result.items.emplace_back("all readable files (" + ListUtils::concatenate(items, " ") + ")");
result.types.push_back(FileTypes::Type::UNKNOWN); // cannot associate a single type to a collection
}
if (style == FilterLayout::ONE_BY_ONE || style == FilterLayout::BOTH)
{
StringList items;
for (const auto& t : type_list_)
{
result.items.push_back(FileTypes::typeToDescription(t) + " (*." + FileTypes::typeToName(t) + ")");
result.types.push_back(t);
}
}
if (add_all_filter)
{
result.items.emplace_back("all files (*)");
result.types.push_back(FileTypes::Type::UNKNOWN); // cannot associate a single type to a collection
}
return result;
}
String FileTypes::typeToName(FileTypes::Type type)
{
for (const auto& t_info : type_with_annotation__)
{
if (t_info.type == type)
{
return t_info.name;
}
}
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Invalid type: Type has no name!", String(type));
}
String FileTypes::typeToDescription(Type type)
{
for (const auto& t_info : type_with_annotation__)
{
if (t_info.type == type) return t_info.description;
}
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Invalid type: Type has no description!", String(type));
}
FileTypes::Type FileTypes::nameToType(const String& name)
{
String name_upper = String(name).toUpper();
// Special case for multiple extensions for PARQUET
if (name_upper == "PQT")
{
return FileTypes::PARQUET;
}
for (const auto& t_info : type_with_annotation__)
{
if (String(t_info.name).toUpper() == name_upper)
{
return t_info.type;
}
}
return FileTypes::UNKNOWN;
}
String FileTypes::typeToMZML(FileTypes::Type type)
{
switch (type)
{
case FileTypes::DTA: return "DTA file";
case FileTypes::DTA2D: return "DTA file"; // technically not correct, but closer than just a random CV term (currently mzData) - entry cannot be left empty
case FileTypes::MZML: return "mzML file";
case FileTypes::MZDATA: return "PSI mzData file";
case FileTypes::MZXML: return "ISB mzXML file";
case FileTypes::MGF: return "Mascot MGF file";
case FileTypes::XMASS: return "Bruker FID file";
default: return "";
}
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/VALIDATORS/MzDataValidator.cpp | .cpp | 5,800 | 157 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#include <OpenMS/FORMAT/VALIDATORS/MzDataValidator.h>
#include <OpenMS/DATASTRUCTURES/CVMappingTerm.h>
#include <OpenMS/DATASTRUCTURES/CVMappingRule.h>
#include <OpenMS/FORMAT/ControlledVocabulary.h>
using namespace xercesc;
using namespace std;
namespace OpenMS::Internal
{
MzDataValidator::MzDataValidator(const CVMappings& mapping, const ControlledVocabulary& cv) :
SemanticValidator(mapping, cv)
{
setCheckUnits(true);
}
MzDataValidator::~MzDataValidator()
= default;
void MzDataValidator::handleTerm_(const String& path, const CVTerm& parsed_term)
{
//check if the term is allowed in this element
//and if there is a mapping rule for this element
//Also store fulfilled rule term counts - this count is used to check of the MUST/MAY and AND/OR/XOR is fulfilled
bool allowed = false;
bool rule_found = false;
vector<CVMappingRule>& rules = rules_[path];
for (Size r = 0; r < rules.size(); ++r) //go thru all rules
{
rule_found = true;
for (Size t = 0; t < rules[r].getCVTerms().size(); ++t) //go thru all terms
{
const CVMappingTerm& term = rules[r].getCVTerms()[t];
if (term.getUseTerm() && term.getAccession() == parsed_term.accession) //check if the term itself is allowed
{
allowed = true;
++fulfilled_[path][rules[r].getIdentifier()][term.getAccession()];
break;
}
if (term.getAllowChildren()) //check if the term's children are allowed
{
auto searcher = [&parsed_term] (const String& child)
{
return child == parsed_term.accession;
};
if (cv_.iterateAllChildren(term.getAccession(), searcher))
{
allowed = true;
++fulfilled_[path][rules[r].getIdentifier()][term.getAccession()];
break;
}
}
}
}
// check units
if (check_units_ && cv_.exists(parsed_term.accession))
{
ControlledVocabulary::CVTerm term = cv_.getTerm(parsed_term.accession);
// check if the cv term has units
if (!term.units.empty())
{
if (!parsed_term.has_unit_accession)
{
errors_.push_back(String("CV term must have a unit: " + parsed_term.accession + " - " + parsed_term.name));
}
else
{
// check if the accession is ok
if (cv_.exists(parsed_term.unit_accession))
{
// check whether this unit is allowed within the cv term
if (term.units.find(parsed_term.unit_accession) == term.units.end())
{
// last chance, a child term of the units was used
auto lambda = [&parsed_term] (const String& child)
{
return child == parsed_term.unit_accession;
};
bool found_unit(false);
for (set<String>::const_iterator it = term.units.begin(); it != term.units.end(); ++it)
{
if (cv_.iterateAllChildren(*it, lambda))
{
found_unit = true;
break;
}
}
if (!found_unit)
{
errors_.push_back(String("Unit CV term not allowed: " + parsed_term.unit_accession + " - " + parsed_term.unit_name + " of term " + parsed_term.accession + " - " + parsed_term.name));
}
}
}
else
{
errors_.push_back(String("Unit CV term not found: " + parsed_term.unit_accession + " - " + parsed_term.unit_name + " of term " + parsed_term.accession + " - " + parsed_term.name));
}
}
}
else
{
// check whether unit was used
if (parsed_term.has_unit_accession || parsed_term.has_unit_name)
{
warnings_.push_back(String("Unit CV term used, but not allowed: " + parsed_term.unit_accession + " - " + parsed_term.unit_name + " of term " + parsed_term.accession + " - " + parsed_term.name));
}
}
}
if (!rule_found) //No rule found
{
warnings_.push_back(String("No mapping rule found for element '") + getPath_(1) + "'");
}
else if (!allowed) //if rule found and not allowed
{
errors_.push_back(String("CV term used in invalid element: '") + parsed_term.accession + " - " + parsed_term.name + "' at element '" + getPath_(1) + "'");
}
//check if term accession and term name match
if (cv_.exists(parsed_term.accession))
{
String parsed_name = parsed_term.name;
parsed_name.trim();
String correct_name = cv_.getTerm(parsed_term.accession).name;
correct_name.trim();
//be a bit more soft: ignore upper-lower case
parsed_name.toLower();
correct_name.toLower();
//be a bit more soft: ignore spaces
parsed_name.removeWhitespaces();
correct_name.removeWhitespaces();
if (parsed_name != correct_name)
{
errors_.push_back(String("Name of CV term not correct: '") + parsed_term.accession + " - " + parsed_name + "' should be '" + correct_name + "'");
}
}
}
} // namespace OpenMS // namespace Internal
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/VALIDATORS/MzMLValidator.cpp | .cpp | 4,935 | 149 | // 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/VALIDATORS/MzMLValidator.h>
#include <OpenMS/FORMAT/ControlledVocabulary.h>
using namespace xercesc;
using namespace std;
namespace OpenMS::Internal
{
MzMLValidator::MzMLValidator(const CVMappings & mapping, const ControlledVocabulary & cv) :
SemanticValidator(mapping, cv),
binary_data_array_(),
binary_data_type_()
{
setCheckUnits(true);
}
MzMLValidator::~MzMLValidator()
= default;
//This method needed to be reimplemented to
// - check CV term values
// - handle referenceableParamGroups
// - check if binaryDataArray name and type match
void MzMLValidator::startElement(const XMLCh * const /*uri*/, const XMLCh * const /*local_name*/, const XMLCh * const qname, const Attributes & attributes)
{
String tag = sm_.convert(qname);
String parent_tag;
if (!open_tags_.empty())
{
parent_tag = open_tags_.back();
}
String path = getPath_() + "/" + cv_tag_ + "/@" + accession_att_;
open_tags_.push_back(tag);
if (tag == "referenceableParamGroup")
{
current_id_ = attributeAsString_(attributes, "id");
}
else if (tag == "referenceableParamGroupRef")
{
const std::vector<CVTerm> & terms = param_groups_[attributeAsString_(attributes, "ref")];
for (Size i = 0; i < terms.size(); ++i)
{
handleTerm_(path, terms[i]);
}
}
else if (tag == "binaryDataArray")
{
binary_data_array_ = "";
binary_data_type_ = "";
}
else if (tag == cv_tag_)
{
//extract accession, name and value
CVTerm parsed_term;
getCVTerm_(attributes, parsed_term);
//check if the term is unknown
if (!cv_.exists(parsed_term.accession))
{
warnings_.push_back(String("Unknown CV term: '") + parsed_term.accession + " - " + parsed_term.name + "' at element '" + getPath_(1) + "'");
return;
}
//check if the term is obsolete
if (cv_.getTerm(parsed_term.accession).obsolete)
{
warnings_.push_back(String("Obsolete CV term: '") + parsed_term.accession + " - " + parsed_term.name + "' at element '" + getPath_(1) + "'");
}
//actual handling of the term
if (parent_tag == "referenceableParamGroup")
{
param_groups_[current_id_].push_back(parsed_term);
}
else
{
handleTerm_(path, parsed_term);
}
}
}
//reimplemented in order to remove the "indexedmzML" tag from the front (if present)
String MzMLValidator::getPath_(UInt remove_from_end) const
{
String path;
if (!open_tags_.empty() && open_tags_.front() == "indexedmzML")
{
path.concatenate(open_tags_.begin() + 1, open_tags_.end() - remove_from_end, "/");
}
else
{
path.concatenate(open_tags_.begin(), open_tags_.end() - remove_from_end, "/");
}
path = String("/") + path;
return path;
}
//reimplemented to
// - catch non-PSI CVs
// - check if binaryDataArray name and type match
void MzMLValidator::handleTerm_(const String & path, const CVTerm & parsed_term)
{
//some CVs cannot be validated because they use 'part_of' which spoils the inheritance
if (parsed_term.accession.hasPrefix("GO:"))
{
return;
}
if (parsed_term.accession.hasPrefix("BTO:"))
{
return;
}
//check binary data array terms
if (path.hasSuffix("/binaryDataArray/cvParam/@accession"))
{
//binary data array
if (cv_.isChildOf(parsed_term.accession, "MS:1000513"))
{
binary_data_array_ = parsed_term.accession;
}
//binary data type
if (cv_.isChildOf(parsed_term.accession, "MS:1000518"))
{
binary_data_type_ = parsed_term.accession;
}
//if both are parsed, check if they match
if (!binary_data_type_.empty() && !binary_data_array_.empty())
{
if (!ListUtils::contains(cv_.getTerm(binary_data_array_).xref_binary, binary_data_type_))
{
errors_.push_back(String("Binary data array of type '") + binary_data_array_ + " ! " + cv_.getTerm(binary_data_array_).name + "' cannot have the value type '" + binary_data_type_ + " ! " + cv_.getTerm(binary_data_type_).name + "'.");
}
}
}
SemanticValidator::handleTerm_(path, parsed_term);
}
} // namespace OpenMS // namespace Internal
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/VALIDATORS/XMLValidator.cpp | .cpp | 3,805 | 117 | // 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/HANDLERS/XMLHandler.h>
#include <OpenMS/FORMAT/VALIDATORS/XMLValidator.h>
#include <OpenMS/SYSTEM/File.h>
#include <xercesc/sax2/SAX2XMLReader.hpp>
#include <xercesc/framework/LocalFileInputSource.hpp>
#include <xercesc/sax2/XMLReaderFactory.hpp>
using namespace xercesc;
using namespace std;
namespace OpenMS
{
XMLValidator::XMLValidator() :
valid_(true),
os_(nullptr)
{
}
bool XMLValidator::isValid(const String & filename, const String & schema, std::ostream & os)
{
filename_ = filename;
os_ = &os;
//try to open file
if (!File::exists(filename))
{
throw Exception::FileNotFound(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename);
}
// initialize parser
try
{
XMLPlatformUtils::Initialize();
}
catch (const XMLException & toCatch)
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"",
String("Error during initialization: ") + Internal::StringManager().convert(toCatch.getMessage()));
}
SAX2XMLReader * parser = XMLReaderFactory::createXMLReader();
parser->setFeature(XMLUni::fgSAX2CoreNameSpaces, true);
parser->setFeature(XMLUni::fgSAX2CoreValidation, true);
parser->setFeature(XMLUni::fgXercesDynamic, false);
parser->setFeature(XMLUni::fgXercesSchema, true);
parser->setFeature(XMLUni::fgXercesSchemaFullChecking, true);
//set this class as error handler
parser->setErrorHandler(this);
parser->setContentHandler(nullptr);
parser->setEntityResolver(nullptr);
//load schema
LocalFileInputSource schema_file(Internal::StringManager().convert(schema).c_str());
parser->loadGrammar(schema_file, Grammar::SchemaGrammarType, true);
parser->setFeature(XMLUni::fgXercesUseCachedGrammarInParse, true);
// try to parse file
LocalFileInputSource source(Internal::StringManager().convert(filename.c_str()).c_str());
try
{
parser->parse(source);
delete(parser);
}
catch (...)
{
/// nothing to do here
}
return valid_;
}
void XMLValidator::warning(const SAXParseException & exception)
{
char * message = XMLString::transcode(exception.getMessage());
String error_message = String("Validation warning in file '") + filename_ + "' line " + (UInt) exception.getLineNumber() + " column " + (UInt) exception.getColumnNumber() + ": " + message;
(*os_) << error_message << endl;
valid_ = false;
XMLString::release(&message);
}
void XMLValidator::error(const SAXParseException & exception)
{
char * message = XMLString::transcode(exception.getMessage());
String error_message = String("Validation error in file '") + filename_ + "' line " + (UInt) exception.getLineNumber() + " column " + (UInt) exception.getColumnNumber() + ": " + message;
(*os_) << error_message << endl;
valid_ = false;
XMLString::release(&message);
}
void XMLValidator::fatalError(const SAXParseException & exception)
{
char * message = XMLString::transcode(exception.getMessage());
String error_message = String("Validation error in file '") + filename_ + "' line " + (UInt) exception.getLineNumber() + " column " + (UInt) exception.getColumnNumber() + ": " + message;
(*os_) << error_message << endl;
valid_ = false;
XMLString::release(&message);
}
void XMLValidator::resetErrors()
{
valid_ = true;
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/VALIDATORS/MzIdentMLValidator.cpp | .cpp | 810 | 26 | // 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/VALIDATORS/MzIdentMLValidator.h>
#include <OpenMS/FORMAT/ControlledVocabulary.h>
using namespace xercesc;
using namespace std;
namespace OpenMS::Internal
{
MzIdentMLValidator::MzIdentMLValidator(const CVMappings & mapping, const ControlledVocabulary & cv) :
SemanticValidator(mapping, cv)
{
setCheckUnits(true);
}
MzIdentMLValidator::~MzIdentMLValidator() = default;
} // namespace OpenMS // namespace Internal
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/VALIDATORS/TraMLValidator.cpp | .cpp | 744 | 26 | // 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/VALIDATORS/TraMLValidator.h>
using namespace xercesc;
using namespace std;
namespace OpenMS::Internal
{
TraMLValidator::TraMLValidator(const CVMappings & mapping, const ControlledVocabulary & cv) :
SemanticValidator(mapping, cv)
{
setCheckUnits(true);
}
TraMLValidator::~TraMLValidator() = default;
} // namespace OpenMS // namespace Internal
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/VALIDATORS/SemanticValidator.cpp | .cpp | 22,408 | 560 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm, Andreas Bertsch $
// --------------------------------------------------------------------------
#include <OpenMS/FORMAT/VALIDATORS/SemanticValidator.h>
#include <OpenMS/SYSTEM/File.h>
#include <OpenMS/FORMAT/ControlledVocabulary.h>
#include <OpenMS/DATASTRUCTURES/CVMappingRule.h>
#include <OpenMS/DATASTRUCTURES/CVMappingTerm.h>
#include <map>
using namespace xercesc;
using namespace std;
namespace OpenMS::Internal
{
SemanticValidator::SemanticValidator(const CVMappings& mapping, const ControlledVocabulary& cv) :
XMLHandler("", 0),
XMLFile(),
mapping_(mapping),
cv_(cv),
open_tags_(),
cv_tag_("cvParam"),
accession_att_("accession"),
name_att_("name"),
value_att_("value"),
unit_accession_att_("unitAccession"),
unit_name_att_("unitName"),
check_term_value_types_(true),
check_units_(false)
{
//order rules by element
for (Size r = 0; r < mapping_.getMappingRules().size(); ++r)
{
rules_[mapping_.getMappingRules()[r].getElementPath()].push_back(mapping_.getMappingRules()[r]);
}
}
SemanticValidator::~SemanticValidator()
= default;
void SemanticValidator::setTag(const String& tag)
{
cv_tag_ = tag;
}
void SemanticValidator::setAccessionAttribute(const String& accession)
{
accession_att_ = accession;
}
void SemanticValidator::setNameAttribute(const String& name)
{
name_att_ = name;
}
void SemanticValidator::setValueAttribute(const String& value)
{
value_att_ = value;
}
void SemanticValidator::setCheckTermValueTypes(bool check)
{
check_term_value_types_ = check;
}
void SemanticValidator::setCheckUnits(bool check)
{
check_units_ = check;
}
void SemanticValidator::setUnitAccessionAttribute(const String& accession)
{
unit_accession_att_ = accession;
}
void SemanticValidator::setUnitNameAttribute(const String& name)
{
unit_name_att_ = name;
}
bool SemanticValidator::validate(const String& filename, StringList& errors, StringList& warnings)
{
//TODO Check if all required CVs are loaded => exception if not
//try to open file
if (!File::exists(filename))
{
throw Exception::FileNotFound(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename);
}
//initialize
errors_.clear();
warnings_.clear();
//parse
file_ = filename;
parse_(filename, this);
//set output
errors = errors_;
warnings = warnings_;
return errors_.empty();
}
void SemanticValidator::startElement(const XMLCh* const /*uri*/, const XMLCh* const /*local_name*/, const XMLCh* const qname, const Attributes& attributes)
{
String tag = sm_.convert(qname);
String path = getPath_() + "/" + cv_tag_ + "/@" + accession_att_;
open_tags_.push_back(tag);
if (tag == cv_tag_)
{
//extract accession, name and value
CVTerm parsed_term;
getCVTerm_(attributes, parsed_term);
//check if the term is unknown
if (!cv_.exists(parsed_term.accession))
{
warnings_.push_back(String("Unknown CV term: '") + parsed_term.accession + " - " + parsed_term.name + "' at element '" + getPath_(1) + "'");
return;
}
//check if the term is obsolete
if (cv_.getTerm(parsed_term.accession).obsolete)
{
warnings_.push_back(String("Obsolete CV term: '") + parsed_term.accession + " - " + parsed_term.name + "' at element '" + getPath_(1) + "'");
}
//actual handling of the term
handleTerm_(path, parsed_term);
}
}
void SemanticValidator::endElement(const XMLCh* const /*uri*/, const XMLCh* const /*local_name*/, const XMLCh* const qname)
{
String tag = sm_.convert(qname);
String path = getPath_() + "/" + cv_tag_ + "/@" + accession_att_;
//look up rules and fulfilled rules/terms
vector<CVMappingRule>& rules = rules_[path];
std::map<String, std::map<String, UInt> >& fulfilled = fulfilled_[path]; //(rule ID => term ID => term count)
//check how often each term appeared
for (Size r = 0; r < rules.size(); ++r)
{
for (Size t = 0; t < rules[r].getCVTerms().size(); ++t)
{
if (!rules[r].getCVTerms()[t].getIsRepeatable() && fulfilled[rules[r].getIdentifier()][rules[r].getCVTerms()[t].getAccession()] > 1)
{
errors_.push_back(String("Violated mapping rule '") + rules[r].getIdentifier() + "' number of term repeats at element '" + getPath_() + "'");
}
}
}
//check if all required rules are fulfilled
for (Size r = 0; r < rules.size(); ++r)
{
//Count the number of distinct matched terms
Size terms_count = rules[r].getCVTerms().size();
UInt match_count = 0;
for (Size t = 0; t < terms_count; ++t)
{
if (fulfilled[rules[r].getIdentifier()][rules[r].getCVTerms()[t].getAccession()] >= 1)
{
++match_count;
}
}
//MUST / AND - all terms must be matched
if (rules[r].getRequirementLevel() == CVMappingRule::MUST && rules[r].getCombinationsLogic() == CVMappingRule::AND)
{
if (match_count != terms_count)
{
errors_.push_back(String("Violated mapping rule '") + rules[r].getIdentifier() + "' at element '" + getPath_() + "', " + String(terms_count) + " term(s) should be present, " + String(match_count) + " found!");
}
}
//MUST / OR - at least one terms must be matched
else if (rules[r].getRequirementLevel() == CVMappingRule::MUST && rules[r].getCombinationsLogic() == CVMappingRule::OR)
{
if (match_count == 0)
{
errors_.push_back(String("Violated mapping rule '") + rules[r].getIdentifier() + "' at element '" + getPath_() + "', at least one term must be present!");
}
}
//MUST / XOR - exactly one term must be matched
else if (rules[r].getRequirementLevel() == CVMappingRule::MUST && rules[r].getCombinationsLogic() == CVMappingRule::XOR)
{
if (match_count != 1)
{
errors_.push_back(String("Violated mapping rule '") + rules[r].getIdentifier() + "' at element '" + getPath_() + "' exactly one of the allowed terms must be used!");
}
}
//MAY(SHOULD) / AND - none or all terms must be matched
else if (rules[r].getRequirementLevel() != CVMappingRule::SHOULD && rules[r].getCombinationsLogic() == CVMappingRule::AND)
{
if (match_count != 0 && match_count != terms_count)
{
errors_.push_back(String("Violated mapping rule '") + rules[r].getIdentifier() + "' at element '" + getPath_() + "', if any, all terms must be given!");
}
}
//MAY(SHOULD) / XOR - zero or one terms must be matched
else if (rules[r].getRequirementLevel() != CVMappingRule::SHOULD && rules[r].getCombinationsLogic() == CVMappingRule::XOR)
{
if (match_count > 1)
{
errors_.push_back(String("Violated mapping rule '") + rules[r].getIdentifier() + "' at element '" + getPath_() + "', if any, only exactly one of the allowed terms can be used!");
}
}
//MAY(SHOULD) / OR - none to all terms must be matched => always true
}
//clear fulfilled rules
fulfilled_.erase(path);
open_tags_.pop_back();
}
void SemanticValidator::characters(const XMLCh* const /*chars*/, const XMLSize_t /*length*/)
{
//nothing to do here
}
String SemanticValidator::getPath_(UInt remove_from_end) const
{
String path;
path.concatenate(open_tags_.begin(), open_tags_.end() - remove_from_end, "/");
path = String("/") + path;
return path;
}
void SemanticValidator::getCVTerm_(const Attributes& attributes, CVTerm& parsed_term)
{
parsed_term.accession = attributeAsString_(attributes, accession_att_.c_str());
parsed_term.name = attributeAsString_(attributes, name_att_.c_str());
parsed_term.has_value = optionalAttributeAsString_(parsed_term.value, attributes, value_att_.c_str());
if (check_units_)
{
parsed_term.has_unit_accession = optionalAttributeAsString_(parsed_term.unit_accession, attributes, unit_accession_att_.c_str());
parsed_term.has_unit_name = optionalAttributeAsString_(parsed_term.unit_name, attributes, unit_name_att_.c_str());
}
else
{
parsed_term.has_unit_accession = false;
parsed_term.has_unit_name = false;
}
}
//~ void SemanticValidator::makeCVTerm_(const ControlledVocabulary::CVTerm lc, CVTerm & parsed_term)
//~ {
//~ parsed_term.accession = lc.id;
//~ parsed_term.name = lc.name;
//~ //no value in ControlledVocabulary::CVTerm
//~ //no units either yet
//~ {
//~ parsed_term.has_unit_accession = false;
//~ parsed_term.has_unit_name = false;
//~ }
//~ }
//reimplemented to
// - ignore values (not known)
// - allow more names (upper-lower-case + spaces)
void SemanticValidator::handleTerm_(const String& path, const CVTerm& parsed_term)
{
//check if the term is allowed in this element
//and if there is a mapping rule for this element
//Also store fulfilled rule term counts - this count is used to check of the MUST/MAY and AND/OR/XOR is fulfilled
bool allowed = false;
bool rule_found = false;
vector<CVMappingRule>& rules = rules_[path];
for (Size r = 0; r < rules.size(); ++r) //go thru all rules
{
rule_found = true;
for (Size t = 0; t < rules[r].getCVTerms().size(); ++t) //go thru all terms
{
const CVMappingTerm& term = rules[r].getCVTerms()[t];
if (term.getUseTerm() && term.getAccession() == parsed_term.accession) //check if the term itself is allowed
{
allowed = true;
fulfilled_[path][rules[r].getIdentifier()][term.getAccession()]++;
break;
}
UInt& counter = fulfilled_[path][rules[r].getIdentifier()][term.getAccession()];
auto searcher = [&allowed, &counter, &parsed_term] (const String& child)
{
if (child == parsed_term.accession)
{
allowed = true;
++counter;
return true;
}
return false;
};
if (term.getAllowChildren() && cv_.iterateAllChildren(term.getAccession(), searcher)) //check if the term's children are allowed
{
break;
}
}
}
// check units
if (check_units_ && cv_.exists(parsed_term.accession))
{
ControlledVocabulary::CVTerm term = cv_.getTerm(parsed_term.accession);
// check if the cv term has units
if (!term.units.empty())
{
if (!parsed_term.has_unit_accession)
{
errors_.push_back(String("CV term must have a unit: " + parsed_term.accession + " - " + parsed_term.name));
}
else
{
// check if the accession is ok
if (cv_.exists(parsed_term.unit_accession))
{
// check whether this unit is allowed within the cv term
if (term.units.find(parsed_term.unit_accession) == term.units.end())
{
// last chance, a child term of the units was used
set<String> child_terms;
bool found_unit(false);
auto lambda = [&parsed_term, &found_unit] (const String& child)
{
if (child == parsed_term.accession)
{
found_unit = true;
return true;
}
return false;
};
for (set<String>::const_iterator it = term.units.begin(); it != term.units.end(); ++it)
{
if (cv_.iterateAllChildren(*it, lambda)) break;
}
if (!found_unit)
{
errors_.push_back(String("Unit CV term not allowed: " + parsed_term.unit_accession + " - " + parsed_term.unit_name + " of term " + parsed_term.accession + " - " + parsed_term.name));
}
}
}
else
{
errors_.push_back(String("Unit CV term not found: " + parsed_term.unit_accession + " - " + parsed_term.unit_name + " of term " + parsed_term.accession + " - " + parsed_term.name));
}
}
}
else
{
// check whether unit was used
if (parsed_term.has_unit_accession || parsed_term.has_unit_name)
{
warnings_.push_back(String("Unit CV term used, but not allowed: " + parsed_term.unit_accession + " - " + parsed_term.unit_name + " of term " + parsed_term.accession + " - " + parsed_term.name));
}
}
}
if (!rule_found) //No rule found
{
warnings_.push_back(String("No mapping rule found for element '") + getPath_(1) + "'");
}
else if (!allowed) //if rule found and not allowed
{
errors_.push_back(String("CV term used in invalid element: '") + parsed_term.accession + " - " + parsed_term.name + "' at element '" + getPath_(1) + "'");
}
//check if term accession and term name match
if (cv_.exists(parsed_term.accession))
{
String parsed_name = parsed_term.name;
parsed_name.trim();
String correct_name = cv_.getTerm(parsed_term.accession).name;
correct_name.trim();
if (parsed_name != correct_name)
{
errors_.push_back(String("Name of CV term not correct: '") + parsed_term.accession + " - " + parsed_name + "' should be '" + correct_name + "'");
}
}
if (check_term_value_types_) //check values
{
ControlledVocabulary::CVTerm::XRefType type = cv_.getTerm(parsed_term.accession).xref_type;
// get value, if it exists
if (parsed_term.has_value && (!parsed_term.value.empty() || type == ControlledVocabulary::CVTerm::XRefType::XSD_STRING))
{
String value = parsed_term.value;
if (type == ControlledVocabulary::CVTerm::XRefType::NONE)
{
//Quality CV does not state value type :(
if (!parsed_term.accession.hasPrefix("PATO:"))
{
errors_.push_back(String("Value of CV term not allowed: '") + parsed_term.accession + " - " + parsed_term.name + "' value='" + value + "' at element '" + getPath_(1) + "'");
}
}
else if (type == ControlledVocabulary::CVTerm::XRefType::XSD_STRING)
{
// nothing to check
}
else if (type == ControlledVocabulary::CVTerm::XRefType::XSD_INTEGER)
{
try
{
parsed_term.value.toInt();
}
catch (Exception::ConversionError& /*e*/)
{
errors_.push_back(String("Value-type of CV term wrong, should be xsd:integer: '") + parsed_term.accession + " - " + parsed_term.name + "' value='" + value + "' at element '" + getPath_(1) + "'");
}
}
else if (type == ControlledVocabulary::CVTerm::XRefType::XSD_DECIMAL)
{
try
{
value.toDouble();
}
catch (Exception::ConversionError& /*e*/)
{
errors_.push_back(String("Value-type of CV term wrong, should be xsd:decimal: '") + parsed_term.accession + " - " + parsed_term.name + "' value='" + value + "' at element '" + getPath_(1) + "'");
}
}
else if (type == ControlledVocabulary::CVTerm::XRefType::XSD_NEGATIVE_INTEGER)
{
try
{
int int_value = value.toInt();
if (int_value >= 0)
{
throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "should be negative");
}
}
catch (Exception::ConversionError& /*e*/)
{
errors_.push_back(String("Value-type of CV term wrong, should be xsd:negativeInteger: '") + parsed_term.accession + " - " + parsed_term.name + "' value='" + value + "' at element '" + getPath_(1) + "'");
}
}
else if (type == ControlledVocabulary::CVTerm::XRefType::XSD_POSITIVE_INTEGER)
{
try
{
int int_value = value.toInt();
if (int_value <= 0)
{
throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "should be positive");
}
}
catch (Exception::ConversionError& /*e*/)
{
errors_.push_back(String("Value-type of CV term wrong, should be xsd:positiveInteger: '") + parsed_term.accession + " - " + parsed_term.name + "' value='" + value + "' at element '" + getPath_(1) + "'");
}
}
else if (type == ControlledVocabulary::CVTerm::XRefType::XSD_NON_NEGATIVE_INTEGER)
{
try
{
int int_value = value.toInt();
if (int_value < 0)
{
throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "should not be negative");
}
}
catch (Exception::ConversionError& /*e*/)
{
errors_.push_back(String("Value-type of CV term wrong, should be xsd:nonNegativeInteger: '") + parsed_term.accession + " - " + parsed_term.name + "' value='" + value + "' at element '" + getPath_(1) + "'");
}
}
else if (type == ControlledVocabulary::CVTerm::XRefType::XSD_NON_POSITIVE_INTEGER)
{
try
{
int int_value = value.toInt();
if (int_value > 0)
{
throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "should not be positive");
}
}
catch (Exception::ConversionError& /*e*/)
{
errors_.push_back(String("Value-type of CV term wrong, should be xsd:nonPositiveInteger: '") + parsed_term.accession + " - " + parsed_term.name + "' value='" + value + "' at element '" + getPath_(1) + "'");
}
}
else if (type == ControlledVocabulary::CVTerm::XRefType::XSD_BOOLEAN)
{
String value_copy = value;
value_copy.trim();
value_copy.toLower();
if (value_copy != "1" && value_copy != "0" && value_copy != "true" && value_copy != "false")
{
errors_.push_back(String("Value-type of CV term wrong, should be xsd:boolean: '") + parsed_term.accession + " - " + parsed_term.name + "' value='" + value + "' at element '" + getPath_(1) + "'");
}
}
else if (type == ControlledVocabulary::CVTerm::XRefType::XSD_DATE)
{
try
{
DateTime tmp;
tmp.set(value);
}
catch (Exception::ParseError&)
{
errors_.push_back(String("Value-type of CV term wrong, should be xsd:date: '") + parsed_term.accession + " - " + parsed_term.name + "' value='" + value + "' at element '" + getPath_(1) + "'");
}
}
else if (type == ControlledVocabulary::CVTerm::XRefType::XSD_ANYURI)
{ // according to RFC 2396 this is there must be a colon (looked only 2 minutes on it)
if (!value.has(':'))
{
errors_.push_back(String("Value-type of CV term wrong, should be xsd:anyURI (at least a colon is needed): '") + parsed_term.accession + " - " + parsed_term.name + "' value=" + value + "' at element '" + getPath_(1) + "'");
}
}
else
{
errors_.push_back(String("Value-type unknown (type #" + String(static_cast<int>(type)) + "): '") + parsed_term.accession + " - " + parsed_term.name + "' value='" + value + "' at element '" + getPath_(1) + "'");
}
}
else if (cv_.getTerm(parsed_term.accession).xref_type != ControlledVocabulary::CVTerm::XRefType::NONE)
{
errors_.push_back(String("Value-type required, but not given (" + ControlledVocabulary::CVTerm::getXRefTypeName(cv_.getTerm(parsed_term.accession).xref_type) + "): '") + parsed_term.accession + " - " + parsed_term.name + "' value='" + parsed_term.value + "' at element '" + getPath_(1) + "'");
}
}
}
bool SemanticValidator::locateTerm(const String& path, const CVTerm& parsed_term) const
{
//check if the term is allowed in this element
//and if there is a mapping rule for this element
//Also store fulfilled rule term counts - this count is used to check of the MUST/MAY and AND/OR/XOR is fulfilled
const vector<CVMappingRule>& rules = rules_.at(path);
for (Size r = 0; r < rules.size(); ++r) //go thru all rules
{
for (Size t = 0; t < rules[r].getCVTerms().size(); ++t) //go thru all terms
{
const CVMappingTerm& term = rules[r].getCVTerms()[t];
if (term.getUseTerm() && term.getAccession() == parsed_term.accession) //check if the term itself is allowed
{
return true;
}
auto searcher = [&parsed_term] (const String& child) { return child == parsed_term.accession; };
if (term.getAllowChildren() && cv_.iterateAllChildren(term.getAccession(), searcher))
{
return true;
}
}
}
return false;
}
} // namespace OpenMS // namespace Internal
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/OPTIONS/PeakFileOptions.cpp | .cpp | 6,740 | 315 | // 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/OPTIONS/PeakFileOptions.h>
using namespace std;
namespace OpenMS
{
PeakFileOptions::PeakFileOptions() = default;
PeakFileOptions::PeakFileOptions(const PeakFileOptions& options) = default;
PeakFileOptions::~PeakFileOptions() = default;
void PeakFileOptions::setMetadataOnly(bool only)
{
metadata_only_ = only;
}
bool PeakFileOptions::getMetadataOnly() const
{
return metadata_only_;
}
void PeakFileOptions::setForceMQCompatability(bool forceMQ)
{
force_maxquant_compatibility_ = forceMQ;
}
bool PeakFileOptions::getForceMQCompatability() const
{
return force_maxquant_compatibility_;
}
void PeakFileOptions::setForceTPPCompatability(bool forceTPP)
{
force_tpp_compatibility_ = forceTPP;
}
bool PeakFileOptions::getForceTPPCompatability() const
{
return force_tpp_compatibility_;
}
void PeakFileOptions::setWriteSupplementalData(bool write)
{
write_supplemental_data_ = write;
}
bool PeakFileOptions::getWriteSupplementalData() const
{
return write_supplemental_data_;
}
void PeakFileOptions::setRTRange(const DRange<1>& range)
{
rt_range_ = range;
has_rt_range_ = !rt_range_.isEmpty();
}
bool PeakFileOptions::hasRTRange() const
{
return has_rt_range_;
}
const DRange<1>& PeakFileOptions::getRTRange() const
{
return rt_range_;
}
void PeakFileOptions::setMZRange(const DRange<1>& range)
{
mz_range_ = range;
has_mz_range_ = true;
}
bool PeakFileOptions::hasMZRange() const
{
return has_mz_range_;
}
const DRange<1>& PeakFileOptions::getMZRange() const
{
return mz_range_;
}
void PeakFileOptions::setIntensityRange(const DRange<1>& range)
{
intensity_range_ = range;
has_intensity_range_ = true;
}
bool PeakFileOptions::hasIntensityRange() const
{
return has_intensity_range_;
}
const DRange<1>& PeakFileOptions::getIntensityRange() const
{
return intensity_range_;
}
void PeakFileOptions::setPrecursorMZRange(const DRange<1>& range)
{
precursor_mz_range_ = range;
has_precursor_mz_range_ = true;
}
bool PeakFileOptions::hasPrecursorMZRange() const
{
return has_precursor_mz_range_;
}
const DRange<1>& PeakFileOptions::getPrecursorMZRange() const
{
return precursor_mz_range_;
}
void PeakFileOptions::setMSLevels(const vector<Int>& levels)
{
ms_levels_ = levels;
}
void PeakFileOptions::addMSLevel(int level)
{
ms_levels_.push_back(level);
}
void PeakFileOptions::clearMSLevels()
{
ms_levels_.clear();
}
bool PeakFileOptions::hasMSLevels() const
{
return !ms_levels_.empty();
}
bool PeakFileOptions::containsMSLevel(int level) const
{
return find(ms_levels_.begin(), ms_levels_.end(), level) != ms_levels_.end();
}
const vector<Int>& PeakFileOptions::getMSLevels() const
{
return ms_levels_;
}
void PeakFileOptions::setCompression(bool compress)
{
zlib_compression_ = compress;
}
bool PeakFileOptions::getCompression() const
{
return zlib_compression_;
}
bool PeakFileOptions::getAlwaysAppendData() const
{
return always_append_data_;
}
void PeakFileOptions::setAlwaysAppendData(bool always_append_data)
{
always_append_data_ = always_append_data;
}
bool PeakFileOptions::getFillData() const
{
return fill_data_;
}
void PeakFileOptions::setSkipXMLChecks(bool skip)
{
skip_xml_checks_ = skip;
}
bool PeakFileOptions::getSkipXMLChecks() const
{
return skip_xml_checks_;
}
void PeakFileOptions::setSortSpectraByMZ(bool sort)
{
sort_spectra_by_mz_ = sort;
}
bool PeakFileOptions::getSortSpectraByMZ() const
{
return sort_spectra_by_mz_;
}
void PeakFileOptions::setSortChromatogramsByRT(bool sort)
{
sort_chromatograms_by_rt_ = sort;
}
bool PeakFileOptions::getSortChromatogramsByRT() const
{
return sort_chromatograms_by_rt_;
}
void PeakFileOptions::setFillData(bool fill_data)
{
fill_data_ = fill_data;
}
void PeakFileOptions::setMz32Bit(bool mz_32_bit)
{
mz_32_bit_ = mz_32_bit;
}
bool PeakFileOptions::getMz32Bit() const
{
return mz_32_bit_;
}
void PeakFileOptions::setIntensity32Bit(bool int_32_bit)
{
int_32_bit_ = int_32_bit;
}
bool PeakFileOptions::getIntensity32Bit() const
{
return int_32_bit_;
}
bool PeakFileOptions::getWriteIndex() const
{
return write_index_;
}
void PeakFileOptions::setWriteIndex(bool write_index)
{
write_index_ = write_index;
}
MSNumpressCoder::NumpressConfig PeakFileOptions::getNumpressConfigurationMassTime() const
{
return np_config_mz_;
}
void PeakFileOptions::setNumpressConfigurationMassTime(MSNumpressCoder::NumpressConfig config)
{
if (config.np_compression == MSNumpressCoder::SLOF || config.np_compression == MSNumpressCoder::PIC)
{
std::cerr << "Warning, compression of m/z or time dimension with pic or slof algorithms can lead to data loss" << std::endl;
}
np_config_mz_ = config;
}
MSNumpressCoder::NumpressConfig PeakFileOptions::getNumpressConfigurationIntensity() const
{
return np_config_int_;
}
void PeakFileOptions::setNumpressConfigurationIntensity(MSNumpressCoder::NumpressConfig config)
{
np_config_int_ = config;
}
MSNumpressCoder::NumpressConfig PeakFileOptions::getNumpressConfigurationFloatDataArray() const
{
return np_config_fda_;
}
void PeakFileOptions::setNumpressConfigurationFloatDataArray(MSNumpressCoder::NumpressConfig config)
{
np_config_fda_ = config;
}
Size PeakFileOptions::getMaxDataPoolSize() const
{
return maximal_data_pool_size_;
}
void PeakFileOptions::setMaxDataPoolSize(Size size)
{
maximal_data_pool_size_ = size;
}
bool PeakFileOptions::getPrecursorMZSelectedIon() const
{
return precursor_mz_selected_ion_;
}
void PeakFileOptions::setPrecursorMZSelectedIon(bool choice)
{
precursor_mz_selected_ion_ = choice;
}
bool PeakFileOptions::hasFilters() const
{
return (has_rt_range_ || hasMSLevels() || has_precursor_mz_range_);
}
void PeakFileOptions::setSkipChromatograms(bool skip)
{
skip_chromatograms_ = skip;
}
bool PeakFileOptions::getSkipChromatograms() const
{
return skip_chromatograms_;
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/OPTIONS/FeatureFileOptions.cpp | .cpp | 2,430 | 117 | // 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/FORMAT/OPTIONS/FeatureFileOptions.h>
using namespace std;
namespace OpenMS
{
FeatureFileOptions::FeatureFileOptions() :
loadConvexhull_(true),
loadSubordinates_(true),
metadata_only_(false),
has_rt_range_(false),
has_mz_range_(false),
has_intensity_range_(false),
size_only_(false)
{
}
FeatureFileOptions::~FeatureFileOptions() = default;
void FeatureFileOptions::setLoadConvexHull(bool convex)
{
loadConvexhull_ = convex;
}
bool FeatureFileOptions::getLoadConvexHull() const
{
return loadConvexhull_;
}
void FeatureFileOptions::setLoadSubordinates(bool sub)
{
loadSubordinates_ = sub;
}
bool FeatureFileOptions::getLoadSubordinates() const
{
return loadSubordinates_;
}
void FeatureFileOptions::setMetadataOnly(bool only)
{
metadata_only_ = only;
}
bool FeatureFileOptions::getMetadataOnly() const
{
return metadata_only_;
}
void FeatureFileOptions::setRTRange(const DRange<1> & range)
{
rt_range_ = range;
has_rt_range_ = true;
}
bool FeatureFileOptions::hasRTRange() const
{
return has_rt_range_;
}
const DRange<1> & FeatureFileOptions::getRTRange() const
{
return rt_range_;
}
void FeatureFileOptions::setMZRange(const DRange<1> & range)
{
mz_range_ = range;
has_mz_range_ = true;
}
bool FeatureFileOptions::hasMZRange() const
{
return has_mz_range_;
}
bool FeatureFileOptions::getSizeOnly() const
{
return size_only_;
}
void FeatureFileOptions::setSizeOnly(bool size_only)
{
size_only_ = size_only;
}
const DRange<1> & FeatureFileOptions::getMZRange() const
{
return mz_range_;
}
void FeatureFileOptions::setIntensityRange(const DRange<1> & range)
{
intensity_range_ = range;
has_intensity_range_ = true;
}
bool FeatureFileOptions::hasIntensityRange() const
{
return has_intensity_range_;
}
const DRange<1> & FeatureFileOptions::getIntensityRange() const
{
return intensity_range_;
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/MSNUMPRESS/MSNumpress.cpp | .cpp | 18,906 | 861 | /*
MSNumpress.cpp
johan.teleman@immun.lth.se
This distribution goes under the BSD 3-clause license. If you prefer to use Apache
version 2.0, that is also available at https://github.com/fickludd/ms-numpress
Copyright (c) 2013, Johan Teleman
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the Lund University nor the names of its contributors may be
used to endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <algorithm> // for min() and max() in VS2013
#include <climits>
#include <cmath>
#include <iostream>
#include <OpenMS/FORMAT/MSNUMPRESS/MSNumpress.h>
namespace ms::numpress::MSNumpress {
using std::cout;
using std::cerr;
using std::endl;
using std::min;
using std::max;
using std::abs;
// This is only valid on systems were ints use more bytes than chars...
const int ONE = 1;
static bool is_big_endian() {
return *((char*)&(ONE)) == 1;
}
bool IS_BIG_ENDIAN = is_big_endian();
/////////////////////////////////////////////////////////////
static void encodeFixedPoint(
double fixedPoint,
unsigned char *result
) {
int i;
unsigned char *fp = (unsigned char*)&fixedPoint;
for (i=0; i<8; i++) {
result[i] = fp[IS_BIG_ENDIAN ? (7-i) : i];
}
}
static double decodeFixedPoint(
const unsigned char *data
) {
int i;
double fixedPoint;
unsigned char *fp = (unsigned char*)&fixedPoint;
for (i=0; i<8; i++)
{
fp[i] = data[IS_BIG_ENDIAN ? (7-i) : i];
}
return fixedPoint;
}
/////////////////////////////////////////////////////////////
/**
* Encodes the int x as a number of halfbytes in res.
* res_length is incremented by the number of halfbytes,
* which will be 1 <= n <= 9
*
* see header file for a detailed description of the algorithm.
*/
static void encodeInt(
const unsigned int x,
unsigned char* res,
size_t *res_length
) {
// get the bit pattern of a signed int x_inp
unsigned int m;
unsigned char i, l; // numbers between 0 and 9
unsigned int mask = 0xf0000000;
unsigned int init = x & mask;
if (init == 0)
{
l = 8;
for (i=0; i<8; i++)
{
m = mask >> (4*i);
if ((x & m) != 0)
{
l = i;
break;
}
}
res[0] = l;
for (i=l; i<8; i++)
{
res[1+i-l] = static_cast<unsigned char>( x >> (4*(i-l)) );
}
*res_length += 1+8-l;
}
else if (init == mask)
{
l = 7;
for (i=0; i<8; i++)
{
m = mask >> (4*i);
if ((x & m) != m)
{
l = i;
break;
}
}
res[0] = l + 8;
for (i=l; i<8; i++)
{
res[1+i-l] = static_cast<unsigned char>( x >> (4*(i-l)) );
}
*res_length += 1+8-l;
}
else
{
res[0] = 0;
for (i=0; i<8; i++)
{
res[1+i] = static_cast<unsigned char>( x >> (4*i) );
}
*res_length += 9;
}
}
/**
* Decodes an int from the half bytes in bp. Lossless reverse of encodeInt
*/
static void decodeInt(
const unsigned char *data,
size_t *di,
size_t max_di,
size_t *half,
unsigned int *res
) {
size_t n, i;
unsigned int mask, m;
unsigned char head;
unsigned char hb;
if (*half == 0)
{
head = data[*di] >> 4;
}
else
{
head = data[*di] & 0xf;
(*di)++;
}
*half = 1-(*half);
*res = 0;
if (head <= 8)
{
n = head;
}
else
{ // leading ones, fill n half bytes in res
n = head - 8;
mask = 0xf0000000;
for (i=0; i<n; i++)
{
m = mask >> (4*i);
*res = *res | m;
}
}
if (n == 8)
{
return;
}
if (*di + ((8 - n) - (1 - *half)) / 2 >= max_di)
{
throw "[MSNumpress::decodeInt] Corrupt input data! ";
}
for (i=n; i<8; i++)
{
if (*half == 0)
{
hb = data[*di] >> 4;
}
else
{
hb = data[*di] & 0xf;
(*di)++;
}
*res = *res | ( static_cast<unsigned int>(hb) << ((i-n)*4));
*half = 1 - (*half);
}
}
/////////////////////////////////////////////////////////////
double optimalLinearFixedPointMass(
const double *data,
size_t dataSize,
double mass_acc
) {
if (dataSize < 3)
{
return 0; // we just encode the first two points as floats
}
// We calculate the maximal fixedPoint we need to achieve a specific mass
// accuracy. Note that the maximal error we will make by encoding as int is
// 0.5 due to rounding errors.
double maxFP = 0.5 / mass_acc;
// There is a maximal value for the FP given by the int length (32bit)
// which means we cannot choose a value higher than that. In case we cannot
// achieve the desired accuracy, return failure (-1).
double maxFP_overflow = optimalLinearFixedPoint(data, dataSize);
if (maxFP > maxFP_overflow)
{
return -1;
}
return maxFP;
}
double optimalLinearFixedPoint(
const double *data,
size_t dataSize
) {
/*
* safer impl - apparently not needed though
*
if (dataSize == 0) return 0;
double maxDouble = 0;
double x;
for (size_t i=0; i<dataSize; i++) {
x = data[i];
maxDouble = max(maxDouble, x);
}
return floor(0xFFFFFFFF / maxDouble);
*/
if (dataSize == 0)
{
return 0;
}
if (dataSize == 1)
{
return floor(0x7FFFFFFFl / data[0]);
}
double maxDouble = max(data[0], data[1]);
double extrapol;
double diff;
for (size_t i=2; i<dataSize; i++) {
extrapol = data[i-1] + (data[i-1] - data[i-2]);
diff = data[i] - extrapol;
maxDouble = max(maxDouble, ceil(abs(diff)+1));
}
return floor(0x7FFFFFFFl / maxDouble);
}
size_t encodeLinear(
const double *data,
size_t dataSize,
unsigned char *result,
double fixedPoint
) {
long long ints[3];
size_t i, ri;
unsigned char halfBytes[10];
size_t halfByteCount;
size_t hbi;
long long extrapol;
int diff;
//printf("Encoding %d doubles with fixed point %f\n", (int)dataSize, fixedPoint);
encodeFixedPoint(fixedPoint, result);
if (dataSize == 0)
{
return 8;
}
ints[1] = static_cast<long long>(data[0] * fixedPoint + 0.5);
for (i=0; i<4; i++)
{
result[8+i] = (ints[1] >> (i*8)) & 0xff;
}
if (dataSize == 1)
{
return 12;
}
ints[2] = static_cast<long long>(data[1] * fixedPoint + 0.5);
for (i=0; i<4; i++) {
result[12+i] = (ints[2] >> (i*8)) & 0xff;
}
halfByteCount = 0;
ri = 16;
for (i=2; i<dataSize; i++) {
ints[0] = ints[1];
ints[1] = ints[2];
if (MS_NUMPRESS_THROW_ON_OVERFLOW && data[i] * fixedPoint + 0.5 > LLONG_MAX )
{
throw "[MSNumpress::encodeLinear] Next number overflows LLONG_MAX.";
}
ints[2] = static_cast<long long>(data[i] * fixedPoint + 0.5);
extrapol = ints[1] + (ints[1] - ints[0]);
if (MS_NUMPRESS_THROW_ON_OVERFLOW &&
( ints[2] - extrapol > INT_MAX
|| ints[2] - extrapol < INT_MIN )) {
throw "[MSNumpress::encodeLinear] Cannot encode a number that exceeds the bounds of [-INT_MAX, INT_MAX].";
}
diff = static_cast<int>(ints[2] - extrapol);
//printf("%lu %lu %lu, extrapol: %ld diff: %d \n", ints[0], ints[1], ints[2], extrapol, diff);
encodeInt(
static_cast<unsigned int>(diff),
&halfBytes[halfByteCount],
&halfByteCount
);
/*
printf("%d (%d): ", diff, (int)halfByteCount);
for (size_t j=0; j<halfByteCount; j++) {
printf("%x ", halfBytes[j] & 0xf);
}
printf("\n");
*/
for (hbi=1; hbi < halfByteCount; hbi+=2) {
result[ri] = static_cast<unsigned char>(
(halfBytes[hbi-1] << 4) | (halfBytes[hbi] & 0xf)
);
//printf("%x \n", result[ri]);
ri++;
}
if (halfByteCount % 2 != 0)
{
halfBytes[0] = halfBytes[halfByteCount-1];
halfByteCount = 1;
}
else
{
halfByteCount = 0;
}
}
if (halfByteCount == 1)
{
result[ri] = static_cast<unsigned char>(halfBytes[0] << 4);
ri++;
}
return ri;
}
size_t decodeLinear(
const unsigned char *data,
const size_t dataSize,
double *result
) {
size_t i;
size_t ri = 0;
unsigned int init, buff;
int diff;
long long ints[3];
//double d;
size_t di;
size_t half;
long long extrapol;
long long y;
double fixedPoint;
//printf("Decoding %d bytes with fixed point %f\n", (int)dataSize, fixedPoint);
if (dataSize == 8)
{
return 0;
}
if (dataSize < 8)
{
throw "[MSNumpress::decodeLinear] Corrupt input data: not enough bytes to read fixed point! ";
}
fixedPoint = decodeFixedPoint(data);
if (dataSize < 12)
{
throw "[MSNumpress::decodeLinear] Corrupt input data: not enough bytes to read first value! ";
}
ints[1] = 0;
for (i=0; i<4; i++)
{
ints[1] = ints[1] | ((0xff & (init = data[8+i])) << (i*8));
}
result[0] = ints[1] / fixedPoint;
if (dataSize == 12)
{
return 1;
}
if (dataSize < 16)
{
throw "[MSNumpress::decodeLinear] Corrupt input data: not enough bytes to read second value! ";
}
ints[2] = 0;
for (i=0; i<4; i++)
{
ints[2] = ints[2] | ((0xff & (init = data[12+i])) << (i*8));
}
result[1] = ints[2] / fixedPoint;
half = 0;
ri = 2;
di = 16;
//printf(" di ri half int[0] int[1] extrapol diff\n");
while (di < dataSize)
{
if (di == (dataSize - 1) && half == 1)
{
if ((data[di] & 0xf) == 0x0)
{
break;
}
}
//printf("%7d %7d %7d %lu %lu %ld", di, ri, half, ints[0], ints[1], extrapol);
ints[0] = ints[1];
ints[1] = ints[2];
decodeInt(data, &di, dataSize, &half, &buff);
diff = static_cast<int>(buff);
extrapol = ints[1] + (ints[1] - ints[0]);
y = extrapol + diff;
//printf(" %d \n", diff);
result[ri++] = y / fixedPoint;
ints[2] = y;
}
return ri;
}
void encodeLinear(
const std::vector<double> &data,
std::vector<unsigned char> &result,
double fixedPoint
) {
size_t dataSize = data.size();
result.resize(dataSize * 5 + 8);
size_t encodedLength = encodeLinear(&data[0], dataSize, &result[0], fixedPoint);
result.resize(encodedLength);
}
void decodeLinear(
const std::vector<unsigned char> &data,
std::vector<double> &result
) {
size_t dataSize = data.size();
result.resize((dataSize - 8) * 2);
size_t decodedLength = decodeLinear(&data[0], dataSize, &result[0]);
result.resize(decodedLength);
}
/////////////////////////////////////////////////////////////
size_t encodeSafe(
const double *data,
const size_t dataSize,
unsigned char *result
) {
size_t i, j, ri = 0;
double latest[3];
double extrapol, diff;
const unsigned char *fp;
//printf("d0 d1 d2 extrapol diff\n");
if (dataSize == 0)
{
return ri;
}
latest[1] = data[0];
fp = (unsigned char*)data;
for (i=0; i<8; i++)
{
result[ri++] = fp[IS_BIG_ENDIAN ? (7-i) : i];
}
if (dataSize == 1)
{
return ri;
}
latest[2] = data[1];
fp = (unsigned char*)&(data[1]);
for (i=0; i<8; i++)
{
result[ri++] = fp[IS_BIG_ENDIAN ? (7-i) : i];
}
fp = (unsigned char*)&diff;
for (i=2; i<dataSize; i++) {
latest[0] = latest[1];
latest[1] = latest[2];
latest[2] = data[i];
extrapol = latest[1] + (latest[1] - latest[0]);
diff = latest[2] - extrapol;
//printf("%f %f %f %f %f\n", latest[0], latest[1], latest[2], extrapol, diff);
for (j=0; j<8; j++)
{
result[ri++] = fp[IS_BIG_ENDIAN ? (7-j) : j];
}
}
return ri;
}
size_t decodeSafe(
const unsigned char *data,
const size_t dataSize,
double *result
) {
size_t i, di, ri;
double extrapol, diff;
double latest[3];
unsigned char *fp;
if (dataSize % 8 != 0)
{
throw "[MSNumpress::decodeSafe] Corrupt input data: number of bytes needs to be multiple of 8! ";
}
//printf("d0 d1 extrapol diff\td2\n");
try {
fp = (unsigned char*)&(latest[1]);
for (i=0; i<8; i++)
{
fp[i] = data[IS_BIG_ENDIAN ? (7-i) : i];
}
result[0] = latest[1];
if (dataSize == 8)
{
return 1;
}
fp = (unsigned char*)&(latest[2]);
for (i=0; i<8; i++)
{
fp[i] = data[8 + (IS_BIG_ENDIAN ? (7-i) : i)];
}
result[1] = latest[2];
ri = 2;
fp = (unsigned char*)&diff;
for (di = 16; di < dataSize; di += 8)
{
latest[0] = latest[1];
latest[1] = latest[2];
for (i=0; i<8; i++)
{
fp[i] = data[di + (IS_BIG_ENDIAN ? (7-i) : i)];
}
extrapol = latest[1] + (latest[1] - latest[0]);
latest[2] = extrapol + diff;
//printf("%f %f %f %f\t%f \n", latest[0], latest[1], extrapol, diff, latest[2]);
result[ri++] = latest[2];
}
} catch (...) {
throw "[MSNumpress::decodeSafe] Unknown error during decode! ";
}
return ri;
}
/////////////////////////////////////////////////////////////
size_t encodePic(
const double *data,
size_t dataSize,
unsigned char *result
) {
size_t i, ri;
unsigned int x;
unsigned char halfBytes[10];
size_t halfByteCount;
size_t hbi;
//printf("Encoding %d doubles\n", (int)dataSize);
halfByteCount = 0;
ri = 0;
for (i=0; i<dataSize; i++) {
if (MS_NUMPRESS_THROW_ON_OVERFLOW &&
(data[i] + 0.5 > INT_MAX || data[i] < -0.5) ){
throw "[MSNumpress::encodePic] Cannot use Pic to encode a number larger than INT_MAX or smaller than 0.";
}
x = static_cast<unsigned int>(data[i] + 0.5);
//printf("%d %d %d, extrapol: %d diff: %d \n", ints[0], ints[1], ints[2], extrapol, diff);
encodeInt(x, &halfBytes[halfByteCount], &halfByteCount);
for (hbi=1; hbi < halfByteCount; hbi+=2) {
result[ri] = static_cast<unsigned char>(
(halfBytes[hbi-1] << 4) | (halfBytes[hbi] & 0xf)
);
//printf("%x \n", result[ri]);
ri++;
}
if (halfByteCount % 2 != 0) {
halfBytes[0] = halfBytes[halfByteCount-1];
halfByteCount = 1;
} else {
halfByteCount = 0;
}
}
if (halfByteCount == 1) {
result[ri] = static_cast<unsigned char>(halfBytes[0] << 4);
ri++;
}
return ri;
}
size_t decodePic(
const unsigned char *data,
const size_t dataSize,
double *result
) {
size_t ri;
unsigned int x;
size_t di;
size_t half;
//printf("ri di half dSize count\n");
half = 0;
ri = 0;
di = 0;
while (di < dataSize)
{
if (di == (dataSize - 1) && half == 1)
{
if ((data[di] & 0xf) == 0x0)
{
break;
}
}
decodeInt(&data[0], &di, dataSize, &half, &x);
//printf("%7d %7d %7d %7d %7d\n", ri, di, half, dataSize, count);
//printf("count: %d \n", count);
result[ri++] = static_cast<double>(x);
}
return ri;
}
void encodePic(
const std::vector<double> &data,
std::vector<unsigned char> &result
) {
size_t dataSize = data.size();
result.resize(dataSize * 5);
size_t encodedLength = encodePic(&data[0], dataSize, &result[0]);
result.resize(encodedLength);
}
void decodePic(
const std::vector<unsigned char> &data,
std::vector<double> &result
) {
size_t dataSize = data.size();
result.resize(dataSize * 2);
size_t decodedLength = decodePic(&data[0], dataSize, &result[0]);
result.resize(decodedLength);
}
/////////////////////////////////////////////////////////////
double optimalSlofFixedPoint(
const double *data,
size_t dataSize
) {
if (dataSize == 0)
{
return 0;
}
double maxDouble = 1;
double x;
double fp;
for (size_t i=0; i<dataSize; i++)
{
x = log(data[i]+1);
maxDouble = max(maxDouble, x);
}
// here we use 0xFFFE as maximal value as we add 0.5 during encoding (see encodeSlof)
fp = floor(0xFFFE / maxDouble);
//cout << " max val: " << maxDouble << endl;
//cout << "fixed point: " << fp << endl;
return fp;
}
size_t encodeSlof(
const double *data,
size_t dataSize,
unsigned char *result,
double fixedPoint
) {
size_t i, ri;
double temp;
unsigned short x;
encodeFixedPoint(fixedPoint, result);
ri = 8;
for (i=0; i<dataSize; i++)
{
temp = log(data[i]+1) * fixedPoint;
if (MS_NUMPRESS_THROW_ON_OVERFLOW &&
temp > USHRT_MAX ) {
throw "[MSNumpress::encodeSlof] Cannot encode a number that overflows USHRT_MAX.";
}
x = static_cast<unsigned short>(temp + 0.5);
result[ri++] = x & 0xff;
result[ri++] = (x >> 8) & 0xff;
}
return ri;
}
size_t decodeSlof(
const unsigned char *data,
const size_t dataSize,
double *result
) {
size_t i, ri;
unsigned short x;
double fixedPoint;
if (dataSize < 8)
{
throw "[MSNumpress::decodeSlof] Corrupt input data: not enough bytes to read fixed point! ";
}
ri = 0;
fixedPoint = decodeFixedPoint(data);
for (i=8; i<dataSize; i+=2) {
x = static_cast<unsigned short>(data[i] | (data[i+1] << 8));
result[ri++] = exp(x / fixedPoint) - 1;
}
return ri;
}
void encodeSlof(
const std::vector<double> &data,
std::vector<unsigned char> &result,
double fixedPoint
) {
size_t dataSize = data.size();
result.resize(dataSize * 2 + 8);
size_t encodedLength = encodeSlof(&data[0], dataSize, &result[0], fixedPoint);
result.resize(encodedLength);
}
void decodeSlof(
const std::vector<unsigned char> &data,
std::vector<double> &result
) {
size_t dataSize = data.size();
result.resize((dataSize - 8) / 2);
size_t decodedLength = decodeSlof(&data[0], dataSize, &result[0]);
result.resize(decodedLength);
}
} // namespace ms // namespace numpress // namespace MSNumpress
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/HANDLERS/MzMLHandlerHelper.cpp | .cpp | 15,297 | 387 | // 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/HANDLERS/MzMLHandlerHelper.h>
#include <OpenMS/FORMAT/HANDLERS/XMLHandler.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/FORMAT/Base64.h>
namespace OpenMS::Internal
{
void MzMLHandlerHelper::warning(int mode, const String & msg, UInt line, UInt column)
{
String error_message;
if (mode == 0)
{
error_message = String("While loading '") + "': " + msg;
}
else if (mode == 1)
{
error_message = String("While storing '") + "': " + msg;
}
if (line != 0 || column != 0)
{
error_message += String("( in line ") + line + " column " + column + ")";
}
OPENMS_LOG_WARN << error_message << std::endl;
}
String MzMLHandlerHelper::getCompressionTerm_(const PeakFileOptions& opt, MSNumpressCoder::NumpressConfig np, const String& indent, bool use_numpress)
{
if (opt.getCompression())
{
if (np.np_compression == MSNumpressCoder::NONE || !use_numpress)
{
return indent + R"(<cvParam cvRef="MS" accession="MS:1000574" name="zlib compression" />)";
}
else if (np.np_compression == MSNumpressCoder::LINEAR)
{
return indent + R"(<cvParam cvRef="MS" accession="MS:1002746" name="MS-Numpress linear prediction compression followed by zlib compression" />)";
}
else if (np.np_compression == MSNumpressCoder::PIC)
{
return indent + R"(<cvParam cvRef="MS" accession="MS:1002747" name="MS-Numpress positive integer compression followed by zlib compression" />)";
}
else if (np.np_compression == MSNumpressCoder::SLOF)
{
return indent + R"(<cvParam cvRef="MS" accession="MS:1002748" name="MS-Numpress short logged float compression followed by zlib compression" />)";
}
}
else
{
if (np.np_compression == MSNumpressCoder::NONE || !use_numpress)
{
// default
return indent + R"(<cvParam cvRef="MS" accession="MS:1000576" name="no compression" />)";
}
else if (np.np_compression == MSNumpressCoder::LINEAR)
{
return indent + R"(<cvParam cvRef="MS" accession="MS:1002312" name="MS-Numpress linear prediction compression" />)";
}
else if (np.np_compression == MSNumpressCoder::PIC)
{
return indent + R"(<cvParam cvRef="MS" accession="MS:1002313" name="MS-Numpress positive integer compression" />)";
}
else if (np.np_compression == MSNumpressCoder::SLOF)
{
return indent + R"(<cvParam cvRef="MS" accession="MS:1002314" name="MS-Numpress short logged float compression" />)";
}
}
// default
return indent + R"(<cvParam cvRef="MS" accession="MS:1000576" name="no compression" />)";
}
void MzMLHandlerHelper::writeFooter_(std::ostream& os,
const PeakFileOptions& options_,
const std::vector< std::pair<std::string, Int64> > & spectra_offsets,
const std::vector< std::pair<std::string, Int64> > & chromatograms_offsets)
{
os << "\t</run>\n";
os << "</mzML>";
if (options_.getWriteIndex())
{
int indexlists = (int) !spectra_offsets.empty() + (int) !chromatograms_offsets.empty();
Int64 indexlistoffset = os.tellp();
os << "\n";
// NOTE: indexList is required, so we need to write one
// NOTE: the spectra and chromatogram ids are user-supplied, so better XML-escape them!
os << "<indexList count=\"" << indexlists << "\">\n";
if (!spectra_offsets.empty())
{
os << "\t<index name=\"spectrum\">\n";
for (Size i = 0; i < spectra_offsets.size(); i++)
{
os << "\t\t<offset idRef=\"" << XMLHandler::writeXMLEscape(spectra_offsets[i].first) << "\">" << spectra_offsets[i].second << "</offset>\n";
}
os << "\t</index>\n";
}
if (!chromatograms_offsets.empty())
{
os << "\t<index name=\"chromatogram\">\n";
for (Size i = 0; i < chromatograms_offsets.size(); i++)
{
os << "\t\t<offset idRef=\"" << XMLHandler::writeXMLEscape(chromatograms_offsets[i].first) << "\">" << chromatograms_offsets[i].second << "</offset>\n";
}
os << "\t</index>\n";
}
if (indexlists == 0)
{
// dummy: at least one index subelement is required by the standard,
// and at least one offset element is required so we need to handle
// the case where no spectra/chromatograms are present.
os << "\t<index name=\"dummy\">\n";
os << "\t\t<offset idRef=\"dummy\">-1</offset>\n";
os << "\t</index>\n";
}
os << "</indexList>\n";
os << "<indexListOffset>" << indexlistoffset << "</indexListOffset>\n";
os << "<fileChecksum>";
// TODO calculate checksum here:
// SHA-1 checksum from beginning of file to end of 'fileChecksum' open tag.
String sha1_checksum = "0";
os << sha1_checksum << "</fileChecksum>\n";
os << "</indexedmzML>";
}
}
void MzMLHandlerHelper::decodeBase64Arrays(std::vector<BinaryData>& data, const bool skipXMLCheck)
{
// decode all base64 arrays
for (auto& bindata : data)
{
// remove whitespaces from binary data
// this should not be necessary, but line breaks inside the base64 data are unfortunately no exception
if (!skipXMLCheck)
{
bindata.base64.removeWhitespaces();
}
// Catch proteowizard invalid conversion where
// (i) no data type is set
// (ii) data type is set to integer for pic compression
//
// Since numpress arrays are always 64 bit and decode to double arrays,
// this should be safe. However, we cannot generally assume that DT_NONE
// means that we are dealing with a 64 bit float type.
if (bindata.np_compression != MSNumpressCoder::NONE &&
bindata.data_type == BinaryData::DT_NONE)
{
MzMLHandlerHelper::warning(0, String("Invalid mzML format: Numpress-compressed binary data array '") +
bindata.meta.getName() + "' has no child term of MS:1000518 (binary data type) set. Assuming 64 bit float data type.");
bindata.data_type = BinaryData::DT_FLOAT;
bindata.precision = BinaryData::PRE_64;
}
if (bindata.np_compression == MSNumpressCoder::PIC &&
bindata.data_type == BinaryData::DT_INT)
{
bindata.data_type = BinaryData::DT_FLOAT;
bindata.precision = BinaryData::PRE_64;
}
// decode data and check if the length of the decoded data matches the expected length
if (bindata.data_type == BinaryData::DT_FLOAT)
{
if (bindata.np_compression != MSNumpressCoder::NONE)
{
// If its numpress, we don't distinguish 32 / 64 bit as the numpress
// decoder always works with 64 bit (takes std::vector<double>)
MSNumpressCoder::NumpressConfig config;
config.np_compression = bindata.np_compression;
MSNumpressCoder().decodeNP(bindata.base64, bindata.floats_64, bindata.compression, config);
// Next, ensure that we only look at the float array even if the
// mzML tags say 32 bit data (I am looking at you, proteowizard)
bindata.precision = BinaryData::PRE_64;
}
else if (bindata.precision == BinaryData::PRE_64)
{
Base64::decode(bindata.base64, Base64::BYTEORDER_LITTLEENDIAN, bindata.floats_64, bindata.compression);
if (bindata.size != bindata.floats_64.size())
{
MzMLHandlerHelper::warning(0, String("Float binary data array '") + bindata.meta.getName() +
"' has length " + bindata.floats_64.size() + ", but should have length " + bindata.size + ".");
bindata.size = bindata.floats_64.size();
}
}
else if (bindata.precision == BinaryData::PRE_32)
{
Base64::decode(bindata.base64, Base64::BYTEORDER_LITTLEENDIAN, bindata.floats_32, bindata.compression);
if (bindata.size != bindata.floats_32.size())
{
MzMLHandlerHelper::warning(0, String("Float binary data array '") + bindata.meta.getName() +
"' has length " + bindata.floats_32.size() + ", but should have length " + bindata.size + ".");
bindata.size = bindata.floats_32.size();
}
}
// check for unit multiplier and correct our units (e.g. seconds vs minutes)
double unit_multiplier = bindata.unit_multiplier;
if (unit_multiplier != 1.0 && bindata.precision == BinaryData::PRE_64)
{
for (auto& it : bindata.floats_64)
{
it = it * unit_multiplier;
}
}
else if (unit_multiplier != 1.0 && bindata.precision == BinaryData::PRE_32)
{
for (auto& it : bindata.floats_32)
{
it = it * unit_multiplier;
}
}
}
else if (bindata.data_type == BinaryData::DT_INT)
{
if (bindata.precision == BinaryData::PRE_64)
{
Base64::decodeIntegers(bindata.base64, Base64::BYTEORDER_LITTLEENDIAN, bindata.ints_64, bindata.compression);
if (bindata.size != bindata.ints_64.size())
{
MzMLHandlerHelper::warning(0, String("Integer binary data array '") + bindata.meta.getName() +
"' has length " + bindata.ints_64.size() + ", but should have length " + bindata.size + ".");
bindata.size = bindata.ints_64.size();
}
}
else if (bindata.precision == BinaryData::PRE_32)
{
Base64::decodeIntegers(bindata.base64, Base64::BYTEORDER_LITTLEENDIAN, bindata.ints_32, bindata.compression);
if (bindata.size != bindata.ints_32.size())
{
MzMLHandlerHelper::warning(0, String("Integer binary data array '") + bindata.meta.getName() +
"' has length " + bindata.ints_32.size() + ", but should have length " + bindata.size + ".");
bindata.size = bindata.ints_32.size();
}
}
}
else if (bindata.data_type == BinaryData::DT_STRING)
{
Base64::decodeStrings(bindata.base64, bindata.decoded_char, bindata.compression);
if (bindata.size != bindata.decoded_char.size())
{
MzMLHandlerHelper::warning(0, String("String binary data array '") + bindata.meta.getName() +
"' has length " + bindata.decoded_char.size() + ", but should have length " + bindata.size + ".");
bindata.size = bindata.decoded_char.size();
}
}
else
{
// TODO throw error?
MzMLHandlerHelper::warning(0, String("Invalid mzML format: Binary data array '") + bindata.meta.getName() +
"' has no child term of MS:1000518 (binary data type) set. Cannot automatically deduce data type.");
}
}
}
void MzMLHandlerHelper::computeDataProperties_(const std::vector<BinaryData>& data, bool& precision_64, SignedSize& index, const String& index_name)
{
SignedSize i(0);
for (auto const& bindata : data)
{
if (bindata.meta.getName() == index_name)
{
index = i;
precision_64 = (bindata.precision == BinaryData::PRE_64);
return;
}
++i;
}
}
bool MzMLHandlerHelper::handleBinaryDataArrayCVParam(std::vector<BinaryData>& data,
const String& accession,
const String& value,
const String& name,
const String& unit_accession)
{
bool is_default_array = (accession == "MS:1000514" || accession == "MS:1000515" || accession == "MS:1000595");
// store unit accession for non-default arrays
if (!unit_accession.empty() && !is_default_array)
{
data.back().meta.setMetaValue("unit_accession", unit_accession);
}
//MS:1000518 ! binary data type
if (accession == "MS:1000523") //64-bit float
{
data.back().precision = BinaryData::PRE_64;
data.back().data_type = BinaryData::DT_FLOAT;
}
else if (accession == "MS:1000521") //32-bit float
{
data.back().precision = BinaryData::PRE_32;
data.back().data_type = BinaryData::DT_FLOAT;
}
else if (accession == "MS:1000519") //32-bit integer
{
data.back().precision = BinaryData::PRE_32;
data.back().data_type = BinaryData::DT_INT;
}
else if (accession == "MS:1000522") //64-bit integer
{
data.back().precision = BinaryData::PRE_64;
data.back().data_type = BinaryData::DT_INT;
}
else if (accession == "MS:1001479")
{
data.back().precision = BinaryData::PRE_NONE;
data.back().data_type = BinaryData::DT_STRING;
}
//MS:1000513 ! binary data array
else if (accession == "MS:1000786") // non-standard binary data array (with name as value)
{
data.back().meta.setName(value);
}
//MS:1000572 ! binary data compression type
else if (accession == "MS:1000574") //zlib compression
{
data.back().compression = true;
}
else if (accession == "MS:1002312") //numpress compression: linear
{
data.back().np_compression = MSNumpressCoder::LINEAR;
}
else if (accession == "MS:1002313") //numpress compression: pic
{
data.back().np_compression = MSNumpressCoder::PIC;
}
else if (accession == "MS:1002314") //numpress compression: slof
{
data.back().np_compression = MSNumpressCoder::SLOF;
}
else if (accession == "MS:1002746") //numpress compression: linear + zlib
{
data.back().np_compression = MSNumpressCoder::LINEAR;
data.back().compression = true;
}
else if (accession == "MS:1002747") //numpress compression: pic + zlib
{
data.back().np_compression = MSNumpressCoder::PIC;
data.back().compression = true;
}
else if (accession == "MS:1002748") //numpress compression: slof + zlib
{
data.back().np_compression = MSNumpressCoder::SLOF;
data.back().compression = true;
}
else if (accession == "MS:1000576") // no compression
{
data.back().compression = false;
data.back().np_compression = MSNumpressCoder::NONE;
}
else if (is_default_array) // handle m/z, intensity, rt
{
data.back().meta.setName(name);
// time array is given in minutes instead of seconds, we need to convert
if (accession == "MS:1000595" && unit_accession == "UO:0000031")
{
data.back().unit_multiplier = 60.0;
}
}
else
{
// CV term not identified
return false;
}
// CV term found
return true;
}
} // namespace OpenMS // namespace Internal
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/HANDLERS/XMLHandler.cpp | .cpp | 20,850 | 573 | // 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/FORMAT/HANDLERS/XMLHandler.h>
#include <OpenMS/FORMAT/ControlledVocabulary.h>
#include <OpenMS/FORMAT/FileHandler.h>
#include <OpenMS/FORMAT/XMLFile.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/METADATA/ProteinIdentification.h>
#include <OpenMS/SYSTEM/SIMDe.h>
#include <algorithm>
#include <bit>
#include <set>
using namespace std;
using namespace xercesc;
namespace OpenMS::Internal
{
// Specializations for character types, released by XMLString::release
template<> void shared_xerces_ptr<char>::doRelease_(char* item)
{
xercesc::XMLString::release(&item);
}
template<> void shared_xerces_ptr<XMLCh>::doRelease_(XMLCh* item)
{
xercesc::XMLString::release(&item);
}
// Specializations for character types, which needs to be
// released by XMLString::release
template <>
void unique_xerces_ptr<char>::doRelease_(char*& item)
{
xercesc::XMLString::release(&item);
}
template <>
void unique_xerces_ptr<XMLCh>::doRelease_(XMLCh*& item)
{
xercesc::XMLString::release(&item);
}
XMLHandler::XMLHandler(const String & filename, const String & version) :
file_(filename),
version_(version),
load_detail_(LD_ALLDATA)
{
}
XMLHandler::~XMLHandler() = default;
void XMLHandler::reset()
{
}
void XMLHandler::fatalError(const SAXParseException & exception)
{
fatalError(LOAD, sm_.convert(exception.getMessage()), exception.getLineNumber(), exception.getColumnNumber());
}
void XMLHandler::error(const SAXParseException & exception)
{
error(LOAD, sm_.convert(exception.getMessage()), exception.getLineNumber(), exception.getColumnNumber());
}
void XMLHandler::warning(const SAXParseException & exception)
{
warning(LOAD, sm_.convert(exception.getMessage()), exception.getLineNumber(), exception.getColumnNumber());
}
void XMLHandler::fatalError(ActionMode mode, const String & msg, UInt line, UInt column) const
{
String error_message;
if (mode == LOAD)
{
error_message = String("While loading '") + file_ + "': " + msg;
// test if file has the wrong extension and is therefore passed to the wrong parser
// only makes sense if we are loading/parsing a file
FileTypes::Type ft_name = FileHandler::getTypeByFileName(file_);
FileTypes::Type ft_content = FileHandler::getTypeByContent(file_);
if (ft_name != ft_content)
{
error_message += String("\nProbable cause: The file suffix (") + FileTypes::typeToName(ft_name)
+ ") does not match the file content (" + FileTypes::typeToName(ft_content) + "). "
+ "Rename the file to fix this.";
}
}
else if (mode == STORE)
{
error_message = String("While storing '") + file_ + "': " + msg;
}
if (line != 0 || column != 0)
{
error_message += String("( in line ") + line + " column " + column + ")";
}
OPENMS_LOG_FATAL_ERROR << error_message << std::endl;
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, file_, error_message);
}
void XMLHandler::error(ActionMode mode, const String & msg, UInt line, UInt column) const
{
String error_message;
if (mode == LOAD)
{
error_message = String("Non-fatal error while loading '") + file_ + "': " + msg;
}
else if (mode == STORE)
{
error_message = String("Non-fatal error while storing '") + file_ + "': " + msg;
}
if (line != 0 || column != 0)
{
error_message += String("( in line ") + line + " column " + column + ")";
}
OPENMS_LOG_ERROR << error_message << std::endl;
}
void XMLHandler::warning(ActionMode mode, const String & msg, UInt line, UInt column) const
{
String error_message;
if (mode == LOAD)
{
error_message = String("While loading '") + file_ + "': " + msg;
}
else if (mode == STORE)
{
error_message = String("While storing '") + file_ + "': " + msg;
}
if (line != 0 || column != 0)
{
error_message += String("( in line ") + line + " column " + column + ")";
}
// warn only in Debug mode but suppress warnings in release mode (more happy users)
#ifdef OPENMS_ASSERTIONS
OPENMS_LOG_WARN << error_message << std::endl;
#else
OPENMS_LOG_DEBUG << error_message << std::endl;
#endif
}
void XMLHandler::characters(const XMLCh * const /*chars*/, const XMLSize_t /*length*/)
{
}
void XMLHandler::startElement(const XMLCh * const /*uri*/, const XMLCh * const /*localname*/, const XMLCh * const /*qname*/, const Attributes & /*attrs*/)
{
}
void XMLHandler::endElement(const XMLCh * const /*uri*/, const XMLCh * const /*localname*/, const XMLCh * const /*qname*/)
{
}
void XMLHandler::writeTo(std::ostream & /*os*/)
{
}
SignedSize XMLHandler::cvStringToEnum_(const Size section, const String & term, const char * message, const SignedSize result_on_error)
{
OPENMS_PRECONDITION(section < cv_terms_.size(), "cvStringToEnum_: Index overflow (section number too large)");
std::vector<String>::const_iterator it = std::find(cv_terms_[section].begin(), cv_terms_[section].end(), term);
if (it != cv_terms_[section].end())
{
return it - cv_terms_[section].begin();
}
else
{
warning(LOAD, String("Unexpected CV entry '") + message + "'='" + term + "'");
return result_on_error;
}
}
/// handlers which support partial loading, implement this method
/// @throws Exception::NotImplemented
XMLHandler::LOADDETAIL XMLHandler::getLoadDetail() const
{
throw Exception::NotImplemented(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
/// handlers which support partial loading, implement this method
/// @throws Exception::NotImplemented
void XMLHandler::setLoadDetail(const LOADDETAIL /*d*/)
{
throw Exception::NotImplemented(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
DataValue XMLHandler::cvParamToValue(const ControlledVocabulary& cv, const String& parent_tag, const String& accession, const String& name,
const String& value, const String& unit_accession) const
{
// the actual value stored in the CVParam
// we assume for now that it is a string value, we update the type later on
DataValue cv_value = value;
// Abort on unknown terms
try
{
const ControlledVocabulary::CVTerm& term = cv.getTerm(accession); // throws Exception::InvalidValue if missing
// check if term name and parsed name match
if (name != term.name)
{
warning(LOAD, String("Name of CV term not correct: '") + term.id + " - " + name + "' should be '" + term.name + "'");
}
if (term.obsolete)
{
warning(LOAD, String("Obsolete CV term '") + accession + " - " + term.name + "' used in tag '" + parent_tag + "'.");
}
// values used in wrong places and wrong value types
if (!value.empty())
{
if (term.xref_type == ControlledVocabulary::CVTerm::XRefType::NONE)
{
// Quality CV does not state value type :(
if (!accession.hasPrefix("PATO:"))
{
warning(LOAD, String("The CV term '") + accession + " - " + term.name + "' used in tag '" + parent_tag + "' must not have a value. The value is '" + value + "'.");
}
}
else
{
switch (term.xref_type)
{
// string value can be anything
case ControlledVocabulary::CVTerm::XRefType::XSD_STRING:
break;
// int value => try casting
case ControlledVocabulary::CVTerm::XRefType::XSD_INTEGER:
case ControlledVocabulary::CVTerm::XRefType::XSD_NEGATIVE_INTEGER:
case ControlledVocabulary::CVTerm::XRefType::XSD_POSITIVE_INTEGER:
case ControlledVocabulary::CVTerm::XRefType::XSD_NON_NEGATIVE_INTEGER:
case ControlledVocabulary::CVTerm::XRefType::XSD_NON_POSITIVE_INTEGER:
try
{
cv_value = value.toInt();
}
catch (Exception::ConversionError&)
{
warning(LOAD, String("The CV term '") + accession + " - " + term.name + "' used in tag '" + parent_tag + "' must have an integer value. The value is '" + value + "'.");
return DataValue::EMPTY;
}
break;
// double value => try casting
case ControlledVocabulary::CVTerm::XRefType::XSD_DECIMAL:
try
{
cv_value = value.toDouble();
}
catch (Exception::ConversionError&)
{
warning(LOAD, String("The CV term '") + accession + " - " + term.name + "' used in tag '" + parent_tag + "' must have a floating-point value. The value is '" + value + "'.");
return DataValue::EMPTY;
}
break;
// date string => try conversion
case ControlledVocabulary::CVTerm::XRefType::XSD_DATE:
try
{
DateTime tmp;
tmp.set(value);
}
catch (Exception::ParseError&)
{
warning(LOAD, String("The CV term '") + accession + " - " + term.name + "' used in tag '" + parent_tag + "' must be a valid date. The value is '" + value + "'.");
return DataValue::EMPTY;
}
break;
case ControlledVocabulary::CVTerm::XRefType::XSD_BOOLEAN:
try
{
cv_value = String(value).toLower();
cv_value.toBool(); // only works if 'true' or 'false'
}
catch (Exception::ConversionError&)
{
warning(LOAD, String("The CV term '") + accession + " - " + term.name + "' used in tag '" + parent_tag + "' must have a boolean value (true/false). The value is '" + value + "'.");
return DataValue::EMPTY;
}
break;
default:
warning(LOAD, String("The CV term '") + accession + " - " + term.name + "' used in tag '" + parent_tag + "' has the unknown value type '" +
ControlledVocabulary::CVTerm::getXRefTypeName(term.xref_type) + "'.");
break;
}
}
}
// no value, although there should be a numerical value
else if (term.xref_type != ControlledVocabulary::CVTerm::XRefType::NONE && term.xref_type != ControlledVocabulary::CVTerm::XRefType::XSD_STRING && // should be numerical
!cv.isChildOf(accession, "MS:1000513") // here the value type relates to the binary data array, not the 'value=' attribute!
)
{
warning(LOAD, String("The CV term '") + accession + " - " + term.name + "' used in tag '" + parent_tag + "' should have a numerical value. The value is '" + value + "'.");
return DataValue::EMPTY;
}
}
catch (const Exception::InvalidValue& /*e*/)
{
// in 'sample' several external CVs are used (Brenda, GO, ...). Do not warn then.
if (parent_tag != "sample")
{
warning(LOAD, String("Unknown cvParam '") + accession + "' in tag '" + parent_tag + "'.");
return DataValue::EMPTY;
}
}
if (!unit_accession.empty())
{
if (unit_accession.hasPrefix("UO:"))
{
cv_value.setUnit(unit_accession.suffix(unit_accession.size() - 3).toInt());
cv_value.setUnitType(DataValue::UnitType::UNIT_ONTOLOGY);
}
else if (unit_accession.hasPrefix("MS:"))
{
cv_value.setUnit(unit_accession.suffix(unit_accession.size() - 3).toInt());
cv_value.setUnitType(DataValue::UnitType::MS_ONTOLOGY);
}
else
{
warning(LOAD, String("Unhandled unit '") + unit_accession + "' in tag '" + parent_tag + "'.");
}
}
return cv_value;
}
DataValue XMLHandler::cvParamToValue(const ControlledVocabulary& cv, const CVTerm& raw_term) const
{
return cvParamToValue(cv, "?", raw_term.getAccession(), raw_term.getName(), raw_term.getValue(), raw_term.getUnit().accession);
}
void XMLHandler::checkUniqueIdentifiers_(const std::vector<ProteinIdentification>& prot_ids) const
{
std::set<String> s;
for (const auto& p : prot_ids)
{
if (s.insert(p.getIdentifier()).second == false) // element already existed
{
fatalError(ActionMode::STORE, "ProteinIdentification run identifiers are not unique. This can lead to loss of unique PeptideIdentification assignment. Duplicated Protein-ID is:" +
p.getIdentifier());
}
}
}
void XMLHandler::writeUserParam_(const String& tag_name, std::ostream& os, const MetaInfoInterface& meta, UInt indent) const
{
std::vector<String> keys;
meta.getKeys(keys);
String val;
String p_prefix = String(indent, '\t') + "<" + writeXMLEscape(tag_name) + " type=\"";
for (Size i = 0; i != keys.size(); ++i)
{
os << p_prefix;
const DataValue& d = meta.getMetaValue(keys[i]);
// determine type
if (d.valueType() == DataValue::STRING_VALUE || d.valueType() == DataValue::EMPTY_VALUE)
{
os << "string";
val = writeXMLEscape(d);
}
else if (d.valueType() == DataValue::INT_VALUE)
{
os << "int";
val = d;
}
else if (d.valueType() == DataValue::DOUBLE_VALUE)
{
os << "float";
val = d;
}
else if (d.valueType() == DataValue::INT_LIST)
{
os << "intList";
val = d.toString();
}
else if (d.valueType() == DataValue::DOUBLE_LIST)
{
os << "floatList";
val = d.toString();
}
else if (d.valueType() == DataValue::STRING_LIST)
{
os << "stringList";
// List elements are separated by comma. In the rare case of comma inside individual strings
// we replace them by an escape symbol '\\|'.
// This allows distinguishing commas as element separator and normal string character and reconstruct the list.
StringList sl = d.toStringList();
for (String& s : sl)
{
if (s.has(',')) s.substitute(",", "\\|");
}
val = "[" + writeXMLEscape(ListUtils::concatenate(sl, ",")) + "]";
}
else
{
throw Exception::NotImplemented(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
os << "\" name=\"" << keys[i] << "\" value=\"" << val << "\"/>\n";
}
}
// https://github.com/OpenMS/OpenMS/issues/8122
#if defined(__GNUC__)
__attribute__((no_sanitize("address")))
#elif defined(_MSC_VER)
__declspec(no_sanitize_address)
#endif
size_t StringManager::strLength(const XMLCh* input_ptr)
{
if (input_ptr == nullptr) {
return 0;
}
XMLSize_t processed_chars = 0;
const XMLCh* pos_ptr = input_ptr;
// find number of characters until we reach a 16-byte aligned address
uintptr_t ptr_value = reinterpret_cast<uintptr_t>(pos_ptr);
size_t misalignment = ptr_value & 15; // modulo 16 to find misalignment
int chars_to_align = misalignment ? (16 - misalignment) / sizeof(XMLCh) : 0;
// process one by one until we reach a 16-byte aligned address (where a SIMD load can be used)
for (int i = 0; i < chars_to_align; ++i)
{
if (*pos_ptr == 0) {
return i;
}
++pos_ptr;
}
processed_chars = chars_to_align;
// SIMD loop: find the first zero character in blocks of 8 UTF-16 characters (16 bytes each)
const simde__m128i zero = simde_mm_setzero_si128();
while (true)
{
simde__m128i bits = simde_mm_load_si128(reinterpret_cast<const simde__m128i*>(pos_ptr));
simde__m128i cmp_zero = simde_mm_cmpeq_epi16(bits, zero); // sets bits to 0xFFFF (2 bytes) for each character that is zero
uint16_t zero_mask = simde_mm_movemask_epi8(cmp_zero); // extracts MSB from each byte
if (zero_mask != 0)
{ // Found a zero character
auto byte_pos_zero = std::countr_zero(zero_mask); // count trailing zeros to find the first zero character
auto char_pos_zero = byte_pos_zero / 2; // each UTF-16 character is 2 bytes, so divide by 2 to get character position
return processed_chars + char_pos_zero;
}
// 8 chars (each 2 bytes) had no zero
pos_ptr += 8;
processed_chars += 8;
}
// never reached
return processed_chars;
}
void StringManager::compress64_(const XMLCh* inputIt, char* outputIt)
{
simde__m128i bits = simde_mm_loadu_si128(reinterpret_cast<const simde__m128i*>(inputIt));
// Select every second byte (little-endian lower byte of each UTF-16 character)
const simde__m128i shuffleMask = simde_mm_setr_epi8(
0, 2, 4, 6, 8, 10, 12, 14,
-1, -1, -1, -1, -1, -1, -1, -1
);
simde__m128i compressed = simde_mm_shuffle_epi8(bits, shuffleMask);
// Store the lower 64 bits (8 ASCII characters)
simde_mm_storel_epi64(reinterpret_cast<simde__m128i*>(outputIt), compressed);
}
bool StringManager::isASCII(const XMLCh* chars, const XMLSize_t length)
{
if (length == 0)
{
return true;
}
Size fullBlocks = length / 8;
Size remainder = length % 8;
const XMLCh* inputPtr = chars;
simde__m128i mask = simde_mm_set1_epi16(0xFF00);
// Process blocks of 8 UTF-16 characters using SIMD
for (Size i = 0; i < fullBlocks; ++i)
{
simde__m128i bits = simde_mm_loadu_si128(reinterpret_cast<const simde__m128i*>(inputPtr));
simde__m128i zero = simde_mm_setzero_si128();
simde__m128i andOp = simde_mm_and_si128(bits, mask);
simde__m128i cmp = simde_mm_cmpeq_epi16(andOp, zero);
if (simde_mm_movemask_epi8(cmp) != 0xFFFF)
{
return false;
}
inputPtr += 8;
}
// Check remaining characters individually
for (Size i = 0; i < remainder; ++i)
{
if (inputPtr[i] & 0xFF00)
{
return false;
}
}
return true;
}
void StringManager::appendASCII(const XMLCh* chars, const XMLSize_t length, String& result)
{
// XMLCh are characters in UTF16 (usually stored as 16-bit unsigned
// short but this is not guaranteed).
// We know that the Base64 string here can only contain plain ASCII
// and all bytes except the least significant one will be zero. Thus
// we can convert to char directly (only keeping the least
// significant byte).
Size fullBlocks = length / 8;
Size remainder = length % 8;
const XMLCh* inputPtr = chars;
Size currentSize = result.size();
result.resize(currentSize + length);
char* outputPtr = &result[currentSize];
// Copy blocks of 8 characters at a time
for (Size i = 0; i < fullBlocks; ++i)
{
compress64_(inputPtr, outputPtr);
inputPtr += 8;
outputPtr += 8;
}
// Copy any remaining characters individually
for (Size i = 0; i < remainder; ++i)
{
outputPtr[i] = static_cast<char>(inputPtr[i] & 0xFF);
}
}
//*******************************************************************************************************************
StringManager::StringManager() = default;
StringManager::~StringManager() = default;
} // namespace OpenMS::Internal
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/HANDLERS/UnimodXMLHandler.cpp | .cpp | 7,244 | 216 | // 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/CHEMISTRY/ResidueModification.h>
#include <OpenMS/FORMAT/HANDLERS/UnimodXMLHandler.h>
using namespace std;
using namespace xercesc;
namespace OpenMS::Internal
{
UnimodXMLHandler::UnimodXMLHandler(vector<ResidueModification*>& mods, const String& filename) :
XMLHandler(filename, "2.0"),
avge_mass_(0.0),
mono_mass_(0.0),
modification_(nullptr),
modifications_(mods)
{
}
UnimodXMLHandler::~UnimodXMLHandler()
= default;
void UnimodXMLHandler::startElement(const XMLCh* const /*uri*/, const XMLCh* const /*local_name*/, const XMLCh* const qname, const Attributes& attributes)
{
tag_ = String(sm_.convert(qname));
// new modification?
if (tag_ == "umod:mod" || tag_ == "mod")
{
sites_.clear();
modification_ = new ResidueModification();
String title(attributeAsString_(attributes, "title"));
modification_->setId(title);
String full_name(attributeAsString_(attributes, "full_name"));
// full_name.substitute("®", ""); // remove damn character (will be interpreted differently across platforms)
// deleted this in the unimod.xml file
modification_->setFullName(full_name);
Int record_id(attributeAsInt_(attributes, "record_id"));
modification_->setUniModRecordId(record_id);
return;
}
// which residues are allowed?
if (tag_ == "umod:specificity" || tag_ == "specificity")
{
// neutral_loss_diff_formula_ = EmpiricalFormula();
neutral_loss_diff_formula_.clear();
// classification of mod
// TODO do this for all mods, do not overwrite for each specificity
String classification(attributeAsString_(attributes, "classification"));
modification_->setSourceClassification(classification);
// allowed site
String site = attributeAsString_(attributes, "site");
//sites_.push_back(site);
// allowed positions
ResidueModification::TermSpecificity position = ResidueModification::ANYWHERE;
String pos(attributeAsString_(attributes, "position"));
if (pos == "Anywhere")
{
position = ResidueModification::ANYWHERE;
}
else if (pos == "Protein N-term")
{
position = ResidueModification::PROTEIN_N_TERM;
}
else if (pos == "Protein C-term")
{
position = ResidueModification::PROTEIN_C_TERM;
}
else if (pos == "Any C-term")
{
position = ResidueModification::C_TERM;
}
else if (pos == "Any N-term")
{
position = ResidueModification::N_TERM;
}
else
{
warning(LOAD, String("Don't know allowed position called: '") + pos + "' - setting to anywhere");
}
was_valid_peptide_modification_ = true;
term_specs_.push_back(position);
if (site.size() > 1)
{
site = "X"; // C-term/N-term
}
sites_.push_back(site[0]);
return;
}
if (tag_ == "umod:NeutralLoss" || tag_ == "NeutralLoss")
{
// mono_mass="97.976896" avge_mass="97.9952" flag="false"
// composition="H(3) O(4) P">
}
// delta mass definitions?
if (tag_ == "umod:delta" || tag_ == "delta")
{
// avge_mass="-0.9848" mono_mass="-0.984016" composition="H N O(-1)" >
avge_mass_ = String(sm_.convert(attributes.getValue(attributes.getIndex(sm_.convert("avge_mass").c_str())))).toDouble();
mono_mass_ = String(sm_.convert(attributes.getValue(attributes.getIndex(sm_.convert("mono_mass").c_str())))).toDouble();
return;
}
// <umod:element symbol="H" number="1"/>
if (tag_ == "umod:element")
{
String symbol = sm_.convert(attributes.getValue(attributes.getIndex(sm_.convert("symbol").c_str())));
String num = sm_.convert(attributes.getValue(attributes.getIndex(sm_.convert("number").c_str())));
String isotope, tmp_symbol;
for (Size i = 0; i != symbol.size(); ++i)
{
if (isdigit(symbol[i]))
{
isotope += symbol[i];
}
else
{
tmp_symbol += symbol[i];
}
}
String formula;
if (!isotope.empty())
{
formula = '(' + isotope + ')' + tmp_symbol + String(num);
}
else
{
formula = tmp_symbol + num;
}
diff_formula_ += EmpiricalFormula(formula);
}
}
void UnimodXMLHandler::endElement(const XMLCh* const /*uri*/, const XMLCh* const /*local_name*/, const XMLCh* const qname)
{
tag_ = String(sm_.convert(qname));
// write the modifications to vector
if (tag_ == "umod:mod" || tag_ == "mod")
{
modification_->setDiffAverageMass(avge_mass_);
modification_->setDiffMonoMass(mono_mass_);
modification_->setDiffFormula(diff_formula_);
for (Size i = 0; i != sites_.size(); ++i)
{
ResidueModification* new_mod = new ResidueModification(*modification_);
new_mod->setOrigin(sites_[i]);
new_mod->setTermSpecificity(term_specs_[i]);
new_mod->setNeutralLossDiffFormulas(neutral_loss_diff_formulas_[i]);
modifications_.push_back(new_mod);
}
avge_mass_ = 0.0;
mono_mass_ = 0.0;
diff_formula_ = EmpiricalFormula();
term_specs_.clear();
sites_.clear();
neutral_loss_diff_formulas_.clear();
delete modification_;
return;
}
if (tag_ == "umod:specificity" || tag_ == "specificity")
{
if (was_valid_peptide_modification_) // as we exclude "Protein" modifications (see above)
{
neutral_loss_diff_formulas_.push_back(neutral_loss_diff_formula_);
modification_->setNeutralLossMonoMasses(neutral_loss_mono_masses_);
modification_->setNeutralLossAverageMasses(neutral_loss_avg_masses_);
neutral_loss_diff_formula_.clear();
neutral_loss_mono_masses_.clear();
neutral_loss_avg_masses_.clear();
}
}
if ( (tag_ == "umod:NeutralLoss" || tag_ == "NeutralLoss") && !diff_formula_.isEmpty() )
{
// now diff_formula_ contains the neutral loss diff formula
neutral_loss_diff_formula_.push_back(diff_formula_);
neutral_loss_mono_masses_.push_back(mono_mass_);
neutral_loss_avg_masses_.push_back(avge_mass_);
avge_mass_ = 0.0;
mono_mass_ = 0.0;
diff_formula_ = EmpiricalFormula();
}
}
void UnimodXMLHandler::characters(const XMLCh* const /*chars*/, const XMLSize_t /*length*/)
{
// nothing to do here
}
} // namespace OpenMS // namespace Internal
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/HANDLERS/XQuestResultXMLHandler.cpp | .cpp | 63,933 | 1,232 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Eugen Netz $
// $Authors: Lukas Zimmermann, Eugen Netz $
// --------------------------------------------------------------------------
#include <OpenMS/FORMAT/HANDLERS/XQuestResultXMLHandler.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/CONCEPT/VersionInfo.h>
#include <OpenMS/CONCEPT/Constants.h>
#include <OpenMS/DATASTRUCTURES/StringUtils.h>
#include <OpenMS/DATASTRUCTURES/StringListUtils.h>
#include <OpenMS/CHEMISTRY/ModificationsDB.h>
#include <OpenMS/CHEMISTRY/CrossLinksDB.h>
#include <cassert>
using namespace std;
using namespace xercesc;
namespace OpenMS::Internal
{
// Initialize static const members
std::map< Size, String > XQuestResultXMLHandler::enzymes
{
std::make_pair(1, "trypsin"), std::make_pair(2, "chymotrypsin"), std::make_pair(3, "unknown_enzyme"),
std::make_pair(9, "unknown_enzyme"), std::make_pair(10, "unknown_enzyme"), std::make_pair(14, "unknown_enzyme"),
std::make_pair(15, "unknown_enzyme"), std::make_pair(16, "unknown_enzyme"), std::make_pair(17, "unknown_enzyme"),
std::make_pair(18, "unknown_enzyme"), std::make_pair(20, "unknown_enzyme")
};
std::map< String, UInt> XQuestResultXMLHandler::months
{
std::make_pair("Jan", 1), std::make_pair("Feb", 2), std::make_pair("Mar", 3), std::make_pair("Apr", 4),
std::make_pair("May", 5), std::make_pair("Jun", 6), std::make_pair("Jul", 7), std::make_pair("Aug", 8),
std::make_pair("Sep", 9), std::make_pair("Oct", 10), std::make_pair("Nov", 11), std::make_pair("Dec", 12)
};
// reader
XQuestResultXMLHandler::XQuestResultXMLHandler(const String &filename,
PeptideIdentificationList & pep_ids,
std::vector< ProteinIdentification > & prot_ids
) :
XMLHandler(filename, "1.0"),
pep_ids_(&pep_ids),
prot_ids_(&prot_ids),
n_hits_(0),
min_score_(0),
max_score_(0)
{
// Initialize the one and only protein identification
this->prot_ids_->clear();
ProteinIdentification prot_id;
prot_id.setSearchEngine("xQuest");
prot_id.setSearchEngineVersion(VersionInfo::getVersion());
prot_id.setMetaValue("SpectrumIdentificationProtocol", DataValue("MS:1002494")); // crosslinking search = MS:1002494
this->prot_ids_->push_back(prot_id);
// Fetch the enzymes database
this->enzymes_db_ = ProteaseDB::getInstance();
// TODO Produce some warnings that are associated with the reading of xQuest result files
// OPENMS_LOG_WARN << "WARNING: Fixed modifications are not available in the xQuest input file and will thus be not present in the loaded data!\n" << std::endl;
}
// writer
XQuestResultXMLHandler::XQuestResultXMLHandler(const std::vector<ProteinIdentification>& pro_id,
const PeptideIdentificationList& pep_id,
const String& filename,
const String& version
) :
XMLHandler(filename, version),
pep_ids_(nullptr),
prot_ids_(nullptr),
cpro_id_(&pro_id),
cpep_id_(&pep_id)
{
}
XQuestResultXMLHandler::~XQuestResultXMLHandler()
= default;
void XQuestResultXMLHandler::extractDateTime_(const String & xquest_datetime_string, DateTime & date_time) const
{
StringList xquest_datetime_string_split;
StringUtils::split(xquest_datetime_string,' ', xquest_datetime_string_split);
if (this->is_openpepxl_)
{
// Example: 2017-03-17 23:04:50
date_time.setDate(xquest_datetime_string_split[0]);
date_time.setTime(xquest_datetime_string_split[1]);
}
else
{
// Example: Fri Dec 18 12:28:42 2015
// Example: Fri Dec 8 12:28:42 2015
// for single digit days, there are two spaces and the day is in the 4th string instead of the 3rd
// that also moves the time and year one slot further
UInt correction = 0;
String day_string = xquest_datetime_string_split[2];
if (day_string.empty())
{
correction = 1;
}
UInt day = xquest_datetime_string_split[2+correction].toInt();
UInt year = xquest_datetime_string_split[4+correction].toInt();
UInt month = XQuestResultXMLHandler::months[xquest_datetime_string_split[1]];
date_time.setDate(month, day, year);
date_time.setTime(xquest_datetime_string_split[3+correction]);
}
}
// Extracts the position of the Cross-Link for intralinks and crosslinks
void XQuestResultXMLHandler::getLinkPosition_(const xercesc::Attributes & attributes, std::pair<SignedSize, SignedSize> & pair)
{
String xlink_position = this->attributeAsString_(attributes, "xlinkposition");
StringList xlink_position_split;
StringUtils::split(xlink_position, "," ,xlink_position_split);
pair.first = xlink_position_split[0].toInt();
pair.second = xlink_position_split.size() == 2 ? xlink_position_split[1].toInt() : 0;
}
void XQuestResultXMLHandler::setPeptideEvidence_(const String & prot_string, PeptideHit & pep_hit)
{
StringList prot_list;
StringUtils::split(prot_string, ",", prot_list);
vector< PeptideEvidence > evidences;
evidences.reserve(prot_list.size());
for (StringList::const_iterator prot_list_it = prot_list.begin();
prot_list_it != prot_list.end(); ++prot_list_it)
{
PeptideEvidence pep_ev;
String accession = *prot_list_it;
if (this->accessions_.find(accession) == this->accessions_.end())
{
this->accessions_.insert(accession);
ProteinHit prot_hit;
prot_hit.setAccession(accession);
prot_hit.setMetaValue("target_decoy", accession.hasSubstring(this->decoy_string_) ? "decoy" : "target");
(*this->prot_ids_)[0].getHits().push_back(prot_hit);
}
pep_ev.setProteinAccession(accession);
pep_ev.setStart(PeptideEvidence::UNKNOWN_POSITION); // These information are not available in the xQuest result file
pep_ev.setEnd(PeptideEvidence::UNKNOWN_POSITION);
pep_ev.setAABefore(PeptideEvidence::UNKNOWN_AA);
pep_ev.setAAAfter(PeptideEvidence::UNKNOWN_AA);
evidences.push_back(pep_ev);
}
pep_hit.setPeptideEvidences(evidences);
}
// Assign all attributes in the peptide_id_attributes map to the MetaInfoInterface object
void XQuestResultXMLHandler::addMetaValues_(MetaInfoInterface & meta_info_interface)
{
for (std::map<String, DataValue>::const_iterator it = this->peptide_id_meta_values_.begin();
it != this->peptide_id_meta_values_.end(); ++it)
{
std::pair<String, DataValue> item = *it;
meta_info_interface.setMetaValue(item.first, item.second);
}
}
double XQuestResultXMLHandler::getMinScore() const
{
return this->min_score_;
}
double XQuestResultXMLHandler::getMaxScore() const
{
return this->max_score_;
}
UInt XQuestResultXMLHandler::getNumberOfHits() const
{
return this->n_hits_;
}
void XQuestResultXMLHandler::endElement(const XMLCh * const /*uri*/, const XMLCh * const /*local_name*/, const XMLCh * const qname)
{
String tag = StringManager::convert(qname);
if (tag == "xquest_results")
{
if (!this->is_openpepxl_)
{
ProteinIdentification::SearchParameters search_params((*this->prot_ids_)[0].getSearchParameters());
search_params.charges = ListUtils::concatenate(this->charges_, ",");
// min and max searched precursor charge not written out in xQuest
// determination by charges in found results is not as clean, but is the best we can do
search_params.setMetaValue("precursor:min_charge", this->min_precursor_charge_);
search_params.setMetaValue("precursor:max_charge", this->max_precursor_charge_);
(*this->prot_ids_)[0].setSearchParameters(search_params);
}
}
}
void XQuestResultXMLHandler::startElement(const XMLCh * const, const XMLCh * const, const XMLCh * const qname, const Attributes &attributes)
{
String tag = StringManager::convert(qname);
// Extract meta information from the xquest_results tag
if (tag == "xquest_results")
{
//cout << "Parse xQuest search settings" << endl;
// Decide whether this Block is original xQuest or OpenPepXL
String xquest_version = this->attributeAsString_(attributes, "xquest_version");
this->is_openpepxl_ = xquest_version.hasSubstring("OpenPepXL");
// Date and Time of Search
DateTime date_time;
//cout << "Parse Date" << endl;
this->extractDateTime_(this->attributeAsString_(attributes, "date"), date_time);
(*this->prot_ids_)[0].setDateTime(date_time);
// Set the search parameters
ProteinIdentification::SearchParameters search_params;
//cout << "Parse Enzyme" << endl;
// General
if (this->is_openpepxl_) // Enzyme via name
{
search_params.digestion_enzyme = dynamic_cast<const DigestionEnzymeProtein&>(*this->enzymes_db_->getEnzyme(this->attributeAsString_(attributes, "enzyme_name")));
}
else // Enzyme via enzyme number in xQuest
{
search_params.digestion_enzyme = dynamic_cast<const DigestionEnzymeProtein&>(*this->enzymes_db_->getEnzyme(XQuestResultXMLHandler::enzymes[this->attributeAsInt_(attributes, "enzyme_num")]));
}
search_params.missed_cleavages = this->attributeAsInt_(attributes, "missed_cleavages");
search_params.db = this->attributeAsString_(attributes, "database");
search_params.precursor_mass_tolerance = this->attributeAsDouble_(attributes, "ms1tolerance");
String tolerancemeasure_ms1 = this->attributeAsString_(attributes, this->is_openpepxl_ ? "tolerancemeasure_ms1" : "tolerancemeasure");
search_params.precursor_mass_tolerance_ppm = tolerancemeasure_ms1 == "ppm";
search_params.fragment_mass_tolerance = this->attributeAsDouble_(attributes, "ms2tolerance");
String tolerancemeasure_ms2 = this->attributeAsString_(attributes, "tolerancemeasure_ms2");
search_params.fragment_mass_tolerance_ppm = tolerancemeasure_ms2 != "Da";
//cout << "Parse Mods" << endl;
// variable Modifications
vector< String > variable_mod_list;
vector< String > variable_mod_split;
String var_mod_string;
if (this->optionalAttributeAsString_(var_mod_string, attributes, "variable_mod") && !var_mod_string.empty())
{
StringUtils::split(var_mod_string, ",", variable_mod_split);
if (variable_mod_split[0].size() == 1 && variable_mod_split[0] != "0") // xQuest style mods= "one-letter-code,mass"
{
double mod_mass = double(DataValue(variable_mod_split[1]));
std::vector<String> mods;
ModificationsDB::getInstance()->searchModificationsByDiffMonoMass(mods, mod_mass, 0.01, variable_mod_split[0]);
if (!mods.empty())
{
variable_mod_list.push_back(mods[0]);
}
}
search_params.variable_modifications = variable_mod_list;
}
// fixed Modifications
String fixed_mod_string;
StringList fixed_mod_list;
if (this->optionalAttributeAsString_(fixed_mod_string, attributes, "fixed_mod") && !fixed_mod_string.empty())
{
fixed_mod_list = ListUtils::create<String>(fixed_mod_string);
search_params.fixed_modifications = fixed_mod_list;
}
//cout << "Parse decoy stuff" << endl;
String decoy_prefix;
// if this info is not available, we can assume the decoy string is a prefix, since that is the standard way
if (!this->optionalAttributeAsString_(decoy_prefix, attributes, "decoy_prefix"))
{
decoy_prefix = "1";
}
// change the default decoy string, if the parameter is given
String current_decoy_string;
if (this->optionalAttributeAsString_(current_decoy_string, attributes, "decoy_string") && !current_decoy_string.empty())
{
this->decoy_string_ = current_decoy_string;
}
// do some stringstream magic to turn "1" or "0" strings into booleans
bool decoy_prefix_bool;
std::istringstream is(decoy_prefix);
is >> decoy_prefix_bool;
// Meta Values
String database_dc;
if (this->optionalAttributeAsString_(database_dc, attributes, "database_dc") && !database_dc.empty())
{
search_params.setMetaValue("input_decoys", DataValue(database_dc));
}
search_params.setMetaValue("decoy_prefix", DataValue(decoy_prefix_bool));
search_params.setMetaValue("decoy_string", DataValue(this->decoy_string_));
search_params.setMetaValue("fragment:mass_tolerance_xlinks", DataValue(this->attributeAsDouble_(attributes, "xlink_ms2tolerance")));
String monolink_masses_string_raw;
StringList monolink_masses_string;
if (this->optionalAttributeAsString_(monolink_masses_string_raw, attributes, "monolinkmw") && !monolink_masses_string_raw.empty())
{
monolink_masses_string = ListUtils::create<String>(monolink_masses_string_raw);
}
if (!monolink_masses_string.empty())
{
DoubleList monolink_masses;
for (String monolink_string : monolink_masses_string)
{
monolink_masses.push_back(monolink_string.trim().toDouble());
}
search_params.setMetaValue("cross_link:mass_monolink", monolink_masses);
}
// xQuest uses the non-standard character "\u2212" for the minus in negative numbers. This can happen for zero-length cross-linkers.
// Replace it with a proper "-" (minus), if there is one, to be able to convert it to a negative double.
String xlinkermw = this->attributeAsString_(attributes, "xlinkermw");
xlinkermw.substitute("\u2212", "-");
search_params.setMetaValue("cross_link:mass_mass", DataValue(xlinkermw.toDouble()));
this->cross_linker_name_ = this->attributeAsString_(attributes, "crosslinkername");
search_params.setMetaValue("cross_link:name", DataValue(this->cross_linker_name_));
String iso_shift = this->attributeAsString_(attributes, "cp_isotopediff");
if (!iso_shift.empty())
{
search_params.setMetaValue("cross_link:mass_isoshift", iso_shift.toDouble());
}
bool ntermxlinkable;
std::istringstream is_nterm(this->attributeAsString_(attributes, "ntermxlinkable"));
is_nterm >> ntermxlinkable;
//cout << "Parse AArequired" << endl;
String aarequired;
// older xQuest versions only allowed homobifunctional cross-linkers
if (this->optionalAttributeAsString_(aarequired, attributes, "AArequired") && !aarequired.empty())
{
if (ntermxlinkable)
{
aarequired += ",N-term";
}
search_params.setMetaValue("cross_link:residue1", ListUtils::create<String>(aarequired));
search_params.setMetaValue("cross_link:residue2", ListUtils::create<String>(aarequired));
}
else
{
String aarequired1 = this->attributeAsString_(attributes, "AArequired1");
String aarequired2 = this->attributeAsString_(attributes, "AArequired2");
if (ntermxlinkable)
{
if ( !(aarequired1.hasSubstring("N-term") || aarequired2.hasSubstring("N-term")) )
{
aarequired1 += ",N-term";
aarequired2 += ",N-term";
}
}
search_params.setMetaValue("cross_link:residue1", ListUtils::create<String>(aarequired1));
search_params.setMetaValue("cross_link:residue2", ListUtils::create<String>(aarequired2));
}
if (this->is_openpepxl_)
{
//cout << "Parse OPXL specific settings" << endl;
String searched_charges = this->attributeAsString_(attributes, "charges");
search_params.charges = searched_charges;
IntList charge_ints = ListUtils::create<Int>(searched_charges);
std::sort(charge_ints.begin(), charge_ints.end());
Int min_charge = charge_ints[0];
Int max_charge = charge_ints.back();
search_params.setMetaValue("precursor:min_charge", min_charge);
search_params.setMetaValue("precursor:max_charge", max_charge);
StringList ms_run = ListUtils::create<String>(this->attributeAsString_(attributes, "run_path"));
}
(*this->prot_ids_)[0].setSearchParameters(search_params);
}
else if (tag == "spectrum_search")
{
// Examples of lines to be parsed with this code
// <spectrum_search spectrum="GUA1354-S15-A-LRRK2_DSG_A4.light.2616_GUA1354-S15-A-LRRK2_DSG_A4.heavy.2481" mz_precursor="590.556396484375" scantype="light_heavy" charge_precursor="4" Mr_precursor="2358.19648007042" rtsecscans="2231.988:2194.8258" mzscans="590.556396484375:592.065673828125" >
// <spectrum_search spectrum="GUA1354-S15-A-LRRK2_DSG_A4.light.1327_GUA1354-S15-A-LRRK2_DSG_A4.heavy.1327" mz_precursor="1008.83288574219" scantype="light" charge_precursor="3" Mr_precursor="3023.47682782626" rtsecscans="2796.68020000002:2796.68020000002" mzscans="1008.83288574219:1008.83288574219" >
// <spectrum_search Mr_precursor="1465.880913324" addedMass="0" apriori_pmatch_common="0.0311" apriori_pmatch_xlink="0.0658" charge_precursor="3" ionintensity_stdev="5.73" iontag_ncandidates="240" mean_ionintensity="2.28" mz_precursor="489.63479614" mzscans="489.63479614:493.6600647" ncommonions="71" nxlinkions="102" rtsecscans="2491:2477" scantype="light_heavy" spectrum="aleitner_M1012_006.c.02942.02942.3_aleitner_M1012_006.c.02913.02913.3">
//cout << "Parse Spectrum" << endl;
// Update retention time of light
StringList rt_split;
StringUtils::split(this->attributeAsString_(attributes, "rtsecscans"), ":", rt_split);
this->rt_light_ = rt_split[0].toDouble();
this->rt_heavy_ = rt_split[1].toDouble();
String mz_scans = this->attributeAsString_(attributes, "mzscans");
if (!mz_scans.empty())
{
StringList mz_split;
StringUtils::split(this->attributeAsString_(attributes, "mzscans"), ":", mz_split);
this->mz_light_ = mz_split[0].toDouble();
this->mz_heavy_ = mz_split[1].toDouble();
}
else
{
double mz_precursor = this->attributeAsString_(attributes, "mz_precursor").toDouble();
this->mz_light_ = mz_precursor;
this->mz_heavy_ = mz_precursor;
}
// Update min and max precursor charge
UInt charge_precursor = this->attributeAsInt_(attributes, "charge_precursor");
if (!this->is_openpepxl_)
{
//cout << "Parse xQuest Spectrum" << endl;
if (charge_precursor < this->min_precursor_charge_)
{
this->min_precursor_charge_ = charge_precursor;
}
if (charge_precursor > this->max_precursor_charge_)
{
this->max_precursor_charge_ = charge_precursor;
}
this->charges_.insert(charge_precursor);
// read input filename (will not contain file type this way), example:
// "C_Lee_141014_CRM_dialysis_NCE20_1.06904.06904.3_C_Lee_141014_CRM_dialysis_NCE20_1.06904.06904.3"
String spectrum = this->attributeAsString_(attributes, "spectrum");
// split into light and heavy (or light and light if unlabeled)
StringList split_spectra = XQuestResultXMLHandler::splitByMiddle(spectrum, '_');
vector<String> split_spectrum_light;
vector<String> split_spectrum_heavy;
// split away the spectrum indices from the file name
StringUtils::split(split_spectra[0], ".", split_spectrum_light);
StringUtils::split(split_spectra[1], ".", split_spectrum_heavy);
String file_name = split_spectrum_light[0];
if (std::find(this->ms_run_path_.begin(), this->ms_run_path_.end(), file_name) == this->ms_run_path_.end())
{
this->ms_run_path_.push_back(file_name);
}
this->spectrum_input_file_ = file_name;
// read spectrum indices
if (split_spectrum_light[split_spectrum_light.size()-1].size() > 1)
{
//cout << "Parse Spectrum index version 1" << endl;
//cout << endl << split_spectrum_light[split_spectrum_light.size()-1] << endl;
//cout << endl << split_spectrum_heavy[split_spectrum_heavy.size()-1] << endl;
this->spectrum_index_light_ = split_spectrum_light[split_spectrum_light.size()-1].toInt();
this->spectrum_index_heavy_ = split_spectrum_heavy[split_spectrum_heavy.size()-1].toInt();
}
else
{
//cout << "Parse Spectrum index version 2" << endl;
//cout << endl << split_spectrum_light[split_spectrum_light.size()-2] << endl;
//cout << endl << split_spectrum_heavy[split_spectrum_heavy.size()-2] << endl;
this->spectrum_index_light_ = split_spectrum_light[split_spectrum_light.size()-2].toInt();
this->spectrum_index_heavy_ = split_spectrum_heavy[split_spectrum_heavy.size()-2].toInt();
}
}
else
{
this->spectrum_index_light_ = this->attributeAsInt_(attributes, "scan_index_light");
this->spectrum_index_heavy_ = this->attributeAsInt_(attributes, "scan_index_heavy");
ProteinIdentification::SearchParameters search_params((*this->prot_ids_)[0].getSearchParameters());
if (!search_params.metaValueExists("input_mzML"))
{
String spectrum = this->attributeAsString_(attributes, "spectrum");
vector<String> split_spectrum;
StringUtils::split(spectrum, ".", split_spectrum);
String file_name = split_spectrum[0];
search_params.setMetaValue("input_mzML", file_name + String(".mzML"));
(*this->prot_ids_)[0].setSearchParameters(search_params);
}
}
}
else if (tag == "search_hit")
{
// Examples of lines to be parsed with this code
// <search_hit search_hit_rank="1" id="DNSTMGYMAAKK-RDVEKFLSK-a11-b5" type="xlink" structure="DNSTMGYMAAKK-RDVEKFLSK" seq1="DNSTM(Oxidation)GYM(Oxidation)AAKK" seq2="RDVEKFLSK" prot1="tr|Q8TBA7|Q8TBA7_HUMAN" prot2="sp|Q5S007-v1|LRRK2_HUMAN" topology="a11-b5" xlinkposition="11,5" Mr="2564.2250873787" mz="855.748972259671" charge="3" xlinkermass="96.0211294" measured_mass="2564.22762128328"
// error="0.000844634859959115" error_rel="0.987012415251626" xlinkions_matched="6" backboneions_matched="1" xcorrx="0.312314444528579" xcorrb="-0.0506118717404067" match_odds="0.794234705691207" prescore="0.0369274467229843" num_of_matched_ions_alpha="3" num_of_matched_ions_beta="4" num_of_matched_common_ions_alpha="1" num_of_matched_common_ions_beta="0" num_of_matched_xlink_ions_alpha="2" num_of_matched_xlink_ions_beta="4"
// TIC="0.0292408974147396" wTIC="0.026377408862402" intsum="0.397526955232024" HyperCommon="0.743940400979002" HyperXlink="34.1231158133129" HyperAlpha="16.0630790689233" HyperBeta="6.84199589723582" HyperBoth="31.1180197102582" selected="false" target_decoy="target" protein_references="unique" annotated_spec="" score="2.32103769126514" >
// <search_hit search_hit_rank="3" id="MGIKTSEGTPGFRAPEVAR-HKMSYSGR-a4-b2" type="xlink" structure="MGIKTSEGTPGFRAPEVAR-HKMSYSGR" seq1="M(Oxidation)GIKTSEGTPGFRAPEVAR" seq2="HKMSYSGR" prot1="sp|Q5S007-v1|LRRK2_HUMAN" prot2="sp|Q5S007-v1|LRRK2_HUMAN" topology="a4-b2" xlinkposition="4,2" Mr="3079.4967874314" mz="770.881473324621" charge="4" xlinkermass="96.0211294" measured_mass="3079.49506405479"
// error="-0.000430844152219834" error_rel="-0.558898049996855" xlinkions_matched="14" backboneions_matched="6" xcorrx="0.198434093695336" xcorrb="0.00514737154810852" match_odds="1.45901170826174" prescore="0.0599999986588955" num_of_matched_ions_alpha="15" num_of_matched_ions_beta="5" num_of_matched_common_ions_alpha="5" num_of_matched_common_ions_beta="1" num_of_matched_xlink_ions_alpha="10" num_of_matched_xlink_ions_beta="4"
// TIC="0.0562770907575218" wTIC="0.0370273112047904" intsum="0.818966233637184" HyperCommon="6.80908719125821" HyperXlink="33.1079286508253" HyperAlpha="15.5319805998036" HyperBeta="1.62767939400878" HyperBoth="23.997840801109" selected="false" target_decoy="target" protein_references="unique" annotated_spec="" score="2.69829871110556" >
// <search_hit Mr="2145.18339" TIC="0.08237" TIC_alpha="0.03287" TIC_beta="0.04951" annotated_spec="" apriori_match_probs="0.99970" apriori_match_probs_log="-0.00013" backboneions_matched="" charge="3" error="1.6" error_rel="-1.6" id="KSKTLQYFA-KQYSAKAK-a1-b1" intsum="91.91980" match_error_mean="-8.04546309837745" match_error_stdev="278.931294616457" match_odds="2.85579" match_odds_alphacommon="1.77210" match_odds_alphaxlink="1.98118"
// match_odds_betacommon="2.35354" match_odds_betaxlink="5.31633" measured_mass="2145.1800" mz="716.06781" num_of_matched_common_ions_alpha="1" num_of_matched_common_ions_beta="1" num_of_matched_ions_alpha="3" num_of_matched_ions_beta="5" num_of_matched_xlink_ions_alpha="2" num_of_matched_xlink_ions_beta="4" prescore="0.11625" prescore_alpha="0.08108" prescore_beta="0.16667"
// prot1="sp|O14126|PRS6A_SCHPO" prot2="decoy_reverse_sp|Q9UUB6|UBLH2_SCHPO" score="8.93" search_hit_rank="2" seq1="KSKTLQYFA" seq2="KQYSAKAK" series_score_mean="2.48843" structure="KSKTLQYFA-KQYSAKAK" topology="a1-b1" type="xlink" wTIC="0.01521" weighted_matchodds_mean="1.31713728336586" weighted_matchodds_sum="0.658568641682928" xcorrall="0.00000" xcorrb="0.05442" xcorrx="0.11647" xlinkermass="138.0680796" xlinkions_matched="" xlinkposition="1,1">
PeptideIdentification peptide_identification;
PeptideHit peptide_hit_alpha;
PeptideHit peptide_hit_beta;
vector<PeptideHit> peptide_hits;
String seq1 = String(this->attributeAsString_(attributes, "seq1"));
if (!this->is_openpepxl_)
{
seq1 = seq1.substitute("X", "M(Oxidation)");
}
// XL Type, determined by "type"
String xlink_type_string = this->attributeAsString_(attributes, "type");
AASequence alpha_seq = AASequence::fromString(seq1);
std::pair<SignedSize, SignedSize> positions;
this->getLinkPosition_(attributes, positions);
int xl_pos = positions.first - 1;
std::vector<String> mods;
// xQuest uses the non-standard character "\u2212" for the minus in negative numbers. This can happen for zero-length cross-linkers.
// Replace it with a proper "-" (minus), if there is one, to be able to convert it to a negative double.
String xlinkermass_string = this->attributeAsString_(attributes, "xlinkermass");
xlinkermass_string.substitute("\u2212", "-");
double xl_mass = DataValue(xlinkermass_string.toDouble());
ModificationsDB::getInstance()->searchModificationsByDiffMonoMass(mods, xl_mass, 0.01, alpha_seq[xl_pos].getOneLetterCode(), ResidueModification::ANYWHERE);
if (xlink_type_string == "monolink")
{
if (!mods.empty())
{
bool mod_set = false;
for (const String& mod : mods)
{
if (mod.hasSubstring(this->cross_linker_name_))
{
alpha_seq.setModification(xl_pos, mod);
mod_set = true;
// do not break to prioritize mods later in the list
// the XLMODS results are further down the list and should be prioritized instead of unimod
//break;
}
}
if (!mod_set)
{
cout << "Set default mono-link: " << mods[0] << endl;
alpha_seq.setModification(xl_pos, mods[0]);
}
}
}
else
{
peptide_hit_alpha.setMetaValue("xl_mod", this->cross_linker_name_);
}
peptide_hit_alpha.setSequence(alpha_seq);
UInt charge = this->attributeAsInt_(attributes, "charge");
peptide_hit_alpha.setCharge(charge);
peptide_hit_alpha.setMetaValue(Constants::UserParam::SPECTRUM_REFERENCE, spectrum_index_light_);
peptide_hit_alpha.setMetaValue("spectrum_index", spectrum_index_light_);
peptide_hit_alpha.setMetaValue("spectrum_input_file", spectrum_input_file_);
String specIDs;
if (spectrum_index_light_ != spectrum_index_heavy_)
{
specIDs = String(spectrum_index_light_) + "," + String(spectrum_index_heavy_);
peptide_hit_alpha.setMetaValue(Constants::UserParam::OPENPEPXL_HEAVY_SPEC_RT, this->rt_heavy_);
peptide_hit_alpha.setMetaValue(Constants::UserParam::OPENPEPXL_HEAVY_SPEC_MZ, this->mz_heavy_);
peptide_hit_alpha.setMetaValue(Constants::UserParam::OPENPEPXL_HEAVY_SPEC_REF, spectrum_index_heavy_);
peptide_hit_alpha.setMetaValue("spectrum_index_heavy", spectrum_index_heavy_);
}
else
{
specIDs = String(spectrum_index_light_);
}
peptide_identification.setMetaValue(Constants::UserParam::SPECTRUM_REFERENCE, specIDs);
// Set xl_chain meta value for alpha
peptide_hit_alpha.setMetaValue("xl_chain", "MS:1002509");
// Set Attributes of Peptide Identification
peptide_identification.setMZ(this->mz_light_);
peptide_identification.setRT(this->rt_light_);
peptide_identification.setScoreType("OpenPepXL:score"); // Needed, since hard-coded in MzIdentMLHandler
String prot1_string = this->attributeAsString_(attributes, "prot1");
// Decide if decoy for alpha
DataValue target_decoy = DataValue(prot1_string.hasSubstring(this->decoy_string_) ? "decoy" : "target");
peptide_hit_alpha.setMetaValue("target_decoy", target_decoy);
// Attributes of peptide_hit_alpha
double score = this->attributeAsDouble_(attributes, "score");
DataValue xlinkermass = DataValue(xl_mass);
// Set minscore and maxscore encountered
if (score < this->min_score_)
{
this->min_score_ = score;
}
if (score > this->max_score_)
{
this->max_score_ = score;
}
peptide_hit_alpha.setScore(score);
peptide_hit_alpha.setMetaValue(Constants::UserParam::PRECURSOR_ERROR_PPM_USERPARAM, DataValue(this->attributeAsDouble_(attributes, "error_rel")));
// Get common attributes of Peptide Identification
this->peptide_id_meta_values_["OpenPepXL:id"] = DataValue(this->attributeAsString_(attributes, "id"));
this->peptide_id_meta_values_["OpenPepXL:xlinkermass"] = xlinkermass;
this->peptide_id_meta_values_[Constants::UserParam::OPENPEPXL_XL_RANK] = DataValue(this->attributeAsInt_(attributes, "search_hit_rank"));
this->peptide_id_meta_values_["OpenPepXL:score"] = DataValue(score);
this->peptide_id_meta_values_["OpenPepXL:structure"] = DataValue(this->attributeAsString_(attributes, "structure"));
// get scores (which might be optional)
String wTIC, TIC, intsum, match_odds, fdr;
if (this->optionalAttributeAsString_(wTIC, attributes, "wTIC") && !wTIC.empty())
{
this->peptide_id_meta_values_["OpenPepXL:wTIC"] = DataValue(wTIC.toDouble());
}
if (this->optionalAttributeAsString_(TIC, attributes, "TIC") && !TIC.empty())
{
this->peptide_id_meta_values_["OpenPepXL:percTIC"] = DataValue(TIC.toDouble());
}
if (this->optionalAttributeAsString_(intsum, attributes, "intsum") && !intsum.empty())
{
this->peptide_id_meta_values_["OpenPepXL:intsum"] = DataValue(intsum.toDouble());
}
if (this->optionalAttributeAsString_(match_odds, attributes, "match_odds") && !match_odds.empty())
{
this->peptide_id_meta_values_["OpenPepXL:match-odds"] = DataValue(match_odds.toDouble());
}
if (this->optionalAttributeAsString_(fdr, attributes, "fdr") && !fdr.empty())
{
this->peptide_id_meta_values_["XFDR:FDR"] = DataValue(fdr.toDouble());
}
String xprophet_f;
if (this->optionalAttributeAsString_(xprophet_f, attributes, "xprophet_f") && !xprophet_f.empty())
{
peptide_hit_alpha.setMetaValue("XFDR:used_for_FDR", xprophet_f.toInt());
}
String fdr_type;
if (this->optionalAttributeAsString_(xprophet_f, attributes, "fdr_type") && !fdr_type.empty())
{
peptide_hit_alpha.setMetaValue("XFDR:fdr_type", fdr_type);
}
assert(this->peptide_id_meta_values_["OpenPepXL:id"] != DataValue::EMPTY);
assert(this->peptide_id_meta_values_["OpenPepXL:xlinkermass"] != DataValue::EMPTY);
assert(this->peptide_id_meta_values_[Constants::UserParam::OPENPEPXL_XL_RANK] != DataValue::EMPTY);
assert(this->peptide_id_meta_values_["OpenPepXL:score"] != DataValue::EMPTY);
assert(this->peptide_id_meta_values_["OpenPepXL:structure"] != DataValue::EMPTY);
this->addMetaValues_(peptide_hit_alpha);
// Store specific stuff for peptide hit alpha
peptide_hit_alpha.setMetaValue("matched_linear_alpha",
DataValue(this->attributeAsInt_(attributes, "num_of_matched_common_ions_alpha")));
peptide_hit_alpha.setMetaValue("matched_xlink_alpha",
DataValue(this->attributeAsInt_(attributes, "num_of_matched_xlink_ions_alpha")));
peptide_hit_alpha.setMetaValue("matched_linear_beta",
DataValue(this->attributeAsInt_(attributes, "num_of_matched_common_ions_beta")));
peptide_hit_alpha.setMetaValue("matched_xlink_beta",
DataValue(this->attributeAsInt_(attributes, "num_of_matched_xlink_ions_beta")));
peptide_hit_alpha.setMetaValue("prot1", DataValue(prot1_string));
peptide_hit_alpha.setMetaValue("prot2", DataValue("-"));
peptide_hit_alpha.setMetaValue(Constants::UserParam::OPENPEPXL_BETA_ACCESSIONS, DataValue("-"));
peptide_hit_alpha.setMetaValue(Constants::UserParam::OPENPEPXL_XL_MASS, xlinkermass);
// Set peptide Evidences for Alpha (need one for each accession in the prot1_string)
this->setPeptideEvidence_(prot1_string, peptide_hit_alpha);
// Switch on Cross-link type
if (xlink_type_string == "xlink")
{
// Set the cross Link Mass
ProteinIdentification::SearchParameters search_params((*this->prot_ids_)[0].getSearchParameters());
if (!search_params.metaValueExists("cross_link:mass"))
{
search_params.setMetaValue("cross_link:mass", DataValue(xlinkermass));
}
(*this->prot_ids_)[0].setSearchParameters(search_params);
peptide_hit_beta.setScore(score);
peptide_hit_beta.setMetaValue(Constants::UserParam::PRECURSOR_ERROR_PPM_USERPARAM, DataValue(this->attributeAsDouble_(attributes, "error_rel")));
String seq2 = String(this->attributeAsString_(attributes, "seq2"));
if (!this->is_openpepxl_)
{
seq2 = seq2.substitute("X", "M(Oxidation)");
}
peptide_hit_beta.setSequence(AASequence::fromString(seq2));
peptide_hit_alpha.setMetaValue(Constants::UserParam::OPENPEPXL_BETA_SEQUENCE, seq2);
peptide_hit_beta.setMetaValue(Constants::UserParam::OPENPEPXL_BETA_SEQUENCE, seq2);
peptide_hit_beta.setCharge(charge);
peptide_hit_beta.setMetaValue(Constants::UserParam::SPECTRUM_REFERENCE, spectrum_index_light_);
if (spectrum_index_light_ != spectrum_index_heavy_)
{
peptide_hit_beta.setMetaValue(Constants::UserParam::OPENPEPXL_HEAVY_SPEC_RT, this->rt_heavy_);
peptide_hit_beta.setMetaValue(Constants::UserParam::OPENPEPXL_HEAVY_SPEC_MZ, this->mz_heavy_);
peptide_hit_beta.setMetaValue(Constants::UserParam::OPENPEPXL_HEAVY_SPEC_REF, spectrum_index_heavy_);
peptide_hit_beta.setMetaValue("spectrum_index_heavy", spectrum_index_heavy_);
}
this->addMetaValues_(peptide_hit_beta);
peptide_hit_alpha.setMetaValue(Constants::UserParam::OPENPEPXL_XL_TYPE, DataValue("cross-link"));
peptide_hit_beta.setMetaValue(Constants::UserParam::OPENPEPXL_XL_TYPE, DataValue("cross-link"));
// Set xl positions, depends on xl_type
this->getLinkPosition_(attributes, positions);
peptide_hit_alpha.setMetaValue(Constants::UserParam::OPENPEPXL_XL_POS1, DataValue(positions.first - 1));
peptide_hit_alpha.setMetaValue(Constants::UserParam::OPENPEPXL_XL_POS2, DataValue(positions.second - 1));
peptide_hit_beta.setMetaValue(Constants::UserParam::OPENPEPXL_XL_POS1, DataValue(positions.first - 1));
peptide_hit_beta.setMetaValue(Constants::UserParam::OPENPEPXL_XL_POS2, DataValue(positions.second - 1));
String term_spec_alpha("ANYWHERE"), term_spec_beta("ANYWHERE");
StringList aarequired1 = search_params.getMetaValue("cross_link:residue1");
StringList aarequired2 = search_params.getMetaValue("cross_link:residue2");
// StringListUtils::searchSuffix(aarequired1, seq1[positions.first-1])
if (positions.first == 1 && StringListUtils::searchSuffix(aarequired1, seq1[0]) == aarequired1.end())
{
term_spec_alpha = "N_TERM";
}
if (positions.second == 1 && StringListUtils::searchSuffix(aarequired2, seq2[0]) == aarequired2.end())
{
term_spec_beta = "N_TERM";
}
if (positions.first == SignedSize(seq1.size()) && StringListUtils::searchSuffix(aarequired1, seq1[positions.first-1]) == aarequired1.end())
{
term_spec_alpha = "C_TERM";
}
if (positions.second == SignedSize(seq2.size()) && StringListUtils::searchSuffix(aarequired2, seq2[positions.second-1]) == aarequired2.end())
{
term_spec_beta = "C_TERM";
}
peptide_hit_alpha.setMetaValue(Constants::UserParam::OPENPEPXL_XL_TERM_SPEC_ALPHA, term_spec_alpha);
peptide_hit_alpha.setMetaValue(Constants::UserParam::OPENPEPXL_XL_TERM_SPEC_BETA, term_spec_beta);
// Protein
String prot2_string = this->attributeAsString_(attributes, "prot2");
// Decide if decoy for beta
target_decoy = DataValue(prot2_string.hasSubstring(this->decoy_string_) ? "decoy" : "target");
peptide_hit_beta.setMetaValue(Constants::UserParam::TARGET_DECOY, target_decoy);
// Set xl_chain meta value for beta
peptide_hit_beta.setMetaValue("xl_chain", "MS:1002510");
// Set peptide_hit specific stuff
peptide_hit_beta.setMetaValue("matched_linear_alpha",
DataValue(this->attributeAsInt_(attributes, "num_of_matched_common_ions_alpha")));
peptide_hit_beta.setMetaValue("matched_xlink_alpha",
DataValue(this->attributeAsInt_(attributes, "num_of_matched_xlink_ions_alpha")));
peptide_hit_beta.setMetaValue("matched_linear_beta",
DataValue(this->attributeAsInt_(attributes, "num_of_matched_common_ions_beta")));
peptide_hit_beta.setMetaValue("matched_xlink_beta",
DataValue(this->attributeAsInt_(attributes, "num_of_matched_xlink_ions_beta")));
peptide_hit_alpha.setMetaValue("prot2", DataValue(prot2_string));
peptide_hit_alpha.setMetaValue(Constants::UserParam::OPENPEPXL_BETA_ACCESSIONS, DataValue(prot2_string));
peptide_hit_beta.setMetaValue("prot1", DataValue(prot1_string));
peptide_hit_beta.setMetaValue(Constants::UserParam::OPENPEPXL_BETA_ACCESSIONS, DataValue(prot2_string));
peptide_hit_beta.setMetaValue(Constants::UserParam::OPENPEPXL_XL_MASS, xlinkermass);
peptide_hit_beta.setMetaValue(Constants::UserParam::OPENPEPXL_XL_MOD, this->cross_linker_name_);
// Set Peptide Evidences for Beta
this->setPeptideEvidence_(prot2_string, peptide_hit_beta);
// TODO Determine if protein is intra/inter protein, check all protein ID combinations
// StringList prot1_list;
// prot1_string.split(",", prot1_list);
// StringList prot2_list;
// prot2_string.split( ",", prot2_list);
}
else if (xlink_type_string == "intralink")
{
// xl type
peptide_hit_alpha.setMetaValue(Constants::UserParam::OPENPEPXL_XL_TYPE, DataValue("loop-link"));
// Set xl positions, depends on xl_type
this->getLinkPosition_(attributes, positions);
peptide_hit_alpha.setMetaValue(Constants::UserParam::OPENPEPXL_XL_POS1, DataValue(positions.first - 1));
peptide_hit_alpha.setMetaValue(Constants::UserParam::OPENPEPXL_XL_POS2, DataValue(positions.second - 1));
peptide_hit_alpha.setMetaValue(Constants::UserParam::OPENPEPXL_XL_MASS, xlinkermass);
peptide_hit_alpha.setMetaValue(Constants::UserParam::OPENPEPXL_XL_MOD, this->cross_linker_name_);
peptide_hit_alpha.setMetaValue(Constants::UserParam::OPENPEPXL_BETA_SEQUENCE, "-");
}
else if (xlink_type_string == "monolink")
{
// TODO Set the xl_mass and xl_mod MetaValues instead
// this->monolinks_masses_.insert(this->attributeAsDouble_(attributes, "xlinkermass"));
// xl_type
peptide_hit_alpha.setMetaValue(Constants::UserParam::OPENPEPXL_XL_TYPE, DataValue("mono-link"));
std::pair< SignedSize, SignedSize > xlink_pos;
this->getLinkPosition_(attributes, xlink_pos);
peptide_hit_alpha.setMetaValue(Constants::UserParam::OPENPEPXL_XL_POS1, DataValue(xlink_pos.first - 1));
peptide_hit_alpha.setMetaValue(Constants::UserParam::OPENPEPXL_XL_POS2, DataValue("-"));
peptide_hit_alpha.setMetaValue(Constants::UserParam::OPENPEPXL_BETA_SEQUENCE, "-");
}
else
{
OPENMS_LOG_ERROR << "ERROR: Unsupported Cross-Link type: " << xlink_type_string << endl;
throw std::exception();
}
// Finalize this record
peptide_hits.push_back(peptide_hit_alpha);
if (peptide_hit_beta.metaValueExists(Constants::UserParam::OPENPEPXL_XL_POS1))
{
peptide_hits.push_back(peptide_hit_beta);
}
peptide_identification.setHits(peptide_hits);
this->peptide_id_meta_values_.clear();
this->pep_ids_->push_back(peptide_identification);
this->n_hits_++;
}
}
StringList XQuestResultXMLHandler::splitByNth(const String& input, const char separator, const Size n)
{
StringList list;
Size current_index = 0;
Size count = 0;
while (current_index < input.size() && count < n)
{
current_index++;
if (input.at(current_index) == separator)
{
count++;
}
}
list.push_back(input.prefix(current_index));
list.push_back(input.suffix(input.size()-current_index-1));
return list;
}
StringList XQuestResultXMLHandler::splitByMiddle(const String& input, const char separator)
{
// count separators
Size n = std::count(input.begin(), input.end(), separator);
if ( (n != 0) && (n % 2 == 1) )
{
n = (n / 2) + 1;
return splitByNth(input, separator, n);
}
else
{
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "The separator has to occur in the input string an uneven number of times (and at least once).");
}
}
void XQuestResultXMLHandler::writeTo(std::ostream& os)
{
ProteinIdentification::SearchParameters search_params;
search_params = (*this->cpro_id_)[0].getSearchParameters();
String input_filename;
if (search_params.metaValueExists("input_mzML"))
{
input_filename = search_params.getMetaValue("input_mzML");
}
String spec_xml_name = search_params.getMetaValue("out_xquest_specxml");
os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
os << "<?xml-stylesheet type=\"text/xsl\" href=\"\"?>\n";
DateTime time= DateTime::now();
String timestring = time.getDate() + " " + time.getTime();
String mono_masses = search_params.getMetaValue("cross_link:mass_monolink");
mono_masses = mono_masses.substr(1).chop(1);
String precursor_mass_tolerance_unit = search_params.precursor_mass_tolerance_ppm ? "ppm" : "Da";
double precursor_mass_tolerance = search_params.precursor_mass_tolerance;
String fragment_mass_tolerance_unit = search_params.fragment_mass_tolerance_ppm ? "ppm" : "Da";
double fragment_mass_tolerance = search_params.fragment_mass_tolerance;
double fragment_mass_tolerance_xlinks = search_params.getMetaValue("fragment:mass_tolerance_xlinks");
String cross_link_name = search_params.getMetaValue("cross_link:name");
double cross_link_mass_light = search_params.getMetaValue("cross_link:mass");
double cross_link_mass_iso_shift = 0;
if (search_params.metaValueExists("cross_link:mass_isoshift"))
{
cross_link_mass_iso_shift = search_params.getMetaValue("cross_link:mass_isoshift");
}
String aarequired1, aarequired2;
aarequired1 = search_params.getMetaValue("cross_link:residue1");
aarequired1 = aarequired1.substr(1).chop(1);
aarequired2 = search_params.getMetaValue("cross_link:residue2");
aarequired2 = aarequired2.substr(1).chop(1);
bool ntermxlinkable = aarequired1.hasSubstring("N-term") || aarequired2.hasSubstring("N-term");
String in_fasta = search_params.db;
String in_decoy_fasta = search_params.getMetaValue("input_decoys");
String enzyme_name = search_params.digestion_enzyme.getName();
int missed_cleavages = search_params.missed_cleavages;
StringList variable_mod_list = search_params.variable_modifications;
String variable_mods;
for (Size i = 0; i < variable_mod_list.size(); ++i)
{
variable_mods += variable_mod_list[i] + ",";
}
variable_mods = variable_mods.chop(1);
StringList fixed_mod_list = search_params.fixed_modifications;
String fixed_mods;
for (Size i = 0; i < fixed_mod_list.size(); ++i)
{
fixed_mods += fixed_mod_list[i] + ",";
}
fixed_mods = fixed_mods.chop(1);
String decoy_prefix = search_params.getMetaValue("decoy_prefix").toString();
String decoy_string = search_params.getMetaValue("decoy_string").toString();
String searched_charges = search_params.charges;
StringList ms_runs;
(*this->cpro_id_)[0].getPrimaryMSRunPath(ms_runs);
String ms_runs_string = ListUtils::concatenate(ms_runs, ",");
os << R"(<xquest_results xquest_version="OpenPepXL 1.0" date=")" << timestring <<
R"(" author="Eugen Netz" tolerancemeasure_ms1=")" << precursor_mass_tolerance_unit <<
"\" tolerancemeasure_ms2=\"" << fragment_mass_tolerance_unit << "\" ms1tolerance=\"" << precursor_mass_tolerance <<
"\" ms2tolerance=\"" << fragment_mass_tolerance << "\" xlink_ms2tolerance=\"" << fragment_mass_tolerance_xlinks <<
"\" crosslinkername=\"" << cross_link_name << "\" xlinkermw=\"" << cross_link_mass_light <<
"\" monolinkmw=\"" << mono_masses << "\" database=\"" << in_fasta << "\" database_dc=\"" << in_decoy_fasta <<
R"(" xlinktypes="1111" AArequired1=")" << aarequired1 << "\" AArequired2=\"" << aarequired2 << "\" cp_isotopediff=\"" << cross_link_mass_iso_shift <<
"\" enzyme_name=\"" << enzyme_name << "\" outputpath=\"" << spec_xml_name <<
"\" missed_cleavages=\"" << missed_cleavages <<
"\" ntermxlinkable=\"" << ntermxlinkable << "\" CID_match2ndisotope=\"1" <<
"\" variable_mod=\"" << variable_mods << "\" fixed_mod=\"" << fixed_mods <<
"\" decoy_prefix=\"" << decoy_prefix << "\" decoy_string=\"" << decoy_string <<
"\" charges=\"" << searched_charges << "\" run_path=\"" << ms_runs_string <<
R"(" nocutatxlink="1">)" << std::endl;
String current_spectrum_light("");
String current_spectrum_heavy("");
for (const auto& current_pep_id : *cpep_id_)
{
std::vector< PeptideHit > pep_hits = current_pep_id.getHits();
if (pep_hits.empty())
{
continue;
}
for (PeptideHit ph : pep_hits)
{
// TODO write the spectrum_search entry for this ph
double precursor_mz = current_pep_id.getMZ();
int precursor_charge = ph.getCharge();
double precursor_mass = precursor_mz * static_cast<double>(precursor_charge) - static_cast<double>(precursor_charge) * Constants::PROTON_MASS_U;
bool new_spectrum(false);
new_spectrum = (ph.getMetaValue(Constants::UserParam::SPECTRUM_REFERENCE) != current_spectrum_light) ||
(ph.metaValueExists(Constants::UserParam::OPENPEPXL_HEAVY_SPEC_REF) && ph.getMetaValue(Constants::UserParam::OPENPEPXL_HEAVY_SPEC_REF) != current_spectrum_heavy);
if (new_spectrum)
{
if (!current_spectrum_light.empty())
{
os << "</spectrum_search>" << std::endl;
}
current_spectrum_light = ph.getMetaValue(Constants::UserParam::SPECTRUM_REFERENCE);
current_spectrum_heavy = "";
if (ph.metaValueExists(Constants::UserParam::OPENPEPXL_HEAVY_SPEC_REF))
{
current_spectrum_heavy = ph.getMetaValue(Constants::UserParam::OPENPEPXL_HEAVY_SPEC_REF);
}
vector<String> input_split_dir;
vector<String> input_split;
String base_name;
if (!input_filename.empty())
{
input_filename.split(String("/"), input_split_dir);
input_split_dir[input_split_dir.size()-1].split(String("."), input_split);
base_name = input_split[0];
}
else if (ph.metaValueExists("spectrum_input_file"))
{
base_name = ph.getMetaValue("spectrum_input_file");
}
Size scan_index_light = ph.getMetaValue("spectrum_index");
Size scan_index_heavy = scan_index_light;
if (ph.metaValueExists("spectrum_index_heavy"))
{
scan_index_heavy = ph.getMetaValue("spectrum_index_heavy");
}
String spectrum_light_name = base_name + ".light." + scan_index_light;
String spectrum_heavy_name = base_name + ".heavy." + scan_index_heavy;
String spectrum_name = spectrum_light_name + String("_") + spectrum_heavy_name;
String rt_scans = String(current_pep_id.getRT()) + ":";
String mz_scans = String(precursor_mz) + ":";
String scantype = "light_heavy";
if (scan_index_light == scan_index_heavy)
{
scantype = "light";
rt_scans += String(current_pep_id.getRT());
mz_scans += String(precursor_mz);
}
else
{
rt_scans += ph.getMetaValue(Constants::UserParam::OPENPEPXL_HEAVY_SPEC_RT).toString();
mz_scans += ph.getMetaValue(Constants::UserParam::OPENPEPXL_HEAVY_SPEC_MZ).toString();
}
os << "<spectrum_search spectrum=\"" << spectrum_name << "\" mz_precursor=\"" << precursor_mz << "\" scantype=\"" << scantype << "\" charge_precursor=\"" << precursor_charge
<< "\" Mr_precursor=\"" << precursor_mass << "\" rtsecscans=\"" << rt_scans << "\" mzscans=\"" << mz_scans
<< "\" scan_index_light=\"" << scan_index_light << "\" scan_index_heavy=\"" << scan_index_heavy
<< "\" >" << std::endl;
// TODO values missing, most of them probably unimportant:
// mean_ionintensity = mean ion intensity of each MS2 spectrum
// ionintensity_stdev = ion intensity spectrum_index_heavy
// addedMass = ???
// iontag_ncandidates = number of candidates extracted per ion tag
// apriori_pmatch_common, apriori_pmatch_xlink = a priori probs from match-odds probability
// ncommonions = number of common ions
// nxlinkions = number of xlinked ions
}
// one of "cross-link", "mono-link" or "loop-link"
String xltype_OPXL = ph.getMetaValue(Constants::UserParam::OPENPEPXL_XL_TYPE);
String xltype = "monolink";
String structure = ph.getSequence().toUnmodifiedString();
String letter_first = structure.substr( Int(ph.getMetaValue(Constants::UserParam::OPENPEPXL_XL_POS1)), 1);
double weight = ph.getSequence().getMonoWeight();
int alpha_pos = Int(ph.getMetaValue(Constants::UserParam::OPENPEPXL_XL_POS1)) + 1;
int beta_pos = 0;
String topology = String("a") + alpha_pos;
String id("");
String seq_beta("");
if (xltype_OPXL == "cross-link")
{
xltype = "xlink";
beta_pos = Int(ph.getMetaValue(Constants::UserParam::OPENPEPXL_XL_POS2)) + 1;
AASequence beta_aaseq = AASequence::fromString(ph.getMetaValue(Constants::UserParam::OPENPEPXL_BETA_SEQUENCE));
structure += "-" + beta_aaseq.toUnmodifiedString();
topology += String("-b") + beta_pos;
weight += beta_aaseq.getMonoWeight() + double(ph.getMetaValue(Constants::UserParam::OPENPEPXL_XL_MASS));
id = structure + "-" + topology;
seq_beta = ph.getMetaValue(Constants::UserParam::OPENPEPXL_BETA_SEQUENCE);
}
else if (xltype_OPXL == "loop-link")
{
xltype = "intralink";
beta_pos = Int(ph.getMetaValue(Constants::UserParam::OPENPEPXL_XL_POS2)) + 1;
topology += String("-b") + beta_pos;
String letter_second = structure.substr(beta_pos-1, 1);
id = structure + String("-") + letter_first + alpha_pos + String("-") + letter_second + beta_pos;
weight += cross_link_mass_light;
}
else // mono-link
{
if (ph.getMetaValue(Constants::UserParam::OPENPEPXL_XL_MOD).toString().hasPrefix("unknown"))
{
weight += double(ph.getMetaValue(Constants::UserParam::OPENPEPXL_XL_MASS));
}
id = structure + String("-") + letter_first + alpha_pos + String("-") + Int(double(ph.getMetaValue(Constants::UserParam::OPENPEPXL_XL_MASS)));
}
// Precursor error calculation, rel_error is read from the metaValue for consistency, but an absolute error is also used in the xQuest format
// use the formula, if the MetaValue is unavailable
double theo_mz = (weight + (static_cast<double>(precursor_charge) * Constants::PROTON_MASS_U)) / static_cast<double>(precursor_charge);
double error = precursor_mz - theo_mz;
double rel_error = 0;
if (ph.metaValueExists(Constants::UserParam::PRECURSOR_ERROR_PPM_USERPARAM))
{
rel_error = double(ph.getMetaValue(Constants::UserParam::PRECURSOR_ERROR_PPM_USERPARAM));
}
else
{
rel_error = (error / theo_mz) / 1e-6;
}
// Protein accessions
String prot_alpha = ph.getPeptideEvidences()[0].getProteinAccession();
if (ph.getPeptideEvidences().size() > 1)
{
for (Size i = 1; i < ph.getPeptideEvidences().size(); ++i)
{
prot_alpha = prot_alpha + "," + ph.getPeptideEvidences()[i].getProteinAccession();
}
}
String prot_beta = "";
if (ph.metaValueExists(Constants::UserParam::OPENPEPXL_BETA_ACCESSIONS) && ph.getMetaValue(Constants::UserParam::OPENPEPXL_BETA_ACCESSIONS) != "-")
{
prot_beta = ph.getMetaValue(Constants::UserParam::OPENPEPXL_BETA_ACCESSIONS);
}
String xlinkposition = String(alpha_pos);
if (beta_pos > 0)
{
xlinkposition += "," + String(beta_pos);
}
os << "<search_hit search_hit_rank=\"" << ph.getMetaValue(Constants::UserParam::OPENPEPXL_XL_RANK).toString() << "\" id=\"" << id << "\" type=\"" << xltype << "\" structure=\"" << structure << "\" seq1=\"" << ph.getSequence().toString() << "\" seq2=\"" << seq_beta
<< "\" prot1=\"" << prot_alpha << "\" prot2=\"" << prot_beta << "\" topology=\"" << topology << "\" xlinkposition=\"" << xlinkposition
<< "\" Mr=\"" << weight << "\" mz=\"" << theo_mz << "\" charge=\"" << precursor_charge << "\" xlinkermass=\"" << ph.getMetaValue(Constants::UserParam::OPENPEPXL_XL_MASS).toString()
<< "\" measured_mass=\"" << precursor_mass << "\" error=\"" << error << "\" error_rel=\"" << rel_error
<< "\" xlinkions_matched=\"" << (Int(ph.getMetaValue("matched_xlink_alpha")) + Int(ph.getMetaValue("matched_xlink_beta"))) << "\" backboneions_matched=\"" << (Int(ph.getMetaValue("matched_linear_alpha")) + Int(ph.getMetaValue("matched_linear_beta")))
<< "\" xcorrx=\"" << ph.getMetaValue("OpenPepXL:xcorr xlink").toString() << "\" xcorrb=\"" << ph.getMetaValue("OpenPepXL:xcorr common").toString() << "\" match_odds=\"" << ph.getMetaValue("OpenPepXL:match-odds").toString() << "\" prescore=\"" << ph.getMetaValue("OpenPepXL:prescore").toString()
<< "\" num_of_matched_ions_alpha=\"" << (Int(ph.getMetaValue("matched_linear_alpha")) + Int(ph.getMetaValue("matched_xlink_alpha")))
<< "\" num_of_matched_ions_beta=\"" << (Int(ph.getMetaValue("matched_xlink_beta")) + Int(ph.getMetaValue("matched_linear_beta")))
<< "\" num_of_matched_common_ions_alpha=\"" << ph.getMetaValue("matched_linear_alpha").toString() << "\" num_of_matched_common_ions_beta=\"" << ph.getMetaValue("matched_linear_beta").toString()
<< "\" num_of_matched_xlink_ions_alpha=\"" << ph.getMetaValue("matched_xlink_alpha").toString() << "\" num_of_matched_xlink_ions_beta=\"" << ph.getMetaValue("matched_xlink_beta").toString()
<< "\" TIC=\"" << ph.getMetaValue("OpenPepXL:TIC").toString() << "\" wTIC=\"" << ph.getMetaValue("OpenPepXL:wTIC").toString() << "\" intsum=\"" << ph.getMetaValue("OpenPepXL:intsum").toString();
if (ph.metaValueExists("XFDR:used_for_FDR"))
{
os << "\" xprophet_f=\"" << ph.getMetaValue("XFDR:used_for_FDR");
}
if (ph.metaValueExists("XFDR:fdr_type"))
{
os << "\" fdr_type=\"" << ph.getMetaValue("XFDR:fdr_type");
}
if (ph.metaValueExists(Constants::UserParam::XFDR_FDR))
{
os << "\" fdr=\"" << ph.getMetaValue(Constants::UserParam::XFDR_FDR);
}
// remove MetaValues, that were already used and written out with a different key.
ph.removeMetaValue(Constants::UserParam::OPENPEPXL_XL_MASS);
ph.removeMetaValue(Constants::UserParam::OPENPEPXL_XL_RANK);
ph.removeMetaValue(Constants::UserParam::OPENPEPXL_XL_POS1);
ph.removeMetaValue(Constants::UserParam::OPENPEPXL_XL_TYPE);
if (ph.metaValueExists(Constants::UserParam::OPENPEPXL_XL_POS2))
{
ph.removeMetaValue(Constants::UserParam::OPENPEPXL_XL_POS2);
}
ph.removeMetaValue("matched_xlink_alpha");
ph.removeMetaValue("matched_linear_alpha");
ph.removeMetaValue("matched_xlink_beta");
ph.removeMetaValue("matched_linear_beta");
ph.removeMetaValue("OpenPepXL:xcorr xlink");
ph.removeMetaValue("OpenPepXL:xcorr common");
ph.removeMetaValue("OpenPepXL:match-odds");
ph.removeMetaValue("OpenPepXL:prescore");
ph.removeMetaValue("OpenPepXL:TIC");
ph.removeMetaValue("OpenPepXL:wTIC");
ph.removeMetaValue("OpenPepXL:intsum");
ph.removeMetaValue("spectrum_reference");
ph.removeMetaValue(Constants::UserParam::OPENPEPXL_HEAVY_SPEC_REF);
ph.removeMetaValue("spectrum_index");
ph.removeMetaValue("spectrum_index_heavy");
ph.removeMetaValue(Constants::UserParam::OPENPEPXL_HEAVY_SPEC_RT);
ph.removeMetaValue(Constants::UserParam::OPENPEPXL_HEAVY_SPEC_MZ);
ph.removeMetaValue(Constants::UserParam::PRECURSOR_ERROR_PPM_USERPARAM);
ph.removeMetaValue(Constants::UserParam::XFDR_FDR);
// also remove MetaValues, that we do not need in xquestXML
ph.removeMetaValue(Constants::UserParam::OPENPEPXL_XL_MOD);
// ph.removeMetaValue("xl_chain");
// these metaValues can be present, e.g. if the data came from loading a xquest.xml file
// since they are already generated by other methods, they should not be duplicated in the output
ph.removeMetaValue("prot1");
ph.removeMetaValue("prot2");
ph.removeMetaValue("OpenPepXL:id");
ph.removeMetaValue("OpenPepXL:percTIC");
ph.removeMetaValue("OpenPepXL:score");
ph.removeMetaValue("OpenPepXL:structure");
ph.removeMetaValue("OpenPepXL:xlinkermass");
// automate writing out any additional MetaValues
std::vector<String> keys;
ph.getKeys(keys);
for (const String& key : keys)
{
os << "\" " << key << "=\"" << ph.getMetaValue(key).toString();
}
// score, end of the line and closing tag for this hit
os << "\" annotated_spec=\"" << "" << "\" score=\"" << ph.getScore() << "\" >\n</search_hit>" << std::endl;
// TODO values missing, most of them probably unimportant:
// weighted_matchodds_mean = a weighted version of match-odds?
// weighted_matchodds_sum
// match_error_mean = is this per peak error?
// match_error_stdev = is this per peak error?
// prescore_alpha, prescore_beta
// match_odds_alphacommon, match_odds_betacommon, match_odds_alphaxlink, match_odds_betaxlink
// xcorrall = xcorr for the whole combined theo spectrum?
// TIC_alpha, TIC_beta
// apriori_match_probs
// apriori_match_probs_log
}
}
os << "</spectrum_search>" << std::endl;
os << "</xquest_results>" << std::endl;
}
} // namespace OpenMS // namespace Internal
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/HANDLERS/MzMLSqliteHandler.cpp | .cpp | 54,535 | 1,427 | // 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/HANDLERS/MzMLSqliteHandler.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/FORMAT/Base64.h>
#include <OpenMS/FORMAT/MSNumpressCoder.h>
#include <OpenMS/FORMAT/MzMLFile.h> // for writing to stringstream
#include <OpenMS/FORMAT/SqliteConnector.h>
#include <OpenMS/FORMAT/ZlibCompression.h>
#include <QtCore/QFileInfo>
// #include <type_traits> // for template arg detection
#include <boost/type_traits.hpp>
#include <sqlite3.h>
#ifdef _OPENMP
#include <omp.h>
#endif
#include <cmath>
namespace OpenMS::Internal
{
namespace Sql = Internal::SqliteHelper;
/*
* @brief Helper function to concatenate integers with ","
*
* @param[in] The integers to concatenate
*
*/
String integerConcatenateHelper(const std::vector<int> & indices)
{
String tmp;
// each element has a size of the "," character plus n digits in base10
tmp.reserve( int(log10(indices.size())+2) * indices.size() );
for (Size k = 0; k < indices.size(); k++)
{
tmp += String(indices[k]) + ",";
}
tmp.resize(tmp.size() - 1); // remove last ","
return tmp;
}
/*
*
* This function populates a set of empty data containers (MSSpectrum or
* MSChromatogram) with data which are read from an SQLite statement. It is
* used when reading sqMass files. It parses all rows produced by an sql
* statement with the following columns:
*
* id (integer)
* native_id (string)
* compression (int)
* data_type (int)
* binary_Data (blob)
*
* It is designed to work with containers of type MSSpectrum and
* MSChromatogram to provide a single function for both use-cases.
*
*/
template<class ContainerT>
void populateContainer_sub_(sqlite3_stmt *stmt, std::vector<ContainerT>& containers)
{
// perform first step
sqlite3_step(stmt);
std::vector<int> cont_data;
cont_data.resize(containers.size());
std::map<Size,Size> sql_container_map;
std::vector<double> data;
String stemp;
while (sqlite3_column_type( stmt, 0 ) != SQLITE_NULL)
{
Size id_orig = sqlite3_column_int( stmt, 0 );
// map the sql table id to the index in the "containers" vector
if (sql_container_map.find(id_orig) == sql_container_map.end())
{
Size tmp = sql_container_map.size();
sql_container_map[id_orig] = tmp;
}
Size curr_id = sql_container_map[id_orig];
const unsigned char * native_id_ = sqlite3_column_text(stmt, 1);
std::string native_id(reinterpret_cast<const char*>(native_id_), sqlite3_column_bytes(stmt, 1));
if (curr_id >= containers.size())
{
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Data for non-existent spectrum / chromatogram found");
}
if (native_id != containers[curr_id].getNativeID())
{
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
String("Native id for spectrum / chromatogram does not match: ") + native_id + " != " + containers[curr_id].getNativeID() );
}
int compression = sqlite3_column_int( stmt, 2 );
int data_type = sqlite3_column_int( stmt, 3 );
const void * raw_text = sqlite3_column_blob(stmt, 4);
size_t blob_bytes = sqlite3_column_bytes(stmt, 4);
// data_type is one of 0 = mz, 1 = int, 2 = rt
// compression is one of 0 = no, 1 = zlib, 2 = np-linear, 3 = np-slof, 4 = np-pic, 5 = np-linear + zlib, 6 = np-slof + zlib, 7 = np-pic + zlib
data.clear();
stemp.clear();
if (compression == 1)
{
OpenMS::ZlibCompression::uncompressData(raw_text, blob_bytes, stemp);
void* byte_buffer = reinterpret_cast<void *>(&stemp[0]);
Size buffer_size = stemp.size();
const double* float_buffer = reinterpret_cast<const double *>(byte_buffer);
if (buffer_size % sizeof(double) != 0)
{
throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Bad BufferCount?");
}
Size float_count = buffer_size / sizeof(double);
// copy values
data.assign(float_buffer, float_buffer + float_count);
}
else if (compression == 5)
{
OpenMS::ZlibCompression::uncompressData(raw_text, blob_bytes, stemp);
MSNumpressCoder::NumpressConfig config;
config.setCompression("linear");
MSNumpressCoder().decodeNPRaw(stemp, data, config);
}
else if (compression == 6)
{
OpenMS::ZlibCompression::uncompressData(raw_text, blob_bytes, stemp);
MSNumpressCoder::NumpressConfig config;
config.setCompression("slof");
MSNumpressCoder().decodeNPRaw(stemp, data, config);
}
else
{
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Compression not supported");
}
if (data_type == 1)
{
// intensity
if (containers[curr_id].empty())
{
containers[curr_id].resize(data.size());
}
std::vector< double >::iterator data_it = data.begin();
for (auto it = containers[curr_id].begin(); it != containers[curr_id].end(); ++it, ++data_it)
{
it->setIntensity(*data_it);
}
cont_data[curr_id] += 1;
}
else if (data_type == 0)
{
// mz (should only occur in spectra)
if (boost::is_same<ContainerT, MSChromatogram>::value)
{
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Found m/z data type for chromatogram (instead of retention time)");
}
if (containers[curr_id].empty())
{
containers[curr_id].resize(data.size());
}
std::vector< double >::iterator data_it = data.begin();
for (auto it = containers[curr_id].begin(); it != containers[curr_id].end(); ++it, ++data_it)
{
it->setPos(*data_it);
}
cont_data[curr_id] += 1;
}
else if (data_type == 2)
{
// rt (should only occur in chromatograms)
if (boost::is_same<ContainerT, MSSpectrum >::value)
{
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Found retention time data type for spectrum (instead of m/z)");
}
if (containers[curr_id].empty()) containers[curr_id].resize(data.size());
std::vector< double >::iterator data_it = data.begin();
for (auto it = containers[curr_id].begin(); it != containers[curr_id].end(); ++it, ++data_it)
{
it->setPos(*data_it);
}
cont_data[curr_id] += 1;
}
else
{
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Found data type other than RT/Intensity for spectra");
}
sqlite3_step( stmt );
}
// ensure that all spectra/chromatograms have their data: we expect two data arrays per container (int and mz/rt)
for (Size k = 0; k < cont_data.size(); k++)
{
if (cont_data[k] < 2)
{
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
String("Spectrum/Chromatogram ") + k + " does not have 2 data arrays.");
}
}
}
// the cost for initialization and copy should be minimal
// - a single C string is created
// - two ints
MzMLSqliteHandler::MzMLSqliteHandler(const String& filename, const UInt64 run_id) :
filename_(filename),
spec_id_(0),
chrom_id_(0),
run_id_(Internal::SqliteHelper::clearSignBit(run_id)),
use_lossy_compression_(true),
linear_abs_mass_acc_(0.0001), // set the desired mass accuracy = 1ppm at 100 m/z
write_full_meta_(true)
{
}
void MzMLSqliteHandler::readExperiment(MSExperiment& exp, bool meta_only) const
{
SqliteConnector conn(filename_);
sqlite3* db = conn.getDB();
Size nr_results = 0;
if (write_full_meta_)
{
std::string select_sql = "SELECT " \
"RUN.ID as run_id," \
"RUN.NATIVE_ID as native_id," \
"RUN.FILENAME as filename," \
"RUN_EXTRA.DATA as data " \
"FROM RUN " \
"LEFT JOIN RUN_EXTRA ON RUN.ID = RUN_EXTRA.RUN_ID " \
";";
sqlite3_stmt* stmt;
conn.prepareStatement(&stmt, select_sql);
sqlite3_step(stmt);
// read data (throw exception if we find multiple runs)
while (sqlite3_column_type(stmt, 0) != SQLITE_NULL)
{
if (nr_results > 0)
{
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"More than one run found, cannot read both into memory");
}
const void* raw_text = sqlite3_column_blob(stmt, 3);
size_t blob_bytes = sqlite3_column_bytes(stmt, 3);
// create mzML file and parse full structure
if (blob_bytes > 0)
{
MzMLFile f;
std::string uncompressed;
OpenMS::ZlibCompression::uncompressData(raw_text, blob_bytes, uncompressed);
f.loadBuffer(uncompressed, exp);
nr_results++;
}
else
{
const unsigned char* native_id = sqlite3_column_text(stmt, 1);
const unsigned char* filename = sqlite3_column_text(stmt, 2);
OPENMS_LOG_WARN << "Warning: no full meta data found for run " << native_id << " from file " << filename << std::endl;
}
sqlite3_step(stmt);
}
// free memory
sqlite3_finalize(stmt);
if (nr_results == 0)
{
OPENMS_LOG_WARN << "Warning: no meta data found, fall back to inference from SQL data structures." << std::endl;
}
}
bool exp_empty = (exp.getNrChromatograms() == 0 && exp.getNrSpectra() == 0);
if (!write_full_meta_ || nr_results == 0 || exp_empty)
{
// creates the spectra and chromatograms but does not fill them with
// data (provides option to return meta-data only)
std::vector<MSChromatogram> chromatograms;
std::vector<MSSpectrum> spectra;
prepareChroms_(db, chromatograms);
prepareSpectra_(db, spectra);
exp.setChromatograms(chromatograms);
exp.setSpectra(spectra);
}
exp.setSqlRunID(getRunID());
if (meta_only)
{
return;
}
populateChromatogramsWithData_(db, exp.getChromatograms());
populateSpectraWithData_(db, exp.getSpectra());
}
UInt64 MzMLSqliteHandler::getRunID() const
{
SqliteConnector conn(filename_);
Size nr_results = 0;
std::string select_sql = "SELECT RUN.ID FROM RUN;";
sqlite3_stmt* stmt;
conn.prepareStatement(&stmt, select_sql);
Sql::SqlState state = Sql::SqlState::SQL_ROW;
UInt64 id;
while ((state = Sql::nextRow(stmt, state)) == Sql::SqlState::SQL_ROW)
{
++nr_results;
id = Sql::extractInt64(stmt, 0);
}
// free memory
sqlite3_finalize(stmt);
if (nr_results != 1)
{
throw Exception::SqlOperationFailed(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "File '" + filename_ + "' contains more than one run. This is currently not supported!");
}
return id;
}
void MzMLSqliteHandler::readSpectra(std::vector<MSSpectrum> & exp, const std::vector<int> & indices, bool meta_only) const
{
OPENMS_PRECONDITION(!indices.empty(), "Need to select at least one index")
// creates the spectra but does not fill them with data (provides option
// to return meta-data only)
SqliteConnector conn(filename_);
prepareSpectra_(conn.getDB(), exp, indices);
if (indices.size() != exp.size())
{
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
String("Illegal spectral indices detected ") + integerConcatenateHelper(indices) + \
" for file of size " + getNrSpectra());
}
if (meta_only)
{
return;
}
populateSpectraWithData_(conn.getDB(), exp, indices);
}
void MzMLSqliteHandler::readChromatograms(std::vector<MSChromatogram> & exp,
const std::vector<int> & indices,
bool meta_only) const
{
OPENMS_PRECONDITION(!indices.empty(), "Need to select at least one index")
// creates the chromatograms but does not fill them with data (provides
// option to return meta-data only)
SqliteConnector conn(filename_);
prepareChroms_(conn.getDB(), exp, indices);
if (indices.size() != exp.size())
{
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
String("Illegal chromatogram indices detected ") + integerConcatenateHelper(indices) + \
" for file of size " + getNrChromatograms());
}
if (meta_only)
{
return;
}
populateChromatogramsWithData_(conn.getDB(), exp, indices);
}
Size MzMLSqliteHandler::getNrSpectra() const
{
SqliteConnector conn(filename_);
int ret(0);
sqlite3_stmt* stmt;
conn.prepareStatement(&stmt, "SELECT COUNT(*) FROM SPECTRUM;");
sqlite3_step(stmt);
Sql::extractValue<int>(&ret, stmt, 0);
sqlite3_finalize(stmt);
return (Size)ret;
}
std::vector<size_t> MzMLSqliteHandler::getSpectraIndicesbyRT(double RT,
double deltaRT,
const std::vector<int>& indices) const
{
// this is necessary for some applications such as the m/z correction
SqliteConnector conn(filename_);
String select_sql = "SELECT " \
"SPECTRUM.ID as spec_id " \
"FROM SPECTRUM ";
if (deltaRT > 0.0)
{
select_sql += " WHERE RETENTION_TIME BETWEEN " + String(RT - deltaRT) + " AND " + String(RT + deltaRT);
}
else
{
select_sql += " WHERE RETENTION_TIME >= " + String(RT);
}
// restrict by a given set of indices
if (!indices.empty())
{
select_sql += " AND SPECTRUM.ID IN (" + integerConcatenateHelper(indices) + ")";
}
if (deltaRT <= 0.0) {select_sql += " LIMIT 1";} // only take the first spectrum larger than RT
select_sql += " ;";
// Execute SQL statement
sqlite3_stmt * stmt;
conn.prepareStatement(&stmt, select_sql);
sqlite3_step(stmt);
std::vector<size_t> result;
while (sqlite3_column_type( stmt, 0 ) != SQLITE_NULL)
{
result.push_back( sqlite3_column_int(stmt, 0) );
sqlite3_step(stmt);
}
sqlite3_finalize(stmt);
return result;
}
Size MzMLSqliteHandler::getNrChromatograms() const
{
SqliteConnector conn(filename_);
int ret(0);
sqlite3_stmt* stmt;
conn.prepareStatement(&stmt, "SELECT COUNT(*) FROM CHROMATOGRAM;");
sqlite3_step(stmt);
Sql::extractValue<int>(&ret, stmt, 0);
sqlite3_finalize(stmt);
return (Size)ret;
}
void MzMLSqliteHandler::populateChromatogramsWithData_(sqlite3* db, std::vector<MSChromatogram>& chromatograms) const
{
std::string select_sql;
select_sql = "SELECT " \
"CHROMATOGRAM.ID as chrom_id," \
"CHROMATOGRAM.NATIVE_ID as chrom_native_id," \
"DATA.COMPRESSION as data_compression," \
"DATA.DATA_TYPE as data_type," \
"DATA.DATA as binary_data " \
"FROM CHROMATOGRAM " \
"INNER JOIN DATA ON CHROMATOGRAM.ID = DATA.CHROMATOGRAM_ID " \
";";
// Execute SQL statement
sqlite3_stmt* stmt;
SqliteConnector::prepareStatement(db, &stmt, select_sql);
populateContainer_sub_<MSChromatogram>(stmt, chromatograms);
sqlite3_finalize(stmt);
}
void MzMLSqliteHandler::populateChromatogramsWithData_(sqlite3* db,
std::vector<MSChromatogram>& chromatograms,
const std::vector<int>& indices) const
{
OPENMS_PRECONDITION(!indices.empty(), "Need to select at least one index.")
OPENMS_PRECONDITION(indices.size() == chromatograms.size(), "Chromatograms and indices need to have the same length.")
String select_sql = "SELECT " \
"CHROMATOGRAM.ID as chrom_id," \
"CHROMATOGRAM.NATIVE_ID as chrom_native_id," \
"DATA.COMPRESSION as data_compression," \
"DATA.DATA_TYPE as data_type," \
"DATA.DATA as binary_data " \
"FROM CHROMATOGRAM " \
"INNER JOIN DATA ON CHROMATOGRAM.ID = DATA.CHROMATOGRAM_ID " \
"WHERE CHROMATOGRAM.ID IN (";
select_sql += integerConcatenateHelper(indices) + ");";
// Execute SQL statement
sqlite3_stmt* stmt;
SqliteConnector::prepareStatement(db, &stmt, select_sql);
populateContainer_sub_<MSChromatogram>(stmt, chromatograms);
sqlite3_finalize(stmt);
}
void MzMLSqliteHandler::populateSpectraWithData_(sqlite3* db, std::vector<MSSpectrum>& spectra) const
{
std::string select_sql;
select_sql = "SELECT " \
"SPECTRUM.ID as spec_id," \
"SPECTRUM.NATIVE_ID as spec_native_id," \
"DATA.COMPRESSION as data_compression," \
"DATA.DATA_TYPE as data_type," \
"DATA.DATA as binary_data " \
"FROM SPECTRUM " \
"INNER JOIN DATA ON SPECTRUM.ID = DATA.SPECTRUM_ID " \
";";
// Execute SQL statement
sqlite3_stmt* stmt;
SqliteConnector::prepareStatement(db, &stmt, select_sql);
populateContainer_sub_<MSSpectrum>(stmt, spectra);
sqlite3_finalize(stmt);
}
void MzMLSqliteHandler::populateSpectraWithData_(sqlite3* db,
std::vector<MSSpectrum>& spectra,
const std::vector<int>& indices) const
{
OPENMS_PRECONDITION(!indices.empty(), "Need to select at least one index.")
OPENMS_PRECONDITION(indices.size() == spectra.size(), "Spectra and indices need to have the same length.")
String select_sql = "SELECT " \
"SPECTRUM.ID as spec_id," \
"SPECTRUM.NATIVE_ID as spec_native_id," \
"DATA.COMPRESSION as data_compression," \
"DATA.DATA_TYPE as data_type," \
"DATA.DATA as binary_data " \
"FROM SPECTRUM " \
"INNER JOIN DATA ON SPECTRUM.ID = DATA.SPECTRUM_ID " \
"WHERE SPECTRUM.ID IN (";
select_sql += integerConcatenateHelper(indices) + ");";
// Execute SQL statement
sqlite3_stmt* stmt;
SqliteConnector::prepareStatement(db, &stmt, select_sql);
populateContainer_sub_<MSSpectrum>(stmt, spectra);
sqlite3_finalize(stmt);
}
void MzMLSqliteHandler::prepareChroms_(sqlite3* db,
std::vector<MSChromatogram>& chromatograms,
const std::vector<int>& indices) const
{
sqlite3_stmt* stmt;
std::string select_sql = "SELECT " \
"CHROMATOGRAM.ID as chrom_id," \
"CHROMATOGRAM.NATIVE_ID as chrom_native_id," \
"PRECURSOR.CHARGE as precursor_charge," \
"PRECURSOR.DRIFT_TIME as precursor_dt," \
"PRECURSOR.ISOLATION_TARGET as precursor_mz," \
"PRECURSOR.ISOLATION_LOWER as precursor_mz_lower," \
"PRECURSOR.ISOLATION_UPPER as precursor_mz_upper," \
"PRECURSOR.PEPTIDE_SEQUENCE as precursor_seq," \
"PRODUCT.CHARGE as product_charge," \
"PRODUCT.ISOLATION_TARGET as product_mz," \
"PRODUCT.ISOLATION_LOWER as product_mz_lower," \
"PRODUCT.ISOLATION_UPPER as product_mz_upper, " \
"PRECURSOR.ACTIVATION_METHOD as prec_activation, " \
"PRECURSOR.ACTIVATION_ENERGY as prec_activation_en " \
"FROM CHROMATOGRAM " \
"INNER JOIN PRECURSOR ON CHROMATOGRAM.ID = PRECURSOR.CHROMATOGRAM_ID " \
"INNER JOIN PRODUCT ON CHROMATOGRAM.ID = PRODUCT.CHROMATOGRAM_ID ";
if (!indices.empty())
{
select_sql += String("WHERE CHROMATOGRAM.ID IN (") + integerConcatenateHelper(indices) + ")";
}
select_sql += ";";
// See https://www.sqlite.org/c3ref/column_blob.html
// The pointers returned are valid until a type conversion occurs as
// described above, or until sqlite3_step() or sqlite3_reset() or
// sqlite3_finalize() is called. The memory space used to hold strings
// and BLOBs is freed automatically. Do not pass the pointers returned
// from sqlite3_column_blob(), sqlite3_column_text(), etc. into
// sqlite3_free().
SqliteConnector::prepareStatement(db, &stmt, select_sql);
sqlite3_step(stmt);
String tmp;
while (sqlite3_column_type( stmt, 0 ) != SQLITE_NULL)
{
chromatograms.resize(chromatograms.size()+1);
MSChromatogram& chrom = chromatograms.back();
OpenMS::Precursor& precursor = chrom.getPrecursor();
OpenMS::Product& product = chrom.getProduct();
if (Sql::extractValue(&tmp, stmt, 1))
{
chrom.setNativeID(tmp);
}
if (sqlite3_column_type(stmt, 2) != SQLITE_NULL)
{
precursor.setCharge(sqlite3_column_int(stmt, 2));
}
if (sqlite3_column_type(stmt, 3) != SQLITE_NULL)
{
precursor.setDriftTime(sqlite3_column_double(stmt, 3));
}
if (sqlite3_column_type(stmt, 4) != SQLITE_NULL)
{
precursor.setMZ(sqlite3_column_double(stmt, 4));
}
if (sqlite3_column_type(stmt, 5) != SQLITE_NULL)
{
double offset_value = sqlite3_column_double(stmt, 5);
if (offset_value >= 0) // Skip negative values (indicate null/invalid)
{
precursor.setIsolationWindowLowerOffset(offset_value);
}
}
if (sqlite3_column_type(stmt, 6) != SQLITE_NULL)
{
double offset_value = sqlite3_column_double(stmt, 6);
if (offset_value >= 0) // Skip negative values (indicate null/invalid)
{
precursor.setIsolationWindowUpperOffset(offset_value);
}
}
if (Sql::extractValue(&tmp, stmt, 7)) precursor.setMetaValue("peptide_sequence", tmp);
// if (sqlite3_column_type(stmt, 8) != SQLITE_NULL) product.setCharge(sqlite3_column_int(stmt, 8));
if (sqlite3_column_type(stmt, 9) != SQLITE_NULL)
{
product.setMZ(sqlite3_column_double(stmt, 9));
}
if (sqlite3_column_type(stmt, 10) != SQLITE_NULL)
{
double offset_value = sqlite3_column_double(stmt, 10);
if (offset_value >= 0) // Skip negative values (indicate null/invalid)
{
product.setIsolationWindowLowerOffset(offset_value);
}
}
if (sqlite3_column_type(stmt, 11) != SQLITE_NULL)
{
double offset_value = sqlite3_column_double(stmt, 11);
if (offset_value >= 0) // Skip negative values (indicate null/invalid)
{
product.setIsolationWindowUpperOffset(offset_value);
}
}
if (sqlite3_column_type(stmt, 12) != SQLITE_NULL && sqlite3_column_int(stmt, 12) != -1
&& sqlite3_column_int(stmt, 12) < static_cast<int>(OpenMS::Precursor::ActivationMethod::SIZE_OF_ACTIVATIONMETHOD))
{
precursor.getActivationMethods().insert(static_cast<OpenMS::Precursor::ActivationMethod>(sqlite3_column_int(stmt, 12)));
}
if (sqlite3_column_type(stmt, 13) != SQLITE_NULL)
{
precursor.setActivationEnergy(sqlite3_column_double(stmt, 13));
}
sqlite3_step( stmt );
}
// free memory
sqlite3_finalize(stmt);
}
void MzMLSqliteHandler::prepareSpectra_(sqlite3 *db,
std::vector<MSSpectrum>& spectra,
const std::vector<int> & indices) const
{
sqlite3_stmt * stmt;
std::string select_sql = "SELECT " \
"SPECTRUM.ID as spec_id," \
"SPECTRUM.NATIVE_ID as spec_native_id," \
"SPECTRUM.MSLEVEL as spec_mslevel," \
"SPECTRUM.RETENTION_TIME as spec_rt," \
"PRECURSOR.CHARGE as precursor_charge," \
"PRECURSOR.DRIFT_TIME as precursor_dt," \
"PRECURSOR.ISOLATION_TARGET as precursor_mz," \
"PRECURSOR.ISOLATION_LOWER as precursor_mz_lower," \
"PRECURSOR.ISOLATION_UPPER as precursor_mz_upper," \
"PRECURSOR.PEPTIDE_SEQUENCE as precursor_seq," \
"PRODUCT.CHARGE as product_charge," \
"PRODUCT.ISOLATION_TARGET as product_mz," \
"PRODUCT.ISOLATION_LOWER as product_mz_lower," \
"PRODUCT.ISOLATION_UPPER as product_mz_upper, " \
"SPECTRUM.SCAN_POLARITY as spec_polarity, " \
"PRECURSOR.ACTIVATION_METHOD as prec_activation, " \
"PRECURSOR.ACTIVATION_ENERGY as prec_activation_en " \
"FROM SPECTRUM " \
"LEFT JOIN PRECURSOR ON SPECTRUM.ID = PRECURSOR.SPECTRUM_ID " \
"LEFT JOIN PRODUCT ON SPECTRUM.ID = PRODUCT.SPECTRUM_ID ";
if (!indices.empty())
{
select_sql += String("WHERE SPECTRUM.ID IN (") + integerConcatenateHelper(indices) + ")";
}
select_sql += ";";
// See https://www.sqlite.org/c3ref/column_blob.html
// The pointers returned are valid until a type conversion occurs as
// described above, or until sqlite3_step() or sqlite3_reset() or
// sqlite3_finalize() is called. The memory space used to hold strings
// and BLOBs is freed automatically. Do not pass the pointers returned
// from sqlite3_column_blob(), sqlite3_column_text(), etc. into
// sqlite3_free().
SqliteConnector::prepareStatement(db, &stmt, select_sql);
sqlite3_step(stmt);
OpenMS::String tmp;
while (sqlite3_column_type(stmt, 0) != SQLITE_NULL)
{
spectra.resize(spectra.size() + 1);
MSSpectrum& spec = spectra.back();
OpenMS::Precursor precursor;
OpenMS::Product product;
if (Sql::extractValue(&tmp, stmt, 1))
{
spec.setNativeID(tmp);
}
if (sqlite3_column_type(stmt, 2) != SQLITE_NULL)
{
spec.setMSLevel(sqlite3_column_int(stmt, 2));
}
if (sqlite3_column_type(stmt, 3) != SQLITE_NULL)
{
spec.setRT(sqlite3_column_double(stmt, 3));
}
if (sqlite3_column_type(stmt, 4) != SQLITE_NULL)
{
precursor.setCharge(sqlite3_column_int(stmt, 4));
}
if (sqlite3_column_type(stmt, 5) != SQLITE_NULL)
{
precursor.setDriftTime(sqlite3_column_double(stmt, 5));
}
if (sqlite3_column_type(stmt, 6) != SQLITE_NULL)
{
precursor.setMZ(sqlite3_column_double(stmt, 6));
}
if (sqlite3_column_type(stmt, 7) != SQLITE_NULL)
{
double offset_value = sqlite3_column_double(stmt, 7);
if (offset_value >= 0) // Skip negative values (indicate null/invalid)
{
precursor.setIsolationWindowLowerOffset(offset_value);
}
}
if (sqlite3_column_type(stmt, 8) != SQLITE_NULL)
{
double offset_value = sqlite3_column_double(stmt, 8);
if (offset_value >= 0) // Skip negative values (indicate null/invalid)
{
precursor.setIsolationWindowUpperOffset(offset_value);
}
}
if (Sql::extractValue(&tmp, stmt, 9))
{
precursor.setMetaValue("peptide_sequence", tmp);
}
// if (sqlite3_column_type(stmt, 10) != SQLITE_NULL) product.setCharge(sqlite3_column_int(stmt, 10));
if (sqlite3_column_type(stmt, 11) != SQLITE_NULL)
{
product.setMZ(sqlite3_column_double(stmt, 11));
}
if (sqlite3_column_type(stmt, 12) != SQLITE_NULL)
{
double offset_value = sqlite3_column_double(stmt, 12);
if (offset_value >= 0) // Skip negative values (indicate null/invalid)
{
product.setIsolationWindowLowerOffset(offset_value);
}
}
if (sqlite3_column_type(stmt, 13) != SQLITE_NULL)
{
double offset_value = sqlite3_column_double(stmt, 13);
if (offset_value >= 0) // Skip negative values (indicate null/invalid)
{
product.setIsolationWindowUpperOffset(offset_value);
}
}
if (sqlite3_column_type(stmt, 14) != SQLITE_NULL)
{
int pol = sqlite3_column_int(stmt, 14);
if (pol == 0)
{
spec.getInstrumentSettings().setPolarity(IonSource::Polarity::NEGATIVE);
}
else
{
spec.getInstrumentSettings().setPolarity(IonSource::Polarity::POSITIVE);
}
}
if (sqlite3_column_type(stmt, 15) != SQLITE_NULL && sqlite3_column_int(stmt, 15) != -1
&& sqlite3_column_int(stmt, 15) < static_cast<int>(OpenMS::Precursor::ActivationMethod::SIZE_OF_ACTIVATIONMETHOD))
{
precursor.getActivationMethods().insert(static_cast<OpenMS::Precursor::ActivationMethod>(sqlite3_column_int(stmt, 15)));
}
if (sqlite3_column_type(stmt, 16) != SQLITE_NULL)
{
precursor.setActivationEnergy(sqlite3_column_double(stmt, 16));
}
if (sqlite3_column_type(stmt, 6) != SQLITE_NULL)
{
spec.getPrecursors().push_back(std::move(precursor));
}
if (sqlite3_column_type(stmt, 11) != SQLITE_NULL)
{
spec.getProducts().push_back(std::move(product));
}
sqlite3_step( stmt );
}
// free memory
sqlite3_finalize(stmt);
}
void MzMLSqliteHandler::writeExperiment(const MSExperiment& exp)
{
// write run level information
writeRunLevelInformation(exp, write_full_meta_);
// write data
writeChromatograms(exp.getChromatograms());
writeSpectra(exp.getSpectra());
}
void MzMLSqliteHandler::writeRunLevelInformation(const MSExperiment& exp, bool write_full_meta)
{
SqliteConnector conn(filename_);
// prepare streams and set required precision (default is 6 digits)
std::stringstream insert_run_sql;
const std::string& native_id = exp.getLoadedFilePath(); // TODO escape stuff like ' (SQL inject)
insert_run_sql << "INSERT INTO RUN (ID, FILENAME, NATIVE_ID) VALUES (" <<
run_id_ << ",'" << native_id << "','" << native_id << "'); ";
conn.executeStatement("BEGIN TRANSACTION");
conn.executeStatement(insert_run_sql.str());
conn.executeStatement("END TRANSACTION");
if (write_full_meta)
{
MSExperiment meta;
// copy experimental settings
meta.reserveSpaceSpectra(exp.getNrSpectra());
meta.reserveSpaceChromatograms(exp.getNrChromatograms());
static_cast<ExperimentalSettings &>(meta) = exp;
for (Size k = 0; k < exp.getNrSpectra(); k++)
{
MSSpectrum s = exp.getSpectra()[k];
s.clear(false);
meta.addSpectrum(s);
}
for (Size k = 0; k < exp.getNrChromatograms(); k++)
{
MSChromatogram c = exp.getChromatograms()[k];
c.clear(false);
meta.addChromatogram(c);
}
String prepare_statement = "INSERT INTO RUN_EXTRA (RUN_ID, DATA) VALUES ";
prepare_statement += String("(") + run_id_ + ", ?)";
std::vector<String> data;
std::string output;
MzMLFile().storeBuffer(output, meta);
// write the full metadata into the sql file (compress with zlib before)
std::string encoded_string;
OpenMS::ZlibCompression::compressString(output, encoded_string);
data.emplace_back(encoded_string);
// data.push_back(output); // in case you need to debug on the uncompressed string ...
conn.executeBindStatement(prepare_statement, data);
}
}
void MzMLSqliteHandler::createTables()
{
// delete file if present
QFile file (filename_.toQString());
file.remove();
SqliteConnector conn(filename_);
// Create SQL structure
char const *create_sql =
// data table
// - compression is one of 0 = no, 1 = zlib, 2 = np-linear, 3 = np-slof, 4 = np-pic, 5 = np-linear + zlib, 6 = np-slof + zlib, 7 = np-pic + zlib
// - data_type is one of 0 = mz, 1 = int, 2 = rt
// - data contains the raw (blob) data for a single data array
"CREATE TABLE DATA(" \
"SPECTRUM_ID INT," \
"CHROMATOGRAM_ID INT," \
"COMPRESSION INT," \
"DATA_TYPE INT," \
"DATA BLOB NOT NULL" \
");" \
// spectrum table
"CREATE TABLE SPECTRUM(" \
"ID INT PRIMARY KEY NOT NULL," \
"RUN_ID INT," \
"MSLEVEL INT NULL," \
"RETENTION_TIME REAL NULL," \
"SCAN_POLARITY INT NULL," \
"NATIVE_ID TEXT NOT NULL" \
");" \
// ms-run table
"CREATE TABLE RUN(" \
"ID INT PRIMARY KEY NOT NULL," \
"FILENAME TEXT NOT NULL, " \
"NATIVE_ID TEXT NOT NULL" \
");" \
// ms-run extra table
"CREATE TABLE RUN_EXTRA(" \
"RUN_ID INT," \
"DATA BLOB NOT NULL" \
");" \
// chromatogram table
"CREATE TABLE CHROMATOGRAM(" \
"ID INT PRIMARY KEY NOT NULL," \
"RUN_ID INT," \
"NATIVE_ID TEXT NOT NULL" \
");" \
// product table
"CREATE TABLE PRODUCT(" \
"SPECTRUM_ID INT," \
"CHROMATOGRAM_ID INT," \
"CHARGE INT NULL," \
"ISOLATION_TARGET REAL NULL," \
"ISOLATION_LOWER REAL NULL," \
"ISOLATION_UPPER REAL NULL" \
");" \
// precursor table
"CREATE TABLE PRECURSOR(" \
"SPECTRUM_ID INT," \
"CHROMATOGRAM_ID INT," \
"CHARGE INT NULL," \
"PEPTIDE_SEQUENCE TEXT NULL," \
"DRIFT_TIME REAL NULL," \
"ACTIVATION_METHOD INT NULL," \
"ACTIVATION_ENERGY REAL NULL," \
"ISOLATION_TARGET REAL NULL," \
"ISOLATION_LOWER REAL NULL," \
"ISOLATION_UPPER REAL NULL" \
");";
// Execute SQL statement
conn.executeStatement(create_sql);
createIndices_();
}
void MzMLSqliteHandler::createIndices_()
{
// Create SQL structure
char const *create_sql =
// data table
"CREATE INDEX data_chr_idx ON DATA(CHROMATOGRAM_ID);" \
"CREATE INDEX data_sp_idx ON DATA(SPECTRUM_ID);" \
"CREATE INDEX spec_rt_idx ON SPECTRUM(RETENTION_TIME);" \
"CREATE INDEX spec_mslevel_idx ON SPECTRUM(MSLEVEL);" \
"CREATE INDEX spec_run_idx ON SPECTRUM(RUN_ID);" \
"CREATE INDEX run_extra_idx ON RUN_EXTRA(RUN_ID);" \
"CREATE INDEX chrom_run_idx ON CHROMATOGRAM(RUN_ID);" \
"CREATE INDEX product_chr_idx ON DATA(CHROMATOGRAM_ID);" \
"CREATE INDEX product_sp_idx ON DATA(SPECTRUM_ID);" \
"CREATE INDEX precursor_chr_idx ON DATA(CHROMATOGRAM_ID);" \
"CREATE INDEX precursor_sp_idx ON DATA(SPECTRUM_ID);";
// Execute SQL statement
SqliteConnector conn(filename_);
conn.executeStatement(create_sql);
}
void MzMLSqliteHandler::writeSpectra(const std::vector<MSSpectrum>& spectra)
{
// prevent writing of empty data which would throw an SQL exception
if (spectra.empty())
{
return;
}
SqliteConnector conn(filename_);
// prepare streams and set required precision (default is 6 digits)
std::stringstream insert_spectra_sql;
std::stringstream insert_precursor_sql;
std::stringstream insert_product_sql;
insert_spectra_sql.precision(11);
insert_precursor_sql.precision(11);
insert_product_sql.precision(11);
// Encoding options
MSNumpressCoder::NumpressConfig npconfig_mz;
npconfig_mz.estimate_fixed_point = true; // critical
npconfig_mz.numpressErrorTolerance = -1.0; // skip check, faster
npconfig_mz.setCompression("linear");
npconfig_mz.linear_fp_mass_acc = linear_abs_mass_acc_;
MSNumpressCoder::NumpressConfig npconfig_int;
npconfig_int.estimate_fixed_point = true; // critical
npconfig_int.numpressErrorTolerance = -1.0; // skip check, faster
npconfig_int.setCompression("slof");
String prepare_statement = "INSERT INTO DATA (SPECTRUM_ID, DATA_TYPE, COMPRESSION, DATA) VALUES ";
std::vector<String> data;
int sql_it = 1;
std::vector<String> encoded_strings_mz(spectra.size());
std::vector<String> encoded_strings_int(spectra.size());
#ifdef _OPENMP
#pragma omp parallel for
#endif
for (SignedSize k = 0; k < (SignedSize)spectra.size(); k++)
{
const MSSpectrum& spec = spectra[k];
// encode mz data (zlib or np-linear + zlib)
{
std::vector<double> data_to_encode;
data_to_encode.resize(spec.size());
for (Size p = 0; p < spec.size(); ++p)
{
data_to_encode[p] = spec[p].getMZ();
}
String uncompressed_str;
String encoded_string;
if (use_lossy_compression_)
{
MSNumpressCoder().encodeNPRaw(data_to_encode, uncompressed_str, npconfig_mz);
OpenMS::ZlibCompression::compressString(uncompressed_str, encoded_string);
encoded_strings_mz[k] = encoded_string;
}
else
{
std::string str_data = std::string((const char*) (&data_to_encode[0]), data_to_encode.size() * sizeof(double));
OpenMS::ZlibCompression::compressString(str_data, encoded_string);
encoded_strings_mz[k] = encoded_string;
}
}
// encode intensity data (zlib or np-slof + zlib)
{
std::vector<double> data_to_encode;
data_to_encode.resize(spec.size());
for (Size p = 0; p < spec.size(); ++p)
{
data_to_encode[p] = spec[p].getIntensity();
}
String uncompressed_str;
String encoded_string;
if (use_lossy_compression_)
{
MSNumpressCoder().encodeNPRaw(data_to_encode, uncompressed_str, npconfig_int);
OpenMS::ZlibCompression::compressString(uncompressed_str, encoded_string);
encoded_strings_int[k] = encoded_string;
}
else
{
std::string str_data = std::string((const char*) (&data_to_encode[0]), data_to_encode.size() * sizeof(double));
OpenMS::ZlibCompression::compressString(str_data, encoded_string);
encoded_strings_int[k] = encoded_string;
}
}
}
int nr_precursors = 0;
int nr_products = 0;
for (Size k = 0; k < spectra.size(); k++)
{
const MSSpectrum& spec = spectra[k];
int polarity = (spec.getInstrumentSettings().getPolarity() == IonSource::Polarity::POSITIVE); // 1 = positive
insert_spectra_sql << "INSERT INTO SPECTRUM(ID, RUN_ID, NATIVE_ID, MSLEVEL, RETENTION_TIME, SCAN_POLARITY) VALUES (" <<
spec_id_ << "," <<
run_id_ << ",'" <<
spec.getNativeID() << "'," <<
spec.getMSLevel() << "," <<
spec.getRT() << "," <<
polarity << "); ";
if (!spec.getPrecursors().empty())
{
if (spec.getPrecursors().size() > 1)
{
std::cout << "WARNING cannot store more than first precursor" << std::endl;
}
if (spec.getPrecursors()[0].getActivationMethods().size() > 1)
{
std::cout << "WARNING cannot store more than one activation method" << std::endl;
}
OpenMS::Precursor prec = spec.getPrecursors()[0];
// see src/openms/include/OpenMS/METADATA/Precursor.h for activation modes
int activation_method = -1;
if (!prec.getActivationMethods().empty() )
{
activation_method = static_cast<int>(*prec.getActivationMethods().begin());
}
String pepseq;
if (prec.metaValueExists("peptide_sequence"))
{
pepseq = prec.getMetaValue("peptide_sequence");
insert_precursor_sql << "INSERT INTO PRECURSOR (SPECTRUM_ID, CHARGE, ISOLATION_TARGET, " <<
"ISOLATION_LOWER, ISOLATION_UPPER, DRIFT_TIME, ACTIVATION_ENERGY, " <<
"ACTIVATION_METHOD, PEPTIDE_SEQUENCE) VALUES (" <<
spec_id_ << "," << prec.getCharge() << "," << prec.getMZ() <<
"," << prec.getIsolationWindowLowerOffset() << "," << prec.getIsolationWindowUpperOffset() <<
"," << prec.getDriftTime() <<
"," << prec.getActivationEnergy() <<
"," << activation_method << ",'" << pepseq << "'" << "); ";
}
else
{
insert_precursor_sql << "INSERT INTO PRECURSOR (SPECTRUM_ID, CHARGE, ISOLATION_TARGET, " <<
"ISOLATION_LOWER, ISOLATION_UPPER, DRIFT_TIME, ACTIVATION_ENERGY, ACTIVATION_METHOD) VALUES (" <<
spec_id_ << "," << prec.getCharge() << "," << prec.getMZ() <<
"," << prec.getIsolationWindowLowerOffset() << "," << prec.getIsolationWindowUpperOffset() <<
"," << prec.getDriftTime() <<
"," << prec.getActivationEnergy() <<
"," << activation_method << "); ";
}
nr_precursors++;
}
if (!spec.getProducts().empty())
{
if (spec.getProducts().size() > 1)
{
std::cout << "WARNING cannot store more than first product" << std::endl;
}
OpenMS::Product prod = spec.getProducts()[0];
insert_product_sql << "INSERT INTO PRODUCT (SPECTRUM_ID, CHARGE, ISOLATION_TARGET, " <<
"ISOLATION_LOWER, ISOLATION_UPPER) VALUES (" <<
spec_id_ << "," << 0 << "," << prod.getMZ() <<
"," << prod.getIsolationWindowLowerOffset() << "," << prod.getIsolationWindowUpperOffset() << "); ";
nr_products++;
}
// data_type is one of 0 = mz, 1 = int, 2 = rt
// compression is one of 0 = no, 1 = zlib, 2 = np-linear, 3 = np-slof, 4 = np-pic, 5 = np-linear + zlib, 6 = np-slof + zlib, 7 = np-pic + zlib
// encode mz data (zlib or np-linear + zlib)
{
data.push_back(encoded_strings_mz[k]);
if (use_lossy_compression_)
{
prepare_statement += String("(") + spec_id_ + ", 0, 5, ?" + sql_it++ + " ),";
}
else
{
prepare_statement += String("(") + spec_id_ + ", 0, 1, ?" + sql_it++ + " ),";
}
}
// encode intensity data (zlib or np-slof + zlib)
{
data.push_back(encoded_strings_int[k]);
if (use_lossy_compression_)
{
prepare_statement += String("(") + spec_id_ + ", 1, 6, ?" + sql_it++ + " ),";
}
else
{
prepare_statement += String("(") + spec_id_ + ", 1, 1, ?" + sql_it++ + " ),";
}
}
spec_id_++;
if (sql_it > sql_batch_size_) // flush as sqlite can only handle so many bind_blob statements
{
// prevent writing of empty data which would throw an SQL exception
if (!data.empty())
{
prepare_statement.resize( prepare_statement.size() -1 ); // remove last ","
conn.executeBindStatement(prepare_statement, data);
}
data.clear();
prepare_statement = "INSERT INTO DATA (SPECTRUM_ID, DATA_TYPE, COMPRESSION, DATA) VALUES ";
sql_it = 1;
}
}
// prevent writing of empty data which would throw an SQL exception
if (!data.empty())
{
prepare_statement.resize( prepare_statement.size() -1 );
conn.executeBindStatement(prepare_statement, data);
}
conn.executeStatement("BEGIN TRANSACTION");
conn.executeStatement(insert_spectra_sql.str());
if (nr_precursors > 0)
{
conn.executeStatement(insert_precursor_sql.str());
}
if (nr_products > 0)
{
conn.executeStatement(insert_product_sql.str());
}
conn.executeStatement("END TRANSACTION");
}
void MzMLSqliteHandler::writeChromatograms(const std::vector<MSChromatogram >& chroms)
{
// prevent writing of empty data which would throw an SQL exception
if (chroms.empty())
{
return;
}
SqliteConnector conn(filename_);
// prepare streams and set required precision (default is 6 digits)
std::stringstream insert_chrom_sql;
std::stringstream insert_precursor_sql;
std::stringstream insert_product_sql;
insert_chrom_sql.precision(11);
insert_precursor_sql.precision(11);
insert_product_sql.precision(11);
// Encoding options
MSNumpressCoder::NumpressConfig npconfig_mz;
npconfig_mz.estimate_fixed_point = true; // critical
npconfig_mz.numpressErrorTolerance = -1.0; // skip check, faster
npconfig_mz.setCompression("linear");
npconfig_mz.linear_fp_mass_acc = 0.05; // set the desired RT accuracy (0.05 seconds)
MSNumpressCoder::NumpressConfig npconfig_int;
npconfig_int.estimate_fixed_point = true; // critical
npconfig_int.numpressErrorTolerance = -1.0; // skip check, faster
npconfig_int.setCompression("slof");
String prepare_statement = "INSERT INTO DATA (CHROMATOGRAM_ID, DATA_TYPE, COMPRESSION, DATA) VALUES ";
int sql_it = 1;
// Perform encoding in parallel
std::vector<String> encoded_strings_rt(chroms.size());
std::vector<String> encoded_strings_int(chroms.size());
#ifdef _OPENMP
#pragma omp parallel for
#endif
for (SignedSize k = 0; k < (SignedSize)chroms.size(); k++)
{
const MSChromatogram& chrom = chroms[k];
// encode retention time data (zlib or np-linear + zlib)
{
std::vector<double> data_to_encode;
data_to_encode.resize(chrom.size());
for (Size p = 0; p < chrom.size(); ++p)
{
data_to_encode[p] = chrom[p].getRT();
}
String uncompressed_str;
String encoded_string;
if (use_lossy_compression_)
{
MSNumpressCoder().encodeNPRaw(data_to_encode, uncompressed_str, npconfig_mz);
OpenMS::ZlibCompression::compressString(uncompressed_str, encoded_string);
encoded_strings_rt[k] = encoded_string;
}
else
{
std::string str_data = std::string((const char*) (&data_to_encode[0]), data_to_encode.size() * sizeof(double));
OpenMS::ZlibCompression::compressString(str_data, encoded_string);
encoded_strings_rt[k] = encoded_string;
}
}
// encode intensity data (zlib or np-slof + zlib)
{
std::vector<double> data_to_encode;
data_to_encode.resize(chrom.size());
for (Size p = 0; p < chrom.size(); ++p)
{
data_to_encode[p] = chrom[p].getIntensity();
}
String uncompressed_str;
String encoded_string;
if (use_lossy_compression_)
{
MSNumpressCoder().encodeNPRaw(data_to_encode, uncompressed_str, npconfig_int);
OpenMS::ZlibCompression::compressString(uncompressed_str, encoded_string);
encoded_strings_int[k] = encoded_string;
}
else
{
std::string str_data = std::string((const char*) (&data_to_encode[0]), data_to_encode.size() * sizeof(double));
OpenMS::ZlibCompression::compressString(str_data, encoded_string);
encoded_strings_int[k] = encoded_string;
}
}
}
std::vector<String> data;
for (Size k = 0; k < chroms.size(); k++)
{
const MSChromatogram& chrom = chroms[k];
insert_chrom_sql << "INSERT INTO CHROMATOGRAM (ID, RUN_ID, NATIVE_ID) VALUES (" << chrom_id_ << "," << run_id_ << ",'" << chrom.getNativeID() << "'); ";
OpenMS::Precursor prec = chrom.getPrecursor();
// see src/openms/include/OpenMS/METADATA/Precursor.h for activation modes
int activation_method = -1;
if (!prec.getActivationMethods().empty() )
{
activation_method = static_cast<int>(*prec.getActivationMethods().begin());
}
String pepseq;
if (prec.metaValueExists("peptide_sequence"))
{
pepseq = prec.getMetaValue("peptide_sequence");
insert_precursor_sql << "INSERT INTO PRECURSOR (CHROMATOGRAM_ID, CHARGE, ISOLATION_TARGET, " <<
"ISOLATION_LOWER, ISOLATION_UPPER, DRIFT_TIME, ACTIVATION_ENERGY, " <<
"ACTIVATION_METHOD, PEPTIDE_SEQUENCE) VALUES (" <<
chrom_id_ << "," << prec.getCharge() << "," << prec.getMZ() <<
"," << prec.getIsolationWindowLowerOffset() << "," << prec.getIsolationWindowUpperOffset() <<
"," << prec.getDriftTime() <<
"," << prec.getActivationEnergy() <<
"," << activation_method << ",'" << pepseq << "'" << "); ";
}
else
{
insert_precursor_sql << "INSERT INTO PRECURSOR (CHROMATOGRAM_ID, CHARGE, ISOLATION_TARGET, " <<
"ISOLATION_LOWER, ISOLATION_UPPER, DRIFT_TIME, ACTIVATION_ENERGY, ACTIVATION_METHOD) VALUES (" <<
chrom_id_ << "," << prec.getCharge() << "," << prec.getMZ() <<
"," << prec.getIsolationWindowLowerOffset() << "," << prec.getIsolationWindowUpperOffset() <<
"," << prec.getDriftTime() <<
"," << prec.getActivationEnergy() <<
"," << activation_method << "); ";
}
OpenMS::Product prod = chrom.getProduct();
insert_product_sql << "INSERT INTO PRODUCT (CHROMATOGRAM_ID, CHARGE, ISOLATION_TARGET, " <<
"ISOLATION_LOWER, ISOLATION_UPPER) VALUES (" <<
chrom_id_ << "," << 0 << "," << prod.getMZ() <<
"," << prod.getIsolationWindowLowerOffset() << "," << prod.getIsolationWindowUpperOffset() << "); ";
// data_type is one of 0 = mz, 1 = int, 2 = rt
// compression is one of 0 = no, 1 = zlib, 2 = np-linear, 3 = np-slof, 4 = np-pic, 5 = np-linear + zlib, 6 = np-slof + zlib, 7 = np-pic + zlib
// encode retention time data (zlib or np-linear + zlib)
{
data.push_back(encoded_strings_rt[k]);
if (use_lossy_compression_)
{
prepare_statement += String("(") + chrom_id_ + ", 2, 5, ?" + sql_it++ + " ),";
}
else
{
prepare_statement += String("(") + chrom_id_ + ", 2, 1, ?" + sql_it++ + " ),";
}
}
// encode intensity data (zlib or np-slof + zlib)
{
data.push_back(encoded_strings_int[k]);
if (use_lossy_compression_)
{
prepare_statement += String("(") + chrom_id_ + ", 1, 6, ?" + sql_it++ + " ),";
}
else
{
prepare_statement += String("(") + chrom_id_ + ", 1, 1, ?" + sql_it++ + " ),";
}
}
chrom_id_++;
if (sql_it > sql_batch_size_) // flush as sqlite can only handle so many bind_blob statements
{
// prevent writing of empty data which would throw an SQL exception
if (!data.empty())
{
prepare_statement.resize( prepare_statement.size() -1 ); // remove last ","
conn.executeBindStatement(prepare_statement, data);
}
data.clear();
prepare_statement = "INSERT INTO DATA (CHROMATOGRAM_ID, DATA_TYPE, COMPRESSION, DATA) VALUES ";
sql_it = 1;
}
}
// prevent writing of empty data which would throw an SQL exception
if (!data.empty())
{
prepare_statement.resize(prepare_statement.size() -1); // remove last ","
conn.executeBindStatement(prepare_statement, data);
}
conn.executeStatement("BEGIN TRANSACTION");
conn.executeStatement(insert_chrom_sql.str());
conn.executeStatement(insert_precursor_sql.str());
conn.executeStatement(insert_product_sql.str());
conn.executeStatement("END TRANSACTION");
}
} // namespace OpenMS // namespace Internal
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/HANDLERS/ToolDescriptionHandler.cpp | .cpp | 6,331 | 228 | // 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/HANDLERS/ToolDescriptionHandler.h>
using namespace std;
namespace OpenMS::Internal
{
ToolDescriptionHandler::ToolDescriptionHandler(const String & filename, const String & version) :
ParamXMLHandler(p_, filename, version),
p_(),
tde_(),
td_(),
td_vec_(),
tag_(),
in_ini_section_(false)
{
}
ToolDescriptionHandler::~ToolDescriptionHandler()
= default;
void ToolDescriptionHandler::startElement(const XMLCh * const uri, const XMLCh * const local_name, const XMLCh * const qname, const xercesc::Attributes & attributes)
{
if (in_ini_section_)
{
ParamXMLHandler::startElement(uri, local_name, qname, attributes);
return;
}
tag_ = sm_.convert(qname);
open_tags_.push_back(tag_);
//std::cout << "starting tag " << tag_ << "\n";
if (tag_ == "tool")
{
String status = attributeAsString_(attributes, "status");
if (status == "external")
{
td_.is_internal = false;
}
else if (status == "internal")
{
td_.is_internal = true;
}
else
{
error(LOAD, "ToolDescriptionHandler::startElement: Element 'status' if tag 'tool' has unknown value " + status + "'.");
}
return;
}
if (tag_ == "mapping")
{
Int id = attributeAsInt_(attributes, "id");
String command = attributeAsString_(attributes, "cl");
tde_.tr_table.mapping[id] = command;
return;
}
if (tag_ == "file_post")
{
Internal::FileMapping fm;
fm.location = attributeAsString_(attributes, "location");
fm.target = attributeAsString_(attributes, "target");
tde_.tr_table.post_moves.push_back(fm);
return;
}
if (tag_ == "file_pre")
{
Internal::FileMapping fm;
fm.location = attributeAsString_(attributes, "location");
fm.target = attributeAsString_(attributes, "target");
tde_.tr_table.pre_moves.push_back(fm);
return;
}
if (tag_ == "ini_param")
{
in_ini_section_ = true;
p_ = Param(); // reset Param
return;
}
if (tag_ == "ttd" || tag_ == "category" || tag_ == "e_category" || tag_ == "type")
{
return;
}
if (td_.is_internal)
{
if (tag_ == "name")
{
return;
}
}
else if (!td_.is_internal)
{
if (tag_ == "external" || tag_ == "cloptions" || tag_ == "path" || tag_ == "mappings" || tag_ == "mapping" || tag_ == "ini_param" ||
tag_ == "text" || tag_ == "onstartup" || tag_ == "onfail" || tag_ == "onfinish" || tag_ == "workingdirectory")
{
return;
}
}
error(LOAD, "ToolDescriptionHandler::startElement(): Unknown element found: '" + tag_ + "', ignoring.");
}
void ToolDescriptionHandler::characters(const XMLCh * const chars, const XMLSize_t length)
{
if (in_ini_section_)
{
ParamXMLHandler::characters(chars, length);
return;
}
//std::cout << "characters '" << sm_.convert(chars) << "' in tag " << tag_ << "\n";
if (tag_ == "ttd" || tag_ == "tool" || tag_ == "mappings" || tag_ == "external" || tag_ == "text")
{
return;
}
if (tag_ == "name")
{
td_.name = sm_.convert(chars);
}
else if (tag_ == "category")
{
td_.category = sm_.convert(chars);
}
else if (tag_ == "type")
{
td_.types.push_back(sm_.convert(chars));
}
else if (tag_ == "e_category")
{
tde_.category = sm_.convert(chars);
}
else if (tag_ == "cloptions")
{
tde_.commandline = sm_.convert(chars);
}
else if (tag_ == "path")
{
tde_.path = sm_.convert(chars);
}
else if (tag_ == "onstartup")
{
tde_.text_startup = sm_.convert(chars);
}
else if (tag_ == "onfail")
{
tde_.text_fail = sm_.convert(chars);
}
else if (tag_ == "onfinish")
{
tde_.text_finish = sm_.convert(chars);
}
else if (tag_ == "workingdirectory")
{
tde_.working_directory = sm_.convert(chars);
}
else
{
error(LOAD, "ToolDescriptionHandler::characters: Unknown character section found: '" + tag_ + "', ignoring.");
}
}
void ToolDescriptionHandler::endElement(const XMLCh * const uri, const XMLCh * const local_name, const XMLCh * const qname)
{
String endtag_ = sm_.convert(qname);
if (in_ini_section_ && endtag_ != "ini_param")
{
ParamXMLHandler::endElement(uri, local_name, qname);
return;
}
open_tags_.pop_back();
//std::cout << "ending tag " << endtag_ << "\n";
if (!open_tags_.empty())
{
tag_ = open_tags_.back();
//std::cout << " --> current Tag: " << tag_ << "\n";
}
if (endtag_ == "ini_param")
{
in_ini_section_ = false;
tde_.param = p_;
return;
}
else if (endtag_ == "external")
{
td_.external_details.push_back(tde_);
tde_ = ToolExternalDetails();
return;
}
else if (endtag_ == "tool")
{
td_vec_.push_back(td_);
td_ = ToolDescription();
return;
}
else
return; // TODO...handle other end tags?
}
void ToolDescriptionHandler::writeTo(std::ostream & /*os*/)
{
throw Exception::NotImplemented(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
void ToolDescriptionHandler::setToolDescriptions(const std::vector<ToolDescription> & tds)
{
td_vec_ = tds;
}
const std::vector<ToolDescription> & ToolDescriptionHandler::getToolDescriptions() const
{
return td_vec_;
}
} // namespace OpenMS //namespace Internal
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/HANDLERS/IndexedMzMLHandler.cpp | .cpp | 9,307 | 305 | // 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/HANDLERS/IndexedMzMLHandler.h>
#include <OpenMS/FORMAT/HANDLERS/IndexedMzMLDecoder.h>
#include <OpenMS/FORMAT/HANDLERS/MzMLSpectrumDecoder.h>
// #define DEBUG_READER
namespace OpenMS::Internal
{
void IndexedMzMLHandler::parseFooter_()
{
//-------------------------------------------------------------
// Find offset
//-------------------------------------------------------------
index_offset_ = IndexedMzMLDecoder().findIndexListOffset(filename_);
if (index_offset_ == (std::streampos)-1)
{
parsing_success_ = false;
return;
}
// typedef std::vector< std::pair<std::string, std::streampos> > OffsetVector;
IndexedMzMLDecoder::OffsetVector spectra_offsets, chromatograms_offsets;
int res = IndexedMzMLDecoder().parseOffsets(filename_, index_offset_, spectra_offsets, chromatograms_offsets);
for (const auto& off : spectra_offsets)
{
spectra_native_ids_.emplace(off.first, spectra_offsets_.size());
spectra_offsets_.push_back(off.second);
}
for (const auto& off : chromatograms_offsets)
{
chromatograms_native_ids_.emplace(off.first, chromatograms_offsets_.size());
chromatograms_offsets_.push_back(off.second);
}
spectra_before_chroms_ = true;
if (!spectra_offsets_.empty() && !chromatograms_offsets_.empty())
{
if (spectra_offsets_[0] < chromatograms_offsets_[0])
{
spectra_before_chroms_ = true;
}
else
{
spectra_before_chroms_ = false;
}
}
parsing_success_ = (res == 0);
}
IndexedMzMLHandler::IndexedMzMLHandler(const String& filename) :
parsing_success_(false),
skip_xml_checks_(false)
{
openFile(filename);
}
IndexedMzMLHandler::IndexedMzMLHandler() :
parsing_success_(false),
skip_xml_checks_(false)
{}
IndexedMzMLHandler::IndexedMzMLHandler(const IndexedMzMLHandler& source) :
filename_(source.filename_),
spectra_offsets_(source.spectra_offsets_),
chromatograms_offsets_(source.chromatograms_offsets_),
index_offset_(source.index_offset_),
spectra_before_chroms_(source.spectra_before_chroms_),
// do not copy the filestream itself but open a new filestream using the same file
// this is critical for parallel access to the same file!
filestream_(source.filename_.c_str()),
parsing_success_(source.parsing_success_),
skip_xml_checks_(source.skip_xml_checks_)
{
}
IndexedMzMLHandler::~IndexedMzMLHandler() = default;
void IndexedMzMLHandler::openFile(const String& filename)
{
if (filestream_.is_open()) // important; otherwise opening again will fail
{
filestream_.close();
}
filename_ = filename;
filestream_.open(filename);
parseFooter_();
}
bool IndexedMzMLHandler::getParsingSuccess() const
{
return parsing_success_;
}
size_t IndexedMzMLHandler::getNrSpectra() const
{
return spectra_offsets_.size();
}
size_t IndexedMzMLHandler::getNrChromatograms() const
{
return chromatograms_offsets_.size();
}
std::string IndexedMzMLHandler::getChromatogramById_helper_(int id)
{
int chromToGet = id;
if (!parsing_success_)
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Parsing was unsuccessful, cannot read file", "");
}
if (chromToGet < 0)
{
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
String( "id needs to be positive, was " + String(id) ));
}
if (chromToGet >= (int)getNrChromatograms())
{
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String(
"id needs to be smaller than the number of spectra, was " + String(id)
+ " maximal allowed is " + String(getNrSpectra()) ));
}
std::streampos startidx = -1;
std::streampos endidx = -1;
if (chromToGet == int(getNrChromatograms() - 1))
{
startidx = chromatograms_offsets_[chromToGet];
if (spectra_offsets_.empty() || spectra_before_chroms_)
{
// just take everything until the index starts
endidx = index_offset_;
}
else
{
// just take everything until the chromatograms start
endidx = spectra_offsets_[0];
}
}
else
{
startidx = chromatograms_offsets_[chromToGet];
endidx = chromatograms_offsets_[chromToGet + 1];
}
std::streampos readl = endidx - startidx;
char* buffer = new char[readl + std::streampos(1)];
filestream_.seekg(startidx, filestream_.beg);
filestream_.read(buffer, readl);
buffer[readl] = '\0';
std::string text(buffer);
delete[] buffer;
#ifdef DEBUG_READER
// print the full text we just read
std::cout << text << std::endl;
#endif
return text;
}
std::string IndexedMzMLHandler::getSpectrumById_helper_(int id)
{
int spectrumToGet = id;
if (!parsing_success_)
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Parsing was unsuccessful, cannot read file", "");
}
if (spectrumToGet < 0)
{
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
String( "id needs to be positive, was " + String(id) ));
}
if (spectrumToGet >= (int)getNrSpectra())
{
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String(
"id needs to be smaller than the number of spectra, was " + String(id)
+ " maximal allowed is " + String(getNrSpectra()) ));
}
std::streampos startidx = -1;
std::streampos endidx = -1;
if (spectrumToGet == int(getNrSpectra() - 1))
{
startidx = spectra_offsets_[spectrumToGet];
if (chromatograms_offsets_.empty() || !spectra_before_chroms_)
{
// just take everything until the index starts
endidx = index_offset_;
}
else
{
// just take everything until the chromatograms start
endidx = chromatograms_offsets_[0];
}
}
else
{
startidx = spectra_offsets_[spectrumToGet];
endidx = spectra_offsets_[spectrumToGet + 1];
}
std::streampos readl = endidx - startidx;
char* buffer = new char[readl + std::streampos(1)];
filestream_.seekg(startidx, filestream_.beg);
filestream_.read(buffer, readl);
buffer[readl] = '\0';
std::string text(buffer);
delete[] buffer;
#ifdef DEBUG_READER
// print the full text we just read
std::cout << text << std::endl;
#endif
return text;
}
OpenMS::Interfaces::SpectrumPtr IndexedMzMLHandler::getSpectrumById(int id)
{
OpenMS::Interfaces::SpectrumPtr sptr(new OpenMS::Interfaces::Spectrum);
std::string text = IndexedMzMLHandler::getSpectrumById_helper_(id);
MzMLSpectrumDecoder(skip_xml_checks_).domParseSpectrum(text, sptr);
return sptr;
}
const OpenMS::MSSpectrum IndexedMzMLHandler::getMSSpectrumById(int id)
{
OpenMS::MSSpectrum s;
getMSSpectrumById(id, s);
return s;
}
void IndexedMzMLHandler::getMSSpectrumByNativeId(const std::string& id, MSSpectrum& s)
{
if (spectra_native_ids_.find(id) == spectra_native_ids_.end())
{
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
String( "Could not find spectrum id " + String(id) ));
}
getMSSpectrumById(spectra_native_ids_[id], s);
}
void IndexedMzMLHandler::getMSSpectrumById(int id, MSSpectrum& s)
{
std::string text = IndexedMzMLHandler::getSpectrumById_helper_(id);
MzMLSpectrumDecoder(skip_xml_checks_).domParseSpectrum(text, s);
s.updateRanges();
}
OpenMS::Interfaces::ChromatogramPtr IndexedMzMLHandler::getChromatogramById(int id)
{
OpenMS::Interfaces::ChromatogramPtr cptr(new OpenMS::Interfaces::Chromatogram);
std::string text = IndexedMzMLHandler::getChromatogramById_helper_(id);
MzMLSpectrumDecoder(skip_xml_checks_).domParseChromatogram(text, cptr);
return cptr;
}
const OpenMS::MSChromatogram IndexedMzMLHandler::getMSChromatogramById(int id)
{
OpenMS::MSChromatogram c;
getMSChromatogramById(id, c);
c.updateRanges();
return c;
}
void IndexedMzMLHandler::getMSChromatogramByNativeId(const std::string& id, OpenMS::MSChromatogram& c)
{
auto it = chromatograms_native_ids_.find(id);
if (it == chromatograms_native_ids_.end())
{
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
String("Could not find chromatogram id ") + id );
}
getMSChromatogramById(it->second, c);
}
void IndexedMzMLHandler::getMSChromatogramById(int id, MSChromatogram& c)
{
std::string text = IndexedMzMLHandler::getChromatogramById_helper_(id);
MzMLSpectrumDecoder(skip_xml_checks_).domParseChromatogram(text, c);
c.updateRanges();
}
} //namespace OpenMS //namespace Internal
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/HANDLERS/MzMLSpectrumDecoder.cpp | .cpp | 25,460 | 623 | // 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/HANDLERS/MzMLSpectrumDecoder.h>
#include <OpenMS/FORMAT/HANDLERS/XMLHandler.h>
#include <xercesc/framework/MemBufInputSource.hpp>
#include <xercesc/parsers/XercesDOMParser.hpp>
#include <xercesc/dom/DOMText.hpp>
#include <xercesc/dom/DOMElement.hpp>
#include <xercesc/dom/DOMNodeList.hpp>
#include <memory>
namespace OpenMS
{
/// Small internal function to check the default data vectors
void checkData_(std::vector<Internal::MzMLHandlerHelper::BinaryData>& data,
SignedSize x_index, SignedSize int_index,
bool x_precision_64, bool int_precision_64)
{
// Error if intensity or m/z (RT) is encoded as int32|64 - they should be float32|64!
if ((!data[x_index].ints_32.empty()) || (!data[x_index].ints_64.empty()))
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"", "Encoding m/z or RT array as integer is not allowed!");
}
if ((!data[int_index].ints_32.empty()) || (!data[int_index].ints_64.empty()))
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"", "Encoding intensity array as integer is not allowed!");
}
Size mz_size = x_precision_64 ? data[x_index].floats_64.size() : data[x_index].floats_32.size();
Size int_size = int_precision_64 ? data[int_index].floats_64.size() : data[int_index].floats_32.size();
// Check if int-size and mz-size are equal
if (mz_size != int_size)
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"", "Error, intensity and m/z array length are unequal");
}
}
inline void fillDataArray(const std::vector<Internal::MzMLHandlerHelper::BinaryData>& data,
const OpenMS::Interfaces::BinaryDataArrayPtr& array, bool precision_64, SignedSize index)
{
// This seems to be the fastest method to move the data (faster than copy or assign)
if (precision_64)
{
array->data.insert(array->data.begin(), data[index].floats_64.begin(), data[index].floats_64.end());
}
else
{
array->data.insert(array->data.begin(), data[index].floats_32.begin(), data[index].floats_32.end());
}
}
template<class T>
inline void fillDataArrayFloat(const Internal::MzMLHandlerHelper::BinaryData& data, T& spectrum)
{
//create new array
spectrum.getFloatDataArrays().resize(spectrum.getFloatDataArrays().size() + 1);
//reserve space in the array
spectrum.getFloatDataArrays().back().reserve(data.size);
//copy meta info into MetaInfoDescription
spectrum.getFloatDataArrays().back().MetaInfoDescription::operator=(data.meta);
if (data.precision == Internal::MzMLHandlerHelper::BinaryData::PRE_64)
{
for (Size n = 0; n < data.floats_64.size(); n++)
{
double value = data.floats_64[n];
spectrum.getFloatDataArrays().back().push_back(value);
}
}
else
{
for (Size n = 0; n < data.floats_32.size(); n++)
{
double value = data.floats_32[n];
spectrum.getFloatDataArrays().back().push_back(value);
}
}
}
template<class T>
inline void fillDataArrayInt(const Internal::MzMLHandlerHelper::BinaryData& data, T& spectrum)
{
//create new array
spectrum.getIntegerDataArrays().resize(spectrum.getIntegerDataArrays().size() + 1);
//reserve space in the array
spectrum.getIntegerDataArrays().back().reserve(data.size);
//copy meta info into MetaInfoDescription
spectrum.getIntegerDataArrays().back().MetaInfoDescription::operator=(data.meta);
if (data.precision == Internal::MzMLHandlerHelper::BinaryData::PRE_64)
{
for (Size n = 0; n < data.ints_64.size(); n++)
{
double value = data.ints_64[n];
spectrum.getIntegerDataArrays().back().push_back(value);
}
}
else
{
for (Size n = 0; n < data.ints_32.size(); n++)
{
double value = data.ints_32[n];
spectrum.getIntegerDataArrays().back().push_back(value);
}
}
}
template<class T>
inline void fillDataArrayString(const Internal::MzMLHandlerHelper::BinaryData& data, T& spectrum)
{
//create new array
spectrum.getStringDataArrays().resize(spectrum.getStringDataArrays().size() + 1);
//reserve space in the array
spectrum.getStringDataArrays().back().reserve(data.decoded_char.size());
//copy meta info into MetaInfoDescription
spectrum.getStringDataArrays().back().MetaInfoDescription::operator=(data.meta);
if (data.precision == Internal::MzMLHandlerHelper::BinaryData::PRE_64)
{
for (Size n = 0; n < data.decoded_char.size(); n++)
{
String value = data.decoded_char[n];
spectrum.getStringDataArrays().back().push_back(value);
}
}
}
inline void fillDataArrays(const std::vector<Internal::MzMLHandlerHelper::BinaryData>& input_data, MSSpectrum& spectrum)
{
for (Size i = 0; i < input_data.size(); i++) //loop over all binary data arrays
{
if (input_data[i].meta.getName() != "m/z array" && input_data[i].meta.getName() != "intensity array") // is meta data array?
{
if (input_data[i].data_type == Internal::MzMLHandlerHelper::BinaryData::DT_FLOAT)
{
fillDataArrayFloat(input_data[i], spectrum);
}
else if (input_data[i].data_type == Internal::MzMLHandlerHelper::BinaryData::DT_INT)
{
fillDataArrayInt(input_data[i], spectrum);
}
else if (input_data[i].data_type == Internal::MzMLHandlerHelper::BinaryData::DT_STRING)
{
fillDataArrayString(input_data[i], spectrum);
}
}
}
}
inline void fillDataArrays(const std::vector<Internal::MzMLHandlerHelper::BinaryData>& input_data, MSChromatogram& spectrum)
{
for (Size i = 0; i < input_data.size(); i++) //loop over all binary data arrays
{
if (input_data[i].meta.getName() != "time array" && input_data[i].meta.getName() != "intensity array") // is meta data array?
{
if (input_data[i].data_type == Internal::MzMLHandlerHelper::BinaryData::DT_FLOAT)
{
fillDataArrayFloat(input_data[i], spectrum);
}
else if (input_data[i].data_type == Internal::MzMLHandlerHelper::BinaryData::DT_INT)
{
fillDataArrayInt(input_data[i], spectrum);
}
else if (input_data[i].data_type == Internal::MzMLHandlerHelper::BinaryData::DT_STRING)
{
fillDataArrayString(input_data[i], spectrum);
}
}
}
}
template<class T>
inline void fillDataArray(const std::vector<Internal::MzMLHandlerHelper::BinaryData>& data,
T& peak_container,
const bool x_precision_64,
const bool int_precision_64,
const SignedSize x_index,
const SignedSize int_index,
const Size default_array_length_)
{
typename T::PeakType tmp;
if (x_precision_64 && !int_precision_64)
{
std::vector< double >::const_iterator mz_it = data[x_index].floats_64.begin();
std::vector< float >::const_iterator int_it = data[int_index].floats_32.begin();
for (Size n = 0; n < default_array_length_; n++)
{
//add peak
tmp.setIntensity(*int_it);
tmp.setPos(*mz_it);
++mz_it;
++int_it;
peak_container.push_back(tmp);
}
}
else if (x_precision_64 && int_precision_64)
{
std::vector< double >::const_iterator mz_it = data[x_index].floats_64.begin();
std::vector< double >::const_iterator int_it = data[int_index].floats_64.begin();
for (Size n = 0; n < default_array_length_; n++)
{
//add peak
tmp.setIntensity(*int_it);
tmp.setPos(*mz_it);
++mz_it;
++int_it;
peak_container.push_back(tmp);
}
}
else if (!x_precision_64 && int_precision_64)
{
std::vector< float >::const_iterator mz_it = data[x_index].floats_32.begin();
std::vector< double >::const_iterator int_it = data[int_index].floats_64.begin();
for (Size n = 0; n < default_array_length_; n++)
{
//add peak
tmp.setIntensity(*int_it);
tmp.setPos(*mz_it);
++mz_it;
++int_it;
peak_container.push_back(tmp);
}
}
else if (!x_precision_64 && !int_precision_64)
{
std::vector< float >::const_iterator mz_it = data[x_index].floats_32.begin();
std::vector< float >::const_iterator int_it = data[int_index].floats_32.begin();
for (Size n = 0; n < default_array_length_; n++)
{
//add peak
tmp.setIntensity(*int_it);
tmp.setPos(*mz_it);
++mz_it;
++int_it;
peak_container.push_back(tmp);
}
}
}
void MzMLSpectrumDecoder::decodeBinaryDataMSSpectrum_(std::vector<BinaryData>& data, OpenMS::MSSpectrum& spectrum) const
{
Internal::MzMLHandlerHelper::decodeBase64Arrays(data, skip_xml_checks_);
//look up the precision and the index of the intensity and m/z array
bool x_precision_64 = true;
bool int_precision_64 = true;
SignedSize x_index = -1;
SignedSize int_index = -1;
Internal::MzMLHandlerHelper::computeDataProperties_(data, x_precision_64, x_index, "m/z array");
Internal::MzMLHandlerHelper::computeDataProperties_(data, int_precision_64, int_index, "intensity array");
//Abort if no m/z or intensity array is present
if (int_index == -1 || x_index == -1)
{
std::cerr << "Error, intensity or m/z array is missing, skipping this spectrum" << std::endl;
return;
}
checkData_(data, x_index, int_index, x_precision_64, int_precision_64);
// At this point, we could check whether the defaultArrayLength from the
// spectrum/chromatogram tag is equivalent to size of the decoded data
Size default_array_length_ = x_precision_64 ? data[x_index].floats_64.size() : data[x_index].floats_32.size();
spectrum.reserve(default_array_length_);
fillDataArray(data, spectrum,
x_precision_64, int_precision_64,
x_index, int_index, default_array_length_);
if (data.size() > 2)
{
fillDataArrays(data, spectrum);
}
}
void MzMLSpectrumDecoder::decodeBinaryDataMSChrom_(std::vector<BinaryData>& data, OpenMS::MSChromatogram& chromatogram) const
{
Internal::MzMLHandlerHelper::decodeBase64Arrays(data, skip_xml_checks_);
//look up the precision and the index of the intensity and m/z array
bool x_precision_64 = true;
bool int_precision_64 = true;
SignedSize x_index = -1;
SignedSize int_index = -1;
Internal::MzMLHandlerHelper::computeDataProperties_(data, x_precision_64, x_index, "time array");
Internal::MzMLHandlerHelper::computeDataProperties_(data, int_precision_64, int_index, "intensity array");
//Abort if no m/z or intensity array is present
if (int_index == -1 || x_index == -1)
{
std::cerr << "Error, intensity or RT array is missing, skipping this spectrum" << std::endl;
return;
}
checkData_(data, x_index, int_index, x_precision_64, int_precision_64);
// At this point, we could check whether the defaultArrayLength from the
// spectrum/chromatogram tag is equivalent to size of the decoded data
Size default_array_length_ = x_precision_64 ? data[x_index].floats_64.size() : data[x_index].floats_32.size();
chromatogram.reserve(default_array_length_);
fillDataArray(data, chromatogram,
x_precision_64, int_precision_64,
x_index, int_index, default_array_length_);
if (data.size() > 2)
{
fillDataArrays(data, chromatogram);
}
}
OpenMS::Interfaces::SpectrumPtr MzMLSpectrumDecoder::decodeBinaryDataSpectrum_(std::vector<BinaryData>& data) const
{
Internal::MzMLHandlerHelper::decodeBase64Arrays(data, skip_xml_checks_);
OpenMS::Interfaces::SpectrumPtr sptr(new OpenMS::Interfaces::Spectrum);
//look up the precision and the index of the intensity and m/z array
bool x_precision_64 = true;
bool int_precision_64 = true;
SignedSize x_index = -1;
SignedSize int_index = -1;
Internal::MzMLHandlerHelper::computeDataProperties_(data, x_precision_64, x_index, "m/z array");
Internal::MzMLHandlerHelper::computeDataProperties_(data, int_precision_64, int_index, "intensity array");
//Abort if no m/z or intensity array is present
if (int_index == -1 || x_index == -1)
{
std::cerr << "Error, intensity or m/z array is missing, skipping this spectrum" << std::endl;
return sptr;
}
checkData_(data, x_index, int_index, x_precision_64, int_precision_64);
// At this point, we could check whether the defaultArrayLength from the
// spectrum/chromatogram tag is equivalent to size of the decoded data
Size default_array_length_ = x_precision_64 ? data[x_index].floats_64.size() : data[x_index].floats_32.size();
// TODO: also handle non-default arrays
if (data.size() > 2)
{
std::cout << "MzMLSpectrumDecoder currently cannot handle meta data arrays, they are ignored." << std::endl;
}
// TODO: handle meta data from the binaryDataArray tag -> currently ignored
// since we have no place to store them
// TODO: would need to adopt OpenMS::Interfaces::SpectrumPtr to store additional arrays
OpenMS::Interfaces::BinaryDataArrayPtr intensity_array(new OpenMS::Interfaces::BinaryDataArray);
OpenMS::Interfaces::BinaryDataArrayPtr x_array(new OpenMS::Interfaces::BinaryDataArray);
x_array->data.reserve(default_array_length_);
intensity_array->data.reserve(default_array_length_);
fillDataArray(data, x_array, x_precision_64, x_index);
fillDataArray(data, intensity_array, int_precision_64, int_index);
// TODO the other arrays
sptr->setMZArray(x_array);
sptr->setIntensityArray(intensity_array);
return sptr;
}
OpenMS::Interfaces::ChromatogramPtr MzMLSpectrumDecoder::decodeBinaryDataChrom_(std::vector<BinaryData>& data) const
{
Internal::MzMLHandlerHelper::decodeBase64Arrays(data, skip_xml_checks_);
OpenMS::Interfaces::ChromatogramPtr sptr(new OpenMS::Interfaces::Chromatogram);
//look up the precision and the index of the intensity and m/z array
bool x_precision_64 = true;
bool int_precision_64 = true;
SignedSize x_index = -1;
SignedSize int_index = -1;
Internal::MzMLHandlerHelper::computeDataProperties_(data, x_precision_64, x_index, "time array");
Internal::MzMLHandlerHelper::computeDataProperties_(data, int_precision_64, int_index, "intensity array");
//Abort if no m/z or intensity array is present
if (int_index == -1 || x_index == -1)
{
std::cerr << "Error, intensity or RT array is missing, skipping this spectrum" << std::endl;
return sptr;
}
checkData_(data, x_index, int_index, x_precision_64, int_precision_64);
// At this point, we could check whether the defaultArrayLength from the
// spectrum/chromatogram tag is equivalent to size of the decoded data
Size default_array_length_ = x_precision_64 ? data[x_index].floats_64.size() : data[x_index].floats_32.size();
// TODO: also handle non-default arrays
if (data.size() > 2)
{
std::cout << "MzMLSpectrumDecoder currently cannot handle meta data arrays, they are ignored." << std::endl;
}
// TODO: handle meta data from the binaryDataArray tag -> currently ignored
// since we have no place to store them
OpenMS::Interfaces::BinaryDataArrayPtr intensity_array(new OpenMS::Interfaces::BinaryDataArray);
OpenMS::Interfaces::BinaryDataArrayPtr x_array(new OpenMS::Interfaces::BinaryDataArray);
x_array->data.reserve(default_array_length_);
intensity_array->data.reserve(default_array_length_);
fillDataArray(data, x_array, x_precision_64, x_index);
fillDataArray(data, intensity_array, int_precision_64, int_index);
// TODO the other arrays
sptr->setTimeArray(x_array);
sptr->setIntensityArray(intensity_array);
return sptr;
}
void MzMLSpectrumDecoder::handleBinaryDataArray_(xercesc::DOMNode* indexListNode, std::vector<BinaryData>& data)
{
// access result through data.back()
data.emplace_back();
// using CONST_XMLCH since writing a u16 char array each time is ugly. disadvantage = no constexpr.
// Uses only reinterpret_cast, so usually no runtime cost though.
static const XMLCh* TAG_CV = CONST_XMLCH("cvParam");
static const XMLCh* TAG_binary = CONST_XMLCH("binary");
static const XMLCh* TAG_userParam = CONST_XMLCH("userParam");
static const XMLCh* TAG_referenceableParamGroupRef = CONST_XMLCH("referenceableParamGroupRef");
static const XMLCh* TAG_accession = CONST_XMLCH("accession");
static const XMLCh* TAG_unit_accession = CONST_XMLCH("unitAccession");
static const XMLCh* TAG_value = CONST_XMLCH("value");
static const XMLCh* TAG_name = CONST_XMLCH("name");
OpenMS::Internal::StringManager sm;
// Iterate through binaryDataArray elements
// only allowed subelements:
// - referenceableParamGroupRef (0+)
// - cvParam (0+)
// - userParam (0+)
// - binary (1)
xercesc::DOMNodeList* index_elems = indexListNode->getChildNodes();
const XMLSize_t nodeCount_ = index_elems->getLength();
bool has_binary_tag = false;
for (XMLSize_t j = 0; j < nodeCount_; ++j)
{
xercesc::DOMNode* currentNode = index_elems->item(j);
if (currentNode->getNodeType() && // true is not NULL
currentNode->getNodeType() == xercesc::DOMNode::ELEMENT_NODE) // is element
{
xercesc::DOMElement* currentElement = dynamic_cast<xercesc::DOMElement*>(currentNode);
if (xercesc::XMLString::equals(currentElement->getTagName(), TAG_binary))
{
// Found the <binary> tag
has_binary_tag = true;
// Skip any empty <binary></binary> tags
if (!currentNode->hasChildNodes())
{
continue;
}
// Valid mzML does not have any other child nodes except text
if (currentNode->getChildNodes()->getLength() != 1)
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"", "Invalid XML: 'binary' element can only have a single, text node child element.");
}
// Now we know that the <binary> node has exactly one single child node, the text that we want!
xercesc::DOMNode* textNode_ = currentNode->getFirstChild();
if (textNode_->getNodeType() == xercesc::DOMNode::TEXT_NODE)
{
xercesc::DOMText* textNode (static_cast<xercesc::DOMText*> (textNode_));
sm.appendASCII(textNode->getData(),
textNode->getLength(), data.back().base64);
}
else
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"", "Invalid XML: 'binary' element can only have a single, text node child element.");
}
}
else if (xercesc::XMLString::equals(currentElement->getTagName(), TAG_CV))
{
std::string accession = sm.convert(currentElement->getAttribute(TAG_accession));
std::string value = sm.convert(currentElement->getAttribute(TAG_value));
std::string name = sm.convert(currentElement->getAttribute(TAG_name));
std::string unit_accession = sm.convert(currentElement->getAttribute(TAG_unit_accession));
// set precision, data_type
Internal::MzMLHandlerHelper::handleBinaryDataArrayCVParam(data, accession, value, name, unit_accession);
}
else if (xercesc::XMLString::equals(currentElement->getTagName(), TAG_userParam))
{
std::cout << " unhandled userParam" << std::endl;
}
else if (xercesc::XMLString::equals(currentElement->getTagName(), TAG_referenceableParamGroupRef))
{
std::cout << " unhandled referenceableParamGroupRef" << std::endl;
}
else
{
//std::cout << "unhandled" << (string)xercesc::XMLString::transcode(currentNode->getNodeName() << std::endl;
}
}
}
// Throw exception upon invalid mzML: the <binary> tag is required inside <binaryDataArray>
if (!has_binary_tag)
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"", "Invalid XML: 'binary' element needs to be present at least once inside 'binaryDataArray' element.");
}
}
std::string MzMLSpectrumDecoder::domParseString_(const std::string& in, std::vector<BinaryData>& data)
{
// PRECONDITON is below (since we first need to do XML parsing before validating)
// initializer list of XMLCh (= usually some type that fits utf16) from ASCII chars
static constexpr XMLCh id_tag[] = {'i','d', 0};
static constexpr XMLCh default_array_length_tag[] = { 'd','e','f','a','u','l','t','A','r','r','a','y','L','e','n','g','t','h', 0};
static constexpr XMLCh binary_data_array_tag[] = { 'b','i','n','a','r','y','D','a','t','a','A','r','r','a','y', 0};
//-------------------------------------------------------------
// Create parser from input string using MemBufInputSource
//-------------------------------------------------------------
xercesc::MemBufInputSource myxml_buf(reinterpret_cast<const unsigned char*>(in.c_str()), in.length(), "myxml (in memory)");
std::unique_ptr<xercesc::XercesDOMParser> parser = std::make_unique<xercesc::XercesDOMParser>(); // make sure it is deleted even in case of exceptions
parser->setDoNamespaces(false);
parser->setDoSchema(false);
parser->setLoadExternalDTD(false);
parser->parse(myxml_buf);
//-------------------------------------------------------------
// Start parsing
// see http://www.yolinux.com/TUTORIALS/XML-Xerces-C.html
//-------------------------------------------------------------
// no need to free this pointer - owned by the parent parser object
xercesc::DOMDocument* doc = parser->getDocument();
// Get the top-level element (needs to be <spectrum> or <chromatogram>)
xercesc::DOMElement* elementRoot = doc->getDocumentElement();
if (!elementRoot)
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, in, "No root element");
}
OPENMS_PRECONDITION(xercesc::XMLString::equals(elementRoot->getTagName(), CONST_XMLCH("spectrum")) || xercesc::XMLString::equals(elementRoot->getTagName(), CONST_XMLCH("chromatogram")),
(String("The input needs to contain a <spectrum> or <chromatogram> tag as root element. Got instead '") +
String(Internal::unique_xerces_ptr(xercesc::XMLString::transcode(elementRoot->getTagName())).get()) + String("'.")).c_str())
// defaultArrayLength is a required attribute for the spectrum and the
// chromatogram tag (but still check for it first to be safe).
if (elementRoot->getAttributeNode(default_array_length_tag) == nullptr)
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
in, "Root element does not contain defaultArrayLength XML tag.");
}
int default_array_length = xercesc::XMLString::parseInt(elementRoot->getAttribute(default_array_length_tag));
OpenMS::Internal::StringManager sm;
std::string id = sm.convert(elementRoot->getAttribute(id_tag));
// Extract the binaryDataArray elements (there may be multiple) and process them
xercesc::DOMNodeList* li = elementRoot->getElementsByTagName(binary_data_array_tag);
for (Size i = 0; i < li->getLength(); i++)
{
// Will append one single BinaryData object to data
handleBinaryDataArray_(li->item(i), data);
// Set the size correctly (otherwise MzMLHandlerHelper complains).
data.back().size = default_array_length;
}
return id;
}
void MzMLSpectrumDecoder::domParseSpectrum(const std::string& in, OpenMS::Interfaces::SpectrumPtr& sptr)
{
std::vector<BinaryData> data;
domParseString_(in, data);
sptr = decodeBinaryDataSpectrum_(data);
}
void MzMLSpectrumDecoder::domParseSpectrum(const std::string& in, MSSpectrum& s)
{
std::vector<BinaryData> data;
std::string id = domParseString_(in, data);
decodeBinaryDataMSSpectrum_(data, s);
s.setNativeID(id);
}
void MzMLSpectrumDecoder::domParseChromatogram(const std::string& in, MSChromatogram& c)
{
std::vector<BinaryData> data;
std::string id = domParseString_(in, data);
decodeBinaryDataMSChrom_(data, c);
c.setNativeID(id);
}
void MzMLSpectrumDecoder::domParseChromatogram(const std::string& in, OpenMS::Interfaces::ChromatogramPtr& sptr)
{
std::vector<BinaryData> data;
domParseString_(in, data);
sptr = decodeBinaryDataChrom_(data);
}
void MzMLSpectrumDecoder::setSkipXMLChecks(bool skip)
{
skip_xml_checks_ = skip;
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/HANDLERS/MzIdentMLDOMHandler.cpp | .cpp | 150,000 | 3,022 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Eugen Netz $
// $Authors: Mathias Walzer, Eugen Netz $
// --------------------------------------------------------------------------
#include <OpenMS/FORMAT/HANDLERS/MzIdentMLDOMHandler.h>
#include <OpenMS/FORMAT/HANDLERS/XMLHandler.h>
#include <OpenMS/SYSTEM/File.h>
#include <OpenMS/CHEMISTRY/ModificationsDB.h>
#include <OpenMS/CHEMISTRY/ResidueDB.h>
#include <OpenMS/CHEMISTRY/ProteaseDB.h>
#include <OpenMS/ANALYSIS/XLMS/OPXLHelper.h>
#include <OpenMS/CONCEPT/Constants.h>
#include <boost/lexical_cast.hpp>
#include <sys/stat.h>
#include <cerrno>
using namespace std;
using namespace xercesc;
namespace OpenMS::Internal
{
//TODO remodel CVTermList
//TODO extend CVTermlist with CVCollection functionality for complete replacement??
//TODO general id openms struct for overall parameter for one id run
MzIdentMLDOMHandler::MzIdentMLDOMHandler(const vector<ProteinIdentification>& pro_id, const PeptideIdentificationList& pep_id, const String& version, const ProgressLogger& logger) :
logger_(logger),
cv_(ControlledVocabulary::getPSIMSCV()),
//~ ms_exp_(0),
cpro_id_(&pro_id),
cpep_id_(&pep_id),
schema_version_(version),
mzid_parser_()
{
unimod_.loadFromOBO("UNIMOD", File::find("/CV/unimod.obo"));
try
{
XMLPlatformUtils::Initialize(); // Initialize Xerces infrastructure
}
catch (XMLException& e)
{
char* message = XMLString::transcode(e.getMessage());
OPENMS_LOG_ERROR << "XML toolkit initialization error: " << message << endl;
XMLString::release(&message);
// throw exception here to return ERROR_XERCES_INIT
}
// Tags and attributes used in XML file.
// Can't call transcode till after Xerces Initialize()
xml_root_tag_ptr_ = XMLString::transcode("MzIdentML");
xml_cvparam_tag_ptr_ = XMLString::transcode("cvParam");
xml_name_attr_ptr_ = XMLString::transcode("option_a");
}
MzIdentMLDOMHandler::MzIdentMLDOMHandler(vector<ProteinIdentification>& pro_id, PeptideIdentificationList& pep_id, const String& version, const ProgressLogger& logger) :
logger_(logger),
cv_(ControlledVocabulary::getPSIMSCV()),
//~ ms_exp_(0),
pro_id_(&pro_id),
pep_id_(&pep_id),
schema_version_(version),
mzid_parser_(),
xl_ms_search_(false)
{
unimod_.loadFromOBO("UNIMOD", File::find("/CV/unimod.obo"));
try
{
XMLPlatformUtils::Initialize(); // Initialize Xerces infrastructure
}
catch (XMLException& e)
{
char* message = XMLString::transcode(e.getMessage());
OPENMS_LOG_ERROR << "XML toolkit initialization error: " << message << endl;
XMLString::release(&message);
}
// Tags and attributes used in XML file.
// Can't call transcode till after Xerces Initialize()
xml_root_tag_ptr_ = XMLString::transcode("MzIdentML");
xml_cvparam_tag_ptr_ = XMLString::transcode("cvParam");
xml_name_attr_ptr_ = XMLString::transcode("name");
}
/*
* Class destructor frees memory used to hold the XML tag and
* attribute definitions. It also terminates use of the xerces-C
* framework.
*/
MzIdentMLDOMHandler::~MzIdentMLDOMHandler()
{
try
{
XMLString::release(&xml_root_tag_ptr_);
XMLString::release(&xml_cvparam_tag_ptr_);
XMLString::release(&xml_name_attr_ptr_);
// if(m_name) XMLString::release( &m_name ); //releasing you here is releasing you twice, dunno yet why?!
}
catch (...)
{
OPENMS_LOG_ERROR << "Unknown exception encountered in 'TagNames' destructor" << endl;
}
// Terminate Xerces
try
{
XMLPlatformUtils::Terminate(); // Terminate after release of memory
}
catch (xercesc::XMLException& e)
{
char* message = xercesc::XMLString::transcode(e.getMessage());
OPENMS_LOG_ERROR << "XML toolkit teardown error: " << message << endl;
XMLString::release(&message);
}
}
/*
* reads a mzid file into handlers pro_id_ & pep_id_ members
*/
void MzIdentMLDOMHandler::readMzIdentMLFile(const std::string& mzid_file)
{
// Test to see if the file is ok.
struct stat fileStatus;
xml_handler_ = make_unique<XMLHandler>(mzid_file, schema_version_);
errno = 0;
if (stat(mzid_file.c_str(), &fileStatus) == -1) // ==0 ok; ==-1 error
{
if (errno == ENOENT) // errno declared by include file errno.h
{
throw (runtime_error("Path file_name does not exist, or path is an empty string."));
}
else if (errno == ENOTDIR)
{
throw (runtime_error("A component of the path is not a directory."));
}
// On MSVC 2008, the ELOOP constant is not declared and thus introduces a compile error
//else if (errno == ELOOP)
// throw (runtime_error("Too many symbolic links encountered while traversing the path."));
else if (errno == EACCES)
{
throw (runtime_error("Permission denied."));
}
else if (errno == ENAMETOOLONG)
{
throw (runtime_error("File can not be read."));
}
}
// Configure DOM parser.
mzid_parser_.setValidationScheme(XercesDOMParser::Val_Never);
mzid_parser_.setDoNamespaces(false);
mzid_parser_.setDoSchema(false);
mzid_parser_.setLoadExternalDTD(false);
try
{
mzid_parser_.parse(mzid_file.c_str());
}
catch (xercesc::XMLException& e)
{
char* message = xercesc::XMLString::transcode(e.getMessage());
// ostringstream errBuf;
// errBuf << "Error parsing file: " << message << flush;
OPENMS_LOG_ERROR << "XERCES error parsing file: " << message << flush << endl;
XMLString::release(&message);
}
// we adopt/own the document so we can free it in case this DOMHandler is reused on another file.
xercesc::DOMDocument* xmlDoc = mzid_parser_.adoptDocument();
try
{
// Catch special case: Cross-Linking MS
DOMNodeList* additionalSearchParams = xmlDoc->getElementsByTagName(CONST_XMLCH("AdditionalSearchParams"));
const XMLSize_t as_node_count = additionalSearchParams->getLength();
for (XMLSize_t i = 0; i < as_node_count; ++i)
{
DOMNode* current_sp = additionalSearchParams->item(i);
DOMElement* element_SearchParams = dynamic_cast<xercesc::DOMElement*>(current_sp);
String cross_linking_search = StringManager::convert(element_SearchParams->getAttribute(CONST_XMLCH("id")));
DOMElement* child = element_SearchParams->getFirstElementChild();
while (child && !xl_ms_search_)
{
String accession = StringManager::convert(child->getAttribute(CONST_XMLCH("accession")));
if (accession == "MS:1002494") // accession for "crosslinking search"
{
xl_ms_search_ = true;
}
child = child->getNextElementSibling();
}
}
if (xl_ms_search_)
{
OPENMS_LOG_DEBUG << "Reading a Cross-Linking MS file." << endl;
}
// 0. AnalysisSoftwareList {0,1}
DOMNodeList* analysisSoftwareElements = xmlDoc->getElementsByTagName(CONST_XMLCH("AnalysisSoftware"));
parseAnalysisSoftwareList_(analysisSoftwareElements);
// 1. DataCollection {1,1}
DOMNodeList* spectraDataElements = xmlDoc->getElementsByTagName(CONST_XMLCH("SpectraData"));
if (spectraDataElements->getLength() == 0)
{
throw(runtime_error("No SpectraData nodes"));
}
parseInputElements_(spectraDataElements);
// 1.2. SearchDatabase {0,unbounded}
DOMNodeList* searchDatabaseElements = xmlDoc->getElementsByTagName(CONST_XMLCH("SearchDatabase"));
parseInputElements_(searchDatabaseElements);
// 1.1 SourceFile {0,unbounded}
DOMNodeList* sourceFileElements = xmlDoc->getElementsByTagName(CONST_XMLCH("SourceFile"));
parseInputElements_(sourceFileElements);
// 2. SpectrumIdentification {1,unbounded} ! creates identification runs (or ProteinIdentifications)
DOMNodeList* spectrumIdentificationElements = xmlDoc->getElementsByTagName(CONST_XMLCH("SpectrumIdentification"));
if (spectrumIdentificationElements->getLength() == 0)
{
throw(runtime_error("No SpectrumIdentification nodes"));
}
parseSpectrumIdentificationElements_(spectrumIdentificationElements);
// 3. AnalysisProtocolCollection {1,1} SpectrumIdentificationProtocol {1,unbounded} ! identification run parameters
DOMNodeList* spectrumIdentificationProtocolElements = xmlDoc->getElementsByTagName(CONST_XMLCH("SpectrumIdentificationProtocol"));
if (spectrumIdentificationProtocolElements->getLength() == 0)
{
throw(runtime_error("No SpectrumIdentificationProtocol nodes"));
}
parseSpectrumIdentificationProtocolElements_(spectrumIdentificationProtocolElements);
// 4. SequenceCollection nodes {0,1} DBSequenceElement {1,unbounded} Peptide {0,unbounded} PeptideEvidence {0,unbounded}
DOMNodeList* dbSequenceElements = xmlDoc->getElementsByTagName(CONST_XMLCH("DBSequence"));
parseDBSequenceElements_(dbSequenceElements);
DOMNodeList* peptideElements = xmlDoc->getElementsByTagName(CONST_XMLCH("Peptide"));
parsePeptideElements_(peptideElements);
DOMNodeList* peptideEvidenceElements = xmlDoc->getElementsByTagName(CONST_XMLCH("PeptideEvidence"));
parsePeptideEvidenceElements_(peptideEvidenceElements);
// mzid_parser_.resetDocumentPool(); //segfault prone: do not use!
// 5. AnalysisSampleCollection ??? contact stuff
// 6. AnalysisCollection {1,1} - build final structures PeptideIdentification (and hits)
// 6.1 SpectrumIdentificationList {0,1}
DOMNodeList* spectrumIdentificationListElements = xmlDoc->getElementsByTagName(CONST_XMLCH("SpectrumIdentificationList"));
if (spectrumIdentificationListElements->getLength() == 0)
{
throw(runtime_error("No SpectrumIdentificationList nodes"));
}
parseSpectrumIdentificationListElements_(spectrumIdentificationListElements);
// 6.2 ProteinDetection {0,1}
DOMNodeList* parseProteinDetectionListElements = xmlDoc->getElementsByTagName(CONST_XMLCH("ProteinDetectionList"));
parseProteinDetectionListElements_(parseProteinDetectionListElements);
for (vector<ProteinIdentification>::iterator it = pro_id_->begin(); it != pro_id_->end(); ++it)
{
it->sort();
}
//note: PeptideIdentification sorting here not necessary any more, due to sorting according to cv in SpectrumIdentificationResult
}
catch (xercesc::XMLException& e)
{
char* message = xercesc::XMLString::transcode(e.getMessage());
// ostringstream errBuf;
// errBuf << "Error parsing file: " << message << flush;
OPENMS_LOG_ERROR << "XERCES error traversing DOM: " << message << flush << endl;
XMLString::release(&message);
}
xmlDoc->release();
if (xl_ms_search_)
{
OPXLHelper::addProteinPositionMetaValues(*this->pep_id_);
OPXLHelper::addBetaAccessions(*this->pep_id_);
OPXLHelper::addXLTargetDecoyMV(*this->pep_id_);
OPXLHelper::removeBetaPeptideHits(*this->pep_id_);
OPXLHelper::computeDeltaScores(*this->pep_id_);
OPXLHelper::addPercolatorFeatureList((*this->pro_id_)[0]);
}
}
void MzIdentMLDOMHandler::writeMzIdentMLFile(const std::string& mzid_file)
{
xml_handler_ = make_unique<XMLHandler>(mzid_file, schema_version_);
DOMImplementation* impl = DOMImplementationRegistry::getDOMImplementation(CONST_XMLCH("XML 1.0")); //XML 3?!
if (impl != nullptr)
{
try
{
xercesc::DOMDocument* xmlDoc = impl->createDocument(
CONST_XMLCH("http://psidev.info/psi/pi/mzIdentML/1.1"),
CONST_XMLCH("MzIdentML"), // root element name
nullptr); // document type object (DTD).
DOMElement* rootElem = xmlDoc->getDocumentElement();
rootElem->setAttribute(CONST_XMLCH("version"),
StringManager::convertPtr(schema_version_).get());
rootElem->setAttribute(CONST_XMLCH("xsi:schemaLocation"),
CONST_XMLCH("http://psidev.info/psi/pi/mzIdentML/1.1 ../../schema/mzIdentML1.1.0.xsd"));
rootElem->setAttribute(CONST_XMLCH("creationDate"),
StringManager::convertPtr(String(DateTime::now().getDate() + "T" + DateTime::now().getTime())).get());
// * cvList *
DOMElement* cvl_p = xmlDoc->createElement(CONST_XMLCH("cvList")); // TODO add generically
buildCvList_(cvl_p);
rootElem->appendChild(cvl_p);
// * AnalysisSoftwareList *
DOMElement* asl_p = xmlDoc->createElement(CONST_XMLCH("AnalysisSoftwareList"));
for (vector<ProteinIdentification>::const_iterator pi = cpro_id_->begin(); pi != cpro_id_->end(); ++pi)
{
// search_engine_version_ = pi->getSearchEngineVersion();
// search_engine_ = pi->getSearchEngine();
}
buildAnalysisSoftwareList_(asl_p);
rootElem->appendChild(asl_p);
// // * AnalysisSampleCollection *
// DOMElement* asc_p = xmlDoc->createElement(CONST_XMLCH("AnalysisSampleCollection"));
// buildAnalysisSampleCollection_(asc_p);
// rootElem->appendChild(asc_p);
// * SequenceCollection *
DOMElement* sc_p = xmlDoc->createElement(CONST_XMLCH("SequenceCollection"));
for (vector<ProteinIdentification>::const_iterator pi = cpro_id_->begin(); pi != cpro_id_->end(); ++pi)
{
String dbref = pi->getSearchParameters().db + pi->getSearchParameters().db_version + pi->getSearchParameters().taxonomy; //TODO @mths : this needs to be more unique, btw add tax etc. as cv to DBSequence
for (vector<ProteinHit>::const_iterator ph = pi->getHits().begin(); ph != pi->getHits().end(); ++ph)
{
CVTermList cvs;
DBSequence temp_struct = {ph->getSequence(), dbref, ph->getAccession(), cvs};
db_sq_map_.insert(make_pair(ph->getAccession(), temp_struct));
}
}
set<AASequence> pepset;
for (PeptideIdentificationList::const_iterator pi = cpep_id_->begin(); pi != cpep_id_->end(); ++pi)
{
for (vector<PeptideHit>::const_iterator ph = pi->getHits().begin(); ph != pi->getHits().end(); ++ph)
{
list<String> pepevs;
for (vector<OpenMS::PeptideEvidence>::const_iterator pev = ph->getPeptideEvidences().begin(); pev != ph->getPeptideEvidences().end(); ++pev)
{
String pepevref = String("OpenMS") + String(UniqueIdGenerator::getUniqueId());
pv_db_map_.insert(make_pair(pepevref, pev->getProteinAccession()));
pepevs.push_back(pepevref);
bool idec = (String(ph->getMetaValue(Constants::UserParam::TARGET_DECOY))).hasSubstring("decoy");
PeptideEvidence temp_struct = {pev->getStart(), pev->getEnd(), pev->getAABefore(), pev->getAAAfter(), idec}; //TODO @ mths : completely switch to PeptideEvidence
pe_ev_map_.insert(make_pair(pepevref, temp_struct)); // TODO @ mths : double check start & end & chars for before & after
}
hit_pev_.push_back(pepevs);
String pepref = String("OpenMS") + String(UniqueIdGenerator::getUniqueId());
if (pepset.find(ph->getSequence()) != pepset.end())
{
pepset.insert(ph->getSequence());
pep_map_.insert(make_pair(pepref, ph->getSequence()));
for (list<String>::iterator pepevref = pepevs.begin(); pepevref != pepevs.end(); ++pepevref)
{
p_pv_map_.insert(make_pair(*pepevref, pepref));
}
}
}
}
buildSequenceCollection_(sc_p);
rootElem->appendChild(sc_p);
// * AnalysisCollection *
DOMElement* analysis_c_p = xmlDoc->createElement(CONST_XMLCH("AnalysisCollection"));
buildAnalysisCollection_(analysis_c_p);
rootElem->appendChild(analysis_c_p);
// * AnalysisProtocolCollection *
DOMElement* apc_p = xmlDoc->createElement(CONST_XMLCH("AnalysisProtocolCollection"));
buildAnalysisCollection_(apc_p);
rootElem->appendChild(apc_p);
// * DataCollection *
DOMElement* dc_p = xmlDoc->createElement(CONST_XMLCH("DataCollection"));
rootElem->appendChild(dc_p);
DOMElement* in_p = dc_p->getOwnerDocument()->createElement(CONST_XMLCH("Inputs"));
DOMElement* ad_p = dc_p->getOwnerDocument()->createElement(CONST_XMLCH("AnalysisData"));
dc_p->appendChild(in_p);
dc_p->appendChild(ad_p);
// * BibliographicReference *
DOMElement* br_p = xmlDoc->createElement(CONST_XMLCH("BibliographicReference"));
br_p->setAttribute(CONST_XMLCH("authors"), CONST_XMLCH("all"));
rootElem->appendChild(br_p);
// * Serialisation *
DOMLSSerializer* serializer = ((DOMImplementationLS*)impl)->createLSSerializer();
// serializer gets prettyprint and stuff
if (serializer->getDomConfig()->canSetParameter(XMLUni::fgDOMWRTDiscardDefaultContent, true))
{
serializer->getDomConfig()->setParameter(XMLUni::fgDOMWRTDiscardDefaultContent, true);
}
if (serializer->getDomConfig()->canSetParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true))
{
serializer->getDomConfig()->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true);
}
// // optionally implement DOMErrorHandler (e.g. MyDOMErrorHandler) and set it to the serializer
// DOMErrorHandler* errHandler = new myDOMErrorHandler();
// serializer->getDomConfig()->setParameter(XMLUni::fgDOMErrorHandler, myErrorHandler);
XMLFormatTarget* file_target = new LocalFileFormatTarget(mzid_file.c_str());
DOMLSOutput* dom_output = ((DOMImplementationLS*)impl)->createLSOutput();
dom_output->setByteStream(file_target);
try
{
// do the serialization through DOMLSSerializer::write();
serializer->write(xmlDoc, dom_output);
}
catch (const XMLException& toCatch)
{
char* message = XMLString::transcode(toCatch.getMessage());
OPENMS_LOG_ERROR << "Serialisation exception: \n"
<< message << "\n";
XMLString::release(&message);
}
catch (const DOMException& toCatch)
{
char* message = XMLString::transcode(toCatch.msg);
OPENMS_LOG_ERROR << "Serialisation exception: \n"
<< message << "\n";
XMLString::release(&message);
}
catch (...)
{
OPENMS_LOG_ERROR << "Unexpected exception building the document tree." << endl;
}
dom_output->release();
serializer->release();
// delete myErrorHandler;
delete file_target;
}
catch (const OutOfMemoryException&)
{
OPENMS_LOG_ERROR << "Xerces OutOfMemoryException" << endl;
}
catch (const DOMException& e)
{
OPENMS_LOG_ERROR << "DOMException code is: " << e.code << endl;
}
catch (const exception& e)
{
OPENMS_LOG_ERROR << "An error occurred creating the document: " << e.what() << endl;
}
} // (inpl != NULL)
else
{
OPENMS_LOG_ERROR << "Requested DOM implementation is not supported" << endl;
}
}
pair<CVTermList, map<String, DataValue> > MzIdentMLDOMHandler::parseParamGroup_(DOMNodeList* paramGroup)
{
CVTermList ret_cv; // cvParam
map<String, DataValue> ret_up; // userParam
const XMLSize_t cv_node_count = paramGroup->getLength();
for (XMLSize_t cvi = 0; cvi < cv_node_count; ++cvi)
{
DOMNode* current_cv = paramGroup->item(cvi);
if (current_cv->getNodeType() && // true is not NULL
current_cv->getNodeType() == DOMNode::ELEMENT_NODE) // is element - possibly not necessary after getElementsByTagName
{
DOMElement* element_param = dynamic_cast<xercesc::DOMElement*>(current_cv);
if (XMLString::equals(element_param->getTagName(), CONST_XMLCH("cvParam")))
{
ret_cv.addCVTerm(parseCvParam_(element_param));
}
else if (XMLString::equals(element_param->getTagName(), CONST_XMLCH("userParam")))
{
ret_up.insert(parseUserParam_(element_param));
}
else if (XMLString::equals(element_param->getTagName(), CONST_XMLCH("PeptideEvidence"))
|| XMLString::equals(element_param->getTagName(), CONST_XMLCH("PeptideEvidenceRef"))
|| XMLString::equals(element_param->getTagName(), CONST_XMLCH("Fragmentation"))
|| XMLString::equals(element_param->getTagName(), CONST_XMLCH("SpectrumIdentificationItem")))
{
//here it's okay to do nothing
}
else
{
OPENMS_LOG_WARN << "Misplaced elements ignored in 'ParamGroup' in " << StringManager::convert(element_param->getTagName()) << endl;
}
}
}
return make_pair(ret_cv, ret_up);
}
CVTerm MzIdentMLDOMHandler::parseCvParam_(DOMElement* param)
{
if (param)
{
// <cvParam accession="MS:1001469" name="taxonomy: scientific name" cvRef="PSI-MS" value="Drosophila melanogaster"/>
String accession = StringManager::convert(param->getAttribute(CONST_XMLCH("accession")));
String name = StringManager::convert(param->getAttribute(CONST_XMLCH("name")));
String cvRef = StringManager::convert(param->getAttribute(CONST_XMLCH("cvRef")));
String value = StringManager::convert(param->getAttribute(CONST_XMLCH("value")));
String unitAcc = StringManager::convert(param->getAttribute(CONST_XMLCH("unitAccession")));
String unitName = StringManager::convert(param->getAttribute(CONST_XMLCH("unitName")));
String unitCvRef = StringManager::convert(param->getAttribute(CONST_XMLCH("unitCvRef")));
CVTerm::Unit u; // TODO @mths : make DataValue usage safe!
if (!unitAcc.empty() && !unitName.empty())
{
u = CVTerm::Unit(unitAcc, unitName, unitCvRef);
if (unitCvRef.empty())
{
OPENMS_LOG_WARN << "This mzid file uses a cv term with units, but without "
<< "unit cv reference (required)! Please notify the mzid "
<< "producer of this file. \"" << name << "\" will be read as \""
<< unitName << "\" but further actions on this unit may fail."
<< endl;
}
}
return CVTerm(accession, name, cvRef, value, u);
}
else
throw invalid_argument("no cv param here");
}
pair<String, DataValue> MzIdentMLDOMHandler::parseUserParam_(DOMElement* param)
{
if (param)
{
// <userParam name="Mascot User Comment" value="Example Mascot MS-MS search for PSI mzIdentML"/>
String name = StringManager::convert(param->getAttribute(CONST_XMLCH("name")));
String value = StringManager::convert(param->getAttribute(CONST_XMLCH("value")));
bool has_value = param->hasAttribute(CONST_XMLCH("value"));
String unitAcc = StringManager::convert(param->getAttribute(CONST_XMLCH("unitAccession")));
String unitName = StringManager::convert(param->getAttribute(CONST_XMLCH("unitName")));
String unitCvRef = StringManager::convert(param->getAttribute(CONST_XMLCH("unitCvRef")));
String type = StringManager::convert(param->getAttribute(CONST_XMLCH("type")));
DataValue dv = DataValue::EMPTY;
if (has_value)
{
dv = XMLHandler::fromXSDString(type, value);
}
// Add unit *after* creating the term
if (!unitAcc.empty())
{
if (unitAcc.hasPrefix("UO:"))
{
dv.setUnit(unitAcc.suffix(unitAcc.size() - 3).toInt());
dv.setUnitType(DataValue::UnitType::UNIT_ONTOLOGY);
}
else if (unitAcc.hasPrefix("MS:"))
{
dv.setUnit(unitAcc.suffix(unitAcc.size() - 3).toInt());
dv.setUnitType(DataValue::UnitType::MS_ONTOLOGY);
}
else
{
OPENMS_LOG_WARN << String("Unhandled unit '") + unitAcc + "' in tag '" + name + "'." << endl;
}
}
return make_pair(name, dv);
}
else
{
OPENMS_LOG_ERROR << "No parameters found at given position." << endl;
throw invalid_argument("no user param here");
}
}
void MzIdentMLDOMHandler::parseAnalysisSoftwareList_(DOMNodeList* analysisSoftwareElements)
{
const XMLSize_t as_node_count = analysisSoftwareElements->getLength();
for (XMLSize_t swni = 0; swni < as_node_count; ++swni)
{
DOMNode* current_as = analysisSoftwareElements->item(swni);
if (current_as->getNodeType() && // true is not NULL
current_as->getNodeType() == DOMNode::ELEMENT_NODE) // is element - possibly not necessary after getElementsByTagName
{
// Found element node: re-cast as element
DOMElement* element_AnalysisSoftware = dynamic_cast<xercesc::DOMElement*>(current_as);
String id = StringManager::convert(element_AnalysisSoftware->getAttribute(CONST_XMLCH("id")));
DOMElement* child = element_AnalysisSoftware->getFirstElementChild();
String swname, swversion;
while (child)
{
if (XMLString::equals(child->getTagName(),CONST_XMLCH("SoftwareName"))) //must have exactly one SoftwareName
{
DOMNodeList* element_pg = child->getChildNodes();
pair<CVTermList, map<String, DataValue> > swn = parseParamGroup_(element_pg);
swversion = StringManager::convert(element_AnalysisSoftware->getAttribute(CONST_XMLCH("version")));
if (!swn.first.getCVTerms().empty())
{
set<String> software_terms;
cv_.getAllChildTerms(software_terms, "MS:1000531");
for (map<String, vector<CVTerm> >::const_iterator it = swn.first.getCVTerms().begin(); it != swn.first.getCVTerms().end(); ++it)
{
if (software_terms.find(it->first) != software_terms.end())
{
swname = it->second.front().getName();
break;
}
}
}
else if (!swn.second.empty())
{
for (map<String, DataValue>::const_iterator up = swn.second.begin(); up != swn.second.end(); ++up)
{
if (up->first.hasSubstring("name"))
{
swname = up->second.toString();
break;
}
else
{
swname = up->first;
}
}
}
}
child = child->getNextElementSibling();
}
if (!swname.empty() && !swversion.empty())
{
AnalysisSoftware temp_struct = {swname, swversion};
as_map_.insert(make_pair(id, temp_struct));
}
else
{
OPENMS_LOG_ERROR << "No name/version found for 'AnalysisSoftware':" << id << "." << endl;
}
}
}
}
void MzIdentMLDOMHandler::parseDBSequenceElements_(DOMNodeList* dbSequenceElements)
{
const XMLSize_t dbs_node_count = dbSequenceElements->getLength();
for (XMLSize_t c = 0; c < dbs_node_count; ++c)
{
DOMNode* current_dbs = dbSequenceElements->item(c);
if (current_dbs->getNodeType() && // true is not NULL
current_dbs->getNodeType() == DOMNode::ELEMENT_NODE) // is element - possibly not necessary after getElementsByTagName
{
// Found element node: re-cast as element
DOMElement* element_dbs = dynamic_cast<xercesc::DOMElement*>(current_dbs);
String id = StringManager::convert(element_dbs->getAttribute(CONST_XMLCH("id")));
String seq = "";
String dbref = StringManager::convert(element_dbs->getAttribute(CONST_XMLCH("searchDatabase_ref")));
String acc = StringManager::convert(element_dbs->getAttribute(CONST_XMLCH("accession")));
CVTermList cvs;
DOMElement* child = element_dbs->getFirstElementChild();
while (child)
{
if (XMLString::equals(child->getTagName(), CONST_XMLCH("Seq")))
{
seq = StringManager::convert(child->getTextContent());
}
else if (XMLString::equals(child->getTagName(), CONST_XMLCH("cvParam")))
{
cvs.addCVTerm(parseCvParam_(child));
}
child = child->getNextElementSibling();
}
if (!acc.empty())
{
DBSequence temp_struct = {seq, dbref, acc, cvs};
db_sq_map_.insert(make_pair(id, temp_struct));
}
}
}
}
void MzIdentMLDOMHandler::parsePeptideElements_(DOMNodeList* peptideElements)
{
const XMLSize_t pep_node_count = peptideElements->getLength();
for (XMLSize_t c = 0; c < pep_node_count; ++c)
{
DOMNode* current_pep = peptideElements->item(c);
if (current_pep->getNodeType() && // true is not NULL
current_pep->getNodeType() == DOMNode::ELEMENT_NODE) // is element - possibly not necessary after getElementsByTagName
{
// Found element node: re-cast as element
DOMElement* element_pep = dynamic_cast<xercesc::DOMElement*>(current_pep);
String id = StringManager::convert(element_pep->getAttribute(CONST_XMLCH("id")));
//DOMNodeList* pep_sib = element_pep->getChildNodes();
AASequence aas;
try
{
//aas = parsePeptideSiblings_(pep_sib);
try
{
aas = parsePeptideSiblings_(element_pep);
}
catch (Exception::MissingInformation&)
{
// We found an unknown modification, we could try to rescue this
// situation. The "name" attribute, if present, may be parsable:
// The potentially ambiguous common identifier, such as a
// human-readable name for the instance.
String name = StringManager::convert(element_pep->getAttribute(CONST_XMLCH("name")));
if (!name.empty()) aas = AASequence::fromString(name);
}
}
catch (...)
{
OPENMS_LOG_ERROR << "No amino acid sequence readable from 'Peptide'" << endl;
}
pep_map_.insert(make_pair(id, aas));
}
}
}
void MzIdentMLDOMHandler::parsePeptideEvidenceElements_(DOMNodeList* peptideEvidenceElements)
{
const XMLSize_t pev_node_count = peptideEvidenceElements->getLength();
for (XMLSize_t c = 0; c < pev_node_count; ++c)
{
DOMNode* current_pev = peptideEvidenceElements->item(c);
if (current_pev->getNodeType() && // true is not NULL
current_pev->getNodeType() == DOMNode::ELEMENT_NODE) // is element - possibly not necessary after getElementsByTagName
{
// Found element node: re-cast as element
DOMElement* element_pev = dynamic_cast<xercesc::DOMElement*>(current_pev);
// <PeptideEvidence peptide_ref="peptide_1_1" id="PE_1_1_HSP70_ECHGR_0" start="161" end="172" pre="K" post="I" isDecoy="false" dBSequence_ref="DBSeq_HSP70_ECHGR"/>
String id = StringManager::convert(element_pev->getAttribute(CONST_XMLCH("id")));
String peptide_ref = StringManager::convert(element_pev->getAttribute(CONST_XMLCH("peptide_ref")));
String dBSequence_ref = StringManager::convert(element_pev->getAttribute(CONST_XMLCH("dBSequence_ref")));
//rest is optional !!
int start = -1;
int end = -1;
try
{
start = StringManager::convert(element_pev->getAttribute(CONST_XMLCH("start"))).toInt();
end = StringManager::convert(element_pev->getAttribute(CONST_XMLCH("end"))).toInt();
}
catch (...)
{
OPENMS_LOG_WARN << "'PeptideEvidence' without reference to the position in the originating sequence found." << endl;
}
char pre = '-';
char post = '-';
try
{
if (element_pev->hasAttribute(CONST_XMLCH("pre")))
{
pre = StringManager::convert(element_pev->getAttribute(CONST_XMLCH("pre")))[0];
}
if (element_pev->hasAttribute(CONST_XMLCH("post")))
{
post = StringManager::convert(element_pev->getAttribute(CONST_XMLCH("post")))[0];
}
}
catch (...)
{
OPENMS_LOG_WARN << "'PeptideEvidence' without reference to the bordering amino acids in the originating sequence found." << endl;
}
bool idec = false;
try
{
String d = StringManager::convert(element_pev->getAttribute(CONST_XMLCH("isDecoy")));
if (d.hasPrefix('t') || d.hasPrefix('1'))
idec = true;
}
catch (...)
{
OPENMS_LOG_WARN << "'PeptideEvidence' with unreadable 'isDecoy' status found." << endl;
}
PeptideEvidence temp_struct = {start, end, pre, post, idec};
pe_ev_map_.insert(make_pair(id, temp_struct));
p_pv_map_.insert(make_pair(peptide_ref, id));
pv_db_map_.insert(make_pair(id, dBSequence_ref));
}
}
}
void MzIdentMLDOMHandler::parseSpectrumIdentificationElements_(DOMNodeList* spectrumIdentificationElements)
{
const XMLSize_t si_node_count = spectrumIdentificationElements->getLength();
for (XMLSize_t c = 0; c < si_node_count; ++c)
{
DOMNode* current_si = spectrumIdentificationElements->item(c);
if (current_si->getNodeType() && // true is not NULL
current_si->getNodeType() == DOMNode::ELEMENT_NODE) // is element - possibly not necessary after getElementsByTagName
{
// Found element node: re-cast as element
DOMElement* element_si = dynamic_cast<xercesc::DOMElement*>(current_si);
String id = StringManager::convert(element_si->getAttribute(CONST_XMLCH("id")));
String spectrumIdentificationProtocol_ref = StringManager::convert(element_si->getAttribute(CONST_XMLCH("spectrumIdentificationProtocol_ref")));
String spectrumIdentificationList_ref = StringManager::convert(element_si->getAttribute(CONST_XMLCH("spectrumIdentificationList_ref")));
String spectrumIdentification_date = StringManager::convert(element_si->getAttribute(CONST_XMLCH("activityDate")));
String searchDatabase_ref = "";
String spectra_data_ref = "";
DOMElement* child = element_si->getFirstElementChild();
while (child)
{
if (XMLString::equals(child->getTagName(), CONST_XMLCH("InputSpectra")))
{
spectra_data_ref = StringManager::convert(child->getAttribute(CONST_XMLCH("spectraData_ref")));
}
else if (XMLString::equals(child->getTagName(), CONST_XMLCH("SearchDatabaseRef")))
{
searchDatabase_ref = StringManager::convert(child->getAttribute(CONST_XMLCH("searchDatabase_ref")));
}
child = child->getNextElementSibling();
}
SpectrumIdentification temp_struct = {spectra_data_ref, searchDatabase_ref, spectrumIdentificationProtocol_ref, spectrumIdentificationList_ref};
si_map_.insert(make_pair(id, temp_struct));
pro_id_->push_back(ProteinIdentification());
ProteinIdentification::SearchParameters sp;
sp.db = db_map_[searchDatabase_ref].location;
sp.db_version = db_map_[searchDatabase_ref].version;
pro_id_->back().setSearchParameters(sp);
if (xl_ms_search_)
{
pro_id_->back().setMetaValue("SpectrumIdentificationProtocol", "MS:1002494"); // XL-MS CV term
}
// internally we store a list of files so convert the mzIdentML file String to a StringList
StringList spectra_data_list;
spectra_data_list.push_back(sd_map_[spectra_data_ref]);
pro_id_->back().setMetaValue("spectra_data", spectra_data_list);
if (!spectrumIdentification_date.empty())
{
pro_id_->back().setDateTime(DateTime::fromString(spectrumIdentification_date));
}
else
{
pro_id_->back().setDateTime(DateTime::now());
}
pro_id_->back().setIdentifier(UniqueIdGenerator::getUniqueId()); // no more identification wit engine/date/time!
//TODO setIdentifier to xml id?
si_pro_map_.insert(make_pair(spectrumIdentificationList_ref, pro_id_->size() - 1));
}
}
}
void MzIdentMLDOMHandler::parseSpectrumIdentificationProtocolElements_(DOMNodeList* spectrumIdentificationProtocolElements)
{
const XMLSize_t si_node_count = spectrumIdentificationProtocolElements->getLength();
for (XMLSize_t c = 0; c < si_node_count; ++c)
{
ProteinIdentification::SearchParameters sp;
DOMNode* current_sip = spectrumIdentificationProtocolElements->item(c);
if (current_sip->getNodeType() && // true is not NULL
current_sip->getNodeType() == DOMNode::ELEMENT_NODE) // is element - possibly not necessary after getElementsByTagName
{
// Found element node: re-cast as element
DOMElement* element_sip = dynamic_cast<xercesc::DOMElement*>(current_sip);
String id = StringManager::convert(element_sip->getAttribute(CONST_XMLCH("id")));
String swr = StringManager::convert(element_sip->getAttribute(CONST_XMLCH("analysisSoftware_ref")));
CVTerm searchtype;
String enzymename;
CVTermList param_cv;
map<String, DataValue> param_up;
CVTermList modparam;
double p_tol = 0;
double f_tol = 0;
CVTermList tcv;
map<String, DataValue> tup;
DOMElement* child = element_sip->getFirstElementChild();
while (child)
{
if (XMLString::equals(child->getTagName(), CONST_XMLCH("SearchType")))
{
searchtype = parseCvParam_(child->getFirstElementChild());
}
else if (XMLString::equals(child->getTagName(), CONST_XMLCH("AdditionalSearchParams")))
{
pair<CVTermList, map<String, DataValue> > as_params = parseParamGroup_(child->getChildNodes());
sp = findSearchParameters_(as_params); // this must be renamed!!
}
else if (XMLString::equals(child->getTagName(), CONST_XMLCH("ModificationParams"))) // TODO @all where to store the specificities?
{
vector<String> fix, var;
DOMElement* sm = child->getFirstElementChild();
while (sm)
{
String residues = StringManager::convert(sm->getAttribute(CONST_XMLCH("residues")));
bool fixedMod = false;
XSValue::Status status;
XSValue* val = XSValue::getActualValue(sm->getAttribute(CONST_XMLCH("fixedMod")), XSValue::dt_boolean, status);
if (status == XSValue::st_Init)
{
fixedMod = val->fData.fValue.f_bool;
}
delete val;
// double massDelta = 0;
// try
// {
// massDelta = boost::lexical_cast<double>(StringManager::convert(sm->getAttribute(CONST_XMLCH("massDelta"))));
// }
// catch (...)
// {
// OPENMS_LOG_ERROR << "Could not cast ModificationParam massDelta from " << StringManager::convert(sm->getAttribute(CONST_XMLCH("massDelta")));
// }
String mname;
CVTermList specificity_rules;
DOMElement* sub = sm->getFirstElementChild();
while (sub)
{
if (XMLString::equals(sub->getTagName(), CONST_XMLCH("cvParam")))
{
mname = StringManager::convert(sub->getAttribute(CONST_XMLCH("name")));
if (mname == "unknown modification")
{
// e.g. <cvParam cvRef="MS" accession="MS:1001460" name="unknown modification" value="N-Glycan"/>
mname = StringManager::convert(sub->getAttribute(CONST_XMLCH("value")));
}
}
else if (XMLString::equals(sub->getTagName(), CONST_XMLCH("SpecificityRules")))
{
specificity_rules.consumeCVTerms(parseParamGroup_(sub->getChildNodes()).first.getCVTerms());
// let's press them where all other SearchengineAdapters press them in
}
else
{
OPENMS_LOG_ERROR << "Misplaced information in 'ModificationParams' ignored." << endl;
}
sub = sub->getNextElementSibling();
}
if (!mname.empty())
{
String mod;
String r = (residues != ".") ? residues : "";
if (!specificity_rules.empty())
{
for (map<String, vector<CVTerm> >::const_iterator spci = specificity_rules.getCVTerms().begin(); spci != specificity_rules.getCVTerms().end(); ++spci)
{
if (spci->second.front().getAccession() == "MS:1001189") // nterm
{
const ResidueModification* m = ModificationsDB::getInstance()->getModification(mname, r, ResidueModification::N_TERM);
mod = m->getFullId();
}
else if (spci->second.front().getAccession() == "MS:1001190") // cterm
{
const ResidueModification* m = ModificationsDB::getInstance()->getModification(mname, r, ResidueModification::C_TERM);
mod = m->getFullId();
}
else if (spci->second.front().getAccession() == "MS:1002057") // protein nterm
{
const ResidueModification* m = ModificationsDB::getInstance()->getModification(mname, r, ResidueModification::PROTEIN_N_TERM);
mod = m->getFullId();
}
else if (spci->second.front().getAccession() == "MS:1002058") // protein cterm
{
const ResidueModification* m = ModificationsDB::getInstance()->getModification(mname, r, ResidueModification::PROTEIN_C_TERM);
mod = m->getFullId();
}
}
}
else // anywhere
{
const ResidueModification* m = ModificationsDB::getInstance()->getModification(mname, r);
mod = m->getFullId();
}
if (fixedMod)
{
fix.push_back(mod);
}
else
{
var.push_back(mod);
}
}
sm = sm->getNextElementSibling();
}
sp.fixed_modifications = fix;
sp.variable_modifications = var;
}
else if (XMLString::equals(child->getTagName(), CONST_XMLCH("Enzymes"))) // TODO @all : where store multiple enzymes for one identificationrun?
{
DOMElement* enzyme = child->getFirstElementChild(); //Enzyme elements
while (enzyme)
{
int missedCleavages = -1;
try
{
missedCleavages = StringManager::convert(enzyme->getAttribute(CONST_XMLCH("missedCleavages"))).toInt();
}
catch (exception& e)
{
OPENMS_LOG_WARN << "Search engine enzyme settings for 'missedCleavages' unreadable: " << e.what() << StringManager::convert(enzyme->getAttribute(CONST_XMLCH("missedCleavages"))) << endl;
}
if (missedCleavages < 0)
{
OPENMS_LOG_WARN << "missedCleavages has a negative value. Assuming unlimited and setting it to 1000." << endl;
missedCleavages = 1000;
}
sp.missed_cleavages = missedCleavages;
// String semiSpecific = StringManager::convert(enzyme->getAttribute(CONST_XMLCH("semiSpecific"))); //xsd:boolean
// String cTermGain = StringManager::convert(enzyme->getAttribute(CONST_XMLCH("cTermGain")));
// String nTermGain = StringManager::convert(enzyme->getAttribute(CONST_XMLCH("nTermGain")));
// int minDistance = -1;
// try
// {
// minDistance = StringManager::convert(enzyme->getAttribute(CONST_XMLCH("minDistance"))).toInt();
// }
// catch (...)
// {
// OPENMS_LOG_WARN << "Search engine settings for 'minDistance' unreadable." << endl;
// }
enzymename = "UNKNOWN";
DOMElement* sub = enzyme->getFirstElementChild();
while (sub)
{
//SiteRegex unstorable just now
if (XMLString::equals(sub->getTagName(), CONST_XMLCH("EnzymeName")))
{
set<String> enzymes_terms;
cv_.getAllChildTerms(enzymes_terms, "MS:1001045"); // cleavage agent name
pair<CVTermList, map<String, DataValue> > params = parseParamGroup_(sub->getChildNodes());
for (map<String, vector<CVTerm> >::const_iterator it = params.first.getCVTerms().begin(); it != params.first.getCVTerms().end(); ++it)
{
if (enzymes_terms.find(it->first) != enzymes_terms.end())
{
enzymename = it->second.front().getName();
}
else
{
OPENMS_LOG_WARN << "Additional parameters for enzyme settings not readable." << endl;
}
}
}
sub = sub->getNextElementSibling();
}
if (ProteaseDB::getInstance()->hasEnzyme(enzymename))
{
sp.digestion_enzyme = *(ProteaseDB::getInstance()->getEnzyme(enzymename));
}
enzyme = enzyme->getNextElementSibling();
}
}
else if (XMLString::equals(child->getTagName(), CONST_XMLCH("FragmentTolerance")))
{
pair<CVTermList, map<String, DataValue> > params = parseParamGroup_(child->getChildNodes());
//+- take the numerically greater
for (map<String, vector<CVTerm> >::const_iterator it = params.first.getCVTerms().begin(); it != params.first.getCVTerms().end(); ++it)
{
f_tol = max(f_tol, it->second.front().getValue().toString().toDouble());
sp.fragment_mass_tolerance = f_tol;
if (it->second.front().getUnit().name == "parts per million" )
{
sp.fragment_mass_tolerance_ppm = true;
}
}
}
else if (XMLString::equals(child->getTagName(), CONST_XMLCH("ParentTolerance")))
{
pair<CVTermList, map<String, DataValue> > params = parseParamGroup_(child->getChildNodes());
//+- take the numerically greater
for (map<String, vector<CVTerm> >::const_iterator it = params.first.getCVTerms().begin(); it != params.first.getCVTerms().end(); ++it)
{
p_tol = max(p_tol, it->second.front().getValue().toString().toDouble());
sp.precursor_mass_tolerance = p_tol;
if (it->second.front().getUnit().name == "parts per million" )
{
sp.precursor_mass_tolerance_ppm = true;
}
}
}
else if (XMLString::equals(child->getTagName(), CONST_XMLCH("Threshold")))
{
pair<CVTermList, map<String, DataValue> > params = parseParamGroup_(child->getChildNodes());
tcv = params.first;
tup = params.second;
}
child = child->getNextElementSibling();
// <DatabaseFilters> omitted for now, not reflectable by our member structures
// <DatabaseTranslation> omitted for now, not reflectable by our member structures
// <MassTable> omitted for now, not reflectable by our member structures
}
SpectrumIdentificationProtocol temp_struct = {searchtype, enzymename, param_cv, param_up, modparam, p_tol, f_tol, tcv, tup};
sp_map_.insert(make_pair(id, temp_struct));
double thresh = 0.0;
bool use_thresh = false;
set<String> threshold_terms;
cv_.getAllChildTerms(threshold_terms, "MS:1002482"); //statistical threshold
for (map<String, vector<OpenMS::CVTerm> >::const_iterator thit = tcv.getCVTerms().begin(); thit != tcv.getCVTerms().end(); ++thit)
{
if (threshold_terms.find(thit->first) != threshold_terms.end())
{
if (thit->first != "MS:1001494") // no threshold
{
thresh = thit->second.front().getValue().toString().toDouble(); // cast fix needed as DataValue is init with XercesString
use_thresh = true;
break;
}
else
{
break;
}
}
}
String search_engine, search_engine_version;
for (map<String, SpectrumIdentification>::const_iterator si_it = si_map_.begin(); si_it != si_map_.end(); ++si_it)
{
if (si_it->second.spectrum_identification_protocol_ref == id)
{
search_engine = as_map_[swr].name;
search_engine_version = as_map_[swr].version;
// String identi = search_engine+"_"+si_pro_map_[si_it->second.spectrum_identification_list_ref]->getDateTime().getDate()+"T"
// +si_pro_map_[si_it->second.spectrum_identification_list_ref]->getDateTime().getTime();
// pro_id_->at(si_pro_map_[si_it->second.spectrum_identification_list_ref]).setIdentifier(identi);
pro_id_->at(si_pro_map_[si_it->second.spectrum_identification_list_ref]).setSearchEngine(search_engine);
pro_id_->at(si_pro_map_[si_it->second.spectrum_identification_list_ref]).setSearchEngineVersion(search_engine_version);
sp.db = pro_id_->at(si_pro_map_[si_it->second.spectrum_identification_list_ref]).getSearchParameters().db; // was previously set, but main parts of sp are set here
sp.db_version = pro_id_->at(si_pro_map_[si_it->second.spectrum_identification_list_ref]).getSearchParameters().db_version; // was previously set, but main parts of sp are set here
pro_id_->at(si_pro_map_[si_it->second.spectrum_identification_list_ref]).setSearchParameters(sp);
if (use_thresh)
{
pro_id_->at(si_pro_map_[si_it->second.spectrum_identification_list_ref]).setSignificanceThreshold(thresh);
}
}
}
}
}
}
void MzIdentMLDOMHandler::parseInputElements_(DOMNodeList* inputElements)
{
const XMLSize_t node_count = inputElements->getLength();
for (XMLSize_t c = 0; c < node_count; ++c)
{
DOMNode* current_in = inputElements->item(c);
if (current_in->getNodeType() && // true is not NULL
current_in->getNodeType() == DOMNode::ELEMENT_NODE) // is element - possibly not necessary after getElementsByTagName
{
// Found element node: re-cast as element
DOMElement* element_in = dynamic_cast<xercesc::DOMElement*>(current_in);
String id = StringManager::convert(element_in->getAttribute(CONST_XMLCH("id")));
String location = StringManager::convert(element_in->getAttribute(CONST_XMLCH("location")));
if (XMLString::equals(element_in->getTagName(), CONST_XMLCH("SpectraData")))
{
// <FileFormat> omitted for now, not reflectable by our member structures
// <SpectrumIDFormat> omitted for now, not reflectable by our member structures
sd_map_.insert(make_pair(id, location));
}
else if (XMLString::equals(element_in->getTagName(), CONST_XMLCH("SourceFile")))
{
// <FileFormat> omitted for now, not reflectable by our member structures
sr_map_.insert(make_pair(id, location));
}
else if (XMLString::equals(element_in->getTagName(), CONST_XMLCH("SearchDatabase")))
{
// <FileFormat> omitted for now, not reflectable by our member structures
DateTime releaseDate;
// releaseDate.set(StringManager::convert(element_in->getAttribute(CONST_XMLCH("releaseDate"))));
String version = StringManager::convert(element_in->getAttribute(CONST_XMLCH("version")));
String dbname;
DOMElement* element_dbn = element_in->getFirstElementChild();
while (element_dbn)
{
if (XMLString::equals(element_dbn->getTagName(), CONST_XMLCH("DatabaseName")))
{
DOMElement* databasename_param = element_dbn->getFirstElementChild();
while (databasename_param)
{
if (XMLString::equals(databasename_param->getTagName(), CONST_XMLCH("cvParam")))
{
CVTerm param = parseCvParam_(databasename_param);
dbname = param.getValue();
}
else if (XMLString::equals(databasename_param->getTagName(), CONST_XMLCH("userParam")))
{
pair<String, DataValue> param = parseUserParam_(databasename_param);
// issue #7099: mzID might have missing "value" for this element
// in this case, just use the "name"
dbname = param.second.isEmpty() ? dbname = param.first : param.second.toString();
}
databasename_param = databasename_param->getNextElementSibling();
}
//each SearchDatabase element may have one DatabaseName, each DatabaseName only one param
}
element_dbn = element_dbn->getNextElementSibling();
}
if (dbname.empty())
{
OPENMS_LOG_WARN << "No DatabaseName element found, use results at own risk." << endl;
dbname = "unknown";
}
DatabaseInput temp_struct = {dbname, location, version, releaseDate};
db_map_.insert(make_pair(id, temp_struct));
}
}
}
}
void MzIdentMLDOMHandler::parseSpectrumIdentificationListElements_(DOMNodeList* spectrumIdentificationListElements)
{
const XMLSize_t node_count = spectrumIdentificationListElements->getLength();
for (XMLSize_t c = 0; c < node_count; ++c)
{
DOMNode* current_lis = spectrumIdentificationListElements->item(c);
if (current_lis->getNodeType() && // true is not NULL
current_lis->getNodeType() == DOMNode::ELEMENT_NODE) // is element - possibly not necessary after getElementsByTagName
{
// Found element node: re-cast as element
DOMElement* element_lis = dynamic_cast<xercesc::DOMElement*>(current_lis);
String id = StringManager::convert(element_lis->getAttribute(CONST_XMLCH("id")));
// String name = StringManager::convert(element_res->getAttribute(CONST_XMLCH("name")));
DOMElement* element_res = element_lis->getFirstElementChild();
while (element_res)
{
if (XMLString::equals(element_res->getTagName(), CONST_XMLCH("SpectrumIdentificationResult")))
{
String spectra_data_ref = StringManager::convert(element_res->getAttribute(CONST_XMLCH("spectraData_ref"))); //ref to the sourcefile, could be useful but now nowhere to store
String spectrumID = StringManager::convert(element_res->getAttribute(CONST_XMLCH("spectrumID")));
pair<CVTermList, map<String, DataValue> > params = parseParamGroup_(element_res->getChildNodes());
if (xl_ms_search_) // XL-MS data has a different structure (up to 4 spectrum identification items for the same PSM)
{
std::multimap<String, int> xl_val_map;
std::set<String> xl_val_set;
int index_counter = 0;
DOMElement* sii = element_res->getFirstElementChild();
// loop over all SIIs of a spectrum and group together the SIIs belonging to the same cross-link spectrum match
while (sii)
{
if (XMLString::equals(sii->getTagName(), CONST_XMLCH("SpectrumIdentificationItem")))
{
DOMNodeList* sii_cvp = sii->getElementsByTagName(CONST_XMLCH("cvParam"));
const XMLSize_t cv_count = sii_cvp->getLength();
for (XMLSize_t i = 0; i < cv_count; ++i)
{
DOMElement* element_sii_cvp = dynamic_cast<xercesc::DOMElement*>(sii_cvp->item(i));
if (XMLString::equals(element_sii_cvp->getAttribute(CONST_XMLCH("accession")), CONST_XMLCH("MS:1002511"))) // cross-link spectrum identification item
{
String xl_val = StringManager::convert(element_sii_cvp->getAttribute(CONST_XMLCH("value")));
xl_val_map.insert(make_pair(xl_val, index_counter));
xl_val_set.insert(xl_val);
}
}
}
sii = sii->getNextElementSibling();
++index_counter;
}
// fix for label-free mono-links
// those only have one SII and no "cross-link spectrum identification item" value
if (xl_val_set.empty())
{
xl_val_set.insert("0");
xl_val_map.insert(make_pair("0", 0));
}
for (set<String>::const_iterator set_it = xl_val_set.begin(); set_it != xl_val_set.end(); ++set_it)
{
parseSpectrumIdentificationItemSetXLMS(set_it, xl_val_map, element_res, spectrumID);
}
pep_id_->back().setIdentifier(pro_id_->at(si_pro_map_[id]).getIdentifier());
}
else // general case
{
pep_id_->push_back(PeptideIdentification());
pep_id_->back().setHigherScoreBetter(false); //either a q-value or an e-value, only if neither available there will be another
pep_id_->back().setSpectrumReference( spectrumID); // SpectrumIdentificationResult attribute spectrumID is taken from the mz_file and should correspond to MSSpectrum.nativeID, thus spectrum_reference will serve as reference. As the format of the 'reference' widely varies from vendor to vendor, spectrum_reference as string will serve best, indices are not recommended.
//fill pep_id_->back() with content
DOMElement* parent = dynamic_cast<xercesc::DOMElement*>(element_res->getParentNode());
String sil = StringManager::convert(parent->getAttribute(CONST_XMLCH("id")));
DOMElement* child = element_res->getFirstElementChild();
while (child)
{
if (XMLString::equals(child->getTagName(), CONST_XMLCH("SpectrumIdentificationItem")))
{
parseSpectrumIdentificationItemElement_(child, pep_id_->back(), sil);
}
child = child->getNextElementSibling();
}
} // end of "not-XLMS-results"
pep_id_->back().setIdentifier(pro_id_->at(si_pro_map_[id]).getIdentifier());
pep_id_->back().sort();
//adopt cv s
for (map<String, vector<CVTerm> >::const_iterator cvit = params.first.getCVTerms().begin(); cvit != params.first.getCVTerms().end(); ++cvit)
{
// check for retention time or scan time entry
/* N.B.: MzIdentML does not impose the requirement to store
'redundant' data (e.g. RT) as the identified spectrum is
unambiguously referenceable by the spectrumID (OpenMS
internally spectrum_reference) and hence such data can be
looked up in the mz file. For convenience, and as OpenMS
relies on the smallest common denominator to reference a
spectrum (RT/precursor MZ), we provide functionality to amend
RT data to identifications and support reading such from mzid
*/
if (cvit->first == "MS:1000894" || cvit->first == "MS:1000016") //TODO use subordinate terms which define units
{
double rt = cvit->second.front().getValue().toString().toDouble();
if (cvit->second.front().getUnit().accession == "UO:0000031") // minutes
{
rt *= 60.0;
}
pep_id_->back().setRT(rt);
}
else
{
pep_id_->back().setMetaValue(cvit->first, cvit->second.front().getValue()); // TODO? all DataValues - are there more then one, my guess is this is overdesigned
}
}
//adopt up s
for (map<String, DataValue>::const_iterator upit = params.second.begin(); upit != params.second.end(); ++upit)
{
pep_id_->back().setMetaValue(upit->first, upit->second);
}
if (pep_id_->back().getRT() != pep_id_->back().getRT())
{
OPENMS_LOG_WARN << "No retention time found for 'SpectrumIdentificationResult'" << endl;
}
}
element_res = element_res->getNextElementSibling();
}
}
}
}
void MzIdentMLDOMHandler::parseSpectrumIdentificationItemSetXLMS(set<String>::const_iterator set_it, std::multimap<String, int> xl_val_map, DOMElement* element_res, const String& spectrumID)
{
// each value in the set corresponds to one PeptideIdentification object
std::pair <std::multimap<String, int>::iterator, std::multimap<String, int>::iterator> range;
range = xl_val_map.equal_range(*set_it);
DOMNodeList* siis = element_res->getElementsByTagName(CONST_XMLCH("SpectrumIdentificationItem"));
DOMElement* parent = dynamic_cast<xercesc::DOMElement*>(element_res->getParentNode());
String spectrumIdentificationList_ref = StringManager::convert(parent->getAttribute(CONST_XMLCH("id")));
// initialize all needed values, extract them one by one in vectors, e.g. using max and min to determine which are heavy which light
// get peptide id, that way determine donor, acceptor (alpha, beta)
std::vector<String> peptides;
double score = -1;
std::vector<double> exp_mzs;
std::vector<double> RTs;
int rank = 0;
int charge = 0;
vector<PeptideHit::PeakAnnotation> frag_annotations;
double xcorrx = 0;
double xcorrc = 0;
double matchodds = 0;
double intsum = 0;
double wTIC = 0;
vector< vector<String> > userParamNameLists;
vector< vector<String> > userParamValueLists;
vector< vector<String> > userParamUnitLists;
for (std::multimap<String, int>::iterator it=range.first; it!=range.second; ++it)
{
DOMElement* cl_sii = dynamic_cast<xercesc::DOMElement*>(siis->item(it->second));
// Attributes
String peptide = StringManager::convert(cl_sii->getAttribute(CONST_XMLCH("peptide_ref")));
peptides.push_back(peptide);
double exp_mz =StringManager::convert(cl_sii->getAttribute(CONST_XMLCH("experimentalMassToCharge"))).toDouble();
exp_mzs.push_back(exp_mz);
if (rank == 0)
{
rank = StringManager::convert(cl_sii->getAttribute(CONST_XMLCH("rank"))).toInt();
}
if (charge == 0)
{
charge = StringManager::convert(cl_sii->getAttribute(CONST_XMLCH("chargeState"))).toInt();
}
// CVs
DOMNodeList* sii_cvp = cl_sii->getElementsByTagName(CONST_XMLCH("cvParam"));
const XMLSize_t cv_count = sii_cvp->getLength();
for (XMLSize_t i = 0; i < cv_count; ++i)
{
DOMElement* element_sii_cvp = dynamic_cast<xercesc::DOMElement*>(sii_cvp->item(i));
if (XMLString::equals(element_sii_cvp->getAttribute(CONST_XMLCH("accession")), CONST_XMLCH("MS:1002681"))) // OpenXQuest:combined score
{
score = StringManager::convert(element_sii_cvp->getAttribute(CONST_XMLCH("value"))).toDouble();
}
else if (XMLString::equals(element_sii_cvp->getAttribute(CONST_XMLCH("accession")), CONST_XMLCH("MS:1002682"))) // OpenXQuest: xcorr common
{
xcorrx = StringManager::convert(element_sii_cvp->getAttribute(CONST_XMLCH("value"))).toDouble();
}
else if (XMLString::equals(element_sii_cvp->getAttribute(CONST_XMLCH("accession")), CONST_XMLCH("MS:1002683"))) // OpenXQuest: xcorr xlink
{
xcorrc = StringManager::convert(element_sii_cvp->getAttribute(CONST_XMLCH("value"))).toDouble();
}
else if (XMLString::equals(element_sii_cvp->getAttribute(CONST_XMLCH("accession")), CONST_XMLCH("MS:1002684"))) // OpenXQuest: match-odds
{
matchodds = StringManager::convert(element_sii_cvp->getAttribute(CONST_XMLCH("value"))).toDouble();
}
else if (XMLString::equals(element_sii_cvp->getAttribute(CONST_XMLCH("accession")), CONST_XMLCH("MS:1002685"))) // OpenXQuest: intsum
{
intsum = StringManager::convert(element_sii_cvp->getAttribute(CONST_XMLCH("value"))).toDouble();
}
else if (XMLString::equals(element_sii_cvp->getAttribute(CONST_XMLCH("accession")), CONST_XMLCH("MS:1002686"))) // OpenXQuest: wTIC
{
wTIC = StringManager::convert(element_sii_cvp->getAttribute(CONST_XMLCH("value"))).toDouble();
}
else if (XMLString::equals(element_sii_cvp->getAttribute(CONST_XMLCH("accession")), CONST_XMLCH("MS:1003024"))) // OpenPepXL:score
{
score = StringManager::convert(element_sii_cvp->getAttribute(CONST_XMLCH("value"))).toDouble();
}
else if (XMLString::equals(element_sii_cvp->getAttribute(CONST_XMLCH("accession")), CONST_XMLCH("MS:1000894"))) // retention time
{
double RT = StringManager::convert(element_sii_cvp->getAttribute(CONST_XMLCH("value"))).toDouble();
RTs.push_back(RT);
}
}
// userParams
vector<String> userParamNames;
vector<String> userParamValues;
vector<String> userParamUnits;
DOMNodeList* sii_up = cl_sii->getElementsByTagName(CONST_XMLCH("userParam"));
const XMLSize_t up_count = sii_up->getLength();
for (XMLSize_t i = 0; i < up_count; ++i)
{
DOMElement* element_sii_up = dynamic_cast<xercesc::DOMElement*>(sii_up->item(i));
userParamNames.push_back(StringManager::convert(element_sii_up->getAttribute(CONST_XMLCH("name"))));
userParamValues.push_back(StringManager::convert(element_sii_up->getAttribute(CONST_XMLCH("value"))));
userParamUnits.push_back(StringManager::convert(element_sii_up->getAttribute(CONST_XMLCH("unitName"))));
}
userParamNameLists.push_back(userParamNames);
userParamValueLists.push_back(userParamValues);
userParamUnitLists.push_back(userParamUnits);
// Fragmentation, does not matter where to get them. Look for them as long as the vector is empty
if (frag_annotations.empty())
{
DOMNodeList* frag_element_list = cl_sii->getElementsByTagName(CONST_XMLCH("Fragmentation"));
if (frag_element_list->getLength() > 0)
{
DOMElement* frag_element = dynamic_cast<xercesc::DOMElement*>(frag_element_list->item(0));
DOMNodeList* ion_types = frag_element->getElementsByTagName(CONST_XMLCH("IonType"));
const XMLSize_t ion_type_count = ion_types->getLength();
for (XMLSize_t i = 0; i < ion_type_count; ++i)
{
DOMElement* ion_type_element = dynamic_cast<xercesc::DOMElement*>(ion_types->item(i));
int ion_charge = StringManager::convert(ion_type_element ->getAttribute(CONST_XMLCH("charge"))).toInt();
vector<String> indices;
vector<String> positions;
vector<String> intensities;
vector<String> chains;
vector<String> categories;
String frag_type;
String loss = "";
StringManager::convert(ion_type_element ->getAttribute(CONST_XMLCH("index"))).split(" ", indices);
DOMNodeList* frag_arrays = ion_type_element ->getElementsByTagName(CONST_XMLCH("FragmentArray"));
const XMLSize_t frag_array_count = frag_arrays->getLength();
for (XMLSize_t f = 0; f < frag_array_count; ++f)
{
DOMElement* frag_array_element = dynamic_cast<xercesc::DOMElement*>(frag_arrays->item(f));
if ( XMLString::equals(frag_array_element->getAttribute(CONST_XMLCH("measure_ref")), CONST_XMLCH("Measure_mz")))
{
StringManager::convert(frag_array_element->getAttribute(CONST_XMLCH("values"))).split(" ", positions);
}
if ( XMLString::equals(frag_array_element->getAttribute(CONST_XMLCH("measure_ref")), CONST_XMLCH("Measure_int")))
{
StringManager::convert(frag_array_element->getAttribute(CONST_XMLCH("values"))).split(" ", intensities);
}
}
DOMNodeList* userParams = ion_type_element->getElementsByTagName(CONST_XMLCH("userParam"));
const XMLSize_t userParam_count = userParams->getLength();
for (XMLSize_t u = 0; u < userParam_count; ++u)
{
DOMElement* userParam_element = dynamic_cast<xercesc::DOMElement*>(userParams->item(u));
if ( XMLString::equals(userParam_element ->getAttribute(CONST_XMLCH("name")), CONST_XMLCH("cross-link_chain")))
{
StringManager::convert(userParam_element ->getAttribute(CONST_XMLCH("value"))).split(" ", chains);
}
if ( XMLString::equals(userParam_element ->getAttribute(CONST_XMLCH("name")), CONST_XMLCH("cross-link_ioncategory")))
{
StringManager::convert(userParam_element ->getAttribute(CONST_XMLCH("value"))).split(" ", categories);
}
}
DOMNodeList* cvts = ion_type_element->getElementsByTagName(CONST_XMLCH("cvParam"));
const XMLSize_t cvt_count = cvts->getLength();
for (XMLSize_t cvt = 0; cvt < cvt_count; ++cvt)
{
DOMElement* cvt_element = dynamic_cast<xercesc::DOMElement*>(cvts->item(cvt));
// Standard ions
if (XMLString::equals(cvt_element->getAttribute(CONST_XMLCH("accession")), CONST_XMLCH("MS:1001229"))) // frag: a ion
{
frag_type = "a";
}
if (XMLString::equals(cvt_element->getAttribute(CONST_XMLCH("accession")), CONST_XMLCH("MS:1001224"))) // frag: b ion
{
frag_type = "b";
}
if (XMLString::equals(cvt_element->getAttribute(CONST_XMLCH("accession")), CONST_XMLCH("MS:1001231"))) // frag: c ion
{
frag_type = "c";
}
if (XMLString::equals(cvt_element->getAttribute(CONST_XMLCH("accession")), CONST_XMLCH("MS:1001228"))) // frag: x ion
{
frag_type = "x";
}
if (XMLString::equals(cvt_element->getAttribute(CONST_XMLCH("accession")), CONST_XMLCH("MS:1001220"))) // frag: y ion
{
frag_type = "y";
}
if (XMLString::equals(cvt_element->getAttribute(CONST_XMLCH("accession")), CONST_XMLCH("MS:1001230"))) // frag: z ion
{
frag_type = "z";
}
// Ions with H2O losses
if (XMLString::equals(cvt_element->getAttribute(CONST_XMLCH("accession")), CONST_XMLCH("MS:1001234"))) // frag: a ion - H2O
{
frag_type = "a";
loss = "-H2O";
}
if (XMLString::equals(cvt_element->getAttribute(CONST_XMLCH("accession")), CONST_XMLCH("MS:1001222"))) // frag: b ion - H20
{
frag_type = "b";
loss = "-H2O";
}
if (XMLString::equals(cvt_element->getAttribute(CONST_XMLCH("accession")), CONST_XMLCH("MS:1001515"))) // frag: c ion - H20
{
frag_type = "c";
loss = "-H2O";
}
if (XMLString::equals(cvt_element->getAttribute(CONST_XMLCH("accession")), CONST_XMLCH("MS:1001519"))) // frag: x ion - H20
{
frag_type = "x";
loss = "-H2O";
}
if (XMLString::equals(cvt_element->getAttribute(CONST_XMLCH("accession")), CONST_XMLCH("MS:1001223"))) // frag: y ion - H20
{
frag_type = "y";
loss = "-H2O";
}
if (XMLString::equals(cvt_element->getAttribute(CONST_XMLCH("accession")), CONST_XMLCH("MS:1001517"))) // frag: z ion - H20
{
frag_type = "z";
loss = "-H2O";
}
// Ions with NH3 losses
if (XMLString::equals(cvt_element->getAttribute(CONST_XMLCH("accession")), CONST_XMLCH("MS:1001235"))) // frag: a ion - NH3
{
frag_type = "a";
loss = "-NH3";
}
if (XMLString::equals(cvt_element->getAttribute(CONST_XMLCH("accession")), CONST_XMLCH("MS:1001232"))) // frag: b ion - NH3
{
frag_type = "b";
loss = "-NH3";
}
if (XMLString::equals(cvt_element->getAttribute(CONST_XMLCH("accession")), CONST_XMLCH("MS:1001516"))) // frag: c ion - NH3
{
frag_type = "c";
loss = "-NH3";
}
if (XMLString::equals(cvt_element->getAttribute(CONST_XMLCH("accession")), CONST_XMLCH("MS:1001520"))) // frag: x ion - NH3
{
frag_type = "x";
loss = "-NH3";
}
if (XMLString::equals(cvt_element->getAttribute(CONST_XMLCH("accession")), CONST_XMLCH("MS:1001233"))) // frag: y ion - NH3
{
frag_type = "y";
loss = "-NH3";
}
if (XMLString::equals(cvt_element->getAttribute(CONST_XMLCH("accession")), CONST_XMLCH("MS:1001518"))) // frag: z ion - NH3
{
frag_type = "z";
loss = "-NH3";
}
}
for (Size s = 0; s < indices.size(); ++s)
{
String annotation= "[" + chains[s] + "|" + categories[s] + "$" + frag_type + indices[s] + loss + "]";
PeptideHit::PeakAnnotation frag_anno;
frag_anno.charge = ion_charge;
frag_anno.mz = positions[s].toDouble();
frag_anno.intensity = intensities[s].toDouble();
frag_anno.annotation = annotation;
frag_annotations.push_back(frag_anno);
}
}
}
}
}
// Generate and fill PeptideIdentification
vector<Size> light;
vector<Size> heavy;
double MZ_light = *std::min_element(exp_mzs.begin(), exp_mzs.end());
double MZ_heavy = *std::max_element(exp_mzs.begin(), exp_mzs.end());
// are the cross-links labeled?
bool labeled = MZ_light != MZ_heavy;
for (Size i = 0; i < exp_mzs.size(); ++i)
{
if (MZ_light == exp_mzs[i])
{
light.push_back(i);
}
else
{
heavy.push_back(i);
}
}
double RT_light = RTs[light[0]];
double RT_heavy = RT_light;
if (labeled)
{
RT_heavy = RTs[heavy[0]];
}
vector<Size> alpha;
vector<Size> beta;
for (Size i = 0; i < peptides.size(); ++i)
{
try
{
String donor_pep = xl_id_donor_map_.at(peptides[i]); // map::at throws an out-of-range
alpha.push_back(i);
}
catch (const std::out_of_range& /*oor*/)
{
beta.push_back(i);
}
}
String xl_type = "mono-link";
SignedSize alpha_pos = xl_donor_pos_map_.at(xl_id_donor_map_.at(peptides[alpha[0]]));
vector<String> spectrumIDs;
spectrumID.split(",", spectrumIDs);
if (alpha.size() == beta.size()) // if a beta exists at all, it must be cross-link. But they should also each have the same number of SIIs in the mzid
{
xl_type = "cross-link";
}
else
{
try
{
String donor_val = xl_id_donor_map_.at(peptides[alpha[0]]); // map::at throws an out-of-range
String acceptor_val = xl_id_acceptor_map_.at(peptides[alpha[0]]);
if (donor_val == acceptor_val) // if donor and acceptor on the same peptide belong to the same cross-link, it must be a loop-link
{
xl_type = "loop-link";
}
}
catch (const std::out_of_range& /*oor*/)
{
// do nothing. Must be a mono-link, which is already set
}
}
PeptideIdentification current_pep_id;
current_pep_id.setRT(RT_light);
current_pep_id.setMZ(MZ_light);
current_pep_id.setMetaValue(Constants::UserParam::SPECTRUM_REFERENCE, spectrumID);
current_pep_id.setScoreType(Constants::UserParam::OPENPEPXL_SCORE);
current_pep_id.setHigherScoreBetter(true);
vector<PeptideHit> phs;
PeptideHit ph_alpha;
ph_alpha.setSequence((*pep_map_.find(peptides[alpha[0]])).second);
ph_alpha.setCharge(charge);
ph_alpha.setScore(score);
ph_alpha.setRank(rank - 1); // rank is 1-based in mzid, OpenMS uses 0-based
ph_alpha.setMetaValue(Constants::UserParam::SPECTRUM_REFERENCE, spectrumIDs[0]);
ph_alpha.setMetaValue("xl_chain", "MS:1002509"); // donor
if (labeled)
{
ph_alpha.setMetaValue(Constants::UserParam::OPENPEPXL_HEAVY_SPEC_RT, RT_heavy);
ph_alpha.setMetaValue(Constants::UserParam::OPENPEPXL_HEAVY_SPEC_MZ, MZ_heavy);
ph_alpha.setMetaValue(Constants::UserParam::OPENPEPXL_HEAVY_SPEC_REF, spectrumIDs[1]);
}
ph_alpha.setMetaValue(Constants::UserParam::OPENPEPXL_XL_TYPE, xl_type);
ph_alpha.setMetaValue(Constants::UserParam::OPENPEPXL_XL_RANK, rank);
ph_alpha.setMetaValue("OpenPepXL:xcorr xlink",xcorrx);
ph_alpha.setMetaValue("OpenPepXL:xcorr common", xcorrc);
ph_alpha.setMetaValue("OpenPepXL:match-odds", matchodds);
ph_alpha.setMetaValue("OpenPepXL:intsum", intsum);
ph_alpha.setMetaValue("OpenPepXL:wTIC", wTIC);
vector<String> userParamNames_alpha = userParamNameLists[alpha[0]];
vector<String> userParamValues_alpha = userParamValueLists[alpha[0]];
vector<String> userParamUnits_alpha = userParamUnitLists[alpha[0]];
for (Size i = 0; i < userParamNames_alpha.size(); ++i)
{
ph_alpha.setMetaValue(userParamNames_alpha[i], XMLHandler::fromXSDString(userParamUnits_alpha[i], userParamValues_alpha[i]));
}
ph_alpha.setPeakAnnotations(frag_annotations);
if (xl_type == "loop-link")
{
Size pos2 = xl_acceptor_pos_map_.at(xl_id_acceptor_map_.at(peptides[alpha[0]]));
ph_alpha.setMetaValue(Constants::UserParam::OPENPEPXL_XL_POS2, pos2);
}
if (xl_type != "mono-link")
{
ph_alpha.setMetaValue(Constants::UserParam::OPENPEPXL_XL_MOD, xl_mod_map_.at(peptides[alpha[0]]));
ph_alpha.setMetaValue(Constants::UserParam::OPENPEPXL_XL_MASS,DataValue(xl_mass_map_.at(peptides[alpha[0]])));
}
else if ( xl_mod_map_.find(peptides[alpha[0]]) != xl_mod_map_.end() )
{
ph_alpha.setMetaValue(Constants::UserParam::OPENPEPXL_XL_MOD, xl_mod_map_.at(peptides[alpha[0]]));
}
// correction for terminal modifications
if (alpha_pos == -1)
{
ph_alpha.setMetaValue(Constants::UserParam::OPENPEPXL_XL_POS1, ++alpha_pos);
ph_alpha.setMetaValue(Constants::UserParam::OPENPEPXL_XL_TERM_SPEC_ALPHA, "N_TERM");
}
else if (alpha_pos == static_cast<SignedSize>(ph_alpha.getSequence().size()))
{
ph_alpha.setMetaValue(Constants::UserParam::OPENPEPXL_XL_POS1, --alpha_pos);
ph_alpha.setMetaValue(Constants::UserParam::OPENPEPXL_XL_TERM_SPEC_ALPHA, "C_TERM");
}
else
{
ph_alpha.setMetaValue(Constants::UserParam::OPENPEPXL_XL_POS1, alpha_pos);
ph_alpha.setMetaValue(Constants::UserParam::OPENPEPXL_XL_TERM_SPEC_ALPHA, "ANYWHERE");
}
if (xl_type == "cross-link")
{
PeptideHit ph_beta;
SignedSize beta_pos = xl_acceptor_pos_map_.at(xl_id_acceptor_map_.at(peptides[beta[0]]));
ph_alpha.setMetaValue(Constants::UserParam::OPENPEPXL_BETA_SEQUENCE, (*pep_map_.find(peptides[beta[0]])).second.toString());
ph_beta.setSequence((*pep_map_.find(peptides[beta[0]])).second);
ph_beta.setCharge(charge);
ph_beta.setScore(score);
ph_beta.setRank(rank - 1); // rank is 1-based in mzid, OpenMS uses 0-based
ph_beta.setMetaValue(Constants::UserParam::SPECTRUM_REFERENCE, spectrumIDs[0]);
ph_beta.setMetaValue("xl_chain", "MS:1002510"); // receiver
// correction for terminal modifications
if (beta_pos == -1)
{
ph_alpha.setMetaValue(Constants::UserParam::OPENPEPXL_XL_POS2, ++beta_pos);
ph_alpha.setMetaValue(Constants::UserParam::OPENPEPXL_XL_TERM_SPEC_BETA, "N_TERM");
}
else if (beta_pos == static_cast<SignedSize>(ph_beta.getSequence().size()))
{
ph_alpha.setMetaValue(Constants::UserParam::OPENPEPXL_XL_POS2, --beta_pos);
ph_alpha.setMetaValue(Constants::UserParam::OPENPEPXL_XL_TERM_SPEC_BETA, "C_TERM");
}
else
{
ph_alpha.setMetaValue(Constants::UserParam::OPENPEPXL_XL_POS2, beta_pos);
ph_alpha.setMetaValue(Constants::UserParam::OPENPEPXL_XL_TERM_SPEC_BETA, "ANYWHERE");
}
phs.push_back(ph_alpha);
phs.push_back(ph_beta);
}
else
{
ph_alpha.setMetaValue(Constants::UserParam::OPENPEPXL_XL_TERM_SPEC_BETA, "ANYWHERE");
ph_alpha.setMetaValue(Constants::UserParam::OPENPEPXL_XL_POS2, "-");
ph_alpha.setMetaValue(Constants::UserParam::OPENPEPXL_BETA_SEQUENCE, "-");
phs.push_back(ph_alpha);
}
std::vector<String> unique_peptides;
unique_peptides.push_back(peptides[alpha[0]]);
if (!beta.empty())
{
unique_peptides.push_back(peptides[beta[0]]);
}
for (Size pep = 0; pep < unique_peptides.size(); ++pep)
{
String peptide_ref = unique_peptides[pep];
// Debug output
// cout << "peptides: ";
// for (Size k = 0; k < peptides.size(); ++k)
// {
// cout << "nr." << k << ": " << peptides[k] << "\t";
// }
// cout << endl << "unique peptides: ";
// for (Size k = 0; k < unique_peptides.size(); ++k)
// {
// cout << "nr." << k << ": " << unique_peptides[k] << "\t";
// }
// cout << endl << "alpha: " << alpha[0];
// if (beta.size() > 0)
// {
// cout << "\t beta: " << beta[0];
// }
// cout << endl;
// cout << "xl_type: " << xl_type << "\tphs_size: " << phs.size() << endl;
// cout << "phs0: " << phs[0].getSequence().toString() << endl;
// if (phs.size() > 1)
// {
// cout << "phs1: " << phs[1].getSequence().toString() << endl;
// }
//connect the PeptideHit with PeptideEvidences (for AABefore/After) and subsequently with DBSequence (for ProteinAccession)
pair<multimap<String, String>::iterator, multimap<String, String>::iterator> pev_its;
pev_its = p_pv_map_.equal_range(peptide_ref);
for (multimap<String, String>::iterator pev_it = pev_its.first; pev_it != pev_its.second; ++pev_it)
{
bool idec = false;
OpenMS::PeptideEvidence pev;
if (pe_ev_map_.find(pev_it->second) != pe_ev_map_.end())
{
MzIdentMLDOMHandler::PeptideEvidence& pv = pe_ev_map_[pev_it->second];
if (pv.pre != '-') pev.setAABefore(pv.pre);
if (pv.post != '-') pev.setAAAfter(pv.post);
if (pv.start != OpenMS::PeptideEvidence::UNKNOWN_POSITION && pv.stop != OpenMS::PeptideEvidence::UNKNOWN_POSITION)
{
pev.setStart(pv.start);
pev.setEnd(pv.stop);
}
idec = pv.idec;
if (idec)
{
if (phs[pep].metaValueExists(Constants::UserParam::TARGET_DECOY))
{
if (phs[pep].getMetaValue(Constants::UserParam::TARGET_DECOY) != "decoy")
{
phs[pep].setMetaValue(Constants::UserParam::TARGET_DECOY, "target+decoy");
}
else
{
phs[pep].setMetaValue(Constants::UserParam::TARGET_DECOY, "decoy");
}
}
else
{
phs[pep].setMetaValue(Constants::UserParam::TARGET_DECOY, "decoy");
}
}
else
{
if (phs[pep].metaValueExists(Constants::UserParam::TARGET_DECOY))
{
if (phs[pep].getMetaValue(Constants::UserParam::TARGET_DECOY) != "target")
{
phs[pep].setMetaValue(Constants::UserParam::TARGET_DECOY, "target+decoy");
}
else
{
phs[pep].setMetaValue(Constants::UserParam::TARGET_DECOY, "target");
}
}
else
{
phs[pep].setMetaValue(Constants::UserParam::TARGET_DECOY, "target");
}
}
}
if (pv_db_map_.find(pev_it->second) != pv_db_map_.end())
{
String& dpv = pv_db_map_[pev_it->second];
DBSequence& db = db_sq_map_[dpv];
pev.setProteinAccession(db.accession);
if (pro_id_->at(si_pro_map_[spectrumIdentificationList_ref]).findHit(db.accession)
== pro_id_->at(si_pro_map_[spectrumIdentificationList_ref]).getHits().end())
{ // butt ugly! TODO @ mths for ProteinInference
pro_id_->at(si_pro_map_[spectrumIdentificationList_ref]).insertHit(ProteinHit());
pro_id_->at(si_pro_map_[spectrumIdentificationList_ref]).getHits().back().setSequence(db.sequence);
pro_id_->at(si_pro_map_[spectrumIdentificationList_ref]).getHits().back().setAccession(db.accession);
if (idec)
{
pro_id_->at(si_pro_map_[spectrumIdentificationList_ref]).getHits().back().setMetaValue("isDecoy", "true");
}
else
{
pro_id_->at(si_pro_map_[spectrumIdentificationList_ref]).getHits().back().setMetaValue("isDecoy", "false");
}
}
}
phs[pep].addPeptideEvidence(pev);
}
}
current_pep_id.setHits(phs);
pep_id_->push_back(current_pep_id);
pep_id_->back().sort();
}
void MzIdentMLDOMHandler::parseSpectrumIdentificationItemElement_(DOMElement* spectrumIdentificationItemElement, PeptideIdentification& spectrum_identification, String& spectrumIdentificationList_ref)
{
String id = StringManager::convert(spectrumIdentificationItemElement->getAttribute(CONST_XMLCH("id")));
String name = StringManager::convert(spectrumIdentificationItemElement->getAttribute(CONST_XMLCH("name")));
long double calculatedMassToCharge = StringManager::convert(spectrumIdentificationItemElement->getAttribute(CONST_XMLCH("calculatedMassToCharge"))).toDouble();
// long double calculatedPI = StringManager::convert(spectrumIdentificationItemElement->getAttribute(CONST_XMLCH("calculatedPI"))).toDouble();
int chargeState = 0;
try
{
chargeState = StringManager::convert(spectrumIdentificationItemElement->getAttribute(CONST_XMLCH("chargeState"))).toInt();
}
catch (...)
{
OPENMS_LOG_WARN << "Found unreadable 'chargeState'." << endl;
}
long double experimentalMassToCharge = StringManager::convert(spectrumIdentificationItemElement->getAttribute(CONST_XMLCH("experimentalMassToCharge"))).toDouble();
int rank = 0;
try
{
rank = StringManager::convert(spectrumIdentificationItemElement->getAttribute(CONST_XMLCH("rank"))).toInt();
if (rank == 0)
{
// MzIdentML ranks are typically 1-based. For some special data (PMF) it can be 0.
// In that case we treat it as 1-based as well otherwise it will underflow if converted to the 0-based OpenMS ranks.
rank = 1;
OPENMS_LOG_DEBUG << "Found rank 0. Assuming 1-based rank." << std::endl;
}
}
catch (...)
{
OPENMS_LOG_WARN << "Found unreadable PSM rank." << endl;
}
String peptide_ref = StringManager::convert(spectrumIdentificationItemElement->getAttribute(CONST_XMLCH("peptide_ref")));
// String sample_ref = StringManager::convert(spectrumIdentificationItemElement->getAttribute(CONST_XMLCH("sample_ref")));
// String massTable_ref = StringManager::convert(spectrumIdentificationItemElement->getAttribute(CONST_XMLCH("massTable_ref")));
XSValue::Status status;
std::unique_ptr<XSValue> val(XSValue::getActualValue(spectrumIdentificationItemElement->getAttribute(CONST_XMLCH("passThreshold")), XSValue::dt_boolean, status));
bool pass = false;
if (status == XSValue::st_Init)
{
pass = val->fData.fValue.f_bool;
}
// TODO @all: where to store passThreshold value? set after score type eval in pass_threshold
long double score = 0;
const auto& [param_cv, param_user] = parseParamGroup_(spectrumIdentificationItemElement->getChildNodes());
set<String> q_score_terms;
set<String> e_score_terms,e_score_tmp;
set<String> specific_score_terms;
cv_.getAllChildTerms(q_score_terms, "MS:1002354"); //q-value for peptides
cv_.getAllChildTerms(e_score_terms, "MS:1001872");
cv_.getAllChildTerms(e_score_tmp, "MS:1002353");
e_score_terms.insert(e_score_tmp.begin(),e_score_tmp.end()); //E-value for peptides
cv_.getAllChildTerms(specific_score_terms, "MS:1001143"); //search engine specific score for PSMs
bool scoretype = false;
for (map<String, vector<OpenMS::CVTerm>>::const_iterator scoreit = param_cv.getCVTerms().begin(); scoreit != param_cv.getCVTerms().end(); ++scoreit)
{
if (q_score_terms.find(scoreit->first) != q_score_terms.end() || scoreit->first == "MS:1002354")
{
if (scoreit->first != "MS:1002055") // do not use peptide-level q-values for now
{
score = scoreit->second.front().getValue().toString().toDouble(); // cast fix needed as DataValue is init with XercesString
spectrum_identification.setHigherScoreBetter(false);
spectrum_identification.setScoreType("q-value"); //higherIsBetter = false
scoretype = true;
break;
}
}
else if (specific_score_terms.find(scoreit->first) != specific_score_terms.end())
{
score = scoreit->second.front().getValue().toString().toDouble(); // cast fix needed as DataValue is init with XercesString
spectrum_identification.setHigherScoreBetter(ControlledVocabulary::CVTerm::isHigherBetterScore(cv_.getTerm(scoreit->first)));
spectrum_identification.setScoreType(scoreit->second.front().getName());
scoretype = true;
break;
}
else if (e_score_terms.find(scoreit->first) != e_score_terms.end())
{
score = scoreit->second.front().getValue().toString().toDouble(); // cast fix needed as DataValue is init with XercesString
spectrum_identification.setHigherScoreBetter(false);
spectrum_identification.setScoreType("E-value"); //higherIsBetter = false
scoretype = true;
break;
}
else if (scoreit->first == "MS:1001143")
{
spectrum_identification.setScoreType("PSM-level search engine specific statistic");
// TODO this is just an assumption for unknown scores
spectrum_identification.setHigherScoreBetter(true);
scoretype = true;
}
}
if (scoretype) //else (i.e. no q/E/raw score or threshold not passed) no hit will be read TODO @mths: yielding no peptide hits will be error prone!!! what to do? remove and warn peptideidentifications with no hits inside?!
{
//build the PeptideHit from a SpectrumIdentificationItem
PeptideHit hit(score, rank - 1, chargeState, pep_map_[peptide_ref]); // rank in OpenMS is 0-based, in mzIdentML it is 1-based
for (const auto& cvs : param_cv.getCVTerms())
{
for (const auto& cv : cvs.second) // if the same accession occurred multiple times...
{
if (cvs.first == "MS:1002540")
{
hit.setMetaValue(cvs.first, cv.getValue().toString());
}
else if (cvs.first == "MS:1001143") // this is the CV term "PSM-level search engine specific statistic" and it doesn't have a value
{
continue;
}
else
{ // value may be empty, e.g. <cvParam accession="MS:1001363" name="peptide unique to one protein" cvRef="PSI-MS" />
auto value = xml_handler_->cvParamToValue(cv_, cv);
hit.setMetaValue(cvs.first, value);
}
}
}
for (map<String, DataValue>::const_iterator up = param_user.begin(); up != param_user.end(); ++up)
{
hit.setMetaValue(up->first, up->second);
}
hit.setMetaValue("calcMZ", calculatedMassToCharge);
spectrum_identification.setMZ(experimentalMassToCharge); // TODO @ mths for next PSI meeting: why is this not in SpectrumIdentificationResult in the schema? exp. m/z for one spec should not change from one id for it to the next!
hit.setMetaValue("pass_threshold", pass); //TODO @ mths do not write metavalue pass_threshold
//connect the PeptideHit with PeptideEvidences (for AABefore/After) and subsequently with DBSequence (for ProteinAccession)
pair<multimap<String, String>::iterator, multimap<String, String>::iterator> pev_its;
pev_its = p_pv_map_.equal_range(peptide_ref);
for (multimap<String, String>::iterator pev_it = pev_its.first; pev_it != pev_its.second; ++pev_it)
{
bool idec = false;
OpenMS::PeptideEvidence pev;
if (pe_ev_map_.find(pev_it->second) != pe_ev_map_.end())
{
MzIdentMLDOMHandler::PeptideEvidence& pv = pe_ev_map_[pev_it->second];
if (pv.pre != '-') pev.setAABefore(pv.pre);
if (pv.post != '-') pev.setAAAfter(pv.post);
if (pv.start != OpenMS::PeptideEvidence::UNKNOWN_POSITION && pv.stop != OpenMS::PeptideEvidence::UNKNOWN_POSITION)
{
hit.setMetaValue("start", pv.start);
hit.setMetaValue("end", pv.stop);
pev.setStart(pv.start);
pev.setEnd(pv.stop);
}
idec = pv.idec;
if (idec)
{
if (hit.metaValueExists(Constants::UserParam::TARGET_DECOY))
{
if (hit.getMetaValue(Constants::UserParam::TARGET_DECOY) != "decoy")
{
hit.setMetaValue(Constants::UserParam::TARGET_DECOY, "target+decoy");
}
else
{
hit.setMetaValue(Constants::UserParam::TARGET_DECOY, "decoy");
}
}
else
{
hit.setMetaValue(Constants::UserParam::TARGET_DECOY, "decoy");
}
}
else
{
if (hit.metaValueExists(Constants::UserParam::TARGET_DECOY))
{
if (hit.getMetaValue(Constants::UserParam::TARGET_DECOY) != "target")
{
hit.setMetaValue(Constants::UserParam::TARGET_DECOY, "target+decoy");
}
else
{
hit.setMetaValue(Constants::UserParam::TARGET_DECOY, "target");
}
}
else
{
hit.setMetaValue(Constants::UserParam::TARGET_DECOY, "target");
}
}
}
if (pv_db_map_.find(pev_it->second) != pv_db_map_.end())
{
String& dpv = pv_db_map_[pev_it->second];
DBSequence& db = db_sq_map_[dpv];
pev.setProteinAccession(db.accession);
if (pro_id_->at(si_pro_map_[spectrumIdentificationList_ref]).findHit(db.accession)
== pro_id_->at(si_pro_map_[spectrumIdentificationList_ref]).getHits().end())
{ // butt ugly! TODO @ mths for ProteinInference
pro_id_->at(si_pro_map_[spectrumIdentificationList_ref]).insertHit(ProteinHit());
pro_id_->at(si_pro_map_[spectrumIdentificationList_ref]).getHits().back().setSequence(db.sequence);
pro_id_->at(si_pro_map_[spectrumIdentificationList_ref]).getHits().back().setAccession(db.accession);
if (idec)
{
pro_id_->at(si_pro_map_[spectrumIdentificationList_ref]).getHits().back().setMetaValue("isDecoy", "true");
}
else
{
pro_id_->at(si_pro_map_[spectrumIdentificationList_ref]).getHits().back().setMetaValue("isDecoy", "false");
}
}
}
hit.addPeptideEvidence(pev);
}
//sort necessary for tests, as DOM children are obviously randomly ordered.
// vector<String> temp = spectrum_identification.getHits().back().getPeptideEvidences().back().getProteinAccessions();
// sort(temp.begin(), temp.end());
// spectrum_identification.getHits().back().setProteinAccessions(temp);
spectrum_identification.insertHit(hit);
// due to redundant references this is not needed! peptideref already maps to all those PeptideEvidence elements
// DOMElement* child = spectrumIdentificationItemElement->getFirstElementChild();
// while ( child )
// {
// if (XMLString::equals(child->getTagName(), CONST_XMLCH("PeptideEvidenceRef")))
// {
// ref = StringManager::convert(element_si->getAttribute(CONST_XMLCH("peptideEvidence_ref")));
// //...
// spectrum_identification.getHits().back().setAABefore(char acid);
// spectrum_identification.getHits().back().setAAAfter (char acid);
// break;
// }
// child = child->getNextElementSibling();
// }
}
// <Fragmentation> omitted for the time being
}
void MzIdentMLDOMHandler::parseProteinDetectionListElements_(DOMNodeList* proteinDetectionListElements)
{
const XMLSize_t node_count = proteinDetectionListElements->getLength();
for (XMLSize_t c = 0; c < node_count; ++c)
{
DOMNode* current_pr = proteinDetectionListElements->item(c);
if (current_pr->getNodeType() && // true is not NULL
current_pr->getNodeType() == DOMNode::ELEMENT_NODE) // is element - possibly not necessary after getElementsByTagName
{
// Found element node: re-cast as element
DOMElement* element_pr = dynamic_cast<xercesc::DOMElement*>(current_pr);
// String id = StringManager::convert(element_pr->getAttribute(CONST_XMLCH("id")));
// pair<CVTermList, map<String, DataValue> > params = parseParamGroup_(current_pr->getChildNodes());
// TODO @mths : this needs to be a ProteinIdentification for the ProteinDetectionListElement which is not mandatory and used in downstream analysis ProteinInference etc.
// pro_id_->push_back(ProteinIdentification());
// pro_id_->back().setSearchEngine(search_engine_);
// pro_id_->back().setSearchEngineVersion(search_engine_version_);
// pro_id_->back().setIdentifier(search_engine_);
// SearchParameters search_parameters_
// DateTime date_
// String protein_score_type_ <- from ProteinDetectionProtocol
// DoubleReal protein_significance_threshold_ <- from ProteinDetectionProtocol
DOMElement* child = element_pr->getFirstElementChild();
while (child)
{
if (XMLString::equals(child->getTagName(), CONST_XMLCH("ProteinAmbiguityGroup")))
{
parseProteinAmbiguityGroupElement_(child, pro_id_->back());
}
child = child->getNextElementSibling();
}
}
}
}
void MzIdentMLDOMHandler::parseProteinAmbiguityGroupElement_(DOMElement* proteinAmbiguityGroupElement, ProteinIdentification& protein_identification)
{
// String id = StringManager::convert(proteinAmbiguityGroupElement->getAttribute(CONST_XMLCH("id")));
// pair<CVTermList, map<String, DataValue> > params = parseParamGroup_(proteinAmbiguityGroupElement->getChildNodes());
//fill pro_id_->back() with content,
DOMElement* child = proteinAmbiguityGroupElement->getFirstElementChild();
while (child)
{
if (XMLString::equals(child->getTagName(), CONST_XMLCH("ProteinDetectionHypothesis")))
{
parseProteinDetectionHypothesisElement_(child, protein_identification);
}
child = child->getNextElementSibling();
}
}
void MzIdentMLDOMHandler::parseProteinDetectionHypothesisElement_(DOMElement* proteinDetectionHypothesisElement, ProteinIdentification& protein_identification)
{
String dBSequence_ref = StringManager::convert(proteinDetectionHypothesisElement->getAttribute(CONST_XMLCH("dBSequence_ref")));
// pair<CVTermList, map<String, DataValue> > params = parseParamGroup_(proteinDetectionHypothesisElement->getChildNodes());
DBSequence& db = db_sq_map_[dBSequence_ref];
protein_identification.insertHit(ProteinHit());
protein_identification.getHits().back().setSequence(db.sequence);
protein_identification.getHits().back().setAccession(db.accession);
// protein_identification.getHits().back().setCoverage((long double)params.first.getCVTerms()["MS:1001093"].front().getValue()); //TODO @ mths: calc percent
// protein_identification.getHits().back().setScore(boost::lexical_cast<double>(params.first.getCVTerms()["MS:1001171"].front().getValue())); //or any other score
}
AASequence MzIdentMLDOMHandler::parsePeptideSiblings_(DOMElement* peptide)
{
DOMNodeList* peptideSiblings = peptide->getChildNodes();
const XMLSize_t node_count = peptideSiblings->getLength();
String as;
//1. Sequence
for (XMLSize_t c = 0; c < node_count; ++c)
{
DOMNode* current_sib = peptideSiblings->item(c);
if (current_sib->getNodeType() && // true is not NULL
current_sib->getNodeType() == DOMNode::ELEMENT_NODE)
{
DOMElement* element_sib = dynamic_cast<xercesc::DOMElement*>(current_sib);
if (XMLString::equals(element_sib->getTagName(), CONST_XMLCH("PeptideSequence")))
{
DOMNode* tn = element_sib->getFirstChild();
if (tn->getNodeType() == DOMNode::TEXT_NODE)
{
DOMText* data = dynamic_cast<DOMText*>(tn);
const XMLCh* val = data->getWholeText();
as = StringManager::convert(val);
}
else
{
throw std::runtime_error("ERROR : Non Text Node");
}
}
}
}
//2. Substitutions
for (XMLSize_t c = 0; c < node_count; ++c)
{
DOMNode* current_sib = peptideSiblings->item(c);
if (current_sib->getNodeType() && // true is not NULL
current_sib->getNodeType() == DOMNode::ELEMENT_NODE)
{
DOMElement* element_sib = dynamic_cast<xercesc::DOMElement*>(current_sib);
if (XMLString::equals(element_sib->getTagName(), CONST_XMLCH("SubstitutionModification")))
{
String location = StringManager::convert(element_sib->getAttribute(CONST_XMLCH("location")));
char originalResidue = StringManager::convert(element_sib->getAttribute(CONST_XMLCH("originalResidue")))[0];
char replacementResidue = StringManager::convert(element_sib->getAttribute(CONST_XMLCH("replacementResidue")))[0];
if (!location.empty())
{
as[location.toInt() - 1] = replacementResidue;
}
else if (as.hasSubstring(originalResidue)) //no location - every occurrence will be replaced
{
as.substitute(originalResidue, replacementResidue);
}
else
{
throw std::runtime_error("ERROR : Non Text Node");
}
}
}
}
//3. Modifications
as.trim();
AASequence aas = AASequence::fromString(as);
for (XMLSize_t c = 0; c < node_count; ++c)
{
DOMNode* current_sib = peptideSiblings->item(c);
if (current_sib->getNodeType() && // true is not NULL
current_sib->getNodeType() == DOMNode::ELEMENT_NODE)
{
DOMElement* element_sib = dynamic_cast<xercesc::DOMElement*>(current_sib);
if (XMLString::equals(element_sib->getTagName(), CONST_XMLCH("Modification")))
{
SignedSize index = -2;
try
{
index = static_cast<SignedSize>(StringManager::convert(element_sib->getAttribute(CONST_XMLCH("location"))).toInt());
}
catch (...)
{
OPENMS_LOG_WARN << "Found unreadable modification location." << endl;
}
//double monoisotopicMassDelta = StringManager::convert(element_dbs->getAttribute(CONST_XMLCH("monoisotopicMassDelta")));
if (xl_ms_search_) // special case: XL-MS search results
{
String pep_id = StringManager::convert(peptide->getAttribute(CONST_XMLCH("id")));
//DOMNodeList* cvParams = element_sib->getElementsByTagName(CONST_XMLCH("cvParam"));
DOMElement* cvp = element_sib->getFirstElementChild();
//for (XMLSize_t i = 0; i < cvParams.length(); ++i)
bool donor_acceptor_found = false;
bool xlink_mod_found = false;
while (cvp)
{
if (XMLString::equals(cvp->getAttribute(CONST_XMLCH("accession")), CONST_XMLCH("MS:1002509"))) // crosslink donor
{
String donor_val = StringManager::convert(cvp->getAttribute(CONST_XMLCH("value")));
xl_id_donor_map_.insert(make_pair(pep_id, donor_val));
String massdelta = StringManager::convert(element_sib->getAttribute(CONST_XMLCH("monoisotopicMassDelta")));
double monoisotopicMassDelta = massdelta.toDouble();
xl_mass_map_.insert(make_pair(pep_id, monoisotopicMassDelta));
xl_donor_pos_map_.insert(make_pair(donor_val, index-1));
DOMElement* cvp1 = element_sib->getFirstElementChild();
String xl_mod_name = StringManager::convert(cvp1->getAttribute(CONST_XMLCH("name")));
xl_mod_map_.insert(make_pair(pep_id, xl_mod_name));
donor_acceptor_found = true;
}
else if (XMLString::equals(cvp->getAttribute(CONST_XMLCH("accession")), CONST_XMLCH("MS:1002510"))) // crosslink acceptor
{
String acceptor_val = StringManager::convert(cvp->getAttribute(CONST_XMLCH("value")));
xl_id_acceptor_map_.insert(make_pair(pep_id, acceptor_val));
xl_acceptor_pos_map_.insert(make_pair(acceptor_val, index-1));
donor_acceptor_found = true;
}
else
{
CVTerm cv = parseCvParam_(cvp);
const String& cvname = cv.getName();
if (cvname.hasPrefix("Xlink") || cv.getAccession().hasPrefix("XLMOD"))
{
xlink_mod_found = true;
}
if (cvname.hasSubstring("unknown mono-link"))
{
xl_mod_map_.insert(make_pair(pep_id, cvname));
}
else // normal mod, copied from below
{
if ( (cv.getCVIdentifierRef() != "UNIMOD") && (cv.getCVIdentifierRef() != "XLMOD") )
{
// e.g. <cvParam accession="MS:1001524" name="fragment neutral loss" cvRef="PSI-MS" value="0" unitAccession="UO:0000221" unitName="dalton" unitCvRef="UO"/>
cvp = cvp->getNextElementSibling();
continue;
}
if (index == 0)
{
try // does not work for cross-links yet, but the information is finally stored as MetaValues of the PeptideHit
{
if (cvname == "unknown modification")
{
const String & cvvalue = cv.getValue();
if (ModificationsDB::getInstance()->has(cvvalue) && !cvvalue.empty())
{
aas.setNTerminalModification(cv.getValue());
}
}
else
{
aas.setNTerminalModification(cvname);
}
cvp = cvp->getNextElementSibling();
continue;
}
catch (...)
{
// TODO Residue and AASequence should use CrossLinksDB as well
}
}
else if (index == static_cast<SignedSize>(aas.size() + 1))
{
// TODO: does not work for cross-links yet, but the information is finally stored as MetaValues of the PeptideHit
if (cvname == "unknown modification")
{
const String & cvvalue = cv.getValue();
if (ModificationsDB::getInstance()->has(cvvalue) && !cvvalue.empty())
{
aas.setCTerminalModification(cvvalue);
}
else
{
OPENMS_LOG_WARN << "Modification: " << cvvalue << " not found in ModificationsDB." << endl;
// TODO? @enetz look it up in XLDB?
}
}
else
{
if (ModificationsDB::getInstance()->has(cvname))
{
aas.setCTerminalModification(cvname);
}
else
{
OPENMS_LOG_WARN << "Modification: " << cvname << " not found in ModificationsDB." << endl;
// TODO? @enetz look it up in XLDB?
}
}
cvp = cvp->getNextElementSibling();
continue;
}
else
{
if (cvname == "unknown modification")
{
const String & cvvalue = cv.getValue();
if (ModificationsDB::getInstance()->has(cvvalue) && !cvvalue.empty())
{
aas.setModification(index - 1, cvvalue);
}
else
{
OPENMS_LOG_WARN << "Modification: " << cvvalue << " not found in ModificationsDB." << endl;
// TODO? @enetz look it up in XLDB?
}
}
else
{
if (ModificationsDB::getInstance()->has(cvname))
{
aas.setModification(index - 1, cvname);
}
else
{
OPENMS_LOG_WARN << "Modification: " << cvname << " not found in ModificationsDB." << endl;
// TODO? @enetz look it up in XLDB?
}
}
cvp = cvp->getNextElementSibling();
continue;
/* TODO enetz: look up in XLDB and remove this ha
// this is a bad hack to avoid a long list of warnings in the case of XL-MS data
if ( !(String(e.what()).hasSubstring("'DSG'") || String(e.what()).hasSubstring("'DSS'") || String(e.what()).hasSubstring("'EDC'")) || String(e.what()).hasSubstring("'BS3'") || String(e.what()).hasSubstring("'BS2G'") )
{
OPENMS_LOG_WARN << e.getName() << ": " << e.what() << " Sequence: " << aas.toUnmodifiedString() << ", residue " << aas.getResidue(index - 1).getName() << "@" << String(index) << endl;
}
*/
}
}
}
cvp = cvp->getNextElementSibling();
}
if ( (!donor_acceptor_found) && (xlink_mod_found) ) // mono-link, here using pep_id also as the CV value, since mono-links don't have a cross-linking CV term
{
xl_id_donor_map_.insert(make_pair(pep_id, pep_id));
xl_donor_pos_map_.insert(make_pair(pep_id, index-1));
}
}
else // general case: no XL-MS result
{
DOMElement* cvp = element_sib->getFirstElementChild();
while (cvp)
{
CVTerm cv = parseCvParam_(cvp);
if (cv.getAccession() == "MS:1001460") // unknown modification
{
const String & cvvalue = cv.getValue();
if (cv.hasValue() && ModificationsDB::getInstance()->has(cvvalue) && !cvvalue.empty()) // why do we need to check for empty?
{
// Case 1: unknown (to e.g., third-party tool) modification known to OpenMS (see value)
// <Modification location="0" monoisotopicMassDelta="17.031558">
// <cvParam cvRef="PSI-MS" accession="MS:1001460" name="unknown modification" value="Methyl:2H(2)13C"/>
const String & mname = cvvalue;
if (index == 0)
{
aas.setNTerminalModification(mname);
}
else if (index == (int)aas.size() + 1)
{
aas.setCTerminalModification(mname);
}
else if (index > 0 && index <= (int)aas.size() )
{
aas.setModification(index - 1, mname);
}
cvp = cvp->getNextElementSibling();
continue;
}
else
{
// Case 2: unknown modification (needs to be added to ModificationsDB)
// note, this is optional
double mass_delta = 0;
bool has_mass_delta = false;
String mod;
// try to parse information, give up if we cannot
try
{
mod = StringManager::convert(element_sib->getAttribute(CONST_XMLCH("monoisotopicMassDelta")));
mass_delta = static_cast<double>(mod.toDouble());
has_mass_delta = true;
}
catch (...)
{
OPENMS_LOG_WARN << "Found unreadable modification location." << endl;
throw Exception::MissingInformation(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Unknown modification");
}
if (!has_mass_delta)
{
throw Exception::MissingInformation(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Unknown modification");
}
// Parse this and add a new modification of mass "monoisotopicMassDelta" to the AASequence
// e.g. <cvParam cvRef="MS" accession="MS:1001460" name="unknown modification" value="N-Glycan"/>
// compare with String::ConstIterator AASequence::parseModSquareBrackets_
ModificationsDB* mod_db = ModificationsDB::getInstance();
if (index == 0)
{
// n-terminal
String residue_name = ".[+" + mod + "]";
String residue_id = ".n[" + mod + "]";
// Check if it already exists, if not create new modification, transfer
// ownership to ModDB
if (!mod_db->has(residue_id))
{
unique_ptr<ResidueModification> new_mod(new ResidueModification);
new_mod->setFullId(residue_id); // setting FullId but not Id makes it a user-defined mod
new_mod->setFullName(residue_name); // display name
new_mod->setDiffMonoMass(mass_delta);
new_mod->setMonoMass(mass_delta + Residue::getInternalToNTerm().getMonoWeight());
new_mod->setTermSpecificity(ResidueModification::N_TERM);
mod_db->addModification(std::move(new_mod));
}
aas.setNTerminalModification(residue_id);
cvp = cvp->getNextElementSibling();
continue;
}
else if (index == (int)aas.size() +1)
{
// c-terminal
String residue_name = ".[" + mod + "]";
String residue_id = ".c[" + mod + "]";
// Check if it already exists, if not create new modification, transfer
// ownership to ModDB
if (!mod_db->has(residue_name))
{
unique_ptr<ResidueModification> new_mod(new ResidueModification);
new_mod->setFullId(residue_id); // setting FullId but not Id makes it a user-defined mod
new_mod->setFullName(residue_name); // display name
new_mod->setDiffMonoMass(mass_delta);
new_mod->setMonoMass(mass_delta + Residue::getInternalToCTerm().getMonoWeight());
new_mod->setTermSpecificity(ResidueModification::C_TERM);
mod_db->addModification(std::move(new_mod));
}
aas.setCTerminalModification(residue_id);
cvp = cvp->getNextElementSibling();
continue;
}
else if (index > 0 && index <= (int)aas.size() )
{
// internal modification
const Residue& residue = aas[index-1];
String residue_name = residue.getOneLetterCode() + "[" + mod + "]"; // e.g. N[12345.6]
String modification_name = "[" + mod + "]";
if (!mod_db->has(residue_name))
{
// create new modification
unique_ptr<ResidueModification> new_mod(new ResidueModification);
new_mod->setFullId(residue_name); // setting FullId but not Id makes it a user-defined mod
new_mod->setFullName(modification_name); // display name
// We will set origin to make sure the same modification will be used
// for the same AA
new_mod->setOrigin(residue.getOneLetterCode()[0]);
// We cannot set origin if we want to use the same modification name
// also at other AA (and since we have no information here, it is safer
// to assume that this may happen).
// new_mod->setOrigin(residue.getOneLetterCode()[0]);
new_mod->setMonoMass(mass_delta + residue.getMonoWeight());
new_mod->setAverageMass(mass_delta + residue.getAverageWeight());
new_mod->setDiffMonoMass(mass_delta);
mod_db->addModification(std::move(new_mod));
}
// now use the new modification
Size mod_idx = mod_db->findModificationIndex(residue_name);
const ResidueModification* res_mod = mod_db->getModification(mod_idx);
// Set a modification on the given AA
// Note: this calls setModification_ on a new Residue which changes its
// weight to the weight of the modification (set above)
//
aas.setModification(index-1, res_mod->getFullId());
cvp = cvp->getNextElementSibling();
continue;
}
}
}
if (cv.getCVIdentifierRef() != "UNIMOD")
{
// e.g. <cvParam accession="MS:1001524" name="fragment neutral loss" cvRef="PSI-MS" value="0" unitAccession="UO:0000221" unitName="dalton" unitCvRef="UO"/>
cvp = cvp->getNextElementSibling();
continue;
}
if (index == 0)
{
if (cv.getName() == "unknown modification")
{
aas.setNTerminalModification(cv.getValue());
cvp = cvp->getNextElementSibling();
continue;
}
else
{
aas.setNTerminalModification(cv.getName());
cvp = cvp->getNextElementSibling();
continue;
}
}
else if (index == static_cast<SignedSize>(aas.size() + 1))
{
aas.setCTerminalModification(cv.getName());
cvp = cvp->getNextElementSibling();
continue;
}
else
{
try
{
aas.setModification(index - 1, cv.getName()); //TODO @mths,Timo : do this via UNIMOD accessions
cvp = cvp->getNextElementSibling();
continue;
}
catch (Exception::BaseException& e)
{
OPENMS_LOG_WARN << e.getName() << ": " << e.what() << " Sequence: " << aas.toUnmodifiedString() << ", residue " << aas.getResidue(index - 1).getName() << "@" << String(index) << "\n";
}
}
cvp = cvp->getNextElementSibling();
}
}
}
}
}
return aas;
}
void MzIdentMLDOMHandler::buildCvList_(DOMElement* cvElements)
{
DOMElement* cv1 = cvElements->getOwnerDocument()->createElement(CONST_XMLCH("cv"));
cv1->setAttribute(CONST_XMLCH("id"), CONST_XMLCH("PSI-MS"));
cv1->setAttribute(CONST_XMLCH("fullName"),
CONST_XMLCH("Proteomics Standards Initiative Mass Spectrometry Vocabularies"));
cv1->setAttribute(CONST_XMLCH("uri"),
CONST_XMLCH("http://psidev.cvs.sourceforge.net/viewvc/*checkout*/psidev/psi/psi-ms/mzML/controlledVocabulary/psi-ms.obo"));
cv1->setAttribute(CONST_XMLCH("version"), CONST_XMLCH("2.32.0"));
cvElements->appendChild(cv1);
DOMElement* cv2 = cvElements->getOwnerDocument()->createElement(CONST_XMLCH("cv"));
cv2->setAttribute(CONST_XMLCH("id"), CONST_XMLCH("UNIMOD"));
cv2->setAttribute(CONST_XMLCH("fullName"),
CONST_XMLCH("UNIMOD"));
cv2->setAttribute(CONST_XMLCH("uri"),
CONST_XMLCH("http://www.unimod.org/obo/unimod.obo"));
cvElements->appendChild(cv2);
DOMElement* cv3 = cvElements->getOwnerDocument()->createElement(CONST_XMLCH("cv"));
cv3->setAttribute(CONST_XMLCH("id"), CONST_XMLCH("UO"));
cv3->setAttribute(CONST_XMLCH("fullName"),
CONST_XMLCH("UNIT-ONTOLOGY"));
cv3->setAttribute(CONST_XMLCH("uri"),
CONST_XMLCH("http://obo.cvs.sourceforge.net/*checkout*/obo/obo/ontology/phenotype/unit.obo"));
cvElements->appendChild(cv3);
}
void MzIdentMLDOMHandler::buildAnalysisSoftwareList_(DOMElement* analysisSoftwareElements)
{
DOMElement* current_as = analysisSoftwareElements->getOwnerDocument()->createElement(CONST_XMLCH("AnalysisSoftware"));
current_as->setAttribute(CONST_XMLCH("id"), StringManager::convertPtr((String("OpenMS") + UniqueIdGenerator::getUniqueId())).get());
current_as->setAttribute(CONST_XMLCH("version"), CONST_XMLCH("search_engine_version_"));
current_as->setAttribute(CONST_XMLCH("name"), CONST_XMLCH("search_engine_"));
analysisSoftwareElements->appendChild(current_as);
DOMElement* current_sw = current_as->getOwnerDocument()->createElement(CONST_XMLCH("SoftwareName"));
//TODO build extract as function and insert cv
DOMElement* current_cv = current_sw->getOwnerDocument()->createElement(CONST_XMLCH("cvParam"));
current_cv->setAttribute(CONST_XMLCH("name"), CONST_XMLCH("search_engine_"));
current_cv->setAttribute(CONST_XMLCH("cvRef"), CONST_XMLCH("PSI-MS"));
//TODO this needs error handling
current_cv->setAttribute(CONST_XMLCH("accession"), StringManager::convertPtr(cv_.getTermByName("search_engine_").id).get());
current_sw->appendChild(current_cv);
analysisSoftwareElements->appendChild(current_sw);
}
void MzIdentMLDOMHandler::buildSequenceCollection_(DOMElement* sequenceCollectionElements)
{
for (map<String, DBSequence>::iterator dbs = db_sq_map_.begin(); dbs != db_sq_map_.end(); ++dbs)
{
DOMElement* current_dbs = sequenceCollectionElements->getOwnerDocument()->createElement(CONST_XMLCH("DBSequence"));
current_dbs->setAttribute(CONST_XMLCH("id"), StringManager::convertPtr(dbs->second.accession).get());
current_dbs->setAttribute(CONST_XMLCH("length"), StringManager::convertPtr(String(dbs->second.sequence.length())).get());
current_dbs->setAttribute(CONST_XMLCH("accession"), StringManager::convertPtr(dbs->second.accession).get());
current_dbs->setAttribute(CONST_XMLCH("searchDatabase_ref"), StringManager::convertPtr(dbs->second.database_ref).get()); // This is going to be wrong
DOMElement* current_seq = current_dbs->getOwnerDocument()->createElement(CONST_XMLCH("Seq"));
DOMText* current_seqnot = current_seq->getOwnerDocument()->createTextNode(StringManager::convertPtr(dbs->second.sequence).get());
current_seq->appendChild(current_seqnot);
current_dbs->appendChild(current_seq);
sequenceCollectionElements->appendChild(current_dbs);
}
for (map<String, AASequence>::iterator peps = pep_map_.begin(); peps != pep_map_.end(); ++peps)
{
DOMElement* current_pep = sequenceCollectionElements->getOwnerDocument()->createElement(CONST_XMLCH("Peptide"));
current_pep->setAttribute(CONST_XMLCH("id"), StringManager::convertPtr(peps->first).get());
DOMElement* current_seq = current_pep->getOwnerDocument()->createElement(CONST_XMLCH("PeptideSequence"));
DOMText* current_seqnot = current_seq->getOwnerDocument()->createTextNode(StringManager::convertPtr(peps->second.toUnmodifiedString()).get());
current_seq->appendChild(current_seqnot);
current_pep->appendChild(current_seq);
if (peps->second.hasNTerminalModification())
{
const ResidueModification* mod = peps->second.getNTerminalModification();
DOMElement* current_mod = current_pep->getOwnerDocument()->createElement(CONST_XMLCH("Modification"));
DOMElement* current_cv = current_pep->getOwnerDocument()->createElement(CONST_XMLCH("cvParam"));
current_mod->setAttribute(CONST_XMLCH("location"), CONST_XMLCH("0"));
current_mod->setAttribute(CONST_XMLCH("monoisotopicMassDelta"), StringManager::convertPtr(String(mod->getDiffMonoMass())).get());
String origin = mod->getOrigin();
if (origin == "X") origin = ".";
current_mod->setAttribute(CONST_XMLCH("residues"), StringManager::convertPtr(origin).get());
current_cv->setAttribute(CONST_XMLCH("name"), StringManager::convertPtr(mod->getName()).get());
current_cv->setAttribute(CONST_XMLCH("cvRef"), CONST_XMLCH("UNIMOD"));
current_cv->setAttribute(CONST_XMLCH("accession"), StringManager::convertPtr(mod->getUniModAccession()).get());
current_mod->appendChild(current_cv);
current_pep->appendChild(current_mod);
}
if (peps->second.hasCTerminalModification())
{
const ResidueModification* mod = peps->second.getCTerminalModification();
DOMElement* current_mod = current_pep->getOwnerDocument()->createElement(CONST_XMLCH("Modification"));
DOMElement* current_cv = current_mod->getOwnerDocument()->createElement(CONST_XMLCH("cvParam"));
current_mod->setAttribute(CONST_XMLCH("location"), StringManager::convertPtr(String(peps->second.size() + 1)).get());
current_mod->setAttribute(CONST_XMLCH("monoisotopicMassDelta"), StringManager::convertPtr(String(mod->getDiffMonoMass())).get());
String origin = mod->getOrigin();
if (origin == "X") origin = ".";
current_mod->setAttribute(CONST_XMLCH("residues"), StringManager::convertPtr(origin).get());
current_cv->setAttribute(CONST_XMLCH("name"), StringManager::convertPtr(mod->getName()).get());
current_cv->setAttribute(CONST_XMLCH("cvRef"), CONST_XMLCH("UNIMOD"));
current_cv->setAttribute(CONST_XMLCH("accession"), StringManager::convertPtr(mod->getUniModAccession()).get());
current_mod->appendChild(current_cv);
current_pep->appendChild(current_mod);
}
if (peps->second.isModified())
{
Size i = 0;
for (AASequence::ConstIterator res = peps->second.begin(); res != peps->second.end(); ++res, ++i)
{
const ResidueModification* mod = res->getModification();
if (mod == nullptr) continue;
DOMElement* current_mod = current_pep->getOwnerDocument()->createElement(CONST_XMLCH("Modification"));
DOMElement* current_cv = current_pep->getOwnerDocument()->createElement(CONST_XMLCH("cvParam"));
current_mod->setAttribute(CONST_XMLCH("location"), StringManager::convertPtr(String(i)).get());
current_mod->setAttribute(CONST_XMLCH("monoisotopicMassDelta"), StringManager::convertPtr(String(mod->getDiffMonoMass())).get());
current_mod->setAttribute(CONST_XMLCH("residues"), StringManager::convertPtr(String(mod->getOrigin())).get());
current_cv->setAttribute(CONST_XMLCH("name"), StringManager::convertPtr(mod->getName()).get());
current_cv->setAttribute(CONST_XMLCH("cvRef"), CONST_XMLCH("UNIMOD"));
current_cv->setAttribute(CONST_XMLCH("accession"), StringManager::convertPtr(mod->getUniModAccession()).get());
current_mod->appendChild(current_cv);
current_pep->appendChild(current_mod);
}
}
sequenceCollectionElements->appendChild(current_pep);
}
for (map<String, PeptideEvidence>::iterator pevs = pe_ev_map_.begin(); pevs != pe_ev_map_.end(); ++pevs)
{
DOMElement* current_pev = sequenceCollectionElements->getOwnerDocument()->createElement(CONST_XMLCH("PeptideEvidence"));
current_pev->setAttribute(CONST_XMLCH("peptide_ref"), CONST_XMLCH("TBA"));
current_pev->setAttribute(CONST_XMLCH("id"), StringManager::convertPtr(pevs->first).get());
current_pev->setAttribute(CONST_XMLCH("start"), StringManager::convertPtr(String(pevs->second.start)).get());
current_pev->setAttribute(CONST_XMLCH("end"), StringManager::convertPtr(String(pevs->second.stop)).get());
current_pev->setAttribute(CONST_XMLCH("pre"), StringManager::convertPtr(String(pevs->second.pre)).get());
current_pev->setAttribute(CONST_XMLCH("post"), StringManager::convertPtr(String(pevs->second.post)).get());
// do not forget to annotate the decoy
current_pev->setAttribute(CONST_XMLCH("isDecoy"), CONST_XMLCH("false"));
sequenceCollectionElements->appendChild(current_pev);
}
}
void MzIdentMLDOMHandler::buildAnalysisCollection_(DOMElement* analysisCollectionElements)
{
// for now there is only one search per file
DOMElement* current_si = analysisCollectionElements->getOwnerDocument()->createElement(CONST_XMLCH("SpectrumIdentification"));
current_si->setAttribute(CONST_XMLCH("id"), CONST_XMLCH("TBA"));
current_si->setAttribute(CONST_XMLCH("spectrumIdentificationProtocol_ref"), CONST_XMLCH("SIP"));
current_si->setAttribute(CONST_XMLCH("spectrumIdentificationList_ref"), CONST_XMLCH("SIL"));
current_si->setAttribute(CONST_XMLCH("activityDate"), CONST_XMLCH("now"));
DOMElement* current_is = current_si->getOwnerDocument()->createElement(CONST_XMLCH("InputSpectra"));
current_is->setAttribute(CONST_XMLCH("spectraData_ref"), CONST_XMLCH("TODO")); // TODO @ mths while DataCollection
DOMElement* current_sr = current_si->getOwnerDocument()->createElement(CONST_XMLCH("SearchDatabaseRef"));
current_sr->setAttribute(CONST_XMLCH("searchDatabase_ref"), CONST_XMLCH("TODO")); // TODO @ mths while DataCollection
current_si->appendChild(current_is);
current_si->appendChild(current_sr);
// and no ProteinDetection for now
analysisCollectionElements->appendChild(current_si);
}
void MzIdentMLDOMHandler::buildAnalysisProtocolCollection_(DOMElement* protocolElements)
{
// for now there is only one search per file
DOMElement* current_sp = protocolElements->getOwnerDocument()->createElement(CONST_XMLCH("SpectrumIdentificationProtocol"));
current_sp->setAttribute(CONST_XMLCH("id"), CONST_XMLCH("SIP"));
current_sp->setAttribute(CONST_XMLCH("analysisSoftware_ref"), CONST_XMLCH("what now?"));
protocolElements->appendChild(current_sp);
DOMElement* current_st = current_sp->getOwnerDocument()->createElement(CONST_XMLCH("SearchType"));
current_sp->appendChild(current_st);
DOMElement* current_cv = current_st->getOwnerDocument()->createElement(CONST_XMLCH("cvParam"));
current_cv->setAttribute(CONST_XMLCH("accession"), CONST_XMLCH("MS:1001083")); // TODO @ mths for now static cv
current_cv->setAttribute(CONST_XMLCH("name"), CONST_XMLCH("ms-ms search"));
current_cv->setAttribute(CONST_XMLCH("cvRef"), CONST_XMLCH("PSI-MS"));
current_st->appendChild(current_cv);
//for now no <AdditionalSearchParams>, <ModificationParams>, <MassTable id="MT" msLevel="1 2">, <FragmentTolerance>, <ParentTolerance>, <DatabaseFilters>, <DatabaseTranslations>
DOMElement* current_th = current_sp->getOwnerDocument()->createElement(CONST_XMLCH("Threshold"));
DOMElement* current_up = current_th->getOwnerDocument()->createElement(CONST_XMLCH("userParam"));
current_up->setAttribute(CONST_XMLCH("value"), CONST_XMLCH("0.05")); // TODO @ mths for now static cv
current_up->setAttribute(CONST_XMLCH("name"), CONST_XMLCH("some significance threshold"));
current_st->appendChild(current_up);
// and no ProteinDetection for now
protocolElements->appendChild(current_th);
}
void MzIdentMLDOMHandler::buildInputDataCollection_(DOMElement* inputElements)
{
DOMElement* current_sf = inputElements->getOwnerDocument()->createElement(CONST_XMLCH("SourceFile"));
current_sf->setAttribute(CONST_XMLCH("location"), CONST_XMLCH("file:///tmp/test.dat"));
current_sf->setAttribute(CONST_XMLCH("id"), CONST_XMLCH("SF1"));
buildEnclosedCV_(current_sf, "FileFormat", "MS:1001199", "Mascot DAT file", "PSI-MS"); // TODO @ mths for now static cv
inputElements->appendChild(current_sf);
DOMElement* current_sd = inputElements->getOwnerDocument()->createElement(CONST_XMLCH("SearchDatabase"));
current_sd->setAttribute(CONST_XMLCH("location"), CONST_XMLCH("file:///tmp/test.fasta"));
current_sd->setAttribute(CONST_XMLCH("id"), CONST_XMLCH("DB1"));
current_sd->setAttribute(CONST_XMLCH("name"), CONST_XMLCH("SwissProt"));
current_sd->setAttribute(CONST_XMLCH("numDatabaseSequences"), CONST_XMLCH("257964"));
current_sd->setAttribute(CONST_XMLCH("numResidues"), CONST_XMLCH("93947433"));
current_sd->setAttribute(CONST_XMLCH("releaseDate"), CONST_XMLCH("2011-03-01T21:32:52"));
current_sd->setAttribute(CONST_XMLCH("version"), CONST_XMLCH("SwissProt_51.6.fasta"));
buildEnclosedCV_(current_sd, "FileFormat", "MS:1001348", "FASTA format", "PSI-MS"); // TODO @ mths for now static cv
DOMElement* current_dn = current_sd->getOwnerDocument()->createElement(CONST_XMLCH("DatabaseName"));
DOMElement* current_up = current_dn->getOwnerDocument()->createElement(CONST_XMLCH("userParam"));
current_up->setAttribute(CONST_XMLCH("name"), CONST_XMLCH("SwissProt_51.6.fasta")); // TODO @ mths for now static cv
current_dn->appendChild(current_up);
current_sd->appendChild(current_dn);
DOMElement* current_cv = current_sd->getOwnerDocument()->createElement(CONST_XMLCH("cvParam"));
current_cv->setAttribute(CONST_XMLCH("accession"), CONST_XMLCH("MS:1001073")); // TODO @ mths for now static cv
current_cv->setAttribute(CONST_XMLCH("name"), CONST_XMLCH("database type amino acid"));
current_cv->setAttribute(CONST_XMLCH("cvRef"), CONST_XMLCH("PSI-MS"));
current_sd->appendChild(current_cv);
inputElements->appendChild(current_sd);
DOMElement* current_spd = inputElements->getOwnerDocument()->createElement(CONST_XMLCH("SpectraData"));
current_spd->setAttribute(CONST_XMLCH("location"), CONST_XMLCH("file:///tmp/test.mzML"));
current_spd->setAttribute(CONST_XMLCH("id"), CONST_XMLCH("SD1"));
buildEnclosedCV_(current_spd, "FileFormat", "MS:1001062", "Mascot MGF file", "PSI-MS");
buildEnclosedCV_(current_spd, "SpectrumIDFormat", "MS:1001528", "Mascot query number", "PSI-MS");
inputElements->appendChild(current_spd);
}
void MzIdentMLDOMHandler::buildEnclosedCV_(DOMElement* parentElement, const String& encel, const String& acc, const String& name, const String& cvref)
{
DOMElement* current_ff = parentElement->getOwnerDocument()->createElement(StringManager::convertPtr(encel).get());
DOMElement* current_cv = current_ff->getOwnerDocument()->createElement(CONST_XMLCH("cvParam"));
current_cv->setAttribute(CONST_XMLCH("accession"), StringManager::convertPtr(acc).get());
current_cv->setAttribute(CONST_XMLCH("name"), StringManager::convertPtr(name).get());
current_cv->setAttribute(CONST_XMLCH("cvRef"), StringManager::convertPtr(cvref).get());
current_ff->appendChild(current_cv);
parentElement->appendChild(current_ff);
}
void MzIdentMLDOMHandler::buildAnalysisDataCollection_(DOMElement* analysisElements)
{
DOMElement* current_sil = analysisElements->getOwnerDocument()->createElement(CONST_XMLCH("SpectrumIdentificationList"));
current_sil->setAttribute(CONST_XMLCH("id"), CONST_XMLCH("SIL1"));
current_sil->setAttribute(CONST_XMLCH("numSequencesSearched"), CONST_XMLCH("TBA"));
// for now no FragmentationTable
for (PeptideIdentificationList::iterator pi = pep_id_->begin(); pi != pep_id_->end(); ++pi)
{
DOMElement* current_sr = current_sil->getOwnerDocument()->createElement(CONST_XMLCH("SpectrumIdentificationResult"));
current_sr->setAttribute(CONST_XMLCH("id"), StringManager::convertPtr(String(UniqueIdGenerator::getUniqueId())).get());
current_sr->setAttribute(CONST_XMLCH("spectrumID"), StringManager::convertPtr(String(UniqueIdGenerator::getUniqueId())).get());
current_sr->setAttribute(CONST_XMLCH("spectraData_ref"), CONST_XMLCH("SD1"));
for (vector<PeptideHit>::iterator ph = pi->getHits().begin(); ph != pi->getHits().end(); ++ph)
{
DOMElement* current_si = current_sr->getOwnerDocument()->createElement(CONST_XMLCH("SpectrumIdentificationItem"));
current_si->setAttribute(CONST_XMLCH("id"), StringManager::convertPtr(String(UniqueIdGenerator::getUniqueId())).get());
current_si->setAttribute(CONST_XMLCH("calculatedMassToCharge"), StringManager::convertPtr(String(ph->getSequence().getMonoWeight(Residue::Full, ph->getCharge()))).get()); //TODO @mths : this is not correct!1elf - these interfaces are BS!
current_si->setAttribute(CONST_XMLCH("chargeState"), StringManager::convertPtr(String(ph->getCharge())).get());
current_si->setAttribute(CONST_XMLCH("experimentalMassToCharge"), StringManager::convertPtr(String(ph->getSequence().getMonoWeight(Residue::Full, ph->getCharge()))).get()); //TODO @mths : this is not correct!1elf - these interfaces are BS!
current_si->setAttribute(CONST_XMLCH("peptide_ref"), CONST_XMLCH("TBA"));
current_si->setAttribute(CONST_XMLCH("rank"), StringManager::convertPtr(String(ph->getRank() + 1)).get());
current_si->setAttribute(CONST_XMLCH("passThreshold"), CONST_XMLCH("TBA"));
current_si->setAttribute(CONST_XMLCH("sample_ref"), CONST_XMLCH("TBA"));
// TODO cvs for score!
current_sr->appendChild(current_si);
for (list<String>::iterator pepevref = hit_pev_.front().begin(); pepevref != hit_pev_.front().end(); ++pepevref)
{
DOMElement* current_per = current_si->getOwnerDocument()->createElement(CONST_XMLCH("PeptideEvidenceRef"));
current_per->setAttribute(CONST_XMLCH("peptideEvidence_ref"), StringManager::convertPtr(*pepevref).get());
current_si->appendChild(current_per);
}
hit_pev_.pop_front();
// and no Fragmentation annotation for now
}
// <cvParam accession="MS:1001371" name="Mascot:identity threshold" cvRef="PSI-MS" value="44"/>
// <cvParam accession="MS:1001370" name="Mascot:homology threshold" cvRef="PSI-MS" value="18"/>
// <cvParam accession="MS:1001030" name="number of peptide seqs compared to each spectrum" cvRef="PSI-MS" value="26981"/>
// <cvParam accession="MS:1000796" name="spectrum title" cvRef="PSI-MS" value="dp210198 21-Jan-98 DERIVED SPECTRUM #9"/>
current_sil->appendChild(current_sr);
}
// and no ProteinDetection for now
}
ProteinIdentification::SearchParameters MzIdentMLDOMHandler::findSearchParameters_(pair<CVTermList, map<String, DataValue> > as_params)
{
ProteinIdentification::SearchParameters sp = ProteinIdentification::SearchParameters();
for (std::map<String, vector<CVTerm> >::const_iterator cvs = as_params.first.getCVTerms().begin(); cvs != as_params.first.getCVTerms().end(); ++cvs)
{
for (vector<CVTerm>::const_iterator cvit = cvs->second.begin(); cvit != cvs->second.end(); ++cvit)
{
sp.setMetaValue(cvs->first, cvit->getValue());
}
}
int minCharge = 0;
int maxCharge = 0;
for (map<String, DataValue>::const_iterator upit = as_params.second.begin(); upit != as_params.second.end(); ++upit)
{
if (upit->first == "taxonomy")
{
sp.taxonomy = upit->second.toString();
}
else if (upit->first == "charges")
{
sp.charges = upit->second.toString();
}
else if (upit->first == "MinCharge")
{
minCharge = upit->second.toString().toInt();
}
else if (upit->first == "MaxCharge")
{
maxCharge = upit->second.toString().toInt();
}
else if (upit->first == "NumTolerableTermini")
{
sp.enzyme_term_specificity = static_cast<EnzymaticDigestion::Specificity>(upit->second.toString().toInt());
}
else
{
sp.setMetaValue(upit->first, upit->second);
}
}
if (minCharge != 0 || maxCharge != 0) // this means "MinCharge" and "MaxCharge" get preference over "charges"
{
sp.charges = String(minCharge) + "-" + String(maxCharge);
}
return sp;
}
} // namespace OpenMS //namespace Internal
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/HANDLERS/TraMLHandler.cpp | .cpp | 70,733 | 1,746 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hannes Roest $
// $Authors: Andreas Bertsch, Hannes Roest $
// --------------------------------------------------------------------------
#include "OpenMS/CONCEPT/LogStream.h"
#include <OpenMS/FORMAT/HANDLERS/TraMLHandler.h>
#include <OpenMS/CHEMISTRY/ModificationsDB.h>
#include <OpenMS/SYSTEM/File.h>
#include <OpenMS/CONCEPT/PrecisionWrapper.h>
#include <ostream>
#include <map>
namespace OpenMS::Internal
{
TraMLHandler::TraMLHandler(const TargetedExperiment& exp, const String& filename, const String& version, const ProgressLogger& logger) :
XMLHandler(filename, version),
logger_(logger),
exp_(nullptr),
cexp_(&exp)
{
cv_.loadFromOBO("PI", File::find("/CV/psi-ms.obo"));
}
TraMLHandler::TraMLHandler(TargetedExperiment& exp, const String& filename, const String& version, const ProgressLogger& logger) :
XMLHandler(filename, version),
logger_(logger),
exp_(&exp),
cexp_(nullptr)
{
cv_.loadFromOBO("PI", File::find("/CV/psi-ms.obo"));
}
TraMLHandler::~TraMLHandler()
= default;
void TraMLHandler::startElement(const XMLCh* const /*uri*/, const XMLCh* const /*local_name*/, const XMLCh* const qname, const xercesc::Attributes& attributes)
{
static const XMLCh* s_type = xercesc::XMLString::transcode("type");
static const XMLCh* s_value = xercesc::XMLString::transcode("value");
static const XMLCh* s_name = xercesc::XMLString::transcode("name");
static const XMLCh* s_id = xercesc::XMLString::transcode("id");
static const XMLCh* s_sequence = xercesc::XMLString::transcode("sequence");
static const XMLCh* s_fullName = xercesc::XMLString::transcode("fullName");
static const XMLCh* s_version = xercesc::XMLString::transcode("version");
static const XMLCh* s_URI = xercesc::XMLString::transcode("URI");
tag_ = sm_.convert(qname);
open_tags_.push_back(tag_);
static std::set<String> tags_to_ignore;
if (tags_to_ignore.empty())
{
tags_to_ignore.insert("TraML"); // base node
tags_to_ignore.insert("ContactList"); // contains only contact sections
tags_to_ignore.insert("CompoundList"); // contains only compounds
tags_to_ignore.insert("TransitionList"); // contains only transitions
tags_to_ignore.insert("ConfigurationList"); // contains only configurations
tags_to_ignore.insert("cvList"); // contains only CVs
tags_to_ignore.insert("InstrumentList"); // contains only instruments
tags_to_ignore.insert("SoftwareList"); // contains only software
tags_to_ignore.insert("PublicationList"); // contains only publications
tags_to_ignore.insert("ProteinList"); // contains only proteins
tags_to_ignore.insert("SourceFileList"); // contains only source files
tags_to_ignore.insert("InterpretationList"); // contains only interpretations
tags_to_ignore.insert("Evidence"); // only cv terms
tags_to_ignore.insert("ValidationStatus"); // only cv terms
tags_to_ignore.insert("Sequence"); // only sequence as characters
tags_to_ignore.insert("Precursor"); // contains only cv terms
tags_to_ignore.insert("Product"); // contains no attributes
tags_to_ignore.insert("IntermediateProduct"); // contains no attributes
tags_to_ignore.insert("TargetIncludeList");
tags_to_ignore.insert("TargetExcludeList");
tags_to_ignore.insert("TargetList");
tags_to_ignore.insert("RetentionTimeList");
}
// skip tags where nothing is to do
if (tags_to_ignore.find(tag_) != tags_to_ignore.end())
{
return;
}
//determine parent tag
String parent_tag;
if (open_tags_.size() > 1)
{
parent_tag = *(open_tags_.end() - 2);
}
String parent_parent_tag;
if (open_tags_.size() > 2)
{
parent_parent_tag = *(open_tags_.end() - 3);
}
if (tag_ == "cvParam")
{
// These are here because of cppcheck
static const XMLCh* s_accession = xercesc::XMLString::transcode("accession");
static const XMLCh* s_unit_accession = xercesc::XMLString::transcode("unitAccession");
static const XMLCh* s_unit_name = xercesc::XMLString::transcode("unitName");
static const XMLCh* s_unit_cvref = xercesc::XMLString::transcode("unitCvRef");
static const XMLCh* s_unit_ref = xercesc::XMLString::transcode("cvRef");
String value, cv_ref, unit_accession, unit_name, unit_cv_ref;
optionalAttributeAsString_(value, attributes, s_value);
optionalAttributeAsString_(unit_accession, attributes, s_unit_accession);
optionalAttributeAsString_(unit_name, attributes, s_unit_name);
optionalAttributeAsString_(unit_cv_ref, attributes, s_unit_cvref);
optionalAttributeAsString_(cv_ref, attributes, s_unit_ref);
CVTerm::Unit unit(unit_accession, unit_name, unit_cv_ref);
CVTerm cv_term(attributeAsString_(attributes, s_accession),
attributeAsString_(attributes, s_name), cv_ref, value, unit);
handleCVParam_(parent_parent_tag, parent_tag, cv_term);
return;
}
else if (tag_ == "userParam")
{
String type = "";
optionalAttributeAsString_(type, attributes, s_type);
String value = "";
optionalAttributeAsString_(value, attributes, s_value);
handleUserParam_(parent_parent_tag, parent_tag, attributeAsString_(attributes, s_name), type, value);
}
else if (tag_ == "cv")
{
exp_->addCV(TargetedExperiment::CV(attributeAsString_(attributes, s_id),
attributeAsString_(attributes, s_fullName),
attributeAsString_(attributes, s_version),
attributeAsString_(attributes, s_URI)));
}
else if (tag_ == "Contact")
{
actual_contact_.id = attributeAsString_(attributes, s_id);
}
else if (tag_ == "Publication")
{
actual_publication_.id = attributeAsString_(attributes, s_id);
}
else if (tag_ == "Instrument")
{
actual_instrument_.id = attributeAsString_(attributes, s_id);
}
else if (tag_ == "Software")
{
actual_software_.setName(attributeAsString_(attributes, s_id));
actual_software_.setVersion(attributeAsString_(attributes, s_version));
}
else if (tag_ == "Protein")
{
actual_protein_ = TargetedExperiment::Protein();
actual_protein_.id = attributeAsString_(attributes, s_id);
}
else if (tag_ == "Peptide")
{
actual_peptide_ = TargetedExperiment::Peptide();
actual_peptide_.id = attributeAsString_(attributes, s_id);
actual_peptide_.sequence = attributeAsString_(attributes, s_sequence);
}
else if (tag_ == "Modification")
{
TargetedExperiment::Peptide::Modification mod;
double avg_mass_delta(0), mono_mass_delta(0); // zero means no value
optionalAttributeAsDouble_(avg_mass_delta, attributes, "averageMassDelta");
optionalAttributeAsDouble_(mono_mass_delta, attributes, "monoisotopicMassDelta");
mod.avg_mass_delta = avg_mass_delta;
mod.mono_mass_delta = mono_mass_delta;
mod.location = attributeAsInt_(attributes, "location") - 1; // TraML stores location starting with 1
actual_peptide_.mods.push_back(mod);
}
else if (tag_ == "Compound")
{
actual_compound_ = TargetedExperiment::Compound();
actual_compound_.id = attributeAsString_(attributes, s_id);
}
else if (tag_ == "Prediction")
{
actual_prediction_.software_ref = attributeAsString_(attributes, "softwareRef");
String contact_ref;
if (optionalAttributeAsString_(contact_ref, attributes, "contactRef"))
{
actual_prediction_.contact_ref = contact_ref;
}
}
else if (tag_ == "RetentionTime")
{
actual_rt_ = TargetedExperiment::RetentionTime();
String software_ref;
if (optionalAttributeAsString_(software_ref, attributes, "softwareRef"))
{
actual_rt_.software_ref = software_ref;
}
}
else if (tag_ == "Transition")
{
actual_transition_ = ReactionMonitoringTransition();
String id;
if (optionalAttributeAsString_(id, attributes, s_id))
{
actual_transition_.setName(id);
}
String peptide_ref;
if (optionalAttributeAsString_(peptide_ref, attributes, "peptideRef"))
{
actual_transition_.setPeptideRef(peptide_ref);
}
String compound_ref;
if (optionalAttributeAsString_(compound_ref, attributes, "compoundRef"))
{
actual_transition_.setCompoundRef(compound_ref);
}
}
else if (tag_ == "Interpretation")
{
String primary;
if (optionalAttributeAsString_(primary, attributes, "primary"))
{
actual_interpretation_.setMetaValue("primary", primary);
}
}
else if (tag_ == "Configuration")
{
actual_configuration_.instrument_ref = attributeAsString_(attributes, "instrumentRef");
String contact_ref;
if (optionalAttributeAsString_(contact_ref, attributes, "contactRef"))
{
actual_configuration_.contact_ref = contact_ref;
}
}
else if (tag_ == "SourceFile")
{
actual_sourcefile_.setNativeIDType(attributeAsString_(attributes, s_id));
actual_sourcefile_.setNameOfFile(attributeAsString_(attributes, s_name));
actual_sourcefile_.setPathToFile(attributeAsString_(attributes, "location"));
}
else if (tag_ == "ProteinRef")
{
actual_peptide_.protein_refs.push_back(attributeAsString_(attributes, "ref"));
}
else if (tag_ == "Target")
{
actual_target_ = IncludeExcludeTarget();
String id;
if (optionalAttributeAsString_(id, attributes, s_id))
{
actual_target_.setName(id);
}
String peptide_ref;
if (optionalAttributeAsString_(peptide_ref, attributes, "peptideRef"))
{
actual_target_.setPeptideRef(peptide_ref);
}
String compound_ref;
if (optionalAttributeAsString_(compound_ref, attributes, "compoundRef"))
{
actual_target_.setCompoundRef(compound_ref);
}
}
else
{
error(LOAD, "TraMLHandler: unknown tag opening: '" + tag_ + "'");
}
return;
}
void TraMLHandler::characters(const XMLCh* const chars, const XMLSize_t /*length*/)
{
if (open_tags_.back() == "Sequence")
{
actual_protein_.sequence = sm_.convert(chars);
return;
}
return;
}
void TraMLHandler::endElement(const XMLCh* const /*uri*/, const XMLCh* const /*local_name*/, const XMLCh* const qname)
{
tag_ = sm_.convert(qname);
//determine parent tag
String parent_tag;
if (open_tags_.size() > 1)
parent_tag = *(open_tags_.end() - 2);
String parent_parent_tag;
if (open_tags_.size() > 2)
parent_parent_tag = *(open_tags_.end() - 3);
open_tags_.pop_back();
static std::set<String> tags_to_ignore;
if (tags_to_ignore.empty())
{
tags_to_ignore.insert("TraML"); // base node
tags_to_ignore.insert("ContactList"); // contains only contact sections
tags_to_ignore.insert("CompoundList"); // contains only compounds
tags_to_ignore.insert("TransitionList"); // contains only transitions
tags_to_ignore.insert("ConfigurationList"); // contains only configurations
tags_to_ignore.insert("cvList"); // contains only CVs
tags_to_ignore.insert("InstrumentList"); // contains only instruments
tags_to_ignore.insert("SoftwareList"); // contains only software
tags_to_ignore.insert("PublicationList"); // contains only publications
tags_to_ignore.insert("ProteinList"); // contains only proteins
tags_to_ignore.insert("SourceFileList"); // contains only source files
tags_to_ignore.insert("InterpretationList"); // contains only interpretations
tags_to_ignore.insert("Evidence"); // only cv terms
tags_to_ignore.insert("cvParam"); // already handled
tags_to_ignore.insert("userParam"); // already handled
tags_to_ignore.insert("cv"); // already handled
tags_to_ignore.insert("Sequence"); // already handled in characters
tags_to_ignore.insert("Precursor"); // contains only cv terms
tags_to_ignore.insert("RetentionTimeList");
tags_to_ignore.insert("TargetList");
tags_to_ignore.insert("TargetIncludeList");
tags_to_ignore.insert("TargetExcludeList");
tags_to_ignore.insert("ProteinRef");
tags_to_ignore.insert("Modification");
tags_to_ignore.insert("TargetList");
}
// skip tags where nothing is to do
if (tags_to_ignore.find(tag_) != tags_to_ignore.end())
{
return;
}
else if (tag_ == "Contact")
{
exp_->addContact(actual_contact_);
actual_contact_ = TargetedExperiment::Contact();
}
else if (tag_ == "Instrument")
{
exp_->addInstrument(actual_instrument_);
actual_instrument_ = TargetedExperiment::Instrument();
}
else if (tag_ == "Publication")
{
exp_->addPublication(actual_publication_);
actual_publication_ = TargetedExperiment::Publication();
}
else if (tag_ == "Software")
{
exp_->addSoftware(actual_software_);
actual_software_ = Software();
}
else if (tag_ == "Protein")
{
exp_->addProtein(actual_protein_);
}
else if (tag_ == "RetentionTime")
{
if (parent_parent_tag == "Peptide")
{
actual_peptide_.rts.push_back(actual_rt_);
actual_rt_ = TargetedExperiment::RetentionTime();
}
else if (parent_parent_tag == "Compound")
{
actual_compound_.rts.push_back(actual_rt_);
actual_rt_ = TargetedExperiment::RetentionTime();
}
else if (parent_tag == "Target")
{
actual_target_.setRetentionTime(actual_rt_);
actual_rt_ = TargetedExperiment::RetentionTime();
}
else if (parent_tag == "Transition")
{
actual_transition_.setRetentionTime(actual_rt_);
actual_rt_ = TargetedExperiment::RetentionTime();
}
else
{
error(LOAD, "TraMLHandler: tag 'RetentionTime' not allowed at parent tag '" + parent_tag + "', ignoring!");
}
}
else if (tag_ == "Peptide")
{
exp_->addPeptide(actual_peptide_);
actual_peptide_ = TargetedExperiment::Peptide();
}
else if (tag_ == "Compound")
{
exp_->addCompound(actual_compound_);
actual_compound_ = TargetedExperiment::Compound();
}
else if (tag_ == "Transition")
{
exp_->addTransition(actual_transition_);
actual_transition_ = ReactionMonitoringTransition();
}
else if (tag_ == "Product")
{
actual_transition_.setProduct(actual_product_);
actual_product_ = ReactionMonitoringTransition::Product();
}
else if (tag_ == "IntermediateProduct")
{
actual_transition_.addIntermediateProduct(actual_product_);
actual_product_ = ReactionMonitoringTransition::Product();
}
else if (tag_ == "Interpretation")
{
actual_product_.addInterpretation(actual_interpretation_);
actual_interpretation_ = TargetedExperiment::Interpretation();
}
else if (tag_ == "Prediction")
{
actual_transition_.setPrediction(actual_prediction_);
actual_prediction_ = TargetedExperiment::Prediction();
}
else if (tag_ == "Configuration")
{
if (parent_parent_tag == "IntermediateProduct" || parent_parent_tag == "Product")
{
actual_product_.addConfiguration(actual_configuration_);
actual_configuration_ = TargetedExperimentHelper::Configuration();
}
else if (parent_parent_tag == "Target")
{
actual_target_.addConfiguration(actual_configuration_);
actual_configuration_ = TargetedExperimentHelper::Configuration();
}
else
{
error(LOAD, "TraMLHandler: tag 'Configuration' not allowed at parent tag '" + parent_tag + "', ignoring!");
}
}
else if (tag_ == "ValidationStatus")
{
actual_configuration_.validations.push_back(actual_validation_);
actual_validation_ = CVTermList();
}
else if (tag_ == "SourceFile")
{
exp_->addSourceFile(actual_sourcefile_);
actual_sourcefile_ = SourceFile();
}
else if (tag_ == "Target")
{
if (parent_tag == "TargetIncludeList")
{
exp_->addIncludeTarget(actual_target_);
actual_target_ = IncludeExcludeTarget();
}
else if (parent_tag == "TargetExcludeList")
{
exp_->addExcludeTarget(actual_target_);
actual_target_ = IncludeExcludeTarget();
}
else
{
error(LOAD, "TraMLHandler: tag 'Target' not allowed at parent tag '" + parent_tag + "', ignoring!");
}
}
else
{
error(LOAD, "TraMLHandler: unknown tag closing: '" + tag_ + "'");
}
return;
}
void TraMLHandler::writeTo(std::ostream& os)
{
const TargetedExperiment& exp = *(cexp_);
logger_.startProgress(0, exp.getTransitions().size(), "storing TraML file");
// int progress = 0;
os << R"(<?xml version="1.0" encoding="UTF-8"?>)" << "\n";
os << R"(<TraML version="1.0.0" xmlns="http://psi.hupo.org/ms/traml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://psi.hupo.org/ms/traml TraML1.0.0.xsd">)" << "\n";
//--------------------------------------------------------------------------------------------
// CV list
//--------------------------------------------------------------------------------------------
os << " <cvList>" << "\n";
if (exp.getCVs().empty())
{
os << R"( <cv id="MS" fullName="Proteomics Standards Initiative Mass Spectrometry Ontology" version="unknown" URI="http://psidev.cvs.sourceforge.net/*checkout*/psidev/psi/psi-ms/mzML/controlledVocabulary/psi-ms.obo"/>)" << "\n"
<< R"( <cv id="UO" fullName="Unit Ontology" version="unknown" URI="http://obo.cvs.sourceforge.net/obo/obo/ontology/phenotype/unit.obo"/>)" << "\n";
}
else
{
for (std::vector<TargetedExperiment::CV>::const_iterator it = exp.getCVs().begin(); it != exp.getCVs().end(); ++it)
{
os << " <cv id=\"" << writeXMLEscape(it->id) << "\" fullName=\"" << writeXMLEscape(it->fullname) << "\" version=\"" << writeXMLEscape(it->version) << "\" URI=\"" << writeXMLEscape(it->URI) << "\"/>" << "\n";
}
}
os << " </cvList>" << "\n";
// source file list
if (!exp.getSourceFiles().empty())
{
os << " <SourceFileList>" << "\n";
for (std::vector<SourceFile>::const_iterator it = exp.getSourceFiles().begin(); it != exp.getSourceFiles().end(); ++it)
{
os << " <SourceFile id=\""
<< writeXMLEscape(it->getNativeIDType()) << "\" name=\""
<< writeXMLEscape(it->getNameOfFile()) << "\" location=\""
<< writeXMLEscape(it->getPathToFile()) << "\">"
<< "\n";
writeCVParams_(os, *it, 3);
writeUserParam_(os, (MetaInfoInterface) * it, 3);
os << " </SourceFile>" << "\n";
}
os << " </SourceFileList>" << "\n";
}
// contact list
if (!exp.getContacts().empty())
{
os << " <ContactList>" << "\n";
for (std::vector<TargetedExperiment::Contact>::const_iterator it = exp.getContacts().begin(); it != exp.getContacts().end(); ++it)
{
os << " <Contact id=\"" << writeXMLEscape(it->id) << "\">" << "\n";
writeCVParams_(os, *it, 3);
writeUserParam_(os, (MetaInfoInterface) * it, 3);
os << " </Contact>" << "\n";
}
os << " </ContactList>" << "\n";
}
// publication list
if (!exp.getPublications().empty())
{
os << " <PublicationList>" << "\n";
for (std::vector<TargetedExperiment::Publication>::const_iterator it = exp.getPublications().begin(); it != exp.getPublications().end(); ++it)
{
os << " <Publication id=\"" << writeXMLEscape(it->id) << "\">" << "\n";
writeCVParams_(os, *it, 3);
writeUserParam_(os, (MetaInfoInterface) * it, 3);
os << " </Publication>" << "\n";
}
os << " </PublicationList>" << "\n";
}
// instrument list
if (!exp.getInstruments().empty())
{
os << " <InstrumentList>" << "\n";
for (std::vector<TargetedExperiment::Instrument>::const_iterator it = exp.getInstruments().begin(); it != exp.getInstruments().end(); ++it)
{
os << " <Instrument id=\"" << writeXMLEscape(it->id) << "\">" << "\n";
writeCVParams_(os, *it, 3);
writeUserParam_(os, (MetaInfoInterface) * it, 3);
os << " </Instrument>" << "\n";
}
os << " </InstrumentList>" << "\n";
}
// software list
if (!exp.getSoftware().empty())
{
os << " <SoftwareList>" << "\n";
for (std::vector<Software>::const_iterator it = exp.getSoftware().begin(); it != exp.getSoftware().end(); ++it)
{
os << " <Software id=\"" << writeXMLEscape(it->getName()) << "\" version=\"" << writeXMLEscape(it->getVersion()) << "\">" << "\n";
writeCVParams_(os, *it, 3);
writeUserParam_(os, (MetaInfoInterface) * it, 3);
os << " </Software>" << "\n";
}
os << " </SoftwareList>" << "\n";
}
//--------------------------------------------------------------------------------------------
// protein list
//--------------------------------------------------------------------------------------------
if (!exp.getProteins().empty())
{
os << " <ProteinList>" << "\n";
for (std::vector<TargetedExperiment::Protein>::const_iterator it = exp.getProteins().begin(); it != exp.getProteins().end(); ++it)
{
os << " <Protein id=\"" << writeXMLEscape(it->id) << "\">" << "\n";
writeCVParams_(os, *it, 3);
writeUserParam_(os, (MetaInfoInterface) * it, 3);
os << " <Sequence>" << it->sequence << "</Sequence>" << "\n";
os << " </Protein>" << "\n";
}
os << " </ProteinList>" << "\n";
}
//--------------------------------------------------------------------------------------------
// compound list
//--------------------------------------------------------------------------------------------
ModificationsDB* mod_db = ModificationsDB::getInstance();
if (exp.getCompounds().size() + exp.getPeptides().size() > 0)
{
os << " <CompoundList>" << "\n";
std::vector<TargetedExperiment::Peptide> exp_peptides = exp.getPeptides();
// 1. do peptides
for (std::vector<TargetedExperiment::Peptide>::const_iterator it = exp_peptides.begin(); it != exp_peptides.end(); ++it)
{
os << " <Peptide id=\"" << writeXMLEscape(it->id) << "\" sequence=\"" << it->sequence << "\">" << "\n";
if (it->hasCharge())
{
os << R"( <cvParam cvRef="MS" accession="MS:1000041" name="charge state" value=")" << it->getChargeState() << "\"/>\n";
}
if (!it->getPeptideGroupLabel().empty())
{
os << R"( <cvParam cvRef="MS" accession="MS:1000893" name="peptide group label" value=")" << it->getPeptideGroupLabel() << "\"/>\n";
}
if (it->getDriftTime() >= 0.0)
{
os << R"( <cvParam cvRef="MS" accession="MS:1002476" name="ion mobility drift time" value=")" << it->getDriftTime() << "\" unitAccession=\"UO:0000028\" unitName=\"millisecond\" unitCvRef=\"UO\" />\n";
}
writeCVParams_(os, *it, 3);
writeUserParam_(os, (MetaInfoInterface) * it, 3);
for (std::vector<String>::const_iterator rit = it->protein_refs.begin(); rit != it->protein_refs.end(); ++rit)
{
os << " <ProteinRef ref=\"" << writeXMLEscape(*rit) << "\"/>" << "\n";
}
if (!it->mods.empty())
{
for (std::vector<TargetedExperiment::Peptide::Modification>::const_iterator
mit = it->mods.begin(); mit != it->mods.end(); ++mit)
{
os << " <Modification";
os << " location=\"" << mit->location + 1 << "\""; // TraML stores locations starting with 1
if (mit->mono_mass_delta != 0)
{
os << " monoisotopicMassDelta=\"" << mit->mono_mass_delta << "\"";
}
if (mit->avg_mass_delta != 0)
{
os << " averageMassDelta=\"" << mit->avg_mass_delta << "\"";
}
os << ">\n";
if (mit->unimod_id != -1)
{
// Get the name of the modifications from its unimod identifier (using getId)
ResidueModification::TermSpecificity term_spec = ResidueModification::ANYWHERE;
String residue = "";
if (mit->location < 0)
{
term_spec = ResidueModification::N_TERM;
if (!it->sequence.empty()) residue = it->sequence[0];
}
else if (Size(mit->location) >= it->sequence.size())
{
term_spec = ResidueModification::C_TERM;
if (!it->sequence.empty()) residue = it->sequence[it->sequence.size() - 1];
}
else if (!it->sequence.empty())
{
residue = it->sequence[mit->location];
}
const ResidueModification* rmod = mod_db->getModification("UniMod:" + String(mit->unimod_id), residue, term_spec);
const String& modname = rmod->getId();
os << R"( <cvParam cvRef="UNIMOD" accession="UNIMOD:)" << mit->unimod_id
<< "\" name=\"" << modname << "\"/>\n";
}
writeCVParams_(os, *mit, 4);
writeUserParam_(os, (MetaInfoInterface) * mit, 4);
os << " </Modification>\n";
}
}
if (!it->rts.empty())
{
os << " <RetentionTimeList>\n";
for (std::vector<TargetedExperiment::RetentionTime>::const_iterator rit = it->rts.begin(); rit != it->rts.end(); ++rit)
{
writeRetentionTime_(os, *rit);
}
os << " </RetentionTimeList>\n";
}
if (!it->evidence.empty())
{
os << " <Evidence>" << "\n";
writeCVParams_(os, it->evidence, 4);
writeUserParam_(os, (MetaInfoInterface)it->evidence, 4);
os << " </Evidence>" << "\n";
}
os << " </Peptide>" << "\n";
}
// 2. do compounds
for (std::vector<TargetedExperiment::Compound>::const_iterator it = exp.getCompounds().begin(); it != exp.getCompounds().end(); ++it)
{
os << " <Compound id=\"" << writeXMLEscape(it->id) << "\">" << "\n";
if (it->hasCharge())
{
os << R"( <cvParam cvRef="MS" accession="MS:1000041" name="charge state" value=")" << it->getChargeState() << "\"/>\n";
}
if (it->theoretical_mass > 0.0)
{
os << R"( <cvParam cvRef="MS" accession="MS:1001117" name="theoretical mass" value=")" <<
it->theoretical_mass << "\" unitCvRef=\"UO\" unitAccession=\"UO:0000221\" unitName=\"dalton\"/>\n";
}
if (!it->molecular_formula.empty())
{
os << R"( <cvParam cvRef="MS" accession="MS:1000866" name="molecular formula" value=")" <<
it->molecular_formula << "\"/>\n";
}
if (!it->smiles_string.empty())
{
os << R"( <cvParam cvRef="MS" accession="MS:1000868" name="SMILES string" value=")" <<
it->smiles_string << "\"/>\n";
}
writeCVParams_(os, *it, 3);
writeUserParam_(os, (MetaInfoInterface) * it, 3);
if (!it->rts.empty())
{
os << " <RetentionTimeList>\n";
for (std::vector<TargetedExperiment::RetentionTime>::const_iterator rit = it->rts.begin(); rit != it->rts.end(); ++rit)
{
writeRetentionTime_(os, *rit);
}
os << " </RetentionTimeList>\n";
}
os << " </Compound>" << "\n";
}
os << " </CompoundList>" << "\n";
}
//--------------------------------------------------------------------------------------------
// transition list
//--------------------------------------------------------------------------------------------
if (!exp.getTransitions().empty())
{
int progress = 0;
os << " <TransitionList>" << "\n";
for (std::vector<ReactionMonitoringTransition>::const_iterator it = exp.getTransitions().begin(); it != exp.getTransitions().end(); ++it)
{
logger_.setProgress(progress++);
os << " <Transition";
os << " id=\"" << writeXMLEscape(it->getName()) << "\"";
if (!it->getPeptideRef().empty())
{
os << " peptideRef=\"" << writeXMLEscape(it->getPeptideRef()) << "\"";
}
if (!it->getCompoundRef().empty())
{
os << " compoundRef=\"" << writeXMLEscape(it->getCompoundRef()) << "\"";
}
os << ">" << "\n";
// Precursor occurs exactly once (is required according to schema).
// CV term MS:1000827 MUST be supplied for the TransitionList path
os << " <Precursor>" << "\n";
os << R"( <cvParam cvRef="MS" accession="MS:1000827" name="isolation window target m/z" value=")" <<
precisionWrapper(it->getPrecursorMZ()) << "\" unitCvRef=\"MS\" unitAccession=\"MS:1000040\" unitName=\"m/z\"/>\n";
if (it->hasPrecursorCVTerms())
{
writeCVParams_(os, it->getPrecursorCVTermList(), 4);
writeUserParam_(os, (MetaInfoInterface)it->getPrecursorCVTermList(), 4);
}
os << " </Precursor>" << "\n";
for (ProductListType::const_iterator prod_it = it->getIntermediateProducts().begin();
prod_it != it->getIntermediateProducts().end(); ++prod_it)
{
os << " <IntermediateProduct>" << "\n";
writeProduct_(os, prod_it);
os << " </IntermediateProduct>" << "\n";
}
// Product is required
os << " <Product>" << "\n";
ProductListType dummy_vect;
dummy_vect.push_back(it->getProduct());
writeProduct_(os, dummy_vect.begin());
os << " </Product>" << "\n";
const TargetedExperimentHelper::RetentionTime rit = it->getRetentionTime();
if (!rit.getCVTerms().empty())
{
writeRetentionTime_(os, rit);
}
if (it->hasPrediction())
{
os << " <Prediction softwareRef=\"" << writeXMLEscape(it->getPrediction().software_ref) << "\"";
if (!it->getPrediction().contact_ref.empty())
{
os << " contactRef=\"" << writeXMLEscape(it->getPrediction().contact_ref) << "\"";
}
os << ">" << "\n";
writeCVParams_(os, it->getPrediction(), 4);
writeUserParam_(os, (MetaInfoInterface)it->getPrediction(), 4);
os << " </Prediction>" << "\n";
}
writeCVParams_(os, *it, 3);
// Special CV Params
if (it->getLibraryIntensity() > -100)
{
os << R"( <cvParam cvRef="MS" accession="MS:1001226" name="product ion intensity" value=")" << it->getLibraryIntensity() << "\"/>\n";
}
if (it->getDecoyTransitionType() != ReactionMonitoringTransition::UNKNOWN)
{
if (it->getDecoyTransitionType() == ReactionMonitoringTransition::TARGET)
{
os << " <cvParam cvRef=\"MS\" accession=\"MS:1002007\" name=\"target SRM transition\"/>\n";
}
else if (it->getDecoyTransitionType() == ReactionMonitoringTransition::DECOY)
{
os << " <cvParam cvRef=\"MS\" accession=\"MS:1002008\" name=\"decoy SRM transition\"/>\n";
}
}
// Output transition type (only write if non-default, otherwise assume default)
// Default is: true, false, true
// NOTE: do not change that, the same default is implicitly assumed in ReactionMonitoringTransition
if (!it->isDetectingTransition())
{
os << " <userParam name=\"detecting_transition\" type=\"xsd:boolean\" value=\"false\"/>\n";
}
if (it->isIdentifyingTransition())
{
os << " <userParam name=\"identifying_transition\" type=\"xsd:boolean\" value=\"true\"/>\n";
}
if (!it->isQuantifyingTransition())
{
os << " <userParam name=\"quantifying_transition\" type=\"xsd:boolean\" value=\"false\"/>\n";
}
writeUserParam_(os, (MetaInfoInterface) * it, 3);
os << " </Transition>" << "\n";
}
os << " </TransitionList>" << "\n";
}
if (!exp.getIncludeTargets().empty() || !exp.getExcludeTargets().empty())
{
os << " <TargetList>" << "\n";
writeCVParams_(os, exp.getTargetCVTerms(), 2);
writeUserParam_(os, (MetaInfoInterface)exp.getTargetCVTerms(), 2);
if (!exp.getIncludeTargets().empty())
{
os << " <TargetIncludeList>" << "\n";
for (std::vector<IncludeExcludeTarget>::const_iterator it = exp.getIncludeTargets().begin(); it != exp.getIncludeTargets().end(); ++it)
{
writeTarget_(os, it);
}
os << " </TargetIncludeList>" << "\n";
}
if (!exp.getExcludeTargets().empty())
{
os << " <TargetExcludeList>" << "\n";
for (std::vector<IncludeExcludeTarget>::const_iterator it = exp.getExcludeTargets().begin(); it != exp.getExcludeTargets().end(); ++it)
{
writeTarget_(os, it);
}
os << " </TargetExcludeList>" << "\n";
}
os << " </TargetList>" << "\n";
}
os << "</TraML>" << "\n";
logger_.endProgress();
return;
}
void TraMLHandler::writeRetentionTime_(std::ostream& os, const TargetedExperimentHelper::RetentionTime& rt) const
{
const TargetedExperimentHelper::RetentionTime* rit = &rt;
os << " <RetentionTime";
if (!rit->software_ref.empty())
{
os << " softwareRef=\"" << writeXMLEscape(rit->software_ref) << "\"";
}
os << ">" << "\n";
if (rit->isRTset())
{
if (rit->retention_time_type == TargetedExperimentHelper::RetentionTime::RTType::LOCAL)
{
os << R"( <cvParam cvRef="MS" accession="MS:1000895" name="local retention time" value=")" << rit->getRT() << "\"";
}
else if (rit->retention_time_type == TargetedExperimentHelper::RetentionTime::RTType::NORMALIZED)
{
os << R"( <cvParam cvRef="MS" accession="MS:1000896" name="normalized retention time" value=")" << rit->getRT() << "\"";
}
else if (rit->retention_time_type == TargetedExperimentHelper::RetentionTime::RTType::PREDICTED)
{
os << R"( <cvParam cvRef="MS" accession="MS:1000897" name="predicted retention time" value=")" << rit->getRT() << "\"";
}
else if (rit->retention_time_type == TargetedExperimentHelper::RetentionTime::RTType::HPINS)
{
os << R"( <cvParam cvRef="MS" accession="MS:1000902" name="H-PINS retention time normalization standard" value=")" << rit->getRT() << "\"";
}
else if (rit->retention_time_type == TargetedExperimentHelper::RetentionTime::RTType::IRT)
{
os << R"( <cvParam cvRef="MS" accession="MS:1002005" name="iRT retention time normalization standard" value=")" << rit->getRT() << "\"";
}
else
{
os << R"( <cvParam cvRef="MS" accession="MS:1000895" name="local retention time" value=")" << rit->getRT() << "\"";
}
}
// write units (minute, second or none)
if ( rit->retention_time_unit == TargetedExperimentHelper::RetentionTime::RTUnit::SECOND) //seconds
{
os << " unitCvRef=\"UO\" unitAccession=\"UO:0000010\" unitName=\"second\"/>\n";
}
else if ( rit->retention_time_unit == TargetedExperimentHelper::RetentionTime::RTUnit::MINUTE) //minutes
{
os << " unitCvRef=\"UO\" unitAccession=\"UO:0000031\" unitName=\"minute\"/>\n";
}
else
{
os << "/>\n";
}
writeCVParams_(os, *rit, 5);
writeUserParam_(os, (MetaInfoInterface) * rit, 5);
os << " </RetentionTime>" << "\n";
}
void TraMLHandler::writeTarget_(std::ostream& os, const std::vector<IncludeExcludeTarget>::const_iterator& it) const
{
os << " <Target id=\"" << writeXMLEscape(it->getName()) << "\"";
if (!it->getPeptideRef().empty())
{
os << " peptideRef=\"" << writeXMLEscape(it->getPeptideRef()) << "\"";
}
if (!it->getCompoundRef().empty())
{
os << " compoundRef=\"" << writeXMLEscape(it->getCompoundRef()) << "\"";
}
os << ">\n";
os << " <Precursor>\n";
writeCVParams_(os, it->getPrecursorCVTermList(), 5);
writeUserParam_(os, (MetaInfoInterface)it->getPrecursorCVTermList(), 5);
os << " </Precursor>\n";
const IncludeExcludeTarget::RetentionTime* rit = &it->getRetentionTime();
if (!rit->getCVTerms().empty())
{
writeRetentionTime_(os, *rit);
}
if (!it->getConfigurations().empty())
{
os << " <ConfigurationList>\n";
for (auto config_it = it->getConfigurations().begin(); config_it != it->getConfigurations().end(); ++config_it)
{
writeConfiguration_(os, config_it);
}
os << " </ConfigurationList>\n";
}
// TODO : add cv/userparams for Target
os << " </Target>" << "\n";
}
void TraMLHandler::writeProduct_(std::ostream& os, const std::vector<ReactionMonitoringTransition::Product>::const_iterator& prod_it) const
{
if (prod_it->hasCharge())
{
os << R"( <cvParam cvRef="MS" accession="MS:1000041" name="charge state" value=")" << prod_it->getChargeState() << "\"/>\n";
}
if (prod_it->getMZ() > 0)
{
os << R"( <cvParam cvRef="MS" accession="MS:1000827" name="isolation window target m/z" value=")" <<
prod_it->getMZ() << "\" unitCvRef=\"MS\" unitAccession=\"MS:1000040\" unitName=\"m/z\"/>\n";
}
writeCVParams_(os, *prod_it, 4);
writeUserParam_(os, (MetaInfoInterface) * prod_it, 4);
if (!prod_it->getInterpretationList().empty())
{
os << " <InterpretationList>" << "\n";
for (std::vector<TargetedExperiment::Interpretation>::const_iterator inter_it = prod_it->getInterpretationList().begin();
inter_it != prod_it->getInterpretationList().end(); ++inter_it)
{
os << " <Interpretation>" << "\n";
if (inter_it->ordinal > 0)
{
os << R"( <cvParam cvRef="MS" accession="MS:1000903" name="product ion series ordinal" value=")" <<
(int)inter_it->ordinal << "\"/>\n";
}
if (inter_it->rank > 0)
{
os << R"( <cvParam cvRef="MS" accession="MS:1000926" name="product interpretation rank" value=")" <<
(int)inter_it->rank << "\"/>\n";
}
// Ion Type
switch (inter_it->iontype)
{
case Residue::AIon:
os << " <cvParam cvRef=\"MS\" accession=\"MS:1001229\" name=\"frag: a ion\"/>\n";
break;
case Residue::BIon:
os << " <cvParam cvRef=\"MS\" accession=\"MS:1001224\" name=\"frag: b ion\"/>\n";
break;
case Residue::CIon:
os << " <cvParam cvRef=\"MS\" accession=\"MS:1001231\" name=\"frag: c ion\"/>\n";
break;
case Residue::XIon:
os << " <cvParam cvRef=\"MS\" accession=\"MS:1001228\" name=\"frag: x ion\"/>\n";
break;
case Residue::YIon:
os << " <cvParam cvRef=\"MS\" accession=\"MS:1001220\" name=\"frag: y ion\"/>\n";
break;
case Residue::ZIon:
os << " <cvParam cvRef=\"MS\" accession=\"MS:1001230\" name=\"frag: z ion\"/>\n";
break;
case Residue::Precursor:
os << " <cvParam cvRef=\"MS\" accession=\"MS:1001523\" name=\"frag: precursor ion\"/>\n";
break;
case Residue::BIonMinusH20:
os << " <cvParam cvRef=\"MS\" accession=\"MS:1001222\" name=\"frag: b ion - H2O\"/>\n";
break;
case Residue::YIonMinusH20:
os << " <cvParam cvRef=\"MS\" accession=\"MS:1001223\" name=\"frag: y ion - H2O\"/>\n";
break;
case Residue::BIonMinusNH3:
os << " <cvParam cvRef=\"MS\" accession=\"MS:1001232\" name=\"frag: b ion - NH3\"/>\n";
break;
case Residue::YIonMinusNH3:
os << " <cvParam cvRef=\"MS\" accession=\"MS:1001233\" name=\"frag: y ion - NH3\"/>\n";
break;
case Residue::NonIdentified:
os << " <cvParam cvRef=\"MS\" accession=\"MS:1001240\" name=\"non-identified ion\"/>\n";
break;
case Residue::Unannotated:
// means no annotation and no input cvParam - to write out a cvParam, use Residue::NonIdentified
break;
// invalid values
case Residue::Zp1Ion: OPENMS_LOG_ERROR << "Zp1 ions not supported. Ignoring." << std::endl; break;
case Residue::Zp2Ion: OPENMS_LOG_ERROR << "Zp2 ions not supported. Ignoring." << std::endl; break;
case Residue::Full: break;
case Residue::Internal: break;
case Residue::NTerminal: break;
case Residue::CTerminal: break;
case Residue::SizeOfResidueType:
break;
}
writeCVParams_(os, *inter_it, 6);
writeUserParam_(os, (MetaInfoInterface) * inter_it, 6);
os << " </Interpretation>" << "\n";
}
os << " </InterpretationList>" << "\n";
}
if (!prod_it->getConfigurationList().empty())
{
os << " <ConfigurationList>" << "\n";
for (ConfigurationListType::const_iterator config_it = prod_it->getConfigurationList().begin(); config_it != prod_it->getConfigurationList().end(); ++config_it)
{
writeConfiguration_(os, config_it);
}
os << " </ConfigurationList>" << "\n";
}
}
void TraMLHandler::writeConfiguration_(std::ostream& os, const std::vector<ReactionMonitoringTransition::Configuration>::const_iterator& cit) const
{
os << " <Configuration instrumentRef=\"" << writeXMLEscape(cit->instrument_ref) << "\"";
if (!cit->contact_ref.empty())
{
os << " contactRef=\"" << writeXMLEscape(cit->contact_ref) << "\"";
}
os << ">" << "\n";
writeCVParams_(os, *cit, 6);
writeUserParam_(os, (MetaInfoInterface) * cit, 6);
if (!cit->validations.empty())
{
for (std::vector<CVTermList>::const_iterator iit = cit->validations.begin(); iit != cit->validations.end(); ++iit)
{
if (!iit->empty())
{
os << " <ValidationStatus>" << "\n";
writeCVParams_(os, *iit, 7);
writeUserParam_(os, (MetaInfoInterface) * iit, 7);
os << " </ValidationStatus>" << "\n";
}
}
}
os << " </Configuration>" << "\n";
}
void TraMLHandler::handleCVParam_(const String& parent_parent_tag, const String& parent_tag, const CVTerm& cv_term)
{
//Error checks of CV values
const String& accession = cv_term.getAccession();
if (cv_.exists(accession))
{
const ControlledVocabulary::CVTerm& term = cv_.getTerm(accession);
//obsolete CV terms
if (term.obsolete)
{
warning(LOAD, String("Obsolete CV term '") + accession + " - " + cv_.getTerm(accession).name + "' used in tag '" + parent_tag + "'.");
}
//check if term name and parsed name match
String parsed_name = cv_term.getName();
parsed_name.trim();
String correct_name = term.name;
correct_name.trim();
if (parsed_name != correct_name)
{
warning(LOAD, String("Name of CV term not correct: '") + term.id + " - " + parsed_name + "' should be '" + correct_name + "'");
}
if (term.obsolete)
{
warning(LOAD, String("Obsolete CV term '") + accession + " - " + cv_.getTerm(accession).name + "' used in tag '" + parent_tag + "'.");
//values used in wrong places and wrong value types
String value = cv_term.getValue().toString();
if (!value.empty())
{
if (term.xref_type == ControlledVocabulary::CVTerm::XRefType::NONE)
{
//Quality CV does not state value type :(
if (!accession.hasPrefix("PATO:"))
{
warning(LOAD, String("The CV term '") + accession + " - " + cv_.getTerm(accession).name + "' used in tag '" + parent_tag + "' must not have a value. The value is '" + value + "'.");
}
}
else
{
switch (term.xref_type)
{
//string value can be anything
case ControlledVocabulary::CVTerm::XRefType::XSD_STRING:
break;
//int value => try casting
case ControlledVocabulary::CVTerm::XRefType::XSD_INTEGER:
case ControlledVocabulary::CVTerm::XRefType::XSD_NEGATIVE_INTEGER:
case ControlledVocabulary::CVTerm::XRefType::XSD_POSITIVE_INTEGER:
case ControlledVocabulary::CVTerm::XRefType::XSD_NON_NEGATIVE_INTEGER:
case ControlledVocabulary::CVTerm::XRefType::XSD_NON_POSITIVE_INTEGER:
try
{
value.toInt();
}
catch (Exception::ConversionError&)
{
warning(LOAD, String("The CV term '") + accession + " - " + cv_.getTerm(accession).name + "' used in tag '" + parent_tag + "' must have an integer value. The value is '" + value + "'.");
return;
}
break;
//double value => try casting
case ControlledVocabulary::CVTerm::XRefType::XSD_DECIMAL:
try
{
value.toDouble();
}
catch (Exception::ConversionError&)
{
warning(LOAD, String("The CV term '") + accession + " - " + cv_.getTerm(accession).name + "' used in tag '" + parent_tag + "' must have a floating-point value. The value is '" + value + "'.");
return;
}
break;
//date string => try conversion
case ControlledVocabulary::CVTerm::XRefType::XSD_DATE:
try
{
DateTime tmp;
tmp.set(value);
}
catch (Exception::ParseError&)
{
warning(LOAD, String("The CV term '") + accession + " - " + cv_.getTerm(accession).name + "' used in tag '" + parent_tag + "' must be a valid date. The value is '" + value + "'.");
return;
}
break;
default:
warning(LOAD, String("The CV term '") + accession + " - " + cv_.getTerm(accession).name + "' used in tag '" + parent_tag + "' has the unknown value type '" + ControlledVocabulary::CVTerm::getXRefTypeName(term.xref_type) + "'.");
break;
}
}
}
//no value, although there should be a numerical value
else if (term.xref_type != ControlledVocabulary::CVTerm::XRefType::NONE && term.xref_type != ControlledVocabulary::CVTerm::XRefType::XSD_STRING)
{
warning(LOAD, String("The CV term '") + accession + " - " + cv_.getTerm(accession).name + "' used in tag '" + parent_tag + "' should have a numerical value. The value is '" + value + "'.");
return;
}
}
}
// now handle the CVTerm and add it to the object
if (parent_tag == "Software")
{
actual_software_.addCVTerm(cv_term);
}
else if (parent_tag == "Publication")
{
actual_publication_.addCVTerm(cv_term);
}
else if (parent_tag == "Instrument")
{
actual_instrument_.addCVTerm(cv_term);
}
else if (parent_tag == "Contact")
{
actual_contact_.addCVTerm(cv_term);
}
else if (parent_tag == "RetentionTime")
{
// Note: we have to be prepared to have multiple CV terms for the same
// RT, some indicating the unit, some indicating the type of RT
// MAY supply a *child* term of MS:1000915 (retention time window attribute) one or more times
// e.g.: MS:1000916 (retention time window lower offset)
// e.g.: MS:1000917 (retention time window upper offset)
// e.g.: MS:1001907 (retention time window width)
// MAY supply a *child* term of MS:1000901 (retention time normalization standard) only once
// e.g.: MS:1000902 (H-PINS retention time normalization standard)
// e.g.: MS:1002005 (iRT retention time normalization standard)
// MAY supply a *child* term of MS:1000894 (retention time) one or more times
// e.g.: MS:1000895 (local retention time)
// e.g.: MS:1000896 (normalized retention time)
// e.g.: MS:1000897 (predicted retention time)
if ( cv_term.getUnit().accession == "UO:0000010") //seconds
{
actual_rt_.retention_time_unit = TargetedExperimentHelper::RetentionTime::RTUnit::SECOND;
}
else if ( cv_term.getUnit().accession == "UO:0000031") //minutes
{
actual_rt_.retention_time_unit = TargetedExperimentHelper::RetentionTime::RTUnit::MINUTE;
}
else if (actual_rt_.retention_time_unit == TargetedExperimentHelper::RetentionTime::RTUnit::SIZE_OF_RTUNIT) // do not overwrite previous data
{
actual_rt_.retention_time_unit = TargetedExperimentHelper::RetentionTime::RTUnit::UNKNOWN;
}
if (cv_term.getAccession() == "MS:1000895") // local RT
{
actual_rt_.setRT(cv_term.getValue().toString().toDouble());
actual_rt_.retention_time_type = TargetedExperimentHelper::RetentionTime::RTType::LOCAL;
}
else if (cv_term.getAccession() == "MS:1000896") // normalized RT
{
actual_rt_.setRT(cv_term.getValue().toString().toDouble());
actual_rt_.retention_time_type = TargetedExperimentHelper::RetentionTime::RTType::NORMALIZED;
}
else if (cv_term.getAccession() == "MS:1000897") // predicted RT
{
actual_rt_.setRT(cv_term.getValue().toString().toDouble());
actual_rt_.retention_time_type = TargetedExperimentHelper::RetentionTime::RTType::PREDICTED;
}
else if (cv_term.getAccession() == "MS:1000902") // H-PINS
{
if (!cv_term.getValue().toString().empty()) actual_rt_.setRT(cv_term.getValue().toString().toDouble());
actual_rt_.retention_time_type = TargetedExperimentHelper::RetentionTime::RTType::HPINS;
}
else if (cv_term.getAccession() == "MS:1002005") // iRT
{
if (!cv_term.getValue().toString().empty()) actual_rt_.setRT(cv_term.getValue().toString().toDouble());
actual_rt_.retention_time_type = TargetedExperimentHelper::RetentionTime::RTType::IRT;
}
// else if (cv_term.getAccession() == "MS:1000916") // RT lower offset
// {
// actual_rt_.retention_time_lower = cv_term.getValue().toString().toDouble();
// }
// else if (cv_term.getAccession() == "MS:1000917") // RT upper offset
// {
// actual_rt_.retention_time_upper = cv_term.getValue().toString().toDouble();
// }
// else if (cv_term.getAccession() == "MS:1001907") // RT window width
// {
// actual_rt_.retention_time_width = cv_term.getValue().toString().toDouble();
// }
else
{
warning(LOAD, String("The CV term '" + cv_term.getAccession() + "' - '" +
cv_term.getName() + "' used in tag '" + parent_tag + "' is currently not supported!"));
actual_rt_.addCVTerm(cv_term);
}
}
else if (parent_tag == "Evidence")
{
actual_peptide_.evidence.addCVTerm(cv_term);
}
else if (parent_tag == "Peptide")
{
if (cv_term.getAccession() == "MS:1000041")
{
actual_peptide_.setChargeState(cv_term.getValue().toString().toInt());
}
else if (cv_term.getAccession() == "MS:1000893")
{
actual_peptide_.setPeptideGroupLabel(cv_term.getValue().toString());
}
else if (cv_term.getAccession() == "MS:1002476")
{
actual_peptide_.setDriftTime(cv_term.getValue().toString().toDouble());
}
else
{
actual_peptide_.addCVTerm(cv_term);
}
}
else if (parent_tag == "Modification")
{
// if we find a CV term that starts with UniMod, chances are we can use
// the UniMod accession number to identify the modification
if (cv_term.getAccession().size() > 7 && cv_term.getAccession().prefix(7).toLower() == String("unimod:"))
{
// check for Exception::ConversionError ?
actual_peptide_.mods.back().unimod_id = cv_term.getAccession().substr(7).toInt();
}
else
{
actual_peptide_.mods.back().addCVTerm(cv_term);
}
}
else if (parent_tag == "Compound")
{
if (cv_term.getAccession() == "MS:1001117")
{
actual_compound_.theoretical_mass = cv_term.getValue().toString().toDouble();
}
else if (cv_term.getAccession() == "MS:1000866")
{
actual_compound_.molecular_formula = cv_term.getValue().toString();
}
else if (cv_term.getAccession() == "MS:1000868")
{
actual_compound_.smiles_string = cv_term.getValue().toString();
}
else if (cv_term.getAccession() == "MS:1000041")
{
actual_compound_.setChargeState(cv_term.getValue().toString().toInt());
}
else if (cv_term.getAccession() == "MS:1002476")
{
actual_peptide_.setDriftTime(cv_term.getValue().toString().toDouble());
}
else
{
actual_compound_.addCVTerm(cv_term);
}
}
else if (parent_tag == "Protein")
{
actual_protein_.addCVTerm(cv_term);
}
else if (parent_tag == "Configuration")
{
actual_configuration_.addCVTerm(cv_term);
}
else if (parent_tag == "Prediction")
{
actual_prediction_.addCVTerm(cv_term);
}
else if (parent_tag == "Interpretation")
{
////
//// enum ResidueType
//// {
//// Full = 0, // with N-terminus and C-terminus
//// Internal, // internal, without any termini
//// NTerminal, // only N-terminus
//// CTerminal, // only C-terminus
//// AIon, // MS:1001229 N-terminus up to the C-alpha/carbonyl carbon bond
//// BIon, // MS:1001224 N-terminus up to the peptide bond
//// CIon, // MS:1001231 N-terminus up to the amide/C-alpha bond
//// XIon, // MS:1001228 amide/C-alpha bond up to the C-terminus
//// YIon, // MS:1001220 peptide bond up to the C-terminus
//// ZIon, // MS:1001230 C-alpha/carbonyl carbon bond
//// Precursor, // MS:1001523 Precursor ion
//// BIonMinusH20, // MS:1001222 b ion without water
//// YIonMinusH20, // MS:1001223 y ion without water
//// BIonMinusNH3, // MS:1001232 b ion without ammonia
//// YIonMinusNH3, // MS:1001233 y ion without ammonia
//// Unannotated, // unknown annotation
//// SizeOfResidueType
//// };
if (cv_term.getAccession() == "MS:1000903")
{
// name: product ion series ordinal
// def: "The ordinal of the fragment within a specified ion series. (e.g. 8 for a y8 ion)." [PSI:PI]
actual_interpretation_.ordinal = cv_term.getValue().toString().toInt();
}
else if (cv_term.getAccession() == "MS:1000926")
{
// name: product interpretation rank
// def: "The integer rank given an interpretation of an observed product ion. For example, if y8 is selected as the most likely interpretation of a peak, then it is assigned a rank of 1." [PSI:MS]
actual_interpretation_.rank = cv_term.getValue().toString().toInt();
}
else if (cv_term.getAccession() == "MS:1001229")
{
actual_interpretation_.iontype = TargetedExperiment::IonType::AIon;
}
else if (cv_term.getAccession() == "MS:1001224")
{
actual_interpretation_.iontype = TargetedExperiment::IonType::BIon;
}
else if (cv_term.getAccession() == "MS:1001231")
{
actual_interpretation_.iontype = TargetedExperiment::IonType::CIon;
}
else if (cv_term.getAccession() == "MS:1001228")
{
actual_interpretation_.iontype = TargetedExperiment::IonType::XIon;
}
else if (cv_term.getAccession() == "MS:1001220")
{
actual_interpretation_.iontype = TargetedExperiment::IonType::YIon;
}
else if (cv_term.getAccession() == "MS:1001230")
{
actual_interpretation_.iontype = TargetedExperiment::IonType::ZIon;
}
else if (cv_term.getAccession() == "MS:1001523")
{
actual_interpretation_.iontype = TargetedExperiment::IonType::Precursor;
}
else if (cv_term.getAccession() == "MS:1001222")
{
actual_interpretation_.iontype = TargetedExperiment::IonType::BIonMinusH20;
}
else if (cv_term.getAccession() == "MS:1001223")
{
actual_interpretation_.iontype = TargetedExperiment::IonType::YIonMinusH20;
}
else if (cv_term.getAccession() == "MS:1001232")
{
actual_interpretation_.iontype = TargetedExperiment::IonType::BIonMinusNH3;
}
else if (cv_term.getAccession() == "MS:1001233")
{
actual_interpretation_.iontype = TargetedExperiment::IonType::YIonMinusNH3;
}
else if (cv_term.getAccession() == "MS:1001240")
{
actual_interpretation_.iontype = TargetedExperiment::IonType::NonIdentified;
}
else
{
actual_interpretation_.addCVTerm(cv_term);
}
}
else if (parent_tag == "ValidationStatus")
{
actual_validation_.addCVTerm(cv_term);
}
else if (parent_tag == "TargetList")
{
exp_->addTargetCVTerm(cv_term);
}
else if (parent_tag == "Target")
{
actual_target_.addCVTerm(cv_term);
}
else if (parent_tag == "Precursor")
{
if (parent_parent_tag == "Transition")
{
// handle specific CV terms of Transition, currently these are
// id: MS:1000827 name: isolation window target m/z
if (cv_term.getAccession() == "MS:1000827")
{
actual_transition_.setPrecursorMZ(cv_term.getValue().toString().toDouble());
}
else
{
actual_transition_.addPrecursorCVTerm(cv_term);
}
}
if (parent_parent_tag == "Target")
{
actual_target_.addPrecursorCVTerm(cv_term);
}
}
else if (parent_tag == "IntermediateProduct")
{
if (cv_term.getAccession() == "MS:1000041")
{
actual_product_.setChargeState(cv_term.getValue().toString().toDouble());
}
else if (cv_term.getAccession() == "MS:1000827")
{
actual_product_.setMZ(cv_term.getValue().toString().toDouble());
}
else
{
actual_product_.addCVTerm(cv_term);
}
}
else if (parent_tag == "Product")
{
if (cv_term.getAccession() == "MS:1000041")
{
actual_product_.setChargeState(cv_term.getValue().toString().toDouble());
}
else if (cv_term.getAccession() == "MS:1000827")
{
actual_product_.setMZ(cv_term.getValue().toString().toDouble());
}
else
{
actual_product_.addCVTerm(cv_term);
}
}
else if (parent_tag == "SourceFile")
{
// TODO handle checksum type...
actual_sourcefile_.addCVTerm(cv_term);
}
else if (parent_tag == "Transition")
{
// handle specific CV terms of Transition, currently these are
// id: MS:1002007 name: target SRM transition
// id: MS:1002008 name: decoy SRM transition
//
// id: MS:1000905 (percent of base peak times 100) or MS:1001226 (product ion intensity)
if (cv_term.getAccession() == "MS:1002007")
{
actual_transition_.setDecoyTransitionType(ReactionMonitoringTransition::TARGET);
}
else if (cv_term.getAccession() == "MS:1002008")
{
actual_transition_.setDecoyTransitionType(ReactionMonitoringTransition::DECOY);
}
else if (cv_term.getAccession() == "MS:1001226")
{
actual_transition_.setLibraryIntensity(cv_term.getValue().toString().toDouble());
}
else if (cv_term.getAccession() == "MS:1000905")
{
actual_transition_.setLibraryIntensity(cv_term.getValue().toString().toDouble());
}
else
{
actual_transition_.addCVTerm(cv_term);
}
}
else
{
warning(LOAD, String("The CV term '" + cv_term.getAccession() + "' - '" +
cv_term.getName() + "' used in tag '" + parent_tag + "' could not be handled, ignoring it!"));
}
return;
}
void TraMLHandler::handleUserParam_(const String& parent_parent_tag, const String& parent_tag, const String& name, const String& type, const String& value)
{
// create a DataValue that contains the data in the right type
DataValue data_value = fromXSDString(type, value);
// find the right MetaInfoInterface
if (parent_tag == "Software")
{
actual_software_.setMetaValue(name, data_value);
}
else if (parent_tag == "Publication")
{
actual_publication_.setMetaValue(name, data_value);
}
else if (parent_tag == "Instrument")
{
actual_instrument_.setMetaValue(name, data_value);
}
else if (parent_tag == "Contact")
{
actual_contact_.setMetaValue(name, data_value);
}
else if (parent_tag == "RetentionTime")
{
actual_rt_.setMetaValue(name, data_value);
}
else if (parent_tag == "Evidence")
{
actual_peptide_.evidence.setMetaValue(name, data_value);
}
else if (parent_tag == "Peptide")
{
actual_peptide_.setMetaValue(name, data_value);
}
else if (parent_tag == "Modification")
{
actual_peptide_.mods.back().setMetaValue(name, data_value);
}
else if (parent_tag == "Compound")
{
actual_compound_.setMetaValue(name, data_value);
}
else if (parent_tag == "Protein")
{
actual_protein_.setMetaValue(name, data_value);
}
else if (parent_tag == "Configuration")
{
actual_configuration_.setMetaValue(name, data_value);
}
else if (parent_tag == "Prediction")
{
actual_prediction_.setMetaValue(name, data_value);
}
else if (parent_tag == "Interpretation")
{
actual_interpretation_.setMetaValue(name, data_value);
}
else if (parent_tag == "ValidationStatus")
{
actual_validation_.setMetaValue(name, data_value);
}
else if (parent_tag == "TargetList")
{
exp_->setTargetMetaValue(name, data_value);
}
else if (parent_tag == "Target")
{
actual_target_.setMetaValue(name, data_value);
}
else if (parent_tag == "Precursor")
{
if (parent_parent_tag == "Transition")
{
actual_transition_.setMetaValue(name, data_value);
}
if (parent_parent_tag == "Target")
{
actual_target_.setMetaValue(name, data_value);
}
}
else if (parent_tag == "Product")
{
actual_transition_.setMetaValue(name, data_value);
}
else if (parent_tag == "SourceFile")
{
actual_sourcefile_.setMetaValue(name, data_value);
}
else if (parent_tag == "Transition")
{
// see xsd:boolean reference (http://books.xmlschemata.org/relaxng/ch19-77025.html)
// The value space of xsd:boolean is true and false. Its lexical space
// accepts true, false, and also 1 (for true) and 0 (for false).
if (name == "detecting_transition")
{
actual_transition_.setDetectingTransition((value == "true" || value == "1"));
}
else if (name == "identifying_transition")
{
actual_transition_.setIdentifyingTransition((value == "true" || value == "1"));
}
else if (name == "quantifying_transition")
{
actual_transition_.setQuantifyingTransition((value == "true" || value == "1"));
}
else
{
actual_transition_.setMetaValue(name, data_value);
}
}
else
{
warning(LOAD, String("Unhandled userParam '") + name + "' in tag '" + parent_tag + "'.");
}
}
void TraMLHandler::writeUserParam_(std::ostream& os, const MetaInfoInterface& meta, UInt indent) const
{
std::vector<String> keys;
meta.getKeys(keys);
for (Size i = 0; i != keys.size(); ++i)
{
os << String(2 * indent, ' ') << "<userParam name=\"" << writeXMLEscape(keys[i]) << "\" type=\"";
const DataValue& d = meta.getMetaValue(keys[i]);
//determine type
if (d.valueType() == DataValue::INT_VALUE)
{
os << "xsd:integer";
}
else if (d.valueType() == DataValue::DOUBLE_VALUE)
{
os << "xsd:double";
}
else //string or lists are converted to string
{
os << "xsd:string";
}
os << "\" value=\"" << writeXMLEscape((String)(d)) << "\"/>" << "\n";
}
}
void TraMLHandler::writeCVParams_(std::ostream & os, const CVTermList & cv_terms, UInt indent) const
{
writeCVList_(os, cv_terms.getCVTerms(), indent);
}
void TraMLHandler::writeCVParams_(std::ostream & os, const CVTermListInterface & cv_terms, UInt indent) const
{
writeCVList_(os, cv_terms.getCVTerms(), indent);
}
void TraMLHandler::writeCVList_(std::ostream & os, const std::map<String, std::vector<CVTerm>> & cv_terms, UInt indent) const
{
for (std::map<String, std::vector<CVTerm> >::const_iterator it = cv_terms.begin();
it != cv_terms.end(); ++it)
{
for (const CVTerm& cit : it->second)
{
os << String(2 * indent, ' ') << "<cvParam cvRef=\"" << cit.getCVIdentifierRef() << "\" accession=\"" << cit.getAccession() << "\" name=\"" << cit.getName() << "\"";
if (cit.hasValue() && !cit.getValue().isEmpty() && !cit.getValue().toString().empty())
{
os << " value=\"" << cit.getValue().toString() << "\"";
}
if (cit.hasUnit())
{
os << " unitCvRef=\"" << cit.getUnit().cv_ref << "\" unitAccession=\"" << cit.getUnit().accession << "\" unitName=\"" << cit.getUnit().name << "\"";
}
os << "/>" << "\n";
}
}
}
} // namespace OpenMS //namespace Internal
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/HANDLERS/MzMLSqliteSwathHandler.cpp | .cpp | 3,276 | 115 | // 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/HANDLERS/MzMLSqliteSwathHandler.h>
#include <OpenMS/CONCEPT/Exception.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/FORMAT/SqliteConnector.h>
#include <sqlite3.h>
namespace OpenMS::Internal
{
namespace Sql = Internal::SqliteHelper;
std::vector<OpenSwath::SwathMap> MzMLSqliteSwathHandler::readSwathWindows()
{
std::vector<OpenSwath::SwathMap> swath_maps;
SqliteConnector conn(filename_);
sqlite3_stmt * stmt;
std::string select_sql;
select_sql = "SELECT " \
"DISTINCT(ISOLATION_TARGET)," \
"ISOLATION_TARGET - ISOLATION_LOWER," \
"ISOLATION_TARGET + ISOLATION_UPPER " \
"FROM PRECURSOR " \
"INNER JOIN SPECTRUM ON SPECTRUM_ID = SPECTRUM.ID " \
"WHERE MSLEVEL == 2 "\
";";
conn.prepareStatement(&stmt, select_sql);
sqlite3_step( stmt );
while (sqlite3_column_type( stmt, 0 ) != SQLITE_NULL)
{
OpenSwath::SwathMap map;
Sql::extractValue<double>(&map.center, stmt, 0);
Sql::extractValue<double>(&map.lower, stmt, 1);
Sql::extractValue<double>(&map.upper, stmt, 2);
swath_maps.push_back(map);
sqlite3_step( stmt );
}
// free memory
sqlite3_finalize(stmt);
return swath_maps;
}
std::vector<int> MzMLSqliteSwathHandler::readMS1Spectra()
{
std::vector< int > indices;
SqliteConnector conn(filename_);
sqlite3_stmt * stmt;
std::string select_sql;
select_sql = "SELECT ID " \
"FROM SPECTRUM " \
"WHERE MSLEVEL == 1;";
conn.prepareStatement(&stmt, select_sql);
sqlite3_step(stmt);
while (sqlite3_column_type(stmt, 0) != SQLITE_NULL)
{
indices.push_back(sqlite3_column_int(stmt, 0));
sqlite3_step(stmt);
}
// free memory
sqlite3_finalize(stmt);
return indices;
}
std::vector<int> MzMLSqliteSwathHandler::readSpectraForWindow(const OpenSwath::SwathMap& swath_map)
{
std::vector< int > indices;
const double center = swath_map.center;
SqliteConnector conn(filename_);
sqlite3_stmt * stmt;
String select_sql = "SELECT " \
"SPECTRUM_ID " \
"FROM PRECURSOR " \
"WHERE ISOLATION_TARGET BETWEEN ";
select_sql += String(center - 0.01) + " AND " + String(center + 0.01) + ";";
conn.prepareStatement(&stmt, select_sql);
sqlite3_step(stmt);
while (sqlite3_column_type( stmt, 0 ) != SQLITE_NULL)
{
indices.push_back(sqlite3_column_int(stmt, 0));
sqlite3_step(stmt);
}
// free memory
sqlite3_finalize(stmt);
return indices;
}
} // namespace OpenMS // namespace Internal
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/HANDLERS/AcqusHandler.cpp | .cpp | 2,803 | 120 | // 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/HANDLERS/AcqusHandler.h>
#include <OpenMS/CONCEPT/Exception.h>
#include <OpenMS/SYSTEM/File.h>
#include <fstream>
#include <cmath>
using namespace std;
namespace OpenMS::Internal
{
AcqusHandler::AcqusHandler(const String & filename)
{
params_.clear();
std::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);
}
}
//temporary variables
String line;
std::vector<String> strings(2);
//read lines
while (getline(is, line, '\n'))
{
if (line.size() < 5)
{
continue; // minimal string = "##x=x"
}
if (line.prefix(2) != String("##"))
{
continue;
}
if (line.split('=', strings))
{
if (strings.size() == 2)
{
params_[strings[0].substr(2)] = strings[1].trim();
}
}
}
// TOF calibration params
dw_ = params_[String("$DW")].toDouble();
delay_ = (Size)params_[String("$DELAY")].toInt();
ml1_ = params_[String("$ML1")].toDouble();
ml2_ = params_[String("$ML2")].toDouble();
ml3_ = params_[String("$ML3")].toDouble();
td_ = (Size) params_[String("$TD")].toInt();
is.close();
}
AcqusHandler::~AcqusHandler()
{
params_.clear();
}
Size AcqusHandler::getSize() const
{
return td_;
}
double AcqusHandler::getPosition(const Size index) const
{
double sqrt_mz_;
double tof_ = dw_ * index + delay_;
double a_ = ml3_;
double b_ = sqrt(1000000000000.0 / ml1_);
double c_ = ml2_ - tof_;
if (ml3_ == 0.0)
{
sqrt_mz_ = c_ / b_;
}
else
{
sqrt_mz_ = (sqrt(b_ * b_ - 4 * a_ * c_) - b_) / (2 * a_);
}
return sqrt_mz_ * sqrt_mz_;
}
String AcqusHandler::getParam(const String & param)
{
if (param == String("mzMax"))
{
return String(getPosition(td_ - 1));
}
else if (param == String("mzMin"))
{
return String(getPosition(0));
}
return params_[param];
}
} // namespace OpenMS // namespace Internal
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/HANDLERS/FidHandler.cpp | .cpp | 1,317 | 59 | // 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/HANDLERS/FidHandler.h>
using namespace std;
#ifdef OPENMS_BIG_ENDIAN
template <typename T>
T ByteReverse(const T in)
{
T out;
const char * pin = (const char *) ∈
char * pout = (char *) (&out + 1) - 1;
int i;
for (i = sizeof(T); i > 0; --i)
{
*pout-- = *pin++;
}
return out;
}
#endif
namespace OpenMS::Internal
{
FidHandler::FidHandler(const String & filename) :
ifstream(filename.c_str(), ios_base::binary | ios_base::in)
{
index_ = 0;
seekg(0, ios::beg);
}
FidHandler::~FidHandler() = default;
Size FidHandler::getIndex() const
{
return index_;
}
Size FidHandler::getIntensity()
{
// intensity is coded in 32 bits little-endian integer format
Int32 result = 0;
read((char *) &result, 4);
#ifdef OPENMS_BIG_ENDIAN
result = ByteReverse<Int32>(result);
#endif
index_++;
return (result > 0) ? result : 0;
}
} // namespace OpenMS // namespace Internal
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/HANDLERS/ParamXMLHandler.cpp | .cpp | 13,311 | 389 | // 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, Stephan Aiche $
// --------------------------------------------------------------------------
#include <OpenMS/FORMAT/HANDLERS/ParamXMLHandler.h>
#include <OpenMS/CONCEPT/VersionInfo.h>
using namespace xercesc;
using namespace std;
namespace OpenMS::Internal
{
ParamXMLHandler::ParamXMLHandler(Param& param, const String& filename, const String& version) :
XMLHandler(filename, version),
param_(param)
{
}
ParamXMLHandler::~ParamXMLHandler()
= default;
void ParamXMLHandler::startElement(const XMLCh* const /*uri*/, const XMLCh* const /*local_name*/, const XMLCh* const qname, const Attributes& attributes)
{
static const XMLCh* s_restrictions = xercesc::XMLString::transcode("restrictions");
static const XMLCh* s_supported_formats = xercesc::XMLString::transcode("supported_formats");
String element = sm_.convert(qname);
if (element == "ITEM")
{
//parse value/type
String type = attributeAsString_(attributes, "type");
String name = path_ + attributeAsString_(attributes, "name");
String value = attributeAsString_(attributes, "value");
//parse description, if present
String description;
optionalAttributeAsString_(description, attributes, "description");
description.substitute("#br#", "\n");
//tags
String tags_string;
optionalAttributeAsString_(tags_string, attributes, "tags");
std::vector<std::string> tags = ListUtils::create<std::string>(tags_string);
//advanced
String advanced_string;
optionalAttributeAsString_(advanced_string, attributes, "advanced");
if (advanced_string == "true")
{
tags.emplace_back("advanced");
}
//required
String required_string;
optionalAttributeAsString_(advanced_string, attributes, "required");
if (advanced_string == "true")
{
tags.emplace_back("required");
}
//type
if (type == "int")
{
param_.setValue(name, asInt_(value), description, tags);
}
// since 1.7 it supports a separate bool type
else if (type == "bool" || type == "string")
{
param_.setValue(name, value, description, tags);
}
// since param v1.6.2 we support explicitly naming input/output files as types
else if (type == "input-file")
{
tags.emplace_back("input file");
param_.setValue(name, value, description, tags);
}
else if (type == "output-file")
{
tags.emplace_back("output file");
param_.setValue(name, value, description, tags);
}
else if (type == "output-prefix")
{
tags.emplace_back("output prefix");
param_.setValue(name, value, description, tags);
}
else if (type == "float" || type == "double")
{
param_.setValue(name, asDouble_(value), description, tags);
}
else
{
warning(LOAD, String("Ignoring entry '") + name + "' because of unknown type '" + type + "'");
}
//restrictions
// we internally handle bool parameters as strings with restrictions true/false
if (type == "bool")
{
param_.setValidStrings(name, {"true","false"});
}
else
{
// parse restrictions if present
Int restrictions_index = attributes.getIndex(s_restrictions);
if (restrictions_index != -1)
{
String val = sm_.convert(attributes.getValue(restrictions_index));
std::vector<String> parts;
if (type == "int")
{
val.split(':', parts);
if (parts.size() != 2)
val.split('-', parts); //for downward compatibility
if (parts.size() == 2)
{
if (!parts[0].empty())
{
param_.setMinInt(name, parts[0].toInt());
}
if (!parts[1].empty())
{
param_.setMaxInt(name, parts[1].toInt());
}
}
else
{
warning(LOAD, "ITEM " + name + " has an empty restrictions attribute.");
}
}
else if (type == "string")
{
val.split(',', parts);
param_.setValidStrings(name, ListUtils::create<std::string>(parts));
}
else if (type == "float" || type == "double")
{
val.split(':', parts);
if (parts.size() != 2)
{
val.split('-', parts); //for downward compatibility
}
if (parts.size() == 2)
{
if (!parts[0].empty())
{
param_.setMinFloat(name, parts[0].toDouble());
}
if (!parts[1].empty())
{
param_.setMaxFloat(name, parts[1].toDouble());
}
}
else
{
warning(LOAD, "ITEM " + name + " has an empty restrictions attribute.");
}
}
}
}
// check for supported_formats -> supported_formats overwrites restrictions in case of files
if ((ListUtils::contains(tags, "input file") || ListUtils::contains(tags, "output file")) && (type == "string" || type == "input-file" || type == "output-file"))
{
Int supported_formats_index = attributes.getIndex(s_supported_formats);
if (supported_formats_index != -1)
{
String val = sm_.convert(attributes.getValue(supported_formats_index));
std::vector<String> parts;
val.split(',', parts);
param_.setValidStrings(name, ListUtils::create<std::string>(parts));
}
}
}
else if (element == "NODE")
{
//parse name
String name = attributeAsString_(attributes, "name");
open_tags_.push_back(name);
path_ += name + ":";
//parse description
String description;
optionalAttributeAsString_(description, attributes, "description");
if (!description.empty())
{
description.substitute("#br#", "\n");
}
param_.addSection(path_.chop(1), description);
}
else if (element == "ITEMLIST")
{
//tags
String tags_string;
optionalAttributeAsString_(tags_string, attributes, "tags");
list_.tags = ListUtils::create<std::string>(tags_string);
//parse name/type
list_.type = attributeAsString_(attributes, "type");
// handle in-/output file correctly
if (list_.type == "input-file")
{
list_.type = "string";
list_.tags.emplace_back("input file");
}
else if (list_.type == "output-file")
{
list_.type = "string";
list_.tags.emplace_back("output file");
}
list_.name = path_ + attributeAsString_(attributes, "name");
//parse description, if present
list_.description = "";
optionalAttributeAsString_(list_.description, attributes, "description");
list_.description.substitute("#br#", "\n");
//advanced
String advanced_string;
optionalAttributeAsString_(advanced_string, attributes, "advanced");
if (advanced_string == "true")
{
list_.tags.emplace_back("advanced");
}
//advanced
String required_string;
optionalAttributeAsString_(required_string, attributes, "required");
if (required_string == "true")
{
list_.tags.emplace_back("required");
}
list_.restrictions_index = attributes.getIndex(s_restrictions);
if (list_.restrictions_index != -1)
{
list_.restrictions = sm_.convert(attributes.getValue(list_.restrictions_index));
}
// check for supported_formats -> supported_formats overwrites restrictions in case of files
if ((ListUtils::contains(list_.tags, "input file") || ListUtils::contains(list_.tags, "output file")) && list_.type == "string")
{
Int supported_formats_index = attributes.getIndex(s_supported_formats);
if (supported_formats_index != -1)
{
list_.restrictions_index = supported_formats_index;
list_.restrictions = sm_.convert(attributes.getValue(list_.restrictions_index));
}
}
}
else if (element == "LISTITEM")
{
if (list_.type == "string")
{
list_.stringlist.push_back(attributeAsString_(attributes, "value"));
}
else if (list_.type == "int")
{
list_.intlist.push_back(asInt_(attributeAsString_(attributes, "value")));
}
else if (list_.type == "float" || list_.type == "double")
{
list_.doublelist.push_back(asDouble_(attributeAsString_(attributes, "value")));
}
}
else if (element == "PARAMETERS")
{
//check file version against schema version
String file_version = "";
optionalAttributeAsString_(file_version, attributes, "version");
// default version is 1.0
if (file_version.empty())
{
file_version = "1.0";
}
VersionInfo::VersionDetails file_version_details = VersionInfo::VersionDetails::create(file_version);
VersionInfo::VersionDetails parser_version = VersionInfo::VersionDetails::create(version_);
if (file_version_details > parser_version)
{
warning(LOAD, "The XML file (" + file_version + ") is newer than the parser (" + version_ + "). This might lead to undefined program behavior.");
}
}
}
void ParamXMLHandler::endElement(const XMLCh* const /*uri*/, const XMLCh* const /*local_name*/, const XMLCh* const qname)
{
String element = sm_.convert(qname);
if (element == "NODE")
{
open_tags_.pop_back();
//renew path
path_ = "";
for (vector<String>::iterator it = open_tags_.begin(); it != open_tags_.end(); ++it)
{
path_ += *it + ":";
}
}
else if (element == "ITEMLIST")
{
std::vector<String> parts;
if (list_.type == "string")
{
param_.setValue(list_.name, list_.stringlist, list_.description, list_.tags);
if (list_.restrictions_index != -1)
{
list_.restrictions.split(',', parts);
param_.setValidStrings(list_.name, ListUtils::create<std::string>(parts));
}
}
else if (list_.type == "int")
{
param_.setValue(list_.name, list_.intlist, list_.description, list_.tags);
if (list_.restrictions_index != -1)
{
list_.restrictions.split(':', parts);
if (parts.size() != 2)
{
list_.restrictions.split('-', parts); //for downward compatibility
}
if (parts.size() == 2)
{
if (!parts[0].empty())
{
param_.setMinInt(list_.name, parts[0].toInt());
}
if (!parts[1].empty())
{
param_.setMaxInt(list_.name, parts[1].toInt());
}
}
else
{
warning(LOAD, "ITEMLIST " + list_.name + " has an empty restrictions attribute.");
}
}
}
else if (list_.type == "float" || list_.type == "double")
{
param_.setValue(list_.name, list_.doublelist, list_.description, list_.tags);
if (list_.restrictions_index != -1)
{
list_.restrictions.split(':', parts);
if (parts.size() != 2)
{
list_.restrictions.split('-', parts); //for downward compatibility
}
if (parts.size() == 2)
{
if (!parts[0].empty())
{
param_.setMinFloat(list_.name, parts[0].toDouble());
}
if (!parts[1].empty())
{
param_.setMaxFloat(list_.name, parts[1].toDouble());
}
}
else
{
warning(LOAD, "ITEMLIST " + list_.name + " has an empty restrictions attribute.");
}
}
}
else
{
warning(LOAD, String("Ignoring list entry '") + list_.name + "' because of unknown type '" + list_.type + "'");
}
list_.stringlist.clear();
list_.intlist.clear();
list_.doublelist.clear();
}
}
} // namespace OpenMS // namespace Internal
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/HANDLERS/MzIdentMLHandler.cpp | .cpp | 100,099 | 2,267 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Mathias Walzer $
// $Authors: Mathias Walzer, Andreas Bertsch $
// --------------------------------------------------------------------------
#include <OpenMS/FORMAT/HANDLERS/MzIdentMLHandler.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/FORMAT/FileHandler.h>
#include <OpenMS/CONCEPT/Constants.h>
#include <OpenMS/SYSTEM/File.h>
#include <OpenMS/CHEMISTRY/ModificationDefinitionsSet.h>
#include <OpenMS/CHEMISTRY/ModificationsDB.h>
#include <OpenMS/CONCEPT/UniqueIdGenerator.h>
#include <OpenMS/CONCEPT/VersionInfo.h>
#include <OpenMS/CHEMISTRY/CrossLinksDB.h>
#include <boost/lexical_cast.hpp>
#include <boost/regex.hpp>
using namespace std;
namespace OpenMS::Internal
{
void IdentificationHit::setId(const std::string& id) noexcept
{
id_ = id;
}
const std::string& IdentificationHit::getId() const noexcept
{
return id_;
}
void IdentificationHit::setCharge(int charge) noexcept
{
charge_ = charge;
}
int IdentificationHit::getCharge() const noexcept
{
return charge_;
}
void IdentificationHit::setCalculatedMassToCharge(double mz) noexcept
{
calculated_mass_to_charge_ = mz;
}
double IdentificationHit::getCalculatedMassToCharge() const noexcept
{
return calculated_mass_to_charge_;
}
void IdentificationHit::setExperimentalMassToCharge(double mz) noexcept
{
experimental_mass_to_charge_ = mz;
}
double IdentificationHit::getExperimentalMassToCharge() const noexcept
{
return experimental_mass_to_charge_;
}
void IdentificationHit::setName(const std::string& name) noexcept
{
name_ = name;
}
const std::string& IdentificationHit::getName() const noexcept
{
return name_;
}
void IdentificationHit::setPassThreshold(bool pass) noexcept
{
pass_threshold_ = pass;
}
bool IdentificationHit::getPassThreshold() const noexcept
{
return pass_threshold_;
}
void IdentificationHit::setRank(int rank) noexcept
{
rank_ = rank;
}
int IdentificationHit::getRank() const noexcept
{
return rank_;
}
bool IdentificationHit::operator==(const IdentificationHit& rhs) const noexcept
{
return MetaInfoInterface::operator==(rhs)
&& id_ == rhs.id_
&& charge_ == rhs.charge_
&& calculated_mass_to_charge_ == rhs.calculated_mass_to_charge_
&& experimental_mass_to_charge_ == rhs.experimental_mass_to_charge_
&& name_ == rhs.name_
&& pass_threshold_ == rhs.pass_threshold_
&& rank_ == rhs.rank_;
}
bool IdentificationHit::operator!=(const IdentificationHit& rhs) const noexcept
{
return !(*this == rhs);
}
SpectrumIdentification::~SpectrumIdentification() = default;
// Equality operator
bool SpectrumIdentification::operator==(const SpectrumIdentification & rhs) const
{
return MetaInfoInterface::operator==(rhs)
&& id_ == rhs.id_
&& hits_ == rhs.hits_;
}
// Inequality operator
bool SpectrumIdentification::operator!=(const SpectrumIdentification & rhs) const
{
return !(*this == rhs);
}
void SpectrumIdentification::setHits(const vector<IdentificationHit> & hits)
{
hits_ = hits;
}
void SpectrumIdentification::addHit(const IdentificationHit & hit)
{
hits_.push_back(hit);
}
const vector<IdentificationHit> & SpectrumIdentification::getHits() const
{
return hits_;
}
Identification::~Identification() = default;
// Equality operator
bool Identification::operator==(const Identification & rhs) const
{
return MetaInfoInterface::operator==(rhs)
&& id_ == rhs.id_
&& creation_date_ == rhs.creation_date_
&& spectrum_identifications_ == rhs.spectrum_identifications_;
}
// Inequality operator
bool Identification::operator!=(const Identification & rhs) const
{
return !(*this == rhs);
}
void Identification::setCreationDate(const DateTime & date)
{
creation_date_ = date;
}
const DateTime & Identification::getCreationDate() const
{
return creation_date_;
}
void Identification::setSpectrumIdentifications(const vector<SpectrumIdentification> & ids)
{
spectrum_identifications_ = ids;
}
void Identification::addSpectrumIdentification(const SpectrumIdentification & id)
{
spectrum_identifications_.push_back(id);
}
const vector<SpectrumIdentification> & Identification::getSpectrumIdentifications() const
{
return spectrum_identifications_;
}
MzIdentMLHandler::MzIdentMLHandler(const std::vector<ProteinIdentification>& pro_id, const PeptideIdentificationList& pep_id, const String& filename, const String& version, const ProgressLogger& logger) :
XMLHandler(filename, version),
logger_(logger),
//~ ms_exp_(0),
pro_id_(nullptr),
pep_id_(nullptr),
cpro_id_(&pro_id),
cpep_id_(&pep_id)
{
cv_.loadFromOBO("PSI-MS", File::find("/CV/psi-ms.obo"));
unimod_.loadFromOBO("PSI-MS", File::find("/CV/unimod.obo"));
}
MzIdentMLHandler::MzIdentMLHandler(std::vector<ProteinIdentification>& pro_id, PeptideIdentificationList& pep_id, const String& filename, const String& version, const ProgressLogger& logger) :
XMLHandler(filename, version),
logger_(logger),
//~ ms_exp_(0),
pro_id_(&pro_id),
pep_id_(&pep_id),
cpro_id_(nullptr),
cpep_id_(nullptr)
{
cv_.loadFromOBO("PSI-MS", File::find("/CV/psi-ms.obo"));
unimod_.loadFromOBO("PSI-MS", File::find("/CV/unimod.obo"));
}
//~ TODO create MzIdentML instances from MSExperiment which contains much of the information yet needed
//~ MzIdentMLHandler(const PeakMap& mx, const String& filename, const String& version, const ProgressLogger& logger)
//~ : XMLHandler(filename, version),
//~ logger_(logger),
//~ ms_exp_(mx),
//~ pro_id_(0),
//~ pepid_(0),
//~ cpepid_(0),
//~ cpro_id_(0)
//~ {
//~ cv_.loadFromOBO("MS",File::find("/CV/psi-ms.obo"));
//~ unimod_.loadFromOBO("PSI-MS",File::find("/CV/unimod.obo"));
//~ }
MzIdentMLHandler::~MzIdentMLHandler()
= default;
void MzIdentMLHandler::startElement(const XMLCh* const /*uri*/, const XMLCh* const /*local_name*/, const XMLCh* const qname, const xercesc::Attributes& attributes)
{
tag_ = sm_.convert(qname);
open_tags_.push_back(tag_);
static set<String> to_ignore;
if (to_ignore.empty())
{
to_ignore.insert("peptideSequence");
}
if (to_ignore.find(tag_) != to_ignore.end())
{
return;
}
//determine parent tag
String parent_tag;
if (open_tags_.size() > 1)
{
parent_tag = *(open_tags_.end() - 2);
}
String parent_parent_tag;
if (open_tags_.size() > 2)
{
parent_parent_tag = *(open_tags_.end() - 3);
}
if (tag_ == "cvParam")
{
static const XMLCh* s_value = xercesc::XMLString::transcode("value");
static const XMLCh* s_unit_accession = xercesc::XMLString::transcode("unitAccession");
static const XMLCh* s_cv_ref = xercesc::XMLString::transcode("cvRef");
//~ static const XMLCh* s_name = xercesc::XMLString::transcode("name");
static const XMLCh* s_accession = xercesc::XMLString::transcode("accession");
String value, unit_accession, cv_ref;
optionalAttributeAsString_(value, attributes, s_value);
optionalAttributeAsString_(unit_accession, attributes, s_unit_accession);
optionalAttributeAsString_(cv_ref, attributes, s_cv_ref);
handleCVParam_(parent_parent_tag, parent_tag, attributeAsString_(attributes, s_accession), /* attributeAsString_(attributes, s_name), value, */ attributes, cv_ref /*, unit_accession */);
return;
}
if (tag_ == "MzIdentML")
{
// TODO handle version with mzid 1.2 release
return;
}
if (tag_ == "Peptide")
{
// start new peptide
actual_peptide_ = AASequence();
// name attribute (opt)
String name;
if (optionalAttributeAsString_(name, attributes, "name"))
{
// TODO save name in AASequence
}
return;
}
if (tag_ == "Modification")
{
// average mass delta attribute (opt)
// TODO
// location attribute (opt)
Int mod_location = -1;
if (optionalAttributeAsInt_(mod_location, attributes, "location"))
{
current_mod_location_ = mod_location;
}
else
{
current_mod_location_ = -1;
}
// monoisotopic mass delta attribute (opt)
// TODO
// residues attribute (opt)
// TODO
return;
}
if (tag_ == "SpectrumIdentificationList")
{
return;
}
if (tag_ == "SpectrumIdentificationResult")
{
return;
}
if (tag_ == "SpectrumIdentificationItem")
{
// <SpectrumIdentificationItem id="SII_1_1" calculatedMassToCharge="670.86261" chargeState="2" experimentalMassToCharge="671.9" Peptide_ref="peptide_1_1" rank="1" passThreshold="true">
// required attributes
current_id_hit_.setId((attributeAsString_(attributes, "id")));
current_id_hit_.setPassThreshold(asBool_(attributeAsString_(attributes, "passThreshold")));
int rank = attributeAsInt_(attributes, "rank");
current_id_hit_.setRank(rank - 1); // rank starts at 1 in mzid,OpenMS 0-based
// optional attributes
double double_value(0);
if (optionalAttributeAsDouble_(double_value, attributes, "calculatedMassToCharge"))
{
current_id_hit_.setCalculatedMassToCharge(double_value);
}
Int int_value(0);
if (optionalAttributeAsInt_(int_value, attributes, "chargeState"))
{
current_id_hit_.setCharge(int_value);
}
if (optionalAttributeAsDouble_(double_value, attributes, "experimentalMassToCharge"))
{
current_id_hit_.setExperimentalMassToCharge(double_value);
}
if (optionalAttributeAsDouble_(double_value, attributes, "calculatedMassToCharge"))
{
current_id_hit_.setCalculatedMassToCharge(double_value);
}
String string_value("");
if (optionalAttributeAsString_(string_value, attributes, "name"))
{
current_id_hit_.setName(string_value);
}
// TODO PeptideEvidence, pf:cvParam, pf:userParam, Fragmentation
return;
}
error(LOAD, "MzIdentMLHandler::startElement: Unknown element found: '" + tag_ + "' in tag '" + parent_tag + "', ignoring.");
}
void MzIdentMLHandler::characters(const XMLCh* const chars, const XMLSize_t /*length*/)
{
if (tag_ == "Customizations")
{
String customizations = sm_.convert(chars);
// TODO write customizations to Software
return;
}
if (tag_ == "seq")
{
String seq = sm_.convert(chars);
actual_protein_.setSequence(seq);
return;
}
if (tag_ == "peptideSequence")
{
String pep = sm_.convert(chars);
actual_peptide_ = AASequence::fromString(pep);
return;
}
//error(LOAD, "MzIdentMLHandler::characters: Unknown character section found: '" + tag_ + "', ignoring.");
}
void MzIdentMLHandler::endElement(const XMLCh* const /*uri*/, const XMLCh* const /*local_name*/, const XMLCh* const qname)
{
static set<String> to_ignore;
if (to_ignore.empty())
{
to_ignore.insert("mzIdentML");
to_ignore.insert("cvParam");
}
tag_ = sm_.convert(qname);
open_tags_.pop_back();
if (to_ignore.find(tag_) != to_ignore.end())
{
return;
}
if (tag_ == "DataCollection")
{
return;
}
if (tag_ == "AnalysisData")
{
return;
}
if (tag_ == "ProteinDetectionList")
{
return;
}
if (tag_ == "SpectrumIdentificationList")
{
return;
}
if (tag_ == "SpectrumIdentificationResult")
{
return;
}
if (tag_ == "SpectrumIdentificationItem")
{
current_spectrum_id_.addHit(current_id_hit_);
current_id_hit_ = IdentificationHit();
return;
}
error(LOAD, "MzIdentMLHandler::endElement: Unknown element found: '" + tag_ + "', ignoring.");
}
void MzIdentMLHandler::handleCVParam_(const String& /* parent_parent_tag*/, const String& parent_tag, const String& accession, /* const String& name, */ /* const String& value, */ const xercesc::Attributes& attributes, const String& cv_ref /* , const String& unit_accession */)
{
if (parent_tag == "Modification")
{
if (cv_ref == "UNIMOD")
{
set<const ResidueModification*> mods;
Int loc = numeric_limits<Int>::max();
if (optionalAttributeAsInt_(loc, attributes, "location"))
{
String uni_mod_id = accession.suffix(':');
String residues;
if (optionalAttributeAsString_(residues, attributes, "residues"))
{
// TODO handle ambiguous/multiple residues
}
if (loc == 0)
{
ModificationsDB::getInstance()->searchModifications(mods, uni_mod_id, "", ResidueModification::N_TERM);
}
else if (loc == (Int)actual_peptide_.size())
{
ModificationsDB::getInstance()->searchModifications(mods, uni_mod_id, "", ResidueModification::C_TERM);
}
else
{
ModificationsDB::getInstance()->searchModifications(mods, uni_mod_id, residues, ResidueModification::ANYWHERE);
}
}
else
{
warning(LOAD, "location of modification not defined!");
}
if (mods.empty())
{
String message = String("Modification '") + accession + "' is unknown.";
throw Exception::ElementNotFound(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, message);
}
}
}
}
void MzIdentMLHandler::writeTo(std::ostream& os)
{
String cv_ns = cv_.name();
String inputs_element;
std::map<String,String> /* peps, pepevis, */ sil_map, sil_2_date;
std::set<String> sen_set, sof_set, sip_set;
std::map<String, String> sdb_ids, sen_ids, sof_ids, sdat_ids, pep_ids;
//std::map<String, String> pep_pairs_ppxl;
std::map<String, double> pp_identifier_2_thresh;
//std::vector< std::pair<String, String> > pepid_pairs_ppxl;
// file type-specific definitions needed for SpectraData element:
std::map<FileTypes::Type, std::pair<String, String> > formats_map;
formats_map[FileTypes::MZML] = make_pair("mzML format", "mzML unique identifier");
formats_map[FileTypes::MZXML] = make_pair("ISB mzXML format", "scan number only nativeID format");
formats_map[FileTypes::MZDATA] = make_pair("PSI mzData format", "spectrum identifier nativeID format");
formats_map[FileTypes::MGF] = make_pair("Mascot MGF format", "multiple peak list nativeID format");
//TODO if constructed with a msexperiment - not yet implemented
//~ if(ms_exp_ == 0)
//~ {
//~ synthesize spectrum references
//~ }
//~ else
//~ {
//~ extract peptide and proteinid from msexperiment
//~ genereate spectrum references from msexperiment foreach peptideidentification
//~ }
/*---------------------------------------------------------------------
DataCollection:
+Inputs
-AnalysisData collected in sidlist --> unclosed element string
---------------------------------------------------------------------*/
inputs_element += String("\t<Inputs>\n");
String spectra_data, search_database;
/*
1st: iterate over proteinidentification vector
*/
//TODO read type of crosslink reagent from settings
bool is_ppxl = false;
for (std::vector<ProteinIdentification>::const_iterator it = cpro_id_->begin(); it != cpro_id_->end(); ++it)
{
//~ collect analysissoftware in this loop - does not go into inputelement
String sof_id;
String sof_name = String(it->getSearchEngine());
std::map<String, String>::iterator soit = sof_ids.find(sof_name);
String osecv;
if (sof_name == "OMSSA")
{
osecv = "OMSSA";
}
else if (sof_name == "Mascot")
{
osecv = "Mascot";
}
else if (sof_name == "XTandem")
{
osecv = "X\\!Tandem";
}
else if (sof_name == "SEQUEST")
{
osecv = "Sequest";
}
else if (sof_name == "MS-GF+")
{
osecv = "MS-GF+";
}
else if (sof_name == "Percolator")
{
osecv = "Percolator";
}
else if (sof_name == "OpenPepXL")
{
osecv = "OpenPepXL";
}
else if (cv_.hasTermWithName(sof_name))
{
osecv = sof_name;
}
else
{
osecv = "analysis software";
}
if (soit == sof_ids.end())
{
sof_id = "SOF_" + String(UniqueIdGenerator::getUniqueId());
//~ TODO consider not only searchengine but also version!
String sost = String("\t<AnalysisSoftware version=\"") + String(it->getSearchEngineVersion()) + String("\" name=\"") + sof_name + String("\" id=\"") + sof_id + String("\">\n") + String("\t\t<SoftwareName>\n");
sost += "\t\t\t" + cv_.getTermByName(osecv).toXMLString(cv_ns);
sost += String("\n\t\t</SoftwareName>\n\t</AnalysisSoftware>\n");
sof_set.insert(sost);
sof_ids.insert(make_pair(sof_name, sof_id));
}
else
{
sof_id = soit->second;
}
if (it->metaValueExists("is_cross_linking_experiment") ||
(it->metaValueExists("SpectrumIdentificationProtocol") &&
it->getMetaValue("SpectrumIdentificationProtocol") == "MS:1002494"))
{
is_ppxl = true; //needed as incoming data is structured differently and output deviates as well for ppxl
// ppxl is like (1PeptideIdentification, 1-2 PeptideHits) but there might be more PeptideIdentifications for one spectrum
}
String thcv;
pp_identifier_2_thresh.insert(make_pair(it->getIdentifier(),it->getSignificanceThreshold()));
if (it->getSignificanceThreshold() != 0.0)
{
thcv = cv_.getTermByName("PSM-level statistical threshold").toXMLString(cv_ns, String(it->getSignificanceThreshold()));
}
else
{
thcv = cv_.getTermByName("no threshold").toXMLString(cv_ns);
}
// TODO add other software than searchengine for evidence trace
// get a map from identifier to match OpenMS Protein/PeptideIdentification match string;
String sil_id = "SIL_" + String(UniqueIdGenerator::getUniqueId());
pp_identifier_2_sil_.insert(make_pair(it->getIdentifier(), sil_id));
//~ collect SpectrumIdentificationProtocol for analysisprotocol in this loop - does not go into inputelement
String sip_id = "SIP_" + String(UniqueIdGenerator::getUniqueId());
sil_2_sip_.insert(make_pair(sil_id, sip_id));
String sip = "\t<SpectrumIdentificationProtocol id=\"" + String(sip_id) + "\" analysisSoftware_ref=\"" + String(sof_id) + "\">\n";
sip += "\t\t<SearchType>\n\t\t\t" + cv_.getTermByName("ms-ms search").toXMLString(cv_ns) + "\n\t\t</SearchType>\n";
sip += "\t\t<AdditionalSearchParams>\n";
if (is_ppxl)
{
sip += "\n\t\t\t" + cv_.getTermByName("crosslinking search").toXMLString(cv_ns) + "\n";
}
//remove MS:1001029 written if present in <SearchDatabase> as of SearchDatabase_may rule
ProteinIdentification::SearchParameters search_params = it->getSearchParameters();
search_params.removeMetaValue("MS:1001029");
writeMetaInfos_(sip, search_params, 3);
sip += String(3, '\t') + R"(<userParam name="charges" unitName="xsd:string" value=")" + search_params.charges + "\"/>\n";
// sip += String(3, '\t') + "<userParam name=\"" + "missed_cleavages" + "\" unitName=\"" + "xsd:integer" + "\" value=\"" + String(it->getSearchParameters().missed_cleavages) + "\"/>" + "\n";
sip += "\t\t</AdditionalSearchParams>\n";
// modifications:
if (search_params.fixed_modifications.empty() &&
search_params.variable_modifications.empty()
&& (!is_ppxl)) // TODO some OpenPepXL modifications are not covered by the unimod.obo and cause problems in the search_params
{
// no modifications used or are they just missing from the parameters?
ModificationDefinitionsSet mod_defs;
mod_defs.inferFromPeptides(*cpep_id_);
mod_defs.getModificationNames(search_params.fixed_modifications,
search_params.variable_modifications);
}
if (!search_params.fixed_modifications.empty() ||
!search_params.variable_modifications.empty())
{
sip += "\t\t<ModificationParams>\n";
writeModParam_(sip, search_params.fixed_modifications, true, 2);
writeModParam_(sip, search_params.variable_modifications, false, 2);
sip += "\t\t</ModificationParams>\n";
}
writeEnzyme_(sip, search_params.digestion_enzyme, search_params.missed_cleavages, 2);
// TODO MassTable section
sip += String("\t\t<FragmentTolerance>\n");
String unit_str = R"(unitCvRef="UO" unitName="dalton" unitAccession="UO:0000221")";
if (search_params.fragment_mass_tolerance_ppm)
{
unit_str = R"(unitCvRef="UO" unitName="parts per million" unitAccession="UO:0000169")";
}
sip += String(3, '\t') + R"(<cvParam accession="MS:1001412" name="search tolerance plus value" )" + unit_str + R"( cvRef="PSI-MS" value=")" + String(search_params.fragment_mass_tolerance) + "\"/>\n";
sip += String(3, '\t') + R"(<cvParam accession="MS:1001413" name="search tolerance minus value" )" + unit_str + R"( cvRef="PSI-MS" value=")" + String(search_params.fragment_mass_tolerance) + "\"/>\n";
sip += String("\t\t</FragmentTolerance>\n");
sip += String("\t\t<ParentTolerance>\n");
unit_str = R"(unitCvRef="UO" unitName="dalton" unitAccession="UO:0000221")";
if (search_params.precursor_mass_tolerance_ppm)
{
unit_str = R"(unitCvRef="UO" unitName="parts per million" unitAccession="UO:0000169")";
}
sip += String(3, '\t') + R"(<cvParam accession="MS:1001412" name="search tolerance plus value" )" + unit_str + R"( cvRef="PSI-MS" value=")" + String(search_params.precursor_mass_tolerance) + "\"/>\n";
sip += String(3, '\t') + R"(<cvParam accession="MS:1001413" name="search tolerance minus value" )" + unit_str + R"( cvRef="PSI-MS" value=")" + String(search_params.precursor_mass_tolerance) + "\"/>\n";
sip += String("\t\t</ParentTolerance>\n");
sip += String("\t\t<Threshold>\n\t\t\t") + thcv + "\n";
sip += String("\t\t</Threshold>\n");
sip += String("\t</SpectrumIdentificationProtocol>\n");
sip_set.insert(sip);
// empty date would lead to XML schema validation error:
DateTime date_time = it->getDateTime();
if (!date_time.isValid())
{
date_time = DateTime::now();
}
sil_2_date.insert(make_pair(sil_id, String(date_time.getDate() + "T" + date_time.getTime())));
//~ collect SpectraData element for each ProteinIdentification
String sdat_id;
StringList sdat_files;
String sdat_file(it->getMetaValue("spectra_data"));
if (sdat_file.empty())
{
sdat_file = String("UNKNOWN");
}
else
{
sdat_file = trimOpenMSfileURI(sdat_file);
}
std::map<String, String>::iterator sdit = sdat_ids.find(sdat_file); //this part is strongly connected to AnalysisCollection write part
if (sdit == sdat_ids.end())
{
sdat_id = "SDAT_" + String(UniqueIdGenerator::getUniqueId());
FileTypes::Type type = FileHandler::getTypeByFileName(sdat_file);
if (formats_map.find(type) == formats_map.end()) type = FileTypes::MZML; // default
//xml
spectra_data += String("\t\t<SpectraData location=\"") + sdat_file + String("\" id=\"") + sdat_id + String("\">");
spectra_data += String("\n\t\t\t<FileFormat>\n");
spectra_data += String(4, '\t') + cv_.getTermByName(formats_map[type].first).toXMLString(cv_ns);
spectra_data += String("\n\t\t\t</FileFormat>\n\t\t\t<SpectrumIDFormat>\n");
spectra_data += String(4, '\t') + cv_.getTermByName(formats_map[type].second).toXMLString(cv_ns);
spectra_data += String("\n\t\t\t</SpectrumIDFormat>\n\t\t</SpectraData>\n");
sdat_ids.insert(make_pair(sdat_file, sdat_id));
ph_2_sdat_.insert(make_pair(it->getIdentifier(), sdat_id));
}
else
{
sdat_id = sdit->second;
}
sil_2_sdat_.insert(make_pair(sil_id, sdat_id));
//~ collect SearchDatabase element for each ProteinIdentification
String sdb_id;
String sdb_file(search_params.db); //TODO @mths for several IdentificationRuns this must be something else, otherwise for two of the same db just one will be created
std::map<String, String>::iterator dbit = sdb_ids.find(sdb_file);
if (dbit == sdb_ids.end())
{
sdb_id = "SDB_"+ String(UniqueIdGenerator::getUniqueId());
search_database += String("\t\t<SearchDatabase ");
search_database += String("location=\"") + sdb_file + "\" ";
if (!String(search_params.db_version).empty())
{
search_database += String("version=\"") + String(search_params.db_version) + "\" ";
}
search_database += String("id=\"") + sdb_id + String("\">\n\t\t\t<FileFormat>\n");
//TODO Searchdb file format type cvParam handling
search_database += String(4, '\t') + cv_.getTermByName("FASTA format").toXMLString(cv_ns);
search_database += String("\n\t\t\t</FileFormat>\n\t\t\t<DatabaseName>\n\t\t\t\t<userParam name=\"") + sdb_file + String("\"/>\n\t\t\t</DatabaseName>\n");
// "MS:1001029" was removed from the "search_params" copy!
if (it->getSearchParameters().metaValueExists("MS:1001029"))
{
search_database += String(3, '\t') + cv_.getTerm("MS:1001029").toXMLString(cv_ns, it->getSearchParameters().getMetaValue("MS:1001029")) + String("\n");
}
search_database += "\t\t</SearchDatabase>\n";
sdb_ids.insert(make_pair(sdb_file, sdb_id));
}
else
{
sdb_id = dbit->second;
}
sil_2_sdb_.insert(make_pair(sil_id, sdb_id));
for (std::vector<ProteinHit>::const_iterator jt = it->getHits().begin(); jt != it->getHits().end(); ++jt)
{
String enid;
std::map<String, String>::iterator enit = sen_ids.find(String(jt->getAccession()));
if (enit == sen_ids.end())
{
String entry;
enid = "PROT_" + String(UniqueIdGenerator::getUniqueId()); //TODO IDs from metadata or where its stored at read in;
String enst(jt->getAccession());
entry += "\t<DBSequence accession=\"" + enst + "\" ";
entry += "searchDatabase_ref=\"" + sdb_id + "\" ";
String s = String(jt->getSequence());
if (!s.empty())
{
entry += "length=\"" + String(jt->getSequence().length()) + "\" ";
}
entry += String("id=\"") + String(enid) + String("\">\n");
if (!s.empty())
{
entry += "\t<Seq>" + s + "</Seq>\n";
}
entry += "\t\t" + cv_.getTermByName("protein description").toXMLString(cv_ns, enst);
entry += "\n\t</DBSequence>\n";
sen_ids.insert(std::pair<String, String>(enst, enid));
sen_set.insert(entry);
}
else
{
enid = enit->second;
}
}
}
inputs_element += search_database;
inputs_element += spectra_data;
inputs_element += "\t</Inputs>\n";
/*
2nd: iterate over peptideidentification vector
*/
//TODO ppxl - write here "MS:1002511" Cross-linked spectrum identification item linking the other spectrum
// PeptideIdentification represents xl pair.
// PeptideHit score_type is then the final score of xQuest_cpp.
// top5 ids -> 5 PeptideIdentification for one (pair) spectra. SIR with 5 entries and ranks
std::map<String, String> ppxl_specref_2_element; //where the SII will get added for one spectrum reference
std::map<String, std::vector<String> > pep_evis; //maps the sequence to the corresponding evidence elements for the next scope
for (PeptideIdentificationList::const_iterator it = cpep_id_->begin(); it != cpep_id_->end(); ++it)
{
String emz(it->getMZ());
const double rt = it->getRT();
String ert = rt == rt ? String(rt) : "nan";
String sid = it->getMetaValue(Constants::UserParam::SPECTRUM_REFERENCE);
if (sid.empty())
{
sid = String(it->getMetaValue("spectrum_id"));
if (sid.empty())
{
if (it->getMZ() != it->getMZ())
{
emz = "nan";
OPENMS_LOG_WARN << "Found no spectrum reference and no m/z position of identified spectrum! You are probably converting from an old format with insufficient data provision. Setting 'nan' - downstream applications might fail unless you set the references right.\n";
}
if (it->getRT() != it->getRT())
{
ert = "nan";
OPENMS_LOG_WARN << "Found no spectrum reference and no RT position of identified spectrum! You are probably converting from an old format with insufficient data provision. Setting 'nan' - downstream applications might fail unless you set the references right.\n";
}
sid = String("MZ:") + emz + String("@RT:") + ert;
}
}
if (is_ppxl && it->metaValueExists(Constants::UserParam::OPENPEPXL_HEAVY_SPEC_REF))
{
sid.append("," + String(it->getMetaValue(Constants::UserParam::OPENPEPXL_HEAVY_SPEC_REF)));
}
String sidres;
String sir = "SIR_" + String(UniqueIdGenerator::getUniqueId());
String sdr = sdat_ids.begin()->second;
std::map<String, String>::iterator pfo = ph_2_sdat_.find(it->getIdentifier());
if (pfo != ph_2_sdat_.end())
{
sdr = pfo->second;
}
else
{
OPENMS_LOG_WARN << "Falling back to referencing first spectrum file given because file or identifier could not be mapped.\n";
}
sidres += String("\t\t\t<SpectrumIdentificationResult spectraData_ref=\"")
//multi identification runs lookup from file_origin here
+ sdr + String("\" spectrumID=\"")
+ sid + String("\" id=\"") + sir + String("\">\n");
if (is_ppxl)
{
if (ppxl_specref_2_element.find(sid)==ppxl_specref_2_element.end())
{
ppxl_specref_2_element[sid] = sidres;
}
}
//map.begin access ok here because make sure at least one "UNKOWN" element is in the sdats_ids map
double ppxl_crosslink_mass(0);
if (is_ppxl)
{
ProteinIdentification::SearchParameters search_params = cpro_id_->front().getSearchParameters();
ppxl_crosslink_mass = String(search_params.getMetaValue("cross_link:mass")).toDouble();
}
for (std::vector<PeptideHit>::const_iterator jt = it->getHits().begin(); jt != it->getHits().end(); ++jt)
{
if (!is_ppxl)
{
MzIdentMLHandler::writePeptideHit(*jt, it, pep_ids, cv_ns, sen_set, sen_ids, pep_evis, pp_identifier_2_thresh, sidres);
}
else
{
String ppxl_linkid = UniqueIdGenerator::getUniqueId();
MzIdentMLHandler::writeXLMSPeptideHit(*jt, it, ppxl_linkid, pep_ids, cv_ns, sen_set, sen_ids, pep_evis, pp_identifier_2_thresh, ppxl_crosslink_mass, ppxl_specref_2_element, sid, true);
// XL-MS IDs from OpenPepXL can have two Peptides and SpectrumIdentifications, but with practically the same data except for the sequence and its modifications
if (jt->metaValueExists(Constants::UserParam::OPENPEPXL_XL_TYPE) && jt->getMetaValue(Constants::UserParam::OPENPEPXL_XL_TYPE) == "cross-link")
{
MzIdentMLHandler::writeXLMSPeptideHit(*jt, it, ppxl_linkid, pep_ids, cv_ns, sen_set, sen_ids, pep_evis, pp_identifier_2_thresh, ppxl_crosslink_mass, ppxl_specref_2_element, sid, false);
}
}
}
if (!ert.empty() && ert != "nan" && ert != "NaN" && !is_ppxl)
{
DataValue rtcv(ert);
rtcv.setUnit(10); // id: UO:0000010 name: second
rtcv.setUnitType(DataValue::UnitType::UNIT_ONTOLOGY);
sidres += "\t\t\t\t" + cv_.getTermByName("retention time").toXMLString(cv_ns, rtcv) + "\n";
}
if (!is_ppxl)
{
sidres += "\t\t\t</SpectrumIdentificationResult>\n";
std::map<String, String>::const_iterator ps_it = pp_identifier_2_sil_.find(it->getIdentifier());
if (ps_it != pp_identifier_2_sil_.end())
{
std::map<String, String>::iterator sil_it = sil_map.find(ps_it->second);
if (sil_it != sil_map.end())
{
sil_it->second.append(sidres);
}
else
{
sil_map.insert(make_pair(ps_it->second,sidres));
}
}
else
{
//encountered a PeptideIdentification which is not linked to any ProteinIdentification
OPENMS_LOG_ERROR << "encountered a PeptideIdentification which is not linked to any ProteinIdentification\n";
}
}
}
// ppxl - write spectrumidentificationresult closing tags!
if (is_ppxl)
{
for (std::map<String, String>::iterator it = ppxl_specref_2_element.begin(); it != ppxl_specref_2_element.end(); ++it)
{
it->second += "\t\t\t</SpectrumIdentificationResult>\n";
std::map<String, String>::const_iterator ps_it = pp_identifier_2_sil_.begin();
if (ps_it != pp_identifier_2_sil_.end())
{
std::map<String, String>::iterator sil_it = sil_map.find(ps_it->second);
if (sil_it != sil_map.end())
{
sil_it->second.append(it->second);
}
else
{
sil_map.insert(make_pair(ps_it->second,it->second));
}
}
else
{
//encountered a PeptideIdentification which is not linked to any ProteinIdentification
OPENMS_LOG_ERROR << "encountered a PeptideIdentification crosslink information which is not linked to any ProteinIdentification\n";
}
}
}
//--------------------------------------------------------------------------------------------
// XML header
//--------------------------------------------------------------------------------------------
String v_s = "1.1.0";
if (is_ppxl)
{
v_s = "1.2.0";
}
os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
<< "<MzIdentML xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
<< "\txsi:schemaLocation=\"http://psidev.info/psi/pi/mzIdentML/"<< v_s.substr(0,v_s.size()-2) <<" "
<< "https://raw.githubusercontent.com/HUPO-PSI/mzIdentML/master/schema/mzIdentML"<< v_s <<".xsd\"\n"
<< "\txmlns=\"http://psidev.info/psi/pi/mzIdentML/"<< v_s.substr(0,v_s.size()-2) <<"\"\n"
<< "\tversion=\"" << v_s << "\"\n";
os << "\tid=\"OpenMS_" << String(UniqueIdGenerator::getUniqueId()) << "\"\n"
<< "\tcreationDate=\"" << DateTime::now().getDate() << "T" << DateTime::now().getTime() << "\">\n";
//--------------------------------------------------------------------------------------------
// CV list
//--------------------------------------------------------------------------------------------
os << "<cvList>\n"
<< "\t<cv id=\"PSI-MS\" fullName=\"Proteomics Standards Initiative Mass Spectrometry Vocabularies\" "
<< "uri=\"http://purl.obolibrary.org/obo/ms/psi-ms.obo\" "
<< "version=\"3.15.0\"></cv>\n "
<< "\t<cv id=\"UNIMOD\" fullName=\"UNIMOD\" uri=\"http://www.unimod.org/obo/unimod.obo\"></cv>\n"
<< "\t<cv id=\"UO\" fullName=\"UNIT-ONTOLOGY\" "
<< "uri=\"https://raw.githubusercontent.com/bio-ontology-research-group/unit-ontology/master/unit.obo\"></cv>\n";
if (is_ppxl)
{
os << "\t<cv id=\"XLMOD\" fullName=\"PSI cross-link modifications\" "
<< "uri=\"https://raw.githubusercontent.com/HUPO-PSI/mzIdentML/master/cv/XLMOD-1.0.0.obo\"></cv>\n";
}
os << "</cvList>\n";
//--------------------------------------------------------------------------------------------
// AnalysisSoftwareList
//--------------------------------------------------------------------------------------------
os << "<AnalysisSoftwareList>\n";
for (std::set<String>::const_iterator sof = sof_set.begin(); sof != sof_set.end(); ++sof)
{
os << *sof;
}
std::map<String, String>::iterator soit = sof_ids.find("TOPP software");
if (soit == sof_ids.end())
{
os << "\t<AnalysisSoftware version=\"OpenMS TOPP v"<< VersionInfo::getVersion() <<R"(" name="TOPP software" id=")" << String("SOF_") << String(UniqueIdGenerator::getUniqueId()) << "\">\n"
<< "\t\t<SoftwareName>\n\t\t\t" << cv_.getTermByName("TOPP software").toXMLString(cv_ns) << "\n\t\t</SoftwareName>\n\t</AnalysisSoftware>\n";
}
os << "</AnalysisSoftwareList>\n";
//--------------------------------------------------------------------------------------------
// SequenceCollection
//--------------------------------------------------------------------------------------------
os << "<SequenceCollection>\n";
for (std::set<String>::const_iterator sen = sen_set.begin(); sen != sen_set.end(); ++sen)
{
os << *sen;
}
os << "</SequenceCollection>\n";
//--------------------------------------------------------------------------------------------
// AnalysisCollection:
// + SpectrumIdentification
// TODO ProteinDetection
//--------------------------------------------------------------------------------------------
os << "<AnalysisCollection>\n";
for (std::map<String,String>::const_iterator pp2sil_it = pp_identifier_2_sil_.begin(); pp2sil_it != pp_identifier_2_sil_.end(); ++pp2sil_it)
{
String entry = String("\t<SpectrumIdentification id=\"SI_") + pp2sil_it->first + String("\" spectrumIdentificationProtocol_ref=\"")
+ sil_2_sip_[pp2sil_it->second] + String("\" spectrumIdentificationList_ref=\"") + pp2sil_it->second
+ String("\" activityDate=\"") + sil_2_date[pp2sil_it->second]
+ String("\">\n")
//if crosslink +cvparam crosslink search performed
+ "\t\t<InputSpectra spectraData_ref=\"" + sil_2_sdat_[pp2sil_it->second] + "\"/>\n" // spd_ids.insert(std::pair<String, UInt64>(sdst, sdid));
+ "\t\t<SearchDatabaseRef searchDatabase_ref=\"" + sil_2_sdb_[pp2sil_it->second] + "\"/>\n"
+ "\t</SpectrumIdentification>\n";
os << entry;
}
os << "</AnalysisCollection>\n";
//--------------------------------------------------------------------------------------------
// AnalysisProtocolCollection
//+ SpectrumIdentificationProtocol + SearchType + Threshold
//--------------------------------------------------------------------------------------------
os << "<AnalysisProtocolCollection>\n";
for (std::set<String>::const_iterator sip = sip_set.begin(); sip != sip_set.end(); ++sip)
{
os << *sip;
}
os << "</AnalysisProtocolCollection>\n";
//--------------------------------------------------------------------------------------------
// DataCollection
//+Inputs
//+AnalysisData
//--------------------------------------------------------------------------------------------
os << "<DataCollection>\n"
<< inputs_element;
os << "\t<AnalysisData>\n";
for (std::map<String,String>::const_iterator sil_it = sil_map.begin(); sil_it != sil_map.end(); ++sil_it)
{
os << "\t\t<SpectrumIdentificationList id=\"" << sil_it->first << String("\">\n");
os << "\t\t\t<FragmentationTable>\n"
<< "\t\t\t\t<Measure id=\"Measure_mz\">\n"
<< "\t\t\t\t\t<cvParam accession=\"MS:1001225\" cvRef=\"PSI-MS\" unitCvRef=\"PSI-MS\" unitName=\"m/z\" unitAccession=\"MS:1000040\" name=\"product ion m/z\"/>\n"
<< "\t\t\t\t</Measure>\n"
<< "\t\t\t\t<Measure id=\"Measure_int\">\n"
<< "\t\t\t\t\t<cvParam cvRef=\"PSI-MS\" accession=\"MS:1001226\" name=\"product ion intensity\" unitAccession=\"MS:1000131\" unitCvRef=\"UO\" unitName=\"number of detector counts\"/>\n"
<< "\t\t\t\t</Measure>\n"
<< "\t\t\t\t<Measure id=\"Measure_error\">\n"
<< "\t\t\t\t\t<cvParam cvRef=\"PSI-MS\" accession=\"MS:1001227\" name=\"product ion m/z error\" unitAccession=\"MS:1000040\" unitCvRef=\"PSI-MS\" unitName=\"m/z\"/>\n"
<< "\t\t\t\t</Measure>\n";
if (is_ppxl)
{
os << "<!-- userParam cross-link_chain will contain a list of chain type corresponding to the indexed ion [alpha|beta] -->\n";
os << "<!-- userParam cross-link_ioncategory will contain a list of ion category corresponding to the indexed ion [xi|ci] -->\n";
}
os << "\t\t\t</FragmentationTable>\n";
os << sil_it->second;
os << "\t\t</SpectrumIdentificationList>\n";
}
os << "\t</AnalysisData>\n</DataCollection>\n";
//--------------------------------------------------------------------------------------------
// close XML header
//--------------------------------------------------------------------------------------------
os << "</MzIdentML>\n";
}
void MzIdentMLHandler::writeMetaInfos_(String& s, const MetaInfoInterface& meta, UInt indent) const
{
//TODO @mths: write those metas with their name in the cvs loaded as CVs!
if (meta.isMetaEmpty())
{
return;
}
std::vector<String> keys;
meta.getKeys(keys);
for (Size i = 0; i != keys.size(); ++i)
{
if (cv_.exists(keys[i]))
{
ControlledVocabulary::CVTerm a = cv_.getTerm(keys[i]);
s += String(indent, '\t') + a.toXMLString("PSI-MS", (String)(meta.getMetaValue(keys[i]))) + "\n";
}
else
{
s += String(indent, '\t') + "<userParam name=\"" + keys[i] + "\" unitName=\"";
const DataValue& d = meta.getMetaValue(keys[i]);
//determine type
if (d.valueType() == DataValue::INT_VALUE)
{
s += "xsd:integer";
}
else if (d.valueType() == DataValue::DOUBLE_VALUE)
{
s += "xsd:double";
}
else //string or lists are converted to string
{
s += "xsd:string";
}
s += "\" value=\"" + (String)(d) + "\"/>\n";
}
}
}
void MzIdentMLHandler::writeEnzyme_(String& s, const DigestionEnzymeProtein& enzy, UInt miss, UInt indent) const
{
String cv_ns = cv_.name();
s += String(indent, '\t') + "<Enzymes independent=\"false\">\n";
s += String(indent + 1, '\t') + "<Enzyme missedCleavages=\"" + String(miss) + "\" id=\"" + String("ENZ_") + String(UniqueIdGenerator::getUniqueId()) + "\">\n";
s += String(indent + 2, '\t') + "<EnzymeName>\n";
const String& enzymename = enzy.getName();
if (cv_.hasTermWithName(enzymename))
{
s += String(indent + 3, '\t') + cv_.getTermByName(enzymename).toXMLString(cv_ns) + "\n";
}
else if (enzymename == "no cleavage")
{
s += String(indent + 3, '\t') + cv_.getTermByName("NoEnzyme").toXMLString(cv_ns) + "\n";
}
else
{
s += String(indent + 3, '\t') + cv_.getTermByName("cleavage agent details").toXMLString(cv_ns) + "\n";
}
s += String(indent + 2, '\t') + "</EnzymeName>\n";
s += String(indent + 1, '\t') + "</Enzyme>\n";
s += String(indent, '\t') + "</Enzymes>\n";
}
void MzIdentMLHandler::writeModParam_(String& s, const std::vector<String>& mod_names, bool fixed, UInt indent) const
{
String cv_ns = unimod_.name();
for (std::vector<String>::const_iterator it = mod_names.begin(); it != mod_names.end(); ++it)
{
std::set<const ResidueModification*> mods;
ModificationsDB::getInstance()->searchModifications(mods, *it);
if (!mods.empty())
{
// @TODO: if multiple mods match, we write all of them?
for (std::set<const ResidueModification*>::const_iterator mt = mods.begin(); mt != mods.end(); ++mt)
{
char origin = (*mt)->getOrigin();
if (origin == 'X') origin = '.'; // terminal without res. spec.
s += String(indent + 1, '\t') + "<SearchModification fixedMod=\"" + (fixed ? "true" : "false") + "\" massDelta=\"" + String((*mt)->getDiffMonoMass()) + "\" residues=\"" + origin + "\">\n";
// @TODO: handle protein C-term/N-term
ResidueModification::TermSpecificity spec = (*mt)->getTermSpecificity();
if ((spec == ResidueModification::C_TERM) || (spec == ResidueModification::N_TERM))
{
const String& cv_name = "modification specificity peptide " + (*mt)->getTermSpecificityName();
s += String(indent + 2, '\t') + "<SpecificityRules>\n";
s += String(indent + 3, '\t') + cv_.getTermByName(cv_name).toXMLString(cv_ns) + "\n";
s += String(indent + 2, '\t') + "</SpecificityRules>\n";
}
String ac = (*mt)->getUniModAccession();
if (ac.hasPrefix("UniMod:")) ac = "UNIMOD:" + ac.suffix(':');
if (!ac.empty())
{
s += String(indent + 2, '\t') + unimod_.getTerm(ac).toXMLString(cv_ns) + "\n";
}
else
{
s += String(indent + 2, '\t') + "<cvParam cvRef=\"MS\" accession=\"MS:1001460\" name=\"unknown modification\"/>\n";
}
s += String(indent + 1, '\t') + "</SearchModification>\n";
}
}
else
{
String message = String("Registered ") + (fixed ? "fixed" : "variable") + " modification '" + *it + "' is unknown and will be ignored.";
throw Exception::ElementNotFound(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, message);
}
}
}
void MzIdentMLHandler::writeFragmentAnnotations_(String& s, const std::vector<PeptideHit::PeakAnnotation>& annotations, UInt indent, bool is_ppxl) const
{
std::map<UInt,std::map<String,std::vector<StringList> > > annotation_map;
for (const PeptideHit::PeakAnnotation& pep : annotations)
{// string coding example: [alpha|ci$y3-H2O-NH3]5+
// static const boost::regex frag_regex("\\[(?:([\\|\\w]+)\\$)*([abcxyz])(\\d+)((?:[\\+\\-\\w])*)\\](\\d+)\\+"); // this will fetch the complete loss/gain part as one
static const boost::regex frag_regex_tweak(R"(\[(?:([\|\w]+)\$)*([abcxyz])(\d+)(?:-(H2O|NH3))*\][(\d+)\+]*)"); // this will only fetch the last loss - and is preferred for now, as only these extra cv params are present
String ionseries_index;
String iontype;
//String loss_gain;
String loss;
StringList extra;
boost::smatch str_matches;
if (boost::regex_match(pep.annotation, str_matches, frag_regex_tweak))
{
String(str_matches[1]).split("|",extra);
iontype = std::string(str_matches[2]);
ionseries_index = std::string(str_matches[3]);
loss = std::string(str_matches[4]);
}
else
{
// since PeakAnnotations are very flexible and not all of them fit into the limited mzid fragment structure,
// this would happen quite often and flood the output, but we still need them for other output formats
// TODO find ways to represent additional fragment types or filter out known incompatible types
// OPENMS_LOG_WARN << "Well, fudge you very much, there is no matching annotation. ";
// OPENMS_LOG_WARN << pep.annotation << '\n';
continue;
}
String lt = "frag: " + iontype + " ion";
if (!loss.empty())
{
lt += " - "+loss;
}
if (annotation_map.find(pep.charge) == annotation_map.end())
{
annotation_map[pep.charge] = std::map<String, std::vector<StringList> >();
}
if (annotation_map[pep.charge].find(lt) == annotation_map[pep.charge].end())
{
annotation_map[pep.charge][lt] = std::vector<StringList> (3);
if (is_ppxl)
{
annotation_map[pep.charge][lt].push_back(StringList()); // alpha|beta
annotation_map[pep.charge][lt].push_back(StringList()); // ci|xi
}
}
annotation_map[pep.charge][lt][0].push_back(ionseries_index);
annotation_map[pep.charge][lt][1].push_back(String(pep.mz));
annotation_map[pep.charge][lt][2].push_back(String(pep.intensity));
if (is_ppxl)
{
String ab = ListUtils::contains<String>(extra ,String("alpha")) ? String("alpha"):String("beta");
String cx = ListUtils::contains<String>(extra ,String("ci")) ? String("ci"):String("xi");
annotation_map[pep.charge][lt][3].push_back(ab);
annotation_map[pep.charge][lt][4].push_back(cx);
}
}
// stop and return, if no mzid compatible fragments were found
if (annotation_map.empty())
{
return;
}
//double map: charge + ion type; collect in StringList: index + annotations; write:
s += String(indent, '\t') + "<Fragmentation>\n";
for (std::map<UInt,std::map<String,std::vector<StringList> > >::iterator i=annotation_map.begin();
i!=annotation_map.end(); ++i)
{
for (std::map<String,std::vector<StringList> >::iterator j=i->second.begin();
j!= i->second.end(); ++j)
{
s += String(indent+1, '\t') + "<IonType charge=\"" + String(i->first) +"\""
+ " index=\"" + ListUtils::concatenate(j->second[0], " ") + "\">\n";
s += String(indent+2, '\t') + "<FragmentArray measure_ref=\"Measure_mz\""
+ " values=\"" + ListUtils::concatenate(j->second[1], " ") + "\"/>\n";
s += String(indent+2, '\t') + "<FragmentArray measure_ref=\"Measure_int\""
+ " values=\"" + ListUtils::concatenate(j->second[2], " ") + "\"/>\n";
if (is_ppxl)
{
s += String(indent+2, '\t') + "<userParam name=\"cross-link_chain\"" + " unitName=\"xsd:string\""
+ " value=\"" + ListUtils::concatenate(j->second[3], " ") + "\"/>\n";
s += String(indent+2, '\t') + "<userParam name=\"cross-link_ioncategory\"" + " unitName=\"xsd:string\""
+ " value=\"" + ListUtils::concatenate(j->second[4], " ") + "\"/>\n";
}
s += String(indent+2, '\t') + cv_.getTermByName(j->first).toXMLString("PSI-MS") + "\n";
s += String(indent+1, '\t') + "</IonType>\n";
}
}
s += String(indent, '\t') + "</Fragmentation>\n";
//<Fragmentation>
// <IonType charge="1" index="2 3 5 6 5 6 10">
// <FragmentArray measure_ref="Measure_MZ" values="363.908 511.557 754.418 853.489 377.941 427.477 633.674"/>
// <FragmentArray measure_ref="Measure_Int" values="208.52 2034.9 1098.44 239.26 3325.34 3028.33 335.63"/>
// <FragmentArray measure_ref="Measure_Error" values="-0.255 0.326 0.101 0.104 0.285 0.287 0.369"/>
// <cvParam accession="MS:1001118" cvRef="PSI-MS" name="param: b ion"/>
// </IonType>
// <IonType charge="1" index="0 1 3 4 5 6 4 10">
// <FragmentArray measure_ref="Measure_MZ" values="175.202 246.812 474.82 587.465 686.52 814.542 294.235 652.206"/>
// <FragmentArray measure_ref="Measure_Int" values="84.44999 90.26999 143.95 3096.84 815.34 1.15999 612.52 18.79999"/>
// <FragmentArray measure_ref="Measure_Error" values="0.083 0.656 0.553 0.114 0.101 0.064 0.061 0.375"/>
// <cvParam accession="MS:1001262" cvRef="PSI-MS" name="param: y ion"/>
// </IonType>
//</Fragmentation>
}
String MzIdentMLHandler::trimOpenMSfileURI(const String& file) const
{
String r = file;
if (r.hasPrefix("["))
r = r.substr(1);
if (r.hasSuffix("]"))
r = r.substr(0,r.size()-1);
r.substitute("\\","/");
return r;
}
void MzIdentMLHandler::writePeptideHit(const PeptideHit& hit,
PeptideIdentificationList::const_iterator& it,
std::map<String, String>& pep_ids,
const String& cv_ns, std::set<String>& sen_set,
std::map<String, String>& sen_ids,
std::map<String, std::vector<String> >& pep_evis,
std::map<String, double>& pp_identifier_2_thresh,
String& sidres)
{
String pepid = "PEP_" + String(UniqueIdGenerator::getUniqueId());
String pepi = hit.getSequence().toString();
bool duplicate = false;
std::map<String, String>::iterator pit;
// avoid duplicates
pit = pep_ids.find(pepi);
if (pit != pep_ids.end())
{
duplicate = true;
}
if (!duplicate)
{
String p;
//~ TODO simplify mod cv param write
// write peptide id with conversion to universal, "human-readable" bracket string notation
p += String("\t<Peptide id=\"") + pepid + String("\" name=\"") +
hit.getSequence().toBracketString(false) + String("\">\n\t\t<PeptideSequence>") + hit.getSequence().toUnmodifiedString() + String("</PeptideSequence>\n");
if (hit.getSequence().isModified())
{
const ResidueModification* n_term_mod = hit.getSequence().getNTerminalModification();
if (n_term_mod != nullptr)
{
p += "\t\t<Modification location=\"0\">\n";
String acc = n_term_mod->getUniModAccession();
p += "\t\t\t<cvParam accession=\"UNIMOD:" + acc.suffix(':');
p += "\" name=\"" + n_term_mod->getId();
p += R"(" cvRef="UNIMOD"/>)";
p += "\n\t\t</Modification>\n";
}
const ResidueModification* c_term_mod = hit.getSequence().getCTerminalModification();
if (c_term_mod != nullptr)
{
p += "\t\t<Modification location=\"" + String(hit.getSequence().size()) + "\">\n";
String acc = c_term_mod->getUniModAccession();
p += "\t\t\t<cvParam accession=\"UNIMOD:" + acc.suffix(':');
p += "\" name=\"" + c_term_mod->getId();
p += R"(" cvRef="UNIMOD"/>)";
p += "\n\t\t</Modification>\n";
}
for (Size i = 0; i < hit.getSequence().size(); ++i)
{
const ResidueModification* mod = hit.getSequence()[i].getModification(); // "UNIMOD:" prefix??
if (mod != nullptr)
{
//~ p += hit.getSequence()[i].getModification() + "\t" + hit.getSequence()[i].getOneLetterCode() + "\t" + x + "\n" ;
p += "\t\t<Modification location=\"" + String(i + 1);
p += "\" residues=\"" + hit.getSequence()[i].getOneLetterCode();
String acc = mod->getUniModAccession();
if (!acc.empty())
{
p += "\">\n\t\t\t<cvParam accession=\"UNIMOD:" + acc.suffix(':'); //TODO @all: do not exclusively use unimod ...
p += "\" name=\"" + mod->getId();
p += R"(" cvRef="UNIMOD"/>)";
p += "\n\t\t</Modification>\n";
}
else
{
// We have an unknown modification, so lets write unknown
// and at least try to write down the delta mass.
if (mod->getDiffMonoMass() != 0.0)
{
double diffmass = mod->getDiffMonoMass();
p += "\" monoisotopicMassDelta=\"" + String(diffmass);
}
else if (mod->getMonoMass() > 0.0)
{
double diffmass = mod->getMonoMass() - hit.getSequence()[i].getMonoWeight();
p += "\" monoisotopicMassDelta=\"" + String(diffmass);
}
p += "\">\n\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1001460\" name=\"unknown modification\"/>";
p += "\n\t\t</Modification>\n";
}
}
}
}
p += "\t</Peptide>\n ";
sen_set.insert(p);
pep_ids.insert(std::make_pair(pepi, pepid));
}
else
{
pepid = pit->second;
}
std::vector<String> pevid_ids;
if (!duplicate)
{
std::vector<PeptideEvidence> peptide_evidences = hit.getPeptideEvidences();
// TODO idXML allows peptide hits without protein references! Fails in that case - run PeptideIndexer first
for (std::vector<PeptideEvidence>::const_iterator pe = peptide_evidences.begin(); pe != peptide_evidences.end(); ++pe)
{
String pevid = "PEV_" + String(UniqueIdGenerator::getUniqueId());
String dBSequence_ref;
map<String, String>::const_iterator pos = sen_ids.find(pe->getProteinAccession());
if (pos != sen_ids.end())
{
dBSequence_ref = pos->second;
}
else
{
OPENMS_LOG_ERROR << "Error: Missing or invalid protein reference for peptide '" << pepi << "': '" << pe->getProteinAccession() << "' - skipping." << endl;
continue;
}
String idec;
if (hit.metaValueExists(Constants::UserParam::TARGET_DECOY))
{
idec = String(boost::lexical_cast<std::string>((String(hit.getMetaValue(Constants::UserParam::TARGET_DECOY))).hasSubstring("decoy")));
}
String e;
String nc_termini = "-"; // character for N- and C-termini as specified in mzIdentML
e += "\t<PeptideEvidence id=\"" + pevid + "\" peptide_ref=\"" + pepid + "\" dBSequence_ref=\"" + dBSequence_ref + "\"";
if (pe->getAAAfter() != PeptideEvidence::UNKNOWN_AA)
{
e += " post=\"" + (pe->getAAAfter() == PeptideEvidence::C_TERMINAL_AA ? nc_termini : String(pe->getAAAfter())) + "\"";
}
if (pe->getAABefore() != PeptideEvidence::UNKNOWN_AA)
{
e += " pre=\"" + (pe->getAABefore() == PeptideEvidence::N_TERMINAL_AA ? nc_termini : String(pe->getAABefore())) + "\"";
}
if (pe->getStart() != PeptideEvidence::UNKNOWN_POSITION)
{
e += " start=\"" + String(pe->getStart() + 1) + "\"";
}
else if (hit.metaValueExists("start"))
{
e += " start=\"" + String( int(hit.getMetaValue("start")) + 1) + "\"";
}
else
{
OPENMS_LOG_WARN << "Found no start position of peptide hit in protein sequence.\n";
}
if (pe->getEnd() != PeptideEvidence::UNKNOWN_POSITION)
{
e += " end=\"" + String(pe->getEnd() + 1) + "\"";
}
else if (hit.metaValueExists("end"))
{
e += " end=\"" + String( int(hit.getMetaValue("end")) + 1) + "\"";
}
else
{
OPENMS_LOG_WARN << "Found no end position of peptide hit in protein sequence.\n";
}
if (!idec.empty())
{
e += " isDecoy=\"" + String(idec)+ "\"";
}
e += "/>\n";
sen_set.insert(e);
pevid_ids.push_back(pevid);
}
pep_evis.insert(make_pair(pepi, pevid_ids));
}
else
{
pevid_ids = pep_evis[pepi];
}
String cmz(hit.getSequence().getMZ(hit.getCharge())); //calculatedMassToCharge
String r(hit.getRank() + 1); //rank
String sc(hit.getScore());
if (sc.empty())
{
sc = "NA";
OPENMS_LOG_WARN << "No score assigned to this PSM: " /*<< hit.getSequence().toString()*/ << '\n';
}
String c(hit.getCharge()); //charge
String pte;
if (hit.metaValueExists("pass_threshold"))
{
pte = boost::lexical_cast<std::string>(hit.getMetaValue("pass_threshold"));
}
else if (pp_identifier_2_thresh.find(it->getIdentifier())!= pp_identifier_2_thresh.end() && pp_identifier_2_thresh.find(it->getIdentifier())->second != 0.0)
{
double th = pp_identifier_2_thresh.find(it->getIdentifier())->second;
//threshold was 'set' in proteinIdentification (!= default value of member, now check pass
pte = boost::lexical_cast<std::string>(it->isHigherScoreBetter() ? hit.getScore() > th : hit.getScore() < th); //passThreshold-eval
}
else
{
pte = true;
}
//write SpectrumIdentificationItem elements
String emz(it->getMZ());
String sii = "SII_" + String(UniqueIdGenerator::getUniqueId());
String sii_tmp;
sii_tmp += String("\t\t\t\t<SpectrumIdentificationItem passThreshold=\"")
+ pte + String("\" rank=\"") + r + String("\" peptide_ref=\"")
+ pepid + String("\" calculatedMassToCharge=\"") + cmz
+ String("\" experimentalMassToCharge=\"") + emz
+ String("\" chargeState=\"") + c + String("\" id=\"")
+ sii + String("\">\n");
if (pevid_ids.empty())
{
OPENMS_LOG_WARN << "PSM without peptide evidence registered in the given search database found. This will cause an invalid mzIdentML file (which OpenMS can still consume).\n";
}
for (std::vector<String>::const_iterator pevref = pevid_ids.begin(); pevref != pevid_ids.end(); ++pevref)
{
sii_tmp += "\t\t\t\t\t<PeptideEvidenceRef peptideEvidence_ref=\"" + String(*pevref) + "\"/>\n";
}
if (! hit.getPeakAnnotations().empty())
{
writeFragmentAnnotations_(sii_tmp, hit.getPeakAnnotations(), 5, false);
}
std::set<String> peptide_result_details;
cv_.getAllChildTerms(peptide_result_details, "MS:1001143"); // search engine specific score for PSMs
MetaInfoInterface copy_hit = hit;
String st(it->getScoreType()); //scoretype
if (cv_.hasTermWithName(st) && peptide_result_details.find(cv_.getTermByName(st).id) != peptide_result_details.end())
{
sii_tmp += "\t\t\t\t\t" + cv_.getTermByName(st).toXMLString(cv_ns, sc);
copy_hit.removeMetaValue(cv_.getTermByName(st).id);
}
else if (cv_.exists(st) && peptide_result_details.find(st) != peptide_result_details.end())
{
sii_tmp += "\t\t\t\t\t" + cv_.getTerm(st).toXMLString(cv_ns, sc);
copy_hit.removeMetaValue(cv_.getTerm(st).id);
}
else if (st == "q-value" || st == "FDR")
{
sii_tmp += "\t\t\t\t\t" + cv_.getTermByName("PSM-level q-value").toXMLString(cv_ns, sc);
copy_hit.removeMetaValue(cv_.getTermByName("PSM-level q-value").id);
}
else if (st == "Posterior Error Probability")
{
sii_tmp += "\t\t\t\t\t" + cv_.getTermByName("percolator:PEP").toXMLString(cv_ns, sc); // 'percolaror' was not a typo in the code but in the cv.
copy_hit.removeMetaValue(cv_.getTermByName("percolator:PEP").id);
}
else if (st == "OMSSA")
{
sii_tmp += "\t\t\t\t\t" + cv_.getTermByName("OMSSA:evalue").toXMLString(cv_ns, sc);
copy_hit.removeMetaValue(cv_.getTermByName("OMSSA:evalue").id);
}
else if (st == "Mascot")
{
sii_tmp += "\t\t\t\t\t" + cv_.getTermByName("Mascot:score").toXMLString(cv_ns, sc);
copy_hit.removeMetaValue(cv_.getTermByName("Mascot:score").id);
}
else if (st == "XTandem")
{
sii_tmp += "\t\t\t\t\t" + cv_.getTermByName("X\\!Tandem:hyperscore").toXMLString(cv_ns, sc);
copy_hit.removeMetaValue(cv_.getTermByName("X\\!Tandem:hyperscore").id);
}
else if (st == "SEQUEST")
{
sii_tmp += "\t\t\t\t\t" + cv_.getTermByName("Sequest:xcorr").toXMLString(cv_ns, sc);
copy_hit.removeMetaValue(cv_.getTermByName("Sequest:xcorr").id);
}
else if (st == "MS-GF+")
{
sii_tmp += "\t\t\t\t\t" + cv_.getTermByName("MS-GF:RawScore").toXMLString(cv_ns, sc);
copy_hit.removeMetaValue(cv_.getTermByName("MS-GF:RawScore").id);
}
else if (st == Constants::UserParam::OPENPEPXL_SCORE)
{
sii_tmp += "\t\t\t\t\t" + cv_.getTermByName(st).toXMLString(cv_ns, sc);
copy_hit.removeMetaValue(cv_.getTermByName(st).id);
}
else
{
String score_name_placeholder = st.empty()?"PSM-level search engine specific statistic":st;
sii_tmp += String(5, '\t') + cv_.getTermByName("PSM-level search engine specific statistic").toXMLString(cv_ns);
sii_tmp += "\n" + String(5, '\t') + "<userParam name=\"" + score_name_placeholder
+ "\" unitName=\"" + "xsd:double" + "\" value=\"" + sc + "\"/>";
OPENMS_LOG_WARN << "Converting unknown score type to PSM-level search engine specific statistic from PSI controlled vocabulary.\n";
}
sii_tmp += "\n";
copy_hit.removeMetaValue("calcMZ");
copy_hit.removeMetaValue(Constants::UserParam::TARGET_DECOY);
writeMetaInfos_(sii_tmp, copy_hit, 5);
//~ sidres += "<cvParam accession=\"MS:1000796\" cvRef=\"PSI-MS\" value=\"55.835.842.3.dta\" name=\"spectrum title\"/>";
sii_tmp += "\t\t\t\t</SpectrumIdentificationItem>\n";
sidres += sii_tmp;
}
void MzIdentMLHandler::writeXLMSPeptideHit(const PeptideHit& hit,
PeptideIdentificationList::const_iterator& it,
const String& ppxl_linkid, std::map<String, String>& pep_ids,
const String& cv_ns, std::set<String>& sen_set,
std::map<String, String>& sen_ids,
std::map<String, std::vector<String> >& pep_evis,
std::map<String, double>& pp_identifier_2_thresh,
double ppxl_crosslink_mass,
std::map<String, String>& ppxl_specref_2_element,
String& sid, bool alpha_peptide)
{
String pepid = "PEP_" + String(UniqueIdGenerator::getUniqueId());
AASequence peptide_sequence;
if (alpha_peptide)
{
peptide_sequence = hit.getSequence();
}
else
{
peptide_sequence = AASequence::fromString(hit.getMetaValue(Constants::UserParam::OPENPEPXL_BETA_SEQUENCE));
}
String pepi = peptide_sequence.toString();
// The same peptide sequence (including mods and link position) can be used several times in different pairs
// make pepi unique enough, so that PeptideEvidences are written for each case
if (alpha_peptide)
{
pepi += "_MS:1002509";
}
else
{
pepi += "_MS:1002510";
}
if (hit.getMetaValue(Constants::UserParam::OPENPEPXL_XL_TYPE) != "mono-link") //sequence may contain more than one linker anchors; also code position linked
{
if (alpha_peptide)
{
pepi += "_" + hit.getMetaValue(Constants::UserParam::OPENPEPXL_XL_POS1).toString();
}
else
{
pepi += "_" + hit.getMetaValue(Constants::UserParam::OPENPEPXL_XL_POS2).toString();
}
}
pepi += ppxl_linkid;
bool duplicate = false;
std::map<String, String>::iterator pit;
// avoid duplicates in case with only one peptide
if (hit.getMetaValue(Constants::UserParam::OPENPEPXL_XL_TYPE) != "cross-link")
{
pit = pep_ids.find(pepi);
if (pit != pep_ids.end())
{
duplicate = true;
}
}
// TODO another criterion for ppxl: the same "donor" pep_id can only be reused in combination with the same "acceptor" pep_id,
// for now I will just make an exemption for ppxl data, otherwise we get an invalid file as we have missing peptide pairings.
// the redundancy should not increase too much, since pairings between exactly the same peptides for different spectra
// should be a minority
// avoid duplicate pairs in ppxl data
// TODO access to pep_ids for both peptides from each pair necessary for PSMs
// below code does not work at all yet
// if (hit.metaValueExists("xl_chain") && it->getHits().size() == 2)
// {
// std::vector<PeptideHit> peps = it->getHits();
// String pepi2 = peps[1].getSequence().toString();
// std::map<String, String>::iterator pit = pep_pairs_ppxl.find(pepi);
// // last entry in vector
// std::pair<String, String> pepid_pairs_ppxl[pepid_pairs_ppxl.size()-1];
// if (pit != pep_pairs_ppxl.end())
// {
// if (pit->second == pep2)
// {
// duplicate = true;
// }
// }
// }
if (!duplicate)
{
String p;
//~ TODO simplify mod cv param write
// write peptide id with conversion to universal, "human-readable" bracket string notation
p += String("\t<Peptide id=\"") + pepid + String("\" name=\"") +
peptide_sequence.toBracketString(false) + String("\">\n\t\t<PeptideSequence>") + peptide_sequence.toUnmodifiedString() + String("</PeptideSequence>\n");
const ResidueModification* n_term_mod = peptide_sequence.getNTerminalModification();
if (n_term_mod != nullptr)
{
p += "\t\t<Modification location=\"0\">\n";
String acc = n_term_mod->getUniModAccession();
bool unimod = true;
if (!acc.empty())
{
p += "\t\t\t<cvParam accession=\"UNIMOD:" + acc.suffix(':');
}
else
{
acc = n_term_mod->getPSIMODAccession();
p += "\t\t\t<cvParam accession=\"XLMOD:" + acc.suffix(':');
unimod = false;
}
p += "\" name=\"" + n_term_mod->getId();
if (unimod)
{
p += R"(" cvRef="UNIMOD"/>)";
}
else
{
p += R"(" cvRef="XLMOD"/>)";
}
p += "\n\t\t</Modification>\n";
}
const ResidueModification* c_term_mod = peptide_sequence.getCTerminalModification();
if (c_term_mod != nullptr)
{
p += "\t\t<Modification location=\"" + String(peptide_sequence.size()) + "\">\n";
String acc = c_term_mod->getUniModAccession();
bool unimod = true;
if (!acc.empty())
{
p += "\t\t\t<cvParam accession=\"UNIMOD:" + acc.suffix(':');
}
else
{
acc = c_term_mod->getPSIMODAccession();
p += "\t\t\t<cvParam accession=\"XLMOD:" + acc.suffix(':');
unimod = false;
}
p += "\" name=\"" + c_term_mod->getId();
if (unimod)
{
p += R"(" cvRef="UNIMOD"/>)";
}
else
{
p += R"(" cvRef="XLMOD"/>)";
}
p += "\n\t\t</Modification>\n";
}
for (Size i = 0; i < peptide_sequence.size(); ++i)
{
const ResidueModification* mod = peptide_sequence[i].getModification(); // "UNIMOD:" prefix??
if (mod != nullptr)
{
p += "\t\t<Modification location=\"" + String(i + 1);
p += "\" residues=\"" + peptide_sequence[i].getOneLetterCode();
String acc = mod->getUniModAccession();
if (!acc.empty())
{
p += "\">\n\t\t\t<cvParam accession=\"UNIMOD:" + acc.suffix(':'); //TODO @all: do not exclusively use unimod ...
p += "\" name=\"" + mod->getId();
p += R"(" cvRef="UNIMOD"/>)";
p += "\n\t\t</Modification>\n";
}
else
{
acc = mod->getPSIMODAccession();
if (!acc.empty())
{
p += "\">\n\t\t\t<cvParam accession=\"XLMOD:" + acc.suffix(':');
p += "\" name=\"" + mod->getId();
p += R"(" cvRef="XLMOD"/>)";
p += "\n\t\t</Modification>\n";
}
else
{
// We have an unknown modification, so lets write unknown
// and at least try to write down the delta mass.
if (mod->getDiffMonoMass() != 0.0)
{
double diffmass = mod->getDiffMonoMass();
p += "\" monoisotopicMassDelta=\"" + String(diffmass);
}
else if (mod->getMonoMass() > 0.0)
{
double diffmass = mod->getMonoMass() - peptide_sequence[i].getMonoWeight();
p += "\" monoisotopicMassDelta=\"" + String(diffmass);
}
p += "\">\n\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1001460\" name=\"unknown modification\"/>";
p += "\n\t\t</Modification>\n";
}
}
}
// Failsafe, if someone uses a new cross-linker (given these conditions, there MUST be a linker at this position, but it does not have a Unimod or XLMOD entry)
else if (alpha_peptide && hit.metaValueExists(Constants::UserParam::OPENPEPXL_XL_MOD) && (static_cast<Size>(hit.getMetaValue(Constants::UserParam::OPENPEPXL_XL_POS1).toString().toInt()) == i) && (hit.getMetaValue(Constants::UserParam::OPENPEPXL_XL_TYPE).toString() == "mono-link") )
{
p += "\t\t<Modification location=\"" + String(i + 1);
p += "\" residues=\"" + String(peptide_sequence[i].getOneLetterCode());
p += "\">\n\t\t\t<cvParam accession=\"XLMOD:XXXXX";
p += "\" name=\"" + hit.getMetaValue(Constants::UserParam::OPENPEPXL_XL_MOD).toString();
p += R"(" cvRef="XLMOD"/>)";
p += "\n\t\t</Modification>\n";
}
}
if (hit.metaValueExists(Constants::UserParam::OPENPEPXL_XL_TYPE) && hit.getMetaValue(Constants::UserParam::OPENPEPXL_XL_TYPE) != "mono-link")
{
int i = hit.getMetaValue(Constants::UserParam::OPENPEPXL_XL_POS1).toString().toInt();
if (alpha_peptide)
{
CrossLinksDB* xl_db = CrossLinksDB::getInstance();
std::vector<String> mods;
if (hit.metaValueExists(Constants::UserParam::OPENPEPXL_XL_TERM_SPEC_ALPHA) && hit.getMetaValue(Constants::UserParam::OPENPEPXL_XL_TERM_SPEC_ALPHA) == "N_TERM")
{
xl_db->searchModificationsByDiffMonoMass(mods, double(hit.getMetaValue(Constants::UserParam::OPENPEPXL_XL_MASS)), 0.0001, "", ResidueModification::N_TERM);
if (!mods.empty())
{
p += "\t\t<Modification location=\"0";
}
}
else if (hit.metaValueExists(Constants::UserParam::OPENPEPXL_XL_TERM_SPEC_ALPHA) && hit.getMetaValue(Constants::UserParam::OPENPEPXL_XL_TERM_SPEC_ALPHA) == "C_TERM")
{
xl_db->searchModificationsByDiffMonoMass(mods, double(hit.getMetaValue(Constants::UserParam::OPENPEPXL_XL_MASS)), 0.0001, "", ResidueModification::C_TERM);
if (!mods.empty())
{
p += "\t\t<Modification location=\"" + String(i + 2);
}
}
else
{
xl_db->searchModificationsByDiffMonoMass(mods, double(hit.getMetaValue(Constants::UserParam::OPENPEPXL_XL_MASS)), 0.0001, String(hit.getSequence()[i].getOneLetterCode()), ResidueModification::ANYWHERE);
if (!mods.empty())
{
p += "\t\t<Modification location=\"" + String(i + 1);
}
}
String acc = "";
String name = "";
for (Size s = 0; s < mods.size(); ++s)
{
if (mods[s].hasSubstring(hit.getMetaValue(Constants::UserParam::OPENPEPXL_XL_MOD)))
{
const ResidueModification* mod = nullptr;
try
{
mod = xl_db->getModification(mods[s], peptide_sequence[i].getOneLetterCode(), ResidueModification::ANYWHERE);
}
catch (...)
{
if (hit.metaValueExists(Constants::UserParam::OPENPEPXL_XL_TERM_SPEC_ALPHA) && hit.getMetaValue(Constants::UserParam::OPENPEPXL_XL_TERM_SPEC_ALPHA) == "N_TERM")
{
mod = xl_db->getModification(mods[s], "", ResidueModification::N_TERM);
}
else if (hit.metaValueExists(Constants::UserParam::OPENPEPXL_XL_TERM_SPEC_ALPHA) && hit.getMetaValue(Constants::UserParam::OPENPEPXL_XL_TERM_SPEC_ALPHA) == "C_TERM")
{
mod = xl_db->getModification(mods[s], "", ResidueModification::C_TERM);
}
}
// mod should never be null, but gcc complains (-Werror=maybe-uninitialized)
if (mod != nullptr)
{
acc = mod->getPSIMODAccession();
}
if (mod != nullptr)
{
name = mod->getId();
}
}
if (!acc.empty())
{
break;
}
}
if ( acc.empty() && (!mods.empty()) ) // If ambiguity can not be resolved by xl_mod, just take one with the same mass diff from the database
{
const ResidueModification* mod = xl_db->getModification( String(peptide_sequence[i].getOneLetterCode()), mods[0], ResidueModification::ANYWHERE);
acc = mod->getPSIMODAccession();
name = mod->getId();
}
if (!acc.empty())
{
p += "\" residues=\"" + String(peptide_sequence[i].getOneLetterCode());
p += "\" monoisotopicMassDelta=\"" + hit.getMetaValue(Constants::UserParam::OPENPEPXL_XL_MASS).toString() + "\">\n";
p += "\t\t\t<cvParam accession=\"" + acc + R"(" cvRef="XLMOD" name=")" + name + "\"/>\n";
}
else // if there is no matching modification in the database, write out a placeholder
{
p += "\t\t<Modification location=\"" + String(i + 1);
p += "\" residues=\"" + String(peptide_sequence[i].getOneLetterCode());
p += "\" monoisotopicMassDelta=\"" + hit.getMetaValue(Constants::UserParam::OPENPEPXL_XL_MASS).toString() + "\">\n";
p += "\t\t\t<cvParam accession=\"XLMOD:XXXXX\" cvRef=\"XLMOD\" name=\"" + hit.getMetaValue(Constants::UserParam::OPENPEPXL_XL_MOD).toString() + "\"/>\n";
}
}
else // xl_chain = "MS:1002510", acceptor, beta peptide
{
i = hit.getMetaValue(Constants::UserParam::OPENPEPXL_XL_POS2).toString().toInt();
if (hit.metaValueExists(Constants::UserParam::OPENPEPXL_XL_TERM_SPEC_BETA) && hit.getMetaValue(Constants::UserParam::OPENPEPXL_XL_TERM_SPEC_BETA) == "N_TERM")
{
p += "\t\t<Modification location=\"0";
}
else if (hit.metaValueExists(Constants::UserParam::OPENPEPXL_XL_TERM_SPEC_BETA) && hit.getMetaValue(Constants::UserParam::OPENPEPXL_XL_TERM_SPEC_BETA) == "C_TERM")
{
p += "\t\t<Modification location=\"" + String(peptide_sequence.size() + 2);
}
else
{
p += "\t\t<Modification location=\"" + String(i + 1);
}
p += "\" residues=\"" + String(peptide_sequence[i].getOneLetterCode());
p += "\" monoisotopicMassDelta=\"0\">\n";
}
if (alpha_peptide)
{
p += "\t\t\t" + cv_.getTerm(String("MS:1002509")).toXMLString(cv_ns, DataValue(ppxl_linkid));
}
else
{
p += "\t\t\t" + cv_.getTerm(String("MS:1002510")).toXMLString(cv_ns, DataValue(ppxl_linkid));
}
p += "\n\t\t</Modification>\n";
}
if (hit.metaValueExists(Constants::UserParam::OPENPEPXL_XL_TYPE) && hit.getMetaValue(Constants::UserParam::OPENPEPXL_XL_TYPE) == "loop-link")
{
int i = hit.getMetaValue(Constants::UserParam::OPENPEPXL_XL_POS2).toString().toInt();
p += "\t\t<Modification location=\"" + String(i + 1);
p += "\" residues=\"" + String(peptide_sequence[i].getOneLetterCode());
p += "\" monoisotopicMassDelta=\"0";
// ppxl crosslink loop xl_pos2 is always the acceptor ("MS:1002510")
p += "\">\n\t\t\t" + cv_.getTerm("MS:1002510").toXMLString(cv_ns, DataValue(ppxl_linkid));
p += "\n\t\t</Modification>\n";
}
p += "\t</Peptide>\n ";
sen_set.insert(p);
pep_ids.insert(std::make_pair(pepi, pepid));
}
else
{
pepid = pit->second;
}
std::vector<String> pevid_ids;
if (!duplicate)
{
if (alpha_peptide)
{
std::vector<PeptideEvidence> peptide_evidences = hit.getPeptideEvidences();
// TODO idXML allows peptide hits without protein references! Fails in that case - run PeptideIndexer first
// TODO BETA PEPTIDE Protein Info
for (std::vector<PeptideEvidence>::const_iterator pe = peptide_evidences.begin(); pe != peptide_evidences.end(); ++pe)
{
String pevid = "PEV_" + String(UniqueIdGenerator::getUniqueId());
String dBSequence_ref;
map<String, String>::const_iterator pos = sen_ids.find(pe->getProteinAccession());
if (pos != sen_ids.end())
{
dBSequence_ref = pos->second;
}
else
{
OPENMS_LOG_ERROR << "Error: Missing or invalid protein reference for peptide '" << pepi << "': '" << pe->getProteinAccession() << "' - skipping." << endl;
continue;
}
String idec;
if (hit.metaValueExists(Constants::UserParam::OPENPEPXL_TARGET_DECOY_ALPHA))
{
idec = String(boost::lexical_cast<std::string>((String(hit.getMetaValue(Constants::UserParam::OPENPEPXL_TARGET_DECOY_ALPHA))).hasSubstring("decoy")));
}
String e;
String nc_termini = "-"; // character for N- and C-termini as specified in mzIdentML
e += "\t<PeptideEvidence id=\"" + pevid + "\" peptide_ref=\"" + pepid + "\" dBSequence_ref=\"" + dBSequence_ref + "\"";
if (pe->getAAAfter() != PeptideEvidence::UNKNOWN_AA)
{
e += " post=\"" + (pe->getAAAfter() == PeptideEvidence::C_TERMINAL_AA ? nc_termini : String(pe->getAAAfter())) + "\"";
}
if (pe->getAABefore() != PeptideEvidence::UNKNOWN_AA)
{
e += " pre=\"" + (pe->getAABefore() == PeptideEvidence::N_TERMINAL_AA ? nc_termini : String(pe->getAABefore())) + "\"";
}
if (pe->getStart() != PeptideEvidence::UNKNOWN_POSITION)
{
e += " start=\"" + String(pe->getStart() + 1) + "\"";
}
else if (hit.metaValueExists("start"))
{
e += " start=\"" + String( int(hit.getMetaValue("start")) + 1) + "\"";
}
else
{
OPENMS_LOG_WARN << "Found no start position of peptide hit in protein sequence.\n";
}
if (pe->getEnd() != PeptideEvidence::UNKNOWN_POSITION)
{
e += " end=\"" + String(pe->getEnd() + 1) + "\"";
}
else if (hit.metaValueExists("end"))
{
e += " end=\"" + String( int(hit.getMetaValue("end")) + 1) + "\"";
}
else
{
OPENMS_LOG_WARN << "Found no end position of peptide hit in protein sequence.\n";
}
if (!idec.empty())
{
e += " isDecoy=\"" + String(idec)+ "\"";
}
e += "/>\n";
sen_set.insert(e);
pevid_ids.push_back(pevid);
}
pep_evis.insert(make_pair(pepi, pevid_ids));
}
else // acceptor, beta peptide, does not have its own PeptideHit and PeptideEvidences
{
StringList prot = ListUtils::create<String>(String(hit.getMetaValue(Constants::UserParam::OPENPEPXL_BETA_ACCESSIONS)));
StringList pre = ListUtils::create<String>(String(hit.getMetaValue(Constants::UserParam::OPENPEPXL_BETA_PEPEV_PRE)));
StringList post = ListUtils::create<String>(String(hit.getMetaValue(Constants::UserParam::OPENPEPXL_BETA_PEPEV_POST)));
StringList start = ListUtils::create<String>(String(hit.getMetaValue(Constants::UserParam::OPENPEPXL_BETA_PEPEV_START)));
StringList end = ListUtils::create<String>(String(hit.getMetaValue(Constants::UserParam::OPENPEPXL_BETA_PEPEV_END)));
for (Size ev = 0; ev < pre.size(); ++ev)
{
String pevid = "PEV_" + String(UniqueIdGenerator::getUniqueId());
String dBSequence_ref;
map<String, String>::const_iterator pos = sen_ids.find(prot[ev]);
if (pos != sen_ids.end())
{
dBSequence_ref = pos->second;
}
else
{
OPENMS_LOG_ERROR << "Error: Missing or invalid protein reference for peptide '" << pepi << "': '" << prot[ev] << "' - skipping." << endl;
continue;
}
String idec;
if (hit.metaValueExists(Constants::UserParam::OPENPEPXL_TARGET_DECOY_BETA))
{
idec = String(boost::lexical_cast<std::string>((String(hit.getMetaValue(Constants::UserParam::OPENPEPXL_TARGET_DECOY_BETA))).hasSubstring("decoy")));
}
String e;
String nc_termini = "-"; // character for N- and C-termini as specified in mzIdentML
e += "\t<PeptideEvidence id=\"" + pevid + "\" peptide_ref=\"" + pepid + "\" dBSequence_ref=\"" + dBSequence_ref + "\"";
if (post[ev] != String(PeptideEvidence::UNKNOWN_AA))
{
e += " post=\"" + (post[ev] == String(PeptideEvidence::C_TERMINAL_AA) ? nc_termini : post[ev]) + "\"";
}
if (pre[ev] != String(PeptideEvidence::UNKNOWN_AA))
{
e += " pre=\"" + (pre[ev] == String(PeptideEvidence::N_TERMINAL_AA) ? nc_termini : pre[ev]) + "\"";
}
if (start[ev] != String(PeptideEvidence::UNKNOWN_POSITION))
{
e += " start=\"" + String(start[ev].toInt() + 1) + "\"";
}
else
{
OPENMS_LOG_WARN << "Found no start position of peptide hit in protein sequence.\n";
}
if (end[ev] != String(PeptideEvidence::UNKNOWN_POSITION))
{
e += " end=\"" + String(end[ev].toInt() + 1) + "\"";
}
else
{
OPENMS_LOG_WARN << "Found no end position of peptide hit in protein sequence.\n";
}
if (!idec.empty())
{
e += " isDecoy=\"" + String(idec)+ "\"";
}
e += "/>\n";
sen_set.insert(e);
pevid_ids.push_back(pevid);
}
pep_evis.insert(make_pair(pepi, pevid_ids));
}
}
else
{
pevid_ids = pep_evis[pepi];
}
String r(hit.getRank() + 1); //rank
String sc(hit.getScore());
if (hit.metaValueExists(Constants::UserParam::OPENPEPXL_XL_RANK))
{
r = hit.getMetaValue(Constants::UserParam::OPENPEPXL_XL_RANK).toString(); // ppxl remove xl_rank later (in copy_hit)
}
//Calculated mass to charge for cross-linked is both peptides + linker
double calc_ppxl_mass = hit.getSequence().getMonoWeight();
if (hit.getMetaValue(Constants::UserParam::OPENPEPXL_XL_TYPE) == "cross-link")
{
calc_ppxl_mass += ppxl_crosslink_mass + AASequence::fromString(hit.getMetaValue(Constants::UserParam::OPENPEPXL_BETA_SEQUENCE)).getMonoWeight();
}
// if xl_mod and xl_mass MetaValues exist, then the mass of the mono-link could not be set as a AASequence modification and will not be considered by .getMonoWeight
else if (hit.metaValueExists(Constants::UserParam::OPENPEPXL_XL_MOD) && hit.metaValueExists(Constants::UserParam::OPENPEPXL_XL_MASS))
{
calc_ppxl_mass += double(hit.getMetaValue(Constants::UserParam::OPENPEPXL_XL_MASS));
}
String cmz = String( ((calc_ppxl_mass) + (hit.getCharge() * Constants::PROTON_MASS_U)) / hit.getCharge()); //calculatedMassToCharge
if (sc.empty())
{
sc = "NA";
OPENMS_LOG_WARN << "No score assigned to this PSM: " /*<< hit.getSequence().toString()*/ << '\n';
}
String c(hit.getCharge()); //charge
String pte;
if (hit.metaValueExists("pass_threshold"))
{
pte = boost::lexical_cast<std::string>(hit.getMetaValue("pass_threshold"));
}
else if (pp_identifier_2_thresh.find(it->getIdentifier())!= pp_identifier_2_thresh.end() && pp_identifier_2_thresh.find(it->getIdentifier())->second != 0.0)
{
double th = pp_identifier_2_thresh.find(it->getIdentifier())->second;
//threshold was 'set' in proteinIdentification (!= default value of member, now check pass
pte = boost::lexical_cast<std::string>(it->isHigherScoreBetter() ? hit.getScore() > th : hit.getScore() < th); //passThreshold-eval
}
else
{
pte = true;
}
//write SpectrumIdentificationItem elements
String emz(it->getMZ());
String sii = "SII_" + String(UniqueIdGenerator::getUniqueId());
String sii_tmp;
sii_tmp += String("\t\t\t\t<SpectrumIdentificationItem passThreshold=\"")
+ pte + String("\" rank=\"") + r + String("\" peptide_ref=\"")
+ pepid + String("\" calculatedMassToCharge=\"") + cmz
+ String("\" experimentalMassToCharge=\"") + emz
+ String("\" chargeState=\"") + c + String("\" id=\"")
+ sii + String("\">\n");
if (pevid_ids.empty())
{
OPENMS_LOG_WARN << "PSM without peptide evidence registered in the given search database found. This will cause an invalid mzIdentML file (which OpenMS can still consume).\n";
}
for (std::vector<String>::const_iterator pevref = pevid_ids.begin(); pevref != pevid_ids.end(); ++pevref)
{
sii_tmp += "\t\t\t\t\t<PeptideEvidenceRef peptideEvidence_ref=\"" + String(*pevref) + "\"/>\n";
}
if (! hit.getPeakAnnotations().empty() && alpha_peptide)
{
// is_ppxl = true
writeFragmentAnnotations_(sii_tmp, hit.getPeakAnnotations(), 5, true);
}
std::set<String> peptide_result_details;
cv_.getAllChildTerms(peptide_result_details, "MS:1001143"); // search engine specific score for PSMs
MetaInfoInterface copy_hit = hit;
String st(it->getScoreType()); //scoretype
if (cv_.hasTermWithName(st) && peptide_result_details.find(cv_.getTermByName(st).id) != peptide_result_details.end())
{
sii_tmp += "\t\t\t\t\t" + cv_.getTermByName(st).toXMLString(cv_ns, sc);
copy_hit.removeMetaValue(cv_.getTermByName(st).id);
}
else if (cv_.exists(st) && peptide_result_details.find(st) != peptide_result_details.end())
{
sii_tmp += "\t\t\t\t\t" + cv_.getTerm(st).toXMLString(cv_ns, sc);
copy_hit.removeMetaValue(cv_.getTerm(st).id);
}
else if (st == "q-value" || st == "FDR")
{
sii_tmp += "\t\t\t\t\t" + cv_.getTermByName("PSM-level q-value").toXMLString(cv_ns, sc);
copy_hit.removeMetaValue(cv_.getTermByName("PSM-level q-value").id);
}
else if (st == "Posterior Error Probability")
{
sii_tmp += "\t\t\t\t\t" + cv_.getTermByName("percolator:PEP").toXMLString(cv_ns, sc); // 'percolaror' was not a typo in the code but in the cv.
copy_hit.removeMetaValue(cv_.getTermByName("percolator:PEP").id);
}
else if (st == Constants::UserParam::OPENPEPXL_SCORE)
{
sii_tmp += "\t\t\t\t\t" + cv_.getTermByName(st).toXMLString(cv_ns, sc);
copy_hit.removeMetaValue(cv_.getTermByName(st).id);
}
else
{
String score_name_placeholder = st.empty()?"PSM-level search engine specific statistic":st;
sii_tmp += String(5, '\t') + cv_.getTermByName("PSM-level search engine specific statistic").toXMLString(cv_ns);
sii_tmp += "\n" + String(5, '\t') + "<userParam name=\"" + score_name_placeholder
+ "\" unitName=\"" + "xsd:double" + "\" value=\"" + sc + "\"/>";
OPENMS_LOG_WARN << "Converting unknown score type to PSM-level search engine specific statistic from PSI controlled vocabulary.\n";
}
sii_tmp += "\n";
copy_hit.removeMetaValue("calcMZ");
copy_hit.removeMetaValue(Constants::UserParam::TARGET_DECOY);
// TODO this would be the correct way, but need to adjust parsing as well
if (copy_hit.metaValueExists(Constants::UserParam::OPENPEPXL_HEAVY_SPEC_MZ) || copy_hit.getMetaValue(Constants::UserParam::OPENPEPXL_XL_TYPE) == "cross-link")
{
sii_tmp += "\t\t\t\t\t" + cv_.getTerm("MS:1002511").toXMLString(cv_ns, ppxl_linkid) + "\n"; // cross-linked spectrum identification item
}
copy_hit.removeMetaValue(Constants::UserParam::OPENPEPXL_XL_RANK);
copy_hit.removeMetaValue(Constants::UserParam::OPENPEPXL_XL_POS1);
copy_hit.removeMetaValue(Constants::UserParam::OPENPEPXL_XL_POS2);
copy_hit.removeMetaValue(Constants::UserParam::OPENPEPXL_XL_MOD);
copy_hit.removeMetaValue("xl_chain");
copy_hit.removeMetaValue(Constants::UserParam::OPENPEPXL_XL_MASS);
copy_hit.removeMetaValue("protein_references");
copy_hit.removeMetaValue(Constants::UserParam::OPENPEPXL_HEAVY_SPEC_REF);
copy_hit.removeMetaValue(Constants::UserParam::SPECTRUM_REFERENCE);
copy_hit.removeMetaValue(Constants::UserParam::OPENPEPXL_HEAVY_SPEC_MZ);
copy_hit.removeMetaValue(Constants::UserParam::OPENPEPXL_HEAVY_SPEC_RT);
copy_hit.removeMetaValue(Constants::UserParam::OPENPEPXL_BETA_PEPEV_PRE);
copy_hit.removeMetaValue(Constants::UserParam::OPENPEPXL_BETA_PEPEV_POST);
copy_hit.removeMetaValue(Constants::UserParam::OPENPEPXL_BETA_PEPEV_START);
copy_hit.removeMetaValue(Constants::UserParam::OPENPEPXL_BETA_PEPEV_END);
copy_hit.removeMetaValue(Constants::UserParam::OPENPEPXL_BETA_SEQUENCE);
copy_hit.removeMetaValue(Constants::UserParam::OPENPEPXL_BETA_ACCESSIONS);
writeMetaInfos_(sii_tmp, copy_hit, 5);
//~ sidres += "<cvParam accession=\"MS:1000796\" cvRef=\"PSI-MS\" value=\"55.835.842.3.dta\" name=\"spectrum title\"/>";
sii_tmp += "\t\t\t\t</SpectrumIdentificationItem>\n";
const double rt = it->getRT();
String ert = rt == rt ? String(rt) : "nan";
DataValue rtcv(ert);
rtcv.setUnit(10); // id: UO:0000010 name: second
rtcv.setUnitType(DataValue::UnitType::UNIT_ONTOLOGY);
sii_tmp = sii_tmp.substitute("</SpectrumIdentificationItem>",
"\t" + cv_.getTermByName("retention time").toXMLString(cv_ns, rtcv) + "\n\t\t\t\t</SpectrumIdentificationItem>\n");
ppxl_specref_2_element[sid] += sii_tmp;
if (hit.metaValueExists(Constants::UserParam::OPENPEPXL_HEAVY_SPEC_RT) && hit.metaValueExists(Constants::UserParam::OPENPEPXL_HEAVY_SPEC_MZ))
{
// ppxl : TODO remove if existing <Fragmentation/>block
sii_tmp = sii_tmp.substitute(String("experimentalMassToCharge=\"") + String(emz),
String("experimentalMassToCharge=\"") + String(hit.getMetaValue(Constants::UserParam::OPENPEPXL_HEAVY_SPEC_MZ))); // mz
sii_tmp = sii_tmp.substitute(sii, String("SII_") + String(UniqueIdGenerator::getUniqueId())); // uid
sii_tmp = sii_tmp.substitute("value=\"" + ert, "value=\"" + String(hit.getMetaValue(Constants::UserParam::OPENPEPXL_HEAVY_SPEC_RT)));
ProteinIdentification::SearchParameters search_params = cpro_id_->front().getSearchParameters();
double iso_shift = String(search_params.getMetaValue("cross_link:mass_isoshift")).toDouble();
double cmz_heavy = cmz.toDouble() + (iso_shift / hit.getCharge());
sii_tmp = sii_tmp.substitute(String("calculatedMassToCharge=\"") + String(cmz),
String("calculatedMassToCharge=\"") + String(cmz_heavy));
ppxl_specref_2_element[sid] += sii_tmp;
}
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/HANDLERS/IndexedMzMLDecoder.cpp | .cpp | 13,028 | 342 | // 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/HANDLERS/IndexedMzMLDecoder.h>
#include <OpenMS/SYSTEM/File.h>
#include <boost/regex.hpp>
#include <boost/lexical_cast.hpp>
#include <fstream>
#include <iostream>
#include <xercesc/framework/MemBufInputSource.hpp>
#include <xercesc/parsers/XercesDOMParser.hpp>
#include <xercesc/dom/DOMElement.hpp>
#include <xercesc/dom/DOMNodeList.hpp>
namespace OpenMS
{
namespace IndexedMzMLUtils
{
std::streampos stringToStreampos(const std::string& s)
{
// Try to cast the string to a type that can hold the integer value
// stored in the std::streampos type (which can vary from 32 to 128 bits
// depending on the system).
//
// long long has a minimal size of 64 bits and can address a range up to
// 16 Exbibit (or 2 Exbibyte), we can hopefully expect our files to be
// smaller than an Exabyte and should be safe.
std::streampos res;
try
{
res = boost::lexical_cast< unsigned long long >(s);
// TESTING CAST: res = (int) res; // use this only when emulating 32 bit systems
}
catch (boost::bad_lexical_cast&)
{
std::cerr << "Trying to convert corrupted / unreadable value to std::streampos : " << s << std::endl;
std::cerr << "This can also happen if the value exceeds 63 bits, please check your input." << std::endl;
throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
String("Could not convert string '") + s + "' to a 64 bit integer.");
}
// Check if the value can fit into std::streampos
if ( std::abs( boost::lexical_cast< long double >(s) - res) > 0.1)
{
std::cerr << "Your system may not support addressing a file of this size,"
<< " only addresses that fit into a " << sizeof(std::streamsize)*8 <<
" bit integer are supported on your system." << std::endl;
throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
String("Could not convert string '") + s + "' to an integer on your system.");
}
return res;
}
}
int IndexedMzMLDecoder::parseOffsets(const String& filename, std::streampos indexoffset, OffsetVector& spectra_offsets, OffsetVector& chromatograms_offsets)
{
//-------------------------------------------------------------
// Open file, jump to end and read last indexoffset bytes into buffer.
//-------------------------------------------------------------
std::ifstream f(filename.c_str());
if (!f.is_open())
{
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);
}
}
// get length of file:
f.seekg(0, f.end);
std::streampos length = f.tellg();
if (indexoffset < 0 || indexoffset > length)
{
std::cerr << "IndexedMzMLDecoder::parseOffsets Error: Offset was " <<
indexoffset << " (not between 0 and " << length << ")." << std::endl;
return -1;
}
//-------------------------------------------------------------
// Read full end of file to parse offsets for spectra and chroms
//-------------------------------------------------------------
// read data as a block into a buffer
// allocate enough memory in buffer (+1 for string termination)
std::streampos readl = length - indexoffset;
char* buffer = new(std::nothrow) char[readl + std::streampos(1)];
// catch case where not enough memory is available
if (buffer == nullptr)
{
// Warning: Index takes up more than 10 % of the whole file, please check your input file.\n";
std::cerr << "IndexedMzMLDecoder::parseOffsets Could not allocate enough memory to read in index of indexedMzML" << std::endl;
std::cerr << "IndexedMzMLDecoder::parseOffsets calculated index offset " << indexoffset << " and file length " << length <<
", consequently tried to read into memory " << readl << " bytes." << std::endl;
return -1;
}
// read into memory
f.seekg(-readl, f.end);
f.read(buffer, readl);
buffer[readl] = '\0';
//-------------------------------------------------------------
// Add a sane start element and then give it to a DOM parser
//-------------------------------------------------------------
// http://stackoverflow.com/questions/4691039/making-xerces-parse-a-string-insted-of-a-file
std::string tmp_fixed_xml = "<indexedmzML>" + String(buffer) + "\n";
int res = domParseIndexedEnd_(tmp_fixed_xml, spectra_offsets, chromatograms_offsets);
delete[] buffer;
return res;
}
std::streampos IndexedMzMLDecoder::findIndexListOffset(const String& filename, int buffersize)
{
// return value
std::streampos indexoffset = -1;
//-------------------------------------------------------------
// Open file, jump to end and read last n bytes into buffer.
//-------------------------------------------------------------
std::ifstream f(filename.c_str());
if (!f.is_open())
{
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);
}
}
// Read the last few bytes and hope our offset is there to be found
std::unique_ptr<char[]> buffer(new char[buffersize + 1]);
f.seekg(-buffersize, f.end);
f.read(buffer.get(), buffersize);
buffer.get()[buffersize] = '\0';
#ifdef DEBUG_READER
std::cout << " reading file " << filename << " with size " << buffersize << '\n';
std::cout << buffer << '\n';
#endif
//-------------------------------------------------------------
// Since we could be anywhere in the XML structure, use regex to find
// indexListOffset and read its content.
//-------------------------------------------------------------
boost::regex listoffset_rx(R"(<[^>/]*indexListOffset\s*>\s*(\d*))");
boost::cmatch matches;
boost::regex_search(buffer.get(), matches, listoffset_rx);
String thismatch(matches[1].first, matches[1].second);
if (!thismatch.empty())
{
try
{
indexoffset = OpenMS::IndexedMzMLUtils::stringToStreampos(thismatch);
}
catch (Exception::ConversionError& /*e*/)
{
std::cerr << "Corrupted / unreadable value in <indexListOffset> : " << thismatch << std::endl;
// free resources and re-throw
throw; // re-throw conversion error
}
}
else
{
std::cerr << "IndexedMzMLDecoder::findIndexListOffset Error: Could not find element indexListOffset in the last "
<< buffersize << " bytes. Maybe this is not a indexedMzML."
<< buffer.get() << std::endl;
}
return indexoffset;
}
int IndexedMzMLDecoder::domParseIndexedEnd_(const std::string& in, OffsetVector& spectra_offsets, OffsetVector& chromatograms_offsets)
{
/*
We parse something like
<indexedmzML>
<indexList count="1">
<index name="chromatogram">
<offset idRef="1">9752</offset>
</index>
</indexList>
<indexListOffset>26795</indexListOffset>
<fileChecksum>0</fileChecksum>
</indexedmzML>
*/
//-------------------------------------------------------------
// Create parser from input string using MemBufInputSource
//-------------------------------------------------------------
xercesc::MemBufInputSource myxml_buf(
reinterpret_cast<const unsigned char*>(in.c_str()), in.length(), "myxml (in memory)");
xercesc::XercesDOMParser parser;
parser.setDoNamespaces(false);
parser.setDoSchema(false);
parser.setLoadExternalDTD(false);
parser.parse(myxml_buf);
//-------------------------------------------------------------
// Start parsing
// see http://www.yolinux.com/TUTORIALS/XML-Xerces-C.html
//-------------------------------------------------------------
// no need to free this pointer - owned by the parent parser object
xercesc::DOMDocument* doc = parser.getDocument();
// Get the top-level element ("indexedmzML")
xercesc::DOMElement* elementRoot = doc->getDocumentElement();
if (!elementRoot)
{
std::cerr << "IndexedMzMLDecoder::domParseIndexedEnd Error: " <<
"No root element found:" << std::endl << std::endl << in << std::endl;
return -1;
}
// Extract the indexList tag (there should only be one)
XMLCh* x_tag = xercesc::XMLString::transcode("indexList");
xercesc::DOMNodeList* li = elementRoot->getElementsByTagName(x_tag);
xercesc::XMLString::release(&x_tag);
if (li->getLength() != 1)
{
std::cerr << "IndexedMzMLDecoder::domParseIndexedEnd Error: "
<< "no indexList element found:" << std::endl << std::endl << in << std::endl;
return -1;
}
xercesc::DOMNode* indexListNode = li->item(0);
XMLCh* x_idref_tag = xercesc::XMLString::transcode("idRef");
XMLCh* x_name_tag = xercesc::XMLString::transcode("name");
xercesc::DOMNodeList* index_elems = indexListNode->getChildNodes();
const XMLSize_t nodeCount_ = index_elems->getLength();
// Iterate through indexList elements (only two elements should be present
// which should be either spectrum or chromatogram offsets)
for (XMLSize_t j = 0; j < nodeCount_; ++j)
{
xercesc::DOMNode* currentNode = index_elems->item(j);
if (currentNode->getNodeType() && // true is not NULL
currentNode->getNodeType() == xercesc::DOMNode::ELEMENT_NODE) // is element
{
std::vector<std::pair<std::string, std::streampos> > result;
xercesc::DOMNode* firstChild = currentNode->getFirstChild();
xercesc::DOMNode* lastChild = currentNode->getLastChild();
xercesc::DOMNode* iter = firstChild;
// Iterate through children
// NOTE: Using xercesc::DOMNodeList and "item" is a very bad idea since
// each "item" call has complexity of O(n), see the
// implementation in DOMNodeListImpl.cpp :
// https://svn.apache.org/repos/asf/xerces/c/trunk/src/xercesc/dom/impl/DOMNodeListImpl.cpp
//
while (iter != lastChild)
{
iter = iter->getNextSibling();
xercesc::DOMNode* currentONode = iter;
if (currentONode->getNodeType() && // true is not NULL
currentONode->getNodeType() == xercesc::DOMNode::ELEMENT_NODE) // is element
{
xercesc::DOMElement* currentElement = dynamic_cast<xercesc::DOMElement*>(currentONode);
char* x_name = xercesc::XMLString::transcode(currentElement->getAttribute(x_idref_tag));
char* x_offset = xercesc::XMLString::transcode(currentONode->getTextContent());
std::streampos thisOffset = OpenMS::IndexedMzMLUtils::stringToStreampos( String(x_offset) );
result.emplace_back(String(x_name), thisOffset);
xercesc::XMLString::release(&x_name);
xercesc::XMLString::release(&x_offset);
}
}
// should be either spectrum or chromatogram ...
xercesc::DOMElement* currentElement = dynamic_cast<xercesc::DOMElement*>(currentNode);
char* x_indexName = xercesc::XMLString::transcode(currentElement->getAttribute(x_name_tag));
std::string name(x_indexName);
xercesc::XMLString::release(&x_indexName);
if (name == "spectrum")
{
spectra_offsets = result;
}
else if (name == "chromatogram")
{
chromatograms_offsets = result;
}
else
{
std::cerr << "IndexedMzMLDecoder::domParseIndexedEnd Error: expected only " <<
"'spectrum' or 'chromatogram' below indexList but found instead '" <<
name << "'." << std::endl;
xercesc::XMLString::release(&x_idref_tag);
xercesc::XMLString::release(&x_name_tag);
return -1;
}
}
}
xercesc::XMLString::release(&x_idref_tag);
xercesc::XMLString::release(&x_name_tag);
return 0;
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/HANDLERS/MzXMLHandler.cpp | .cpp | 53,271 | 1,298 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm, Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/FORMAT/HANDLERS/MzXMLHandler.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/INTERFACES/IMSDataConsumer.h>
#include <OpenMS/FORMAT/Base64.h>
#include <atomic>
#include <stack>
namespace OpenMS::Internal
{
// class holding the byte offsets to '<scan>' tags in the mzXML file; req. to create the index at the end
struct IndexPos
{
Size id_;
std::ostream::pos_type pos_;
IndexPos(const Size id, const std::ostream::pos_type pos)
: id_(id),
pos_(pos) {}
};
//--------------------------------------------------------------------------------
void writeKeyValue(std::ostream& os, const String& key, const DataValue& value)
{
os << " " << key << "=\"" << value << "\"";
}
/// Constructor for a read-only handler
MzXMLHandler::MzXMLHandler(MapType& exp, const String& filename, const String& version, ProgressLogger& logger) :
XMLHandler(filename, version),
exp_(&exp),
cexp_(nullptr),
nesting_level_(0),
skip_spectrum_(false),
spec_write_counter_(1),
consumer_(nullptr),
scan_count_(0),
logger_(logger)
{
init_();
}
/// Constructor for a write-only handler
MzXMLHandler::MzXMLHandler(const MapType& exp, const String& filename, const String& version, const ProgressLogger& logger) :
XMLHandler(filename, version),
exp_(nullptr),
cexp_(&exp),
nesting_level_(0),
skip_spectrum_(false),
spec_write_counter_(1),
consumer_(nullptr),
scan_count_(0),
logger_(logger)
{
init_();
}
/// handler which support partial loading, implement this method
XMLHandler::LOADDETAIL MzXMLHandler::getLoadDetail() const
{
return load_detail_;
}
/// handler which support partial loading, implement this method
void MzXMLHandler::setLoadDetail(const XMLHandler::LOADDETAIL d)
{
load_detail_ = d;
}
void MzXMLHandler::startElement(const XMLCh* const /*uri*/,
const XMLCh* const /*local_name*/, const XMLCh* const qname,
const xercesc::Attributes& attributes)
{
constexpr XMLCh s_value_[] = {'v', 'a', 'l', 'u', 'e', 0};
constexpr XMLCh s_count_[] = {'s', 'c', 'a', 'n', 'C', 'o', 'u', 'n', 't', 0};
constexpr XMLCh s_type_[] = {'t', 'y', 'p', 'e', 0};
constexpr XMLCh s_name_[] = {'n', 'a', 'm', 'e', 0};
constexpr XMLCh s_version_[] = {'v', 'e', 'r', 's', 'i', 'o', 'n', 0};
constexpr XMLCh s_filename_[] = {'f', 'i', 'l', 'e', 'N', 'a', 'm', 'e', 0};
constexpr XMLCh s_filetype_[] = {'f', 'i', 'l', 'e', 'T', 'y', 'p', 'e', 0};
constexpr XMLCh s_filesha1_[] = {'f', 'i', 'l', 'e', 'S', 'h', 'a', '1', 0};
constexpr XMLCh s_completiontime_[] = {'c', 'o', 'm', 'p', 'l', 'e', 't', 'i', 'o', 'n', 'T', 'i', 'm', 'e', 0};
constexpr XMLCh s_precision_[] = {'p', 'r', 'e', 'c', 'i', 's', 'i', 'o', 'n', 0};
constexpr XMLCh s_byteorder_[] = {'b', 'y', 't', 'e', 'O', 'r', 'd', 'e', 'r', 0};
constexpr XMLCh s_contentType_[] = {'c', 'o', 'n', 't', 'e', 'n', 't', 'T', 'y', 'p', 'e', 0};
constexpr XMLCh s_compressionType_[] = {'c', 'o', 'm', 'p', 'r', 'e', 's', 's', 'i', 'o', 'n', 'T', 'y', 'p', 'e', 0};
constexpr XMLCh s_precursorintensity_[] = {'p', 'r', 'e', 'c', 'u', 'r', 's', 'o', 'r', 'I', 'n', 't', 'e', 'n', 's', 'i', 't', 'y', 0};
constexpr XMLCh s_precursorcharge_[] = {'p', 'r', 'e', 'c', 'u', 'r', 's', 'o', 'r', 'C', 'h', 'a', 'r', 'g', 'e', 0};
constexpr XMLCh s_windowwideness_[] = {'w', 'i', 'n', 'd', 'o', 'w', 'W', 'i', 'd', 'e', 'n', 'e', 's', 's', 0};
constexpr XMLCh s_activationMethod_[] = {'a', 'c', 't', 'i', 'v', 'a', 't', 'i', 'o', 'n', 'M', 'e', 't', 'h', 'o', 'd', 0};
constexpr XMLCh s_mslevel_[] = {'m', 's', 'L', 'e', 'v', 'e', 'l', 0};
constexpr XMLCh s_peakscount_[] = {'p', 'e', 'a', 'k', 's', 'C', 'o', 'u', 'n', 't', 0};
constexpr XMLCh s_polarity_[] = {'p', 'o', 'l', 'a', 'r', 'i', 't', 'y', 0};
constexpr XMLCh s_scantype_[] = {'s', 'c', 'a', 'n', 'T', 'y', 'p', 'e', 0};
constexpr XMLCh s_filterline_[] = {'f', 'i', 'l', 't', 'e', 'r', 'L', 'i', 'n', 'e', 0};
constexpr XMLCh s_retentiontime_[] = {'r', 'e', 't', 'e', 'n', 't', 'i', 'o', 'n', 'T', 'i', 'm', 'e', 0};
constexpr XMLCh s_startmz_[] = {'s', 't', 'a', 'r', 't', 'M', 'z', 0};
constexpr XMLCh s_endmz_[] = {'e', 'n', 'd', 'M', 'z', 0};
constexpr XMLCh s_first_[] = {'f', 'i', 'r', 's', 't', 0};
constexpr XMLCh s_last_[] = {'l', 'a', 's', 't', 0};
constexpr XMLCh s_phone_[] = {'p', 'h', 'o', 'n', 'e', 0};
constexpr XMLCh s_email_[] = {'e', 'm', 'a', 'i', 'l', 0};
constexpr XMLCh s_uri_[] = {'U', 'R', 'I', 0};
constexpr XMLCh s_num_[] = {'n', 'u', 'm', 0};
constexpr XMLCh s_intensitycutoff_[] = {'i', 'n', 't', 'e', 'n', 's', 'i', 't', 'y', 'C', 'u', 't', 'o', 'f', 'f', 0};
constexpr XMLCh s_centroided_[] = {'c', 'e', 'n', 't', 'r', 'o', 'i', 'd', 'e', 'd', 0};
constexpr XMLCh s_deisotoped_[] = {'d', 'e', 'i', 's', 'o', 't', 'o', 'p', 'e', 'd', 0};
constexpr XMLCh s_chargedeconvoluted_[] = {'c', 'h', 'a', 'r', 'g', 'e', 'D', 'e', 'c', 'o', 'n', 'v', 'o', 'l', 'u', 't', 'e', 'd', 0};
OPENMS_PRECONDITION(nesting_level_ >= 0, "Nesting level needs to be zero or more")
String tag = sm_.convert(qname);
open_tags_.push_back(tag);
//std::cout << " -- Start -- "<< tag << " -- " << "\n";
//Skip all tags until the the next scan
if (skip_spectrum_ && tag != "scan")
{
return;
}
if (tag == "msRun")
{
Int count = 0;
optionalAttributeAsInt_(count, attributes, s_count_);
exp_->reserve(count);
logger_.startProgress(0, count, "loading mzXML file");
scan_count_ = 0;
data_processing_.clear();
//start and end time are xs:duration. This makes no sense => ignore them
}
else if (tag == "parentFile")
{
SourceFile sf;
sf.setNameOfFile(attributeAsString_(attributes, s_filename_));
sf.setFileType(attributeAsString_(attributes, s_filetype_));
sf.setChecksum(attributeAsString_(attributes, s_filesha1_), SourceFile::ChecksumType::SHA1);
exp_->getSourceFiles().push_back(sf);
}
else if (tag == "software")
{
String& parent_tag = *(open_tags_.end() - 2);
if (parent_tag == "dataProcessing")
{
data_processing_.back()->getSoftware().setVersion(attributeAsString_(attributes, s_version_));
data_processing_.back()->getSoftware().setName(attributeAsString_(attributes, s_name_));
data_processing_.back()->setMetaValue("#type", String(attributeAsString_(attributes, s_type_)));
String time;
optionalAttributeAsString_(time, attributes, s_completiontime_);
data_processing_.back()->setCompletionTime(asDateTime_(time));
}
else if (parent_tag == "msInstrument")
{
exp_->getInstrument().getSoftware().setVersion(attributeAsString_(attributes, s_version_));
exp_->getInstrument().getSoftware().setName(attributeAsString_(attributes, s_name_));
}
}
else if (tag == "peaks")
{
//precision
spectrum_data_.back().precision_ = "32";
optionalAttributeAsString_(spectrum_data_.back().precision_, attributes, s_precision_);
if (spectrum_data_.back().precision_ != "32" && spectrum_data_.back().precision_ != "64")
{
error(LOAD, String("Invalid precision '") + spectrum_data_.back().precision_ + "' in element 'peaks'");
}
//byte order
String byte_order = "network";
optionalAttributeAsString_(byte_order, attributes, s_byteorder_);
if (byte_order != "network")
{
error(LOAD, String("Invalid or missing byte order '") + byte_order + "' in element 'peaks'. Must be 'network'!");
}
//pair order
String pair_order = "m/z-int";
optionalAttributeAsString_(pair_order, attributes, s_contentType_);
if (pair_order != "m/z-int")
{
error(LOAD, String("Invalid or missing pair order '") + pair_order + "' in element 'peaks'. Must be 'm/z-int'!");
}
//compressionType
spectrum_data_.back().compressionType_ = "none";
optionalAttributeAsString_(spectrum_data_.back().compressionType_, attributes, s_compressionType_);
if (spectrum_data_.back().compressionType_ != "none" && spectrum_data_.back().compressionType_ != "zlib")
{
error(LOAD, String("Invalid compression type ") + spectrum_data_.back().compressionType_ + "in elements 'peaks'. Must be 'none' or 'zlib'! ");
}
}
else if (tag == "precursorMz")
{
// add new precursor
spectrum_data_.back().spectrum.getPrecursors().emplace_back();
// intensity
try
{
spectrum_data_.back().spectrum.getPrecursors().back().setIntensity(attributeAsDouble_(attributes, s_precursorintensity_));
}
catch (Exception::ParseError& /*e*/)
{
error(LOAD, "Mandatory attribute 'precursorIntensity' of tag 'precursorMz' not found! Setting precursor intensity to zero!");
}
// charge
Int charge = 0;
if (optionalAttributeAsInt_(charge, attributes, s_precursorcharge_))
{
spectrum_data_.back().spectrum.getPrecursors().back().setCharge(charge);
}
// window bounds (here only the width is stored in both fields - this is corrected when we parse the m/z position)
double window = 0.0;
if (optionalAttributeAsDouble_(window, attributes, s_windowwideness_))
{
spectrum_data_.back().spectrum.getPrecursors().back().setIsolationWindowLowerOffset(window);
}
// parse activation method (CID, ...)
String activation;
if (optionalAttributeAsString_(activation, attributes, s_activationMethod_))
{
auto it = std::find(Precursor::NamesOfActivationMethodShort,
Precursor::NamesOfActivationMethodShort + static_cast<size_t>(Precursor::ActivationMethod::SIZE_OF_ACTIVATIONMETHOD),
activation);
if (it != Precursor::NamesOfActivationMethodShort + static_cast<size_t>(Precursor::ActivationMethod::SIZE_OF_ACTIVATIONMETHOD))
{
spectrum_data_.back().spectrum.getPrecursors().back().getActivationMethods().insert(Precursor::ActivationMethod(it - Precursor::NamesOfActivationMethodShort));
}
}
}
else if (tag == "scan")
{
skip_spectrum_ = false;
nesting_level_++;
if (options_.getMetadataOnly())
{
throw EndParsingSoftly(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
// check if the scan is in the desired MS / RT range
UInt ms_level = attributeAsInt_(attributes, s_mslevel_);
if (ms_level == 0)
{
warning(LOAD, String("Invalid 'msLevel' attribute with value '0' in 'scan' element found. Assuming ms level 1!"));
ms_level = 1;
}
//parse retention time and convert it from xs:duration to seconds
double retention_time = 0.0;
String time_string = "";
if (optionalAttributeAsString_(time_string, attributes, s_retentiontime_))
{
time_string = time_string.suffix('T');
//std::cout << "Initial trim: " << time_string << "\n";
if (time_string.has('H'))
{
retention_time += 3600 * asDouble_(time_string.prefix('H'));
time_string = time_string.suffix('H');
//std::cout << "After H: " << time_string << "\n";
}
if (time_string.has('M'))
{
retention_time += 60 * asDouble_(time_string.prefix('M'));
time_string = time_string.suffix('M');
//std::cout << "After M: " << time_string << "\n";
}
if (time_string.has('S'))
{
retention_time += asDouble_(time_string.prefix('S'));
time_string = time_string.suffix('S');
//std::cout << "After S: " << time_string << "\n";
}
}
logger_.setProgress(scan_count_);
++scan_count_;
if ((options_.hasRTRange() && !options_.getRTRange().encloses(DPosition<1>(retention_time)))
|| (options_.hasMSLevels() && !options_.containsMSLevel(ms_level))
|| load_detail_ == Internal::XMLHandler::LD_RAWCOUNTS)
{
// skip this tag
skip_spectrum_ = true;
return;
}
// Add a new spectrum, initialize and set MS level and RT
spectrum_data_.resize(spectrum_data_.size() + 1);
spectrum_data_.back().peak_count_ = 0;
spectrum_data_.back().spectrum.setMSLevel(ms_level);
spectrum_data_.back().spectrum.setRT(retention_time);
spectrum_data_.back().spectrum.setNativeID(String("scan=") + attributeAsString_(attributes, s_num_));
//peak count == twice the scan size
spectrum_data_.back().peak_count_ = attributeAsInt_(attributes, s_peakscount_);
spectrum_data_.back().spectrum.reserve(spectrum_data_.back().peak_count_ / 2 + 1);
spectrum_data_.back().spectrum.setDataProcessing(data_processing_);
//centroided, chargeDeconvoluted, deisotoped, collisionEnergy are ignored
//other optional attributes
ScanWindow window;
optionalAttributeAsDouble_(window.begin, attributes, s_startmz_);
optionalAttributeAsDouble_(window.end, attributes, s_endmz_);
if (window.begin != 0.0 || window.end != 0.0)
{
spectrum_data_.back().spectrum.getInstrumentSettings().getScanWindows().push_back(window);
}
String polarity = "any";
optionalAttributeAsString_(polarity, attributes, s_polarity_);
spectrum_data_.back().spectrum.getInstrumentSettings().setPolarity((IonSource::Polarity) cvStringToEnum_(0, polarity, "polarity"));
// Filter string (see CV term MS:1000512 in mzML)
String filterLine = "";
optionalAttributeAsString_(filterLine, attributes, s_filterline_);
if (!filterLine.empty())
{
spectrum_data_.back().spectrum.setMetaValue("filter string", filterLine);
}
String type = "";
optionalAttributeAsString_(type, attributes, s_scantype_);
if (type.empty())
{
//unknown/unset => do nothing here => no warning in the end
}
else if (type == "zoom")
{
spectrum_data_.back().spectrum.getInstrumentSettings().setZoomScan(true);
spectrum_data_.back().spectrum.getInstrumentSettings().setScanMode(InstrumentSettings::ScanMode::MASSSPECTRUM);
}
else if (type == "Full")
{
if (ms_level > 1)
{
spectrum_data_.back().spectrum.getInstrumentSettings().setScanMode(InstrumentSettings::ScanMode::MSNSPECTRUM);
}
else
{
spectrum_data_.back().spectrum.getInstrumentSettings().setScanMode(InstrumentSettings::ScanMode::MASSSPECTRUM);
}
}
else if (type == "SIM")
{
spectrum_data_.back().spectrum.getInstrumentSettings().setScanMode(InstrumentSettings::ScanMode::SIM);
}
else if (type == "SRM" || type == "MRM")
{
spectrum_data_.back().spectrum.getInstrumentSettings().setScanMode(InstrumentSettings::ScanMode::SRM);
}
else if (type == "CRM")
{
spectrum_data_.back().spectrum.getInstrumentSettings().setScanMode(InstrumentSettings::ScanMode::CRM);
}
else if (type == "Q1")
{
spectrum_data_.back().spectrum.getInstrumentSettings().setScanMode(InstrumentSettings::ScanMode::MASSSPECTRUM);
}
else if (type == "Q3")
{
spectrum_data_.back().spectrum.getInstrumentSettings().setScanMode(InstrumentSettings::ScanMode::MASSSPECTRUM);
}
else if (type == "EMS") //Non-standard type: Enhanced MS (ABI - Sashimi converter)
{
spectrum_data_.back().spectrum.getInstrumentSettings().setScanMode(InstrumentSettings::ScanMode::MASSSPECTRUM);
}
else if (type == "EPI") //Non-standard type: Enhanced Product Ion (ABI - Sashimi converter)
{
spectrum_data_.back().spectrum.getInstrumentSettings().setScanMode(InstrumentSettings::ScanMode::MASSSPECTRUM);
spectrum_data_.back().spectrum.setMSLevel(2);
}
else if (type == "ER") // Non-standard type: Enhanced Resolution (ABI - Sashimi converter)
{
spectrum_data_.back().spectrum.getInstrumentSettings().setZoomScan(true);
spectrum_data_.back().spectrum.getInstrumentSettings().setScanMode(InstrumentSettings::ScanMode::MASSSPECTRUM);
}
else
{
spectrum_data_.back().spectrum.getInstrumentSettings().setScanMode(InstrumentSettings::ScanMode::MASSSPECTRUM);
warning(LOAD, String("Unknown scan mode '") + type + "'. Assuming full scan");
}
} // END OF <scan>
else if (tag == "operator")
{
exp_->getContacts().resize(1);
exp_->getContacts().back().setFirstName(attributeAsString_(attributes, s_first_));
exp_->getContacts().back().setLastName(attributeAsString_(attributes, s_last_));
String tmp = "";
optionalAttributeAsString_(tmp, attributes, s_email_);
exp_->getContacts().back().setEmail(tmp);
tmp = "";
optionalAttributeAsString_(tmp, attributes, s_phone_);
if (!tmp.empty())
{
exp_->getContacts().back().setMetaValue("#phone", tmp);
}
tmp = "";
optionalAttributeAsString_(tmp, attributes, s_uri_);
exp_->getContacts().back().setURL(tmp);
}
else if (tag == "msManufacturer")
{
exp_->getInstrument().setVendor(attributeAsString_(attributes, s_value_));
}
else if (tag == "msModel")
{
exp_->getInstrument().setModel(attributeAsString_(attributes, s_value_));
}
else if (tag == "msIonisation")
{
exp_->getInstrument().getIonSources().resize(1);
exp_->getInstrument().getIonSources()[0].setIonizationMethod((IonSource::IonizationMethod) cvStringToEnum_(2, attributeAsString_(attributes, s_value_), "msIonization"));
}
else if (tag == "msMassAnalyzer")
{
exp_->getInstrument().getMassAnalyzers().resize(1);
exp_->getInstrument().getMassAnalyzers()[0].setType((MassAnalyzer::AnalyzerType) cvStringToEnum_(3, attributeAsString_(attributes, s_value_), "msMassAnalyzer"));
}
else if (tag == "msDetector")
{
exp_->getInstrument().getIonDetectors().resize(1);
exp_->getInstrument().getIonDetectors()[0].setType((IonDetector::Type) cvStringToEnum_(4, attributeAsString_(attributes, s_value_), "msDetector"));
}
else if (tag == "msResolution")
{
exp_->getInstrument().getMassAnalyzers()[0].setResolutionMethod((MassAnalyzer::ResolutionMethod) cvStringToEnum_(5, attributeAsString_(attributes, s_value_), "msResolution"));
}
else if (tag == "dataProcessing")
{
data_processing_.push_back(DataProcessingPtr(new DataProcessing));
String boolean = "";
optionalAttributeAsString_(boolean, attributes, s_deisotoped_);
if (boolean == "true" || boolean == "1")
{
data_processing_.back()->getProcessingActions().insert(DataProcessing::DEISOTOPING);
}
boolean = "";
optionalAttributeAsString_(boolean, attributes, s_chargedeconvoluted_);
if (boolean == "true" || boolean == "1")
{
data_processing_.back()->getProcessingActions().insert(DataProcessing::CHARGE_DECONVOLUTION);
}
double cutoff = 0.0;
optionalAttributeAsDouble_(cutoff, attributes, s_intensitycutoff_);
if (cutoff != 0.0)
{
data_processing_.back()->setMetaValue("#intensity_cutoff", cutoff);
}
boolean = "";
optionalAttributeAsString_(boolean, attributes, s_centroided_);
if (boolean == "true" || boolean == "1")
{
data_processing_.back()->getProcessingActions().insert(DataProcessing::PEAK_PICKING);
}
}
else if (tag == "nameValue")
{
String name = "";
optionalAttributeAsString_(name, attributes, s_name_);
if (name.empty())
{
return;
}
String value = "";
optionalAttributeAsString_(value, attributes, s_value_);
String& parent_tag = *(open_tags_.end() - 2);
if (parent_tag == "msInstrument")
{
exp_->getInstrument().setMetaValue(name, value);
}
else if (parent_tag == "scan")
{
spectrum_data_.back().spectrum.setMetaValue(name, value);
}
else
{
std::cout << " Warning: Unexpected tag 'nameValue' in tag '" << parent_tag << "'" << "\n";
}
}
else if (tag == "processingOperation")
{
String name = "";
optionalAttributeAsString_(name, attributes, s_name_);
if (name.empty())
{
return;
}
String value = "";
optionalAttributeAsString_(value, attributes, s_value_);
data_processing_.back()->setMetaValue(name, value);
}
//std::cout << " -- !Start -- " << "\n";
}
void MzXMLHandler::endElement(const XMLCh* const /*uri*/, const XMLCh* const /*local_name*/, const XMLCh* const qname)
{
OPENMS_PRECONDITION(nesting_level_ >= 0, "Nesting level needs to be zero or more")
//std::cout << " -- End -- " << sm_.convert(qname) << " -- " << "\n";
static const XMLCh* s_mzxml = xercesc::XMLString::transcode("mzXML");
static const XMLCh* s_scan = xercesc::XMLString::transcode("scan");
open_tags_.pop_back();
if (equal_(qname, s_mzxml))
{
// Flush the remaining data
populateSpectraWithData_();
// End of mzXML
logger_.endProgress();
}
else if (equal_(qname, s_scan))
{
// End of scan: go up one nesting level
// Check whether to populate spectra when on highest nesting level
nesting_level_--;
OPENMS_PRECONDITION(nesting_level_ >= 0, "Nesting level needs to be zero or more")
if (nesting_level_ == 0 && spectrum_data_.size() >= options_.getMaxDataPoolSize())
{
populateSpectraWithData_();
}
}
//std::cout << " -- End -- " << "\n";
}
void MzXMLHandler::characters(const XMLCh* const chars, const XMLSize_t length)
{
//Abort if this spectrum should be skipped
if (skip_spectrum_)
{
return;
}
if (open_tags_.back() == "peaks")
{
//chars may be split to several chunks => concatenate them
if (options_.getFillData())
{
// Since we convert a Base64 string here, it can only contain plain ASCII
sm_.appendASCII(chars, length, spectrum_data_.back().char_rest_);
}
}
else if (open_tags_.back() == "offset" || open_tags_.back() == "indexOffset" || open_tags_.back() == "sha1")
{
}
else if (open_tags_.back() == "precursorMz")
{
String transcoded_chars = sm_.convert(chars);
double mz_pos = asDouble_(transcoded_chars);
//precursor m/z
spectrum_data_.back().spectrum.getPrecursors().back().setMZ(mz_pos);
//update window bounds - center them around the m/z pos
double window_width = spectrum_data_.back().spectrum.getPrecursors().back().getIsolationWindowLowerOffset();
if (window_width != 0.0)
{
spectrum_data_.back().spectrum.getPrecursors().back().setIsolationWindowLowerOffset(0.5 * window_width);
spectrum_data_.back().spectrum.getPrecursors().back().setIsolationWindowUpperOffset(0.5 * window_width);
}
// Check if precursor m/z is within specified range
if (options_.hasPrecursorMZRange() &&
!options_.getPrecursorMZRange().encloses(DPosition<1>(mz_pos)))
{
skip_spectrum_ = true;
// Remove the spectrum that was already added to spectrum_data_
spectrum_data_.pop_back();
}
}
else if (open_tags_.back() == "comment")
{
String transcoded_chars = sm_.convert(chars);
String parent_tag = *(open_tags_.end() - 2);
//std::cout << "- Comment of parent " << parent_tag << "\n";
if (parent_tag == "msInstrument")
{
exp_->getInstrument().setMetaValue("#comment", transcoded_chars);
}
else if (parent_tag == "dataProcessing")
{
//this is currently ignored
}
else if (parent_tag == "scan")
{
spectrum_data_.back().spectrum.setComment(transcoded_chars);
}
else if (!transcoded_chars.trim().empty())
{
warning(LOAD, String("Unhandled comment '") + transcoded_chars + "' in element '" + open_tags_.back() + "'");
}
}
else
{
String transcoded_chars = sm_.convert(chars);
if (!transcoded_chars.trim().empty())
{
warning(LOAD, String("Unhandled character content '") + transcoded_chars + "' in element '" + open_tags_.back() + "'");
}
}
}
void MzXMLHandler::writeTo(std::ostream& os)
{
// determine how many spectra there are (count only those with peaks)
UInt count_tmp_ = 0;
for (Size s = 0; s < cexp_->size(); s++)
{
const SpectrumType& spec = (*cexp_)[s];
if (!spec.empty())
{
++count_tmp_;
}
}
if (count_tmp_ == 0) ++count_tmp_;
logger_.startProgress(0, cexp_->size(), "storing mzXML file");
double min_rt(0), max_rt(0);
if (!cexp_->empty())
{
min_rt = cexp_->begin()->getRT();
max_rt = (cexp_->end() - 1)->getRT();
}
os << "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"
<< "<mzXML xmlns=\"http://sashimi.sourceforge.net/schema_revision/mzXML_3.1\" \n"
<< " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \n"
<< " xsi:schemaLocation=\"http://sashimi.sourceforge.net/schema_revision/mzXML_3.1"
<< " http://sashimi.sourceforge.net/schema_revision/mzXML_3.1/mzXML_idx_3.1.xsd\">\n"
<< "\t<msRun scanCount=\"" << count_tmp_ << "\" startTime=\"PT" << min_rt << "S\" endTime=\"PT" << max_rt << "S\" >\n";
//----------------------------------------------------------------------------------------
// parent files
//----------------------------------------------------------------------------------------
if (cexp_->getSourceFiles().empty())
{
os << "\t\t<parentFile fileName=\"\" fileType=\"processedData\" fileSha1=\"0000000000000000000000000000000000000000\"/>\n";
}
else
{
for (Size i = 0; i < cexp_->getSourceFiles().size(); ++i)
{
const SourceFile& sf = cexp_->getSourceFiles()[i];
os << "\t\t<parentFile fileName=\"" << sf.getNameOfFile() << "\" fileType=\"";
//file type is an enum in mzXML => search for 'raw' string
if (String(sf.getFileType()).toLower().hasSubstring("raw"))
{
os << "RAWData";
}
else
{
os << "processedData";
}
//Sha1 checksum must have 40 characters => create a fake if it is unknown
os << "\" fileSha1=\"";
if (sf.getChecksum().size() != 40 || sf.getChecksumType() != SourceFile::ChecksumType::SHA1)
{
os << "0000000000000000000000000000000000000000";
}
else
{
os << sf.getChecksum();
}
os << "\"/>\n";
}
}
//----------------------------------------------------------------------------------------
//instrument
//----------------------------------------------------------------------------------------
if (cexp_->getInstrument() != Instrument() || !cexp_->getContacts().empty())
{
const Instrument& inst = cexp_->getInstrument();
// the Instrument Manufacturer is paramount for some downstream tools
// Since the .getVendor() is usually empty, we infer this via the Acquisition Software, which is unique to Thermo
String manufacturer = inst.getVendor();
if (options_.getForceMQCompatability() ||
(manufacturer.empty() && String(inst.getSoftware().getName()).toLower().hasSubstring("xcalibur")))
{ // MaxQuant's internal parameter defaults require either "Thermo Scientific" (MaxQuant 1.2 - 1.5), or "Thermo Finnigan" (MaxQuant 1.3 - 1.5)
manufacturer = "Thermo Scientific";
OPENMS_LOG_INFO << "Detected software '" << inst.getSoftware().getName() << "'. Setting <msManufacturer> as '" << manufacturer << "'." << std::endl;
}
os << "\t\t<msInstrument>\n"
<< "\t\t\t<msManufacturer category=\"msManufacturer\" value=\"" << manufacturer << "\"/>\n"
<< "\t\t\t<msModel category=\"msModel\" value=\"" << inst.getModel() << "\"/>\n";
if (inst.getIonSources().empty() || inst.getIonSources()[0].getIonizationMethod() == IonSource::IonizationMethod::IONMETHODNULL || cv_terms_[2][static_cast<size_t>(inst.getIonSources()[0].getIonizationMethod())].empty())
{ // can be empty for MaxQuant
os << "\t\t\t<msIonisation category=\"msIonisation\" value=\"\"/>\n";
}
else
{
os << "\t\t\t<msIonisation category=\"msIonisation\" value=\"" << cv_terms_[2][static_cast<size_t>(inst.getIonSources()[0].getIonizationMethod())] << "\"/>\n";
}
const std::vector<MassAnalyzer>& analyzers = inst.getMassAnalyzers();
if (analyzers.empty() || cv_terms_[3][static_cast<size_t>(analyzers[0].getType())].empty())
{ // can be empty for MaxQuant
os << "\t\t\t<msMassAnalyzer category=\"msMassAnalyzer\" value=\"\"/>\n";
}
else
{
os << "\t\t\t<msMassAnalyzer category=\"msMassAnalyzer\" value=\"" << cv_terms_[3][static_cast<size_t>(analyzers[0].getType())] << "\"/>\n";
}
if (inst.getIonDetectors().empty() || inst.getIonDetectors()[0].getType() == IonDetector::Type::TYPENULL || cv_terms_[4][static_cast<size_t>(inst.getIonDetectors()[0].getType())].empty())
{ // can be empty for MaxQuant
os << "\t\t\t<msDetector category=\"msDetector\" value=\"\"/>\n";
}
else
{
os << "\t\t\t<msDetector category=\"msDetector\" value=\"" << cv_terms_[4][static_cast<size_t>(inst.getIonDetectors()[0].getType())] << "\"/>\n";
}
os << "\t\t\t<software type=\"acquisition\" name=\"" << inst.getSoftware().getName() << "\" version=\"" << inst.getSoftware().getVersion() << "\"/>\n";
if (!(analyzers.empty() || cv_terms_[5][static_cast<size_t>(analyzers[0].getResolutionMethod())].empty()))
{ // must not be empty, otherwise MaxQuant crashes upon loading mzXML
os << "\t\t\t<msResolution category=\"msResolution\" value=\"" << cv_terms_[5][static_cast<size_t>(analyzers[0].getResolutionMethod())] << "\"/>\n";
}
if (!cexp_->getContacts().empty())
{
const ContactPerson& cont = cexp_->getContacts()[0];
os << "\t\t\t<operator first=\"" << cont.getFirstName() << "\" last=\"" << cont.getLastName() << "\"";
if (!cont.getEmail().empty())
{
os << " email=\"" << cont.getEmail() << "\"";
}
if (!cont.getURL().empty())
{
os << " URI=\"" << cont.getURL() << "\"";
}
if (cont.metaValueExists("#phone"))
{
os << " phone=\"" << writeXMLEscape(cont.getMetaValue("#phone").toString()) << "\"";
}
os << "/>\n";
}
writeUserParam_(os, inst, 3);
if (inst.metaValueExists("#comment"))
{
os << "\t\t\t<comment>" << writeXMLEscape(inst.getMetaValue("#comment")) << "</comment>\n";
}
os << "\t\t</msInstrument>\n";
}
//----------------------------------------------------------------------------------------
// data processing (the information of the first spectrum is assigned to the whole file)
//----------------------------------------------------------------------------------------
if (cexp_->empty() || (*cexp_)[0].getDataProcessing().empty())
{
os << "\t\t<dataProcessing>\n"
<< "\t\t\t<software type=\"processing\" name=\"\" version=\"\"/>\n"
<< "\t\t</dataProcessing>\n";
}
else
{
for (Size i = 0; i < (*cexp_)[0].getDataProcessing().size(); ++i)
{
const DataProcessing& data_processing = *(*cexp_)[0].getDataProcessing()[i].get();
os << "\t\t<dataProcessing deisotoped=\""
<< data_processing.getProcessingActions().count(DataProcessing::DEISOTOPING)
<< "\" chargeDeconvoluted=\""
<< data_processing.getProcessingActions().count(DataProcessing::CHARGE_DECONVOLUTION)
<< "\" centroided=\""
<< data_processing.getProcessingActions().count(DataProcessing::PEAK_PICKING)
<< "\"";
if (data_processing.metaValueExists("#intensity_cutoff"))
{
os << " intensityCutoff=\"" << writeXMLEscape(data_processing.getMetaValue("#intensity_cutoff").toString()) << "\"";
}
os << ">\n"
<< "\t\t\t<software type=\"";
if (data_processing.metaValueExists("#type"))
{
os << writeXMLEscape(data_processing.getMetaValue("#type").toString());
}
else
{
os << "processing";
}
os << "\" name=\"" << data_processing.getSoftware().getName()
<< "\" version=\"" << data_processing.getSoftware().getVersion();
if (data_processing.getCompletionTime() != DateTime())
{
os << "\" completionTime=\"" << data_processing.getCompletionTime().get().substitute(' ', 'T');
}
os << "\"/>\n";
writeUserParam_(os, data_processing, 3, "processingOperation");
os << "\t\t</dataProcessing>\n";
}
}
// Check if the nativeID of all spectra are numbers or numbers prefixed with 'scan='
// If not, we need to renumber all spectra.
bool all_numbers = true;
bool all_empty = true;
bool all_prefixed_numbers = true;
for (Size s = 0; s < cexp_->size(); s++)
{
String native_id = (*cexp_)[s].getNativeID();
if (!native_id.hasPrefix("scan="))
{
all_prefixed_numbers = false;
}
else
{
native_id = native_id.substr(5);
}
try
{
native_id.toInt();
}
catch (Exception::ConversionError&)
{
all_numbers = false;
all_prefixed_numbers = false;
if (!native_id.empty())
{
all_empty = false;
}
}
}
//If we need to renumber and the nativeIDs were not empty, warn the user
if (!all_numbers && !all_empty)
{
warning(STORE, "Not all spectrum native IDs are numbers or correctly prefixed with 'scan='. The spectra are renumbered and the native IDs are lost!");
}
std::vector<IndexPos> scan_index_positions;
// write scans
std::stack<UInt> open_scans;
Size spec_index {0};
for (Size s = 0; s < cexp_->size(); s++)
{
logger_.setProgress(s);
const SpectrumType& spec = (*cexp_)[s];
if (spec.empty() && options_.getForceMQCompatability())
{ // MaxQuant's XML parser cannot deal with empty spectra in mzXML (Error: 'there are multiple root elements'...)
continue;
}
++spec_index; // do not use 's', since we might have skipped empty spectra
UInt ms_level = spec.getMSLevel();
open_scans.push(ms_level);
Size spectrum_id = spec_index;
if (all_prefixed_numbers)
{
spectrum_id = spec.getNativeID().substr(5).toInt();
}
else if (all_numbers)
{
spectrum_id = spec.getNativeID().toInt();
}
os << String(ms_level + 1, '\t');
scan_index_positions.emplace_back(spectrum_id, os.tellp()); // remember scan index
os << "<scan num=\"" << spectrum_id << "\""
<< " msLevel=\"" << ms_level << "\""
<< " peaksCount=\"" << spec.size() << "\""
<< " polarity=\"";
if (spec.getInstrumentSettings().getPolarity() == IonSource::Polarity::POSITIVE)
{
os << "+";
}
else if (spec.getInstrumentSettings().getPolarity() == IonSource::Polarity::NEGATIVE)
{
os << "-";
}
else
{
os << "any";
}
os << "\"";
// scan type
String type;
switch (spec.getInstrumentSettings().getScanMode())
{
case InstrumentSettings::ScanMode::UNKNOWN:
break;
case InstrumentSettings::ScanMode::MASSSPECTRUM:
case InstrumentSettings::ScanMode::MS1SPECTRUM:
case InstrumentSettings::ScanMode::MSNSPECTRUM:
type = (spec.getInstrumentSettings().getZoomScan() ? "zoom" : "Full");
break;
case InstrumentSettings::ScanMode::SIM:
type = "SIM";
break;
case InstrumentSettings::ScanMode::SRM:
type = "SRM";
break;
case InstrumentSettings::ScanMode::CRM:
type = "CRM";
break;
default:
type = "Full";
warning(STORE, String("Scan type '") + InstrumentSettings::NamesOfScanMode[static_cast<size_t>(spec.getInstrumentSettings().getScanMode())] + "' not supported by mzXML. Using 'Full' scan mode!");
}
if (type.empty() && options_.getForceMQCompatability())
{
type = "Full";
warning(STORE, String("Scan type unknown. Assuming 'Full' scan mode for MQ compatibility!"));
}
if (!type.empty())
{
os << " scanType=\""<< type << "\"";
}
// filter line
if (spec.metaValueExists("filter string"))
{
os << " filterLine=\"";
os << writeXMLEscape((String)spec.getMetaValue("filter string"));
os << "\"";
}
// retention time
os << " retentionTime=\"";
if (spec.getRT() < 0)
{
os << "-";
}
os << "PT" << std::fabs(spec.getRT()) << "S\"";
if (!spec.getInstrumentSettings().getScanWindows().empty())
{
os << " startMz=\"" << spec.getInstrumentSettings().getScanWindows()[0].begin << "\" endMz=\"" << spec.getInstrumentSettings().getScanWindows()[0].end << "\"";
if (spec.getInstrumentSettings().getScanWindows().size() > 1)
{
warning(STORE, "The MzXML format can store only one scan window for each scan. Only the first one is stored!");
}
}
// convert meta values to tags
if (!writeAttributeIfExists_(os, spec, "lowest observed m/z", "lowMz") &&
options_.getForceMQCompatability())
{
if (!spec.isSorted()) error(STORE, "Spectrum is not sorted by m/z! Please sort before storing!");
writeKeyValue(os, "lowMz", spec.empty() ? 0 : spec.begin()->getMZ());
}
if (!writeAttributeIfExists_(os, spec, "highest observed m/z", "highMz") &&
options_.getForceMQCompatability())
{
if (!spec.isSorted()) error(STORE, "Spectrum is not sorted by m/z! Please sort before storing!");
writeKeyValue(os, "highMz", spec.empty() ? 0 : spec.rbegin()->getMZ());
}
if (!writeAttributeIfExists_(os, spec, "base peak m/z", "basePeakMz"))
{ // base peak mz (used by some programs like MAVEN), according to xsd: "m/z of the base peak (most intense peak)"
auto it = spec.getBasePeak();
writeKeyValue(os, "basePeakMz", (it != spec.end() ? it->getMZ() : 0.0));
}
if (!writeAttributeIfExists_(os, spec, "base peak intensity", "basePeakIntensity") &&
options_.getForceMQCompatability())
{
auto it = spec.getBasePeak();
writeKeyValue(os, "basePeakIntensity", (it != spec.end() ? it->getIntensity() : 0.0));
}
if (!writeAttributeIfExists_(os, spec, "total ion current", "totIonCurrent") &&
options_.getForceMQCompatability())
{
writeKeyValue(os, "totIonCurrent", spec.calculateTIC());
}
if (ms_level == 2 &&
!spec.getPrecursors().empty() &&
spec.getPrecursors().front().metaValueExists("collision energy"))
{
os << " collisionEnergy=\"" << spec.getPrecursors().front().getMetaValue("collision energy") << "\" ";
}
// end of "scan" attributes
os << ">\n";
for (const auto& precursor : spec.getPrecursors())
{
// intensity
os << String(ms_level + 2, '\t') << "<precursorMz precursorIntensity=\"" << (int)precursor.getIntensity() << "\"";
// charge
if (precursor.getCharge() != 0)
{
os << " precursorCharge=\"" << precursor.getCharge() << "\"";
}
// window size
if (precursor.getIsolationWindowLowerOffset() + precursor.getIsolationWindowUpperOffset() > 0.0)
{
os << " windowWideness=\"" << (precursor.getIsolationWindowUpperOffset() + precursor.getIsolationWindowLowerOffset()) << "\"";
}
if (!precursor.getActivationMethods().empty())
{ // must not be empty, but technically only ETD, ECD, CID are allowed in mzXML 3.1
os << " activationMethod=\"" << Precursor::NamesOfActivationMethodShort[static_cast<size_t>(*(precursor.getActivationMethods().begin()))] << "\" ";
}
else if (options_.getForceMQCompatability())
{ // a missing activation would make old MQ versions crash...
OPENMS_LOG_WARN << "Warning: An MS2 scan does not have data on it's activation method. Using 'CID' as fallback!\n";
os << " activationMethod=\"" << Precursor::NamesOfActivationMethodShort[static_cast<size_t>(Precursor::ActivationMethod::CID)] << "\" ";
}
//m/z
double mz = precursor.getMZ();
if (!spec.getAcquisitionInfo().empty() &&
spec.getAcquisitionInfo().begin()->metaValueExists("[Thermo Trailer Extra]Monoisotopic M/Z:"))
{ // this value is usually more accurate; the old ReAdw-converter uses it as well
mz = spec.getAcquisitionInfo().begin()->getMetaValue("[Thermo Trailer Extra]Monoisotopic M/Z:");
}
os << ">" << mz << "</precursorMz>\n";
}
// Note: Some parsers require the following line breaks (MaxQuants
// mzXML reader will fail otherwise! -- don't ask..) while others cannot
// deal with them (mostly TPP tools such as SpectraST).
String s_peaks;
if (options_.getForceMQCompatability())
{
s_peaks = "<peaks precision=\"32\"\n byteOrder=\"network\"\n contentType=\"m/z-int\"\n compressionType=\"none\"\n compressedLen=\"0\" ";
}
else
{
s_peaks = R"(<peaks precision="32" byteOrder="network" contentType="m/z-int" compressionType="none" compressedLen="0" )";
}
if (options_.getForceMQCompatability() && !s_peaks.has('\n'))
{ // internal check against inadvertently removing line breaks above!
fatalError(STORE, "Internal error: <peaks> tag does not contain newlines as required by MaxQuant. Please report this as a bug.", __LINE__, 0);
}
os << String(ms_level + 2, '\t') << s_peaks;
if (!spec.empty())
{
// for MaxQuant-compatible mzXML, the data type must be 'float', i.e. precision=32 bit. 64bit will crash MaxQuant!
std::vector<float> tmp;
tmp.reserve(spec.size() * 2);
for (const auto& p : spec)
{
tmp.push_back(p.getMZ());
tmp.push_back(p.getIntensity());
}
String encoded;
Base64::encode(tmp, Base64::BYTEORDER_BIGENDIAN, encoded);
os << ">" << encoded << "</peaks>\n";
}
else
{
os << " xsi:nil=\"true\" />\n";
}
writeUserParam_(os, spec, ms_level + 2);
if (!spec.getComment().empty())
{
os << String(ms_level + 2, '\t') << "<comment>" << spec.getComment() << "</comment>\n";
}
//check MS level of next scan and close scans (scans can be nested)
UInt next_ms_level = 0;
if (s < cexp_->size() - 1)
{
next_ms_level = ((*cexp_)[s + 1]).getMSLevel();
}
//std::cout << "scan: " << s << " this: " << ms_level << " next: " << next_ms_level << "\n";
if (next_ms_level <= ms_level)
{
for (Size i = 0; i <= ms_level - next_ms_level && !open_scans.empty(); ++i)
{
os << String(ms_level - i + 1, '\t') << "</scan>\n";
open_scans.pop();
}
}
}
os << "\t</msRun>\n";
if (options_.getWriteIndex() || options_.getForceMQCompatability())
{ // create scan index (does not take a lot of space and is required for MaxQuant)
if (!options_.getWriteIndex())
{
OPENMS_LOG_INFO << "mzXML: index was not requested, but will be written to maintain MaxQuant compatibility." << std::endl;
}
std::ostream::pos_type index_offset = os.tellp();
os << "<index name = \"scan\" >\n";
for (Size i = 0; i < scan_index_positions.size(); ++i)
{
os << "<offset id = \"" << scan_index_positions[i].id_ << "\" >" << scan_index_positions[i].pos_ << "</offset>\n";
}
os << "</index>\n";
os << "<indexOffset>" << index_offset << "</indexOffset>\n";
}
os << "</mzXML>\n";
logger_.endProgress();
spec_write_counter_ = 1;
}
inline bool MzXMLHandler::writeAttributeIfExists_(std::ostream& os, const MetaInfoInterface& meta, const String& metakey, const String& attname)
{
if (meta.metaValueExists(metakey))
{
writeKeyValue(os, attname, meta.getMetaValue(metakey));
return true;
}
return false;
}
inline void MzXMLHandler::writeUserParam_(std::ostream& os, const MetaInfoInterface& meta, int indent, const String& tag)
{
std::vector<String> keys; // Vector to hold keys to meta info
meta.getKeys(keys);
for (const String& key : keys)
{
if (key[0] != '#') // internally used meta info start with '#'
{
os << String(indent, '\t') << "<" << tag << " name=\"" << key << "\" value=\"" << writeXMLEscape(meta.getMetaValue(key)) << "\"/>\n";
}
}
}
void MzXMLHandler::doPopulateSpectraWithData_(SpectrumData & spectrum_data)
{
typedef SpectrumType::PeakType PeakType;
//std::cout << "reading scan" << "\n";
if (spectrum_data.char_rest_.empty()) // no peaks
{
return;
}
//remove whitespaces from binary data
//this should not be necessary, but line breaks inside the base64 data are unfortunately no exception
spectrum_data.char_rest_.removeWhitespaces();
if (spectrum_data.precision_ == "64")
{
std::vector<double> data;
if (spectrum_data.compressionType_ == "zlib")
{
Base64::decode(spectrum_data.char_rest_, Base64::BYTEORDER_BIGENDIAN, data, true);
}
else
{
Base64::decode(spectrum_data.char_rest_, Base64::BYTEORDER_BIGENDIAN, data);
}
spectrum_data.char_rest_ = "";
PeakType peak;
assert(data.size() == 2 * spectrum_data.peak_count_);
//push_back the peaks into the container
for (Size n = 0; n < (2 * spectrum_data.peak_count_); n += 2)
{
// check if peak in in the specified m/z and intensity range
if ((!options_.hasMZRange() || options_.getMZRange().encloses(DPosition<1>(data[n])))
&& (!options_.hasIntensityRange() || options_.getIntensityRange().encloses(DPosition<1>(data[n + 1]))))
{
peak.setMZ(data[n]);
peak.setIntensity(data[n + 1]);
spectrum_data.spectrum.push_back(peak);
}
}
}
else //precision 32
{
std::vector<float> data;
if (spectrum_data.compressionType_ == "zlib")
{
Base64::decode(spectrum_data.char_rest_, Base64::BYTEORDER_BIGENDIAN, data, true);
}
else
{
Base64::decode(spectrum_data.char_rest_, Base64::BYTEORDER_BIGENDIAN, data);
}
spectrum_data.char_rest_ = "";
PeakType peak;
assert(data.size() == 2 * spectrum_data.peak_count_);
//push_back the peaks into the container
for (Size n = 0; n < (2 * spectrum_data.peak_count_); n += 2)
{
if ((!options_.hasMZRange() || options_.getMZRange().encloses(DPosition<1>(data[n])))
&& (!options_.hasIntensityRange() || options_.getIntensityRange().encloses(DPosition<1>(data[n + 1]))))
{
peak.setMZ(data[n]);
peak.setIntensity(data[n + 1]);
spectrum_data.spectrum.push_back(peak);
}
}
}
}
void MzXMLHandler::populateSpectraWithData_()
{
// Whether spectrum should be populated with data
if (options_.getFillData())
{
std::atomic<size_t> err_count{0};
#pragma omp parallel for
for (SignedSize i = 0; i < (SignedSize)spectrum_data_.size(); i++)
{
// parallel exception catching and re-throwing business
if (!err_count) // no need to parse further if already an error was encountered
{
try
{
doPopulateSpectraWithData_(spectrum_data_[i]);
if (options_.getSortSpectraByMZ() && !spectrum_data_[i].spectrum.isSorted())
{
spectrum_data_[i].spectrum.sortByPosition();
}
}
catch (...)
{
++err_count;
}
}
} // end parallel for
if (err_count != 0)
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, file_, "Error during parsing of binary data.");
}
}
// Append all spectra
for (Size i = 0; i < spectrum_data_.size(); i++)
{
if (consumer_ != nullptr)
{
consumer_->consumeSpectrum(spectrum_data_[i].spectrum);
if (options_.getAlwaysAppendData())
{
exp_->addSpectrum(spectrum_data_[i].spectrum);
}
}
else
{
exp_->addSpectrum(spectrum_data_[i].spectrum);
}
}
// Delete batch
spectrum_data_.clear();
}
void MzXMLHandler::init_()
{
cv_terms_.resize(6);
//Polarity
String("any;+;-").split(';', cv_terms_[0]);
//Scan type
// is no longer used cv_terms_[1] is empty now
//Ionization method
String(";ESI;EI;CI;FAB;;;;;;;;;;;;;APCI;;;NSI;;SELDI;;;MALDI").split(';', cv_terms_[2]);
cv_terms_[2].resize(static_cast<size_t>(IonSource::IonizationMethod::SIZE_OF_IONIZATIONMETHOD));
//Mass analyzer
String(";Quadrupole;Quadrupole Ion Trap;;;TOF;Magnetic Sector;FT-ICR;;;;;;FTMS").split(';', cv_terms_[3]);
cv_terms_[3].resize(static_cast<size_t>(MassAnalyzer::AnalyzerType::SIZE_OF_ANALYZERTYPE));
//Detector
String(";EMT;;;Faraday Cup;;;;;Channeltron;Daly;Microchannel plate").split(';', cv_terms_[4]);
cv_terms_[4].resize(static_cast<size_t>(IonDetector::Type::SIZE_OF_TYPE));
//Resolution method
String(";FWHM;TenPercentValley;Baseline").split(';', cv_terms_[5]);
cv_terms_[5].resize(static_cast<size_t>(MassAnalyzer::ResolutionMethod::SIZE_OF_RESOLUTIONMETHOD));
}
} //namespace OpenMS //namespace Internal
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/HANDLERS/MzDataHandler.cpp | .cpp | 60,429 | 1,510 | // 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/HANDLERS/MzDataHandler.h>
#include <OpenMS/FORMAT/Base64.h>
#include <map>
namespace OpenMS::Internal
{
MzDataHandler::MzDataHandler(MapType & exp, const String & filename, const String & version, ProgressLogger & logger) :
XMLHandler(filename, version),
exp_(&exp),
cexp_(nullptr),
peak_count_(0),
meta_id_descs_(),
skip_spectrum_(false),
logger_(logger)
{
init_();
}
MzDataHandler::MzDataHandler(const MapType & exp, const String & filename, const String & version, const ProgressLogger & logger) :
XMLHandler(filename, version),
exp_(nullptr),
cexp_(&exp),
peak_count_(0),
meta_id_descs_(),
skip_spectrum_(false),
logger_(logger)
{
init_();
}
void MzDataHandler::init_()
{
cv_terms_.resize(19);
// SampleState
String(";Solid;Liquid;Gas;Solution;Emulsion;Suspension").split(';', cv_terms_[0]);
// IonizationMode
String(";PositiveIonMode;NegativeIonMode").split(';', cv_terms_[1]);
// ResolutionMethod
String(";FWHM;TenPercentValley;Baseline").split(';', cv_terms_[2]);
// ResolutionType
String(";Constant;Proportional").split(';', cv_terms_[3]);
// ScanFunction
// is no longer used cv_terms_[4] is empty now
// ScanDirection
String(";Up;Down").split(';', cv_terms_[5]);
// ScanLaw
String(";Exponential;Linear;Quadratic").split(';', cv_terms_[6]);
// PeakProcessing
String(";CentroidMassSpectrum;ContinuumMassSpectrum").split(';', cv_terms_[7]);
// ReflectronState
String(";On;Off;None").split(';', cv_terms_[8]);
// AcquisitionMode
String(";PulseCounting;ADC;TDC;TransientRecorder").split(';', cv_terms_[9]);
// IonizationType
String(";ESI;EI;CI;FAB;TSP;LD;FD;FI;PD;SI;TI;API;ISI;CID;CAD;HN;APCI;APPI;ICP").split(';', cv_terms_[10]);
// InletType
String(";Direct;Batch;Chromatography;ParticleBeam;MembraneSeparator;OpenSplit;JetSeparator;Septum;Reservoir;MovingBelt;MovingWire;FlowInjectionAnalysis;ElectrosprayInlet;ThermosprayInlet;Infusion;ContinuousFlowFastAtomBombardment;InductivelyCoupledPlasma").split(';', cv_terms_[11]);
// TandemScanningMethod
// is no longer used cv_terms_[12] is empty now
// DetectorType
String(";EM;Photomultiplier;FocalPlaneArray;FaradayCup;ConversionDynodeElectronMultiplier;ConversionDynodePhotomultiplier;Multi-Collector;ChannelElectronMultiplier").split(';', cv_terms_[13]);
// AnalyzerType
String(";Quadrupole;PaulIonTrap;RadialEjectionLinearIonTrap;AxialEjectionLinearIonTrap;TOF;Sector;FourierTransform;IonStorage").split(';', cv_terms_[14]);
// EnergyUnits
// is no longer used cv_terms_[15] is empty now
// ScanMode
// is no longer used cv_terms_[16] is empty now
// Polarity
// is no longer used cv_terms_[17] is empty now
// ActivationMethod
String("CID;PSD;PD;SID").split(';', cv_terms_[18]);
}
void MzDataHandler::characters(const XMLCh * const chars, const XMLSize_t /*length*/)
{
// skip current spectrum
if (skip_spectrum_)
{
return;
}
String transcoded_chars = sm_.convert(chars);
//current tag
const String & current_tag = open_tags_.back();
//determine the parent tag
String parent_tag;
if (open_tags_.size() > 1)
parent_tag = *(open_tags_.end() - 2);
if (current_tag == "sampleName")
{
exp_->getSample().setName(sm_.convert(chars));
}
else if (current_tag == "instrumentName")
{
exp_->getInstrument().setName(sm_.convert(chars));
}
else if (current_tag == "version")
{
data_processing_->getSoftware().setVersion(sm_.convert(chars));
}
else if (current_tag == "institution")
{
exp_->getContacts().back().setInstitution(sm_.convert(chars));
}
else if (current_tag == "contactInfo")
{
exp_->getContacts().back().setContactInfo(sm_.convert(chars));
}
else if (current_tag == "name" && parent_tag == "contact")
{
exp_->getContacts().back().setName(sm_.convert(chars));
}
else if (current_tag == "name" && parent_tag == "software")
{
data_processing_->getSoftware().setName(sm_.convert(chars));
}
else if (current_tag == "comments" && parent_tag == "software")
{
data_processing_->getSoftware().setMetaValue("comment", String(sm_.convert(chars)));
}
else if (current_tag == "comments" && parent_tag == "spectrumDesc")
{
spec_.setComment(transcoded_chars);
}
else if (current_tag == "data")
{
//chars may be split to several chunks => concatenate them
data_to_decode_.back() += transcoded_chars;
}
else if (current_tag == "arrayName" && parent_tag == "supDataArrayBinary")
{
spec_.getFloatDataArrays().back().setName(transcoded_chars);
}
else if (current_tag == "nameOfFile" && parent_tag == "sourceFile")
{
exp_->getSourceFiles().back().setNameOfFile(sm_.convert(chars));
}
else if (current_tag == "nameOfFile" && parent_tag == "supSourceFile")
{
//ignored
}
else if (current_tag == "pathToFile" && parent_tag == "sourceFile")
{
exp_->getSourceFiles().back().setPathToFile(sm_.convert(chars));
}
else if (current_tag == "pathToFile" && parent_tag == "supSourceFile")
{
//ignored
}
else if (current_tag == "fileType" && parent_tag == "sourceFile")
{
exp_->getSourceFiles().back().setFileType(sm_.convert(chars));
}
else if (current_tag == "fileType" && parent_tag == "supSourceFile")
{
//ignored
}
else
{
String trimmed_transcoded_chars = transcoded_chars;
trimmed_transcoded_chars.trim();
if (!trimmed_transcoded_chars.empty())
{
warning(LOAD, String("Unhandled character content in tag '") + current_tag + "': " + trimmed_transcoded_chars);
}
}
}
void MzDataHandler::startElement(const XMLCh * const /*uri*/, const XMLCh * const /*local_name*/, const XMLCh * const qname, const xercesc::Attributes & attributes)
{
static const XMLCh * s_name = xercesc::XMLString::transcode("name");
static const XMLCh * s_accession = xercesc::XMLString::transcode("accession");
static const XMLCh * s_value = xercesc::XMLString::transcode("value");
static const XMLCh * s_id = xercesc::XMLString::transcode("id");
static const XMLCh * s_count = xercesc::XMLString::transcode("count");
static const XMLCh * s_spectrumtype = xercesc::XMLString::transcode("spectrumType");
static const XMLCh * s_methodofcombination = xercesc::XMLString::transcode("methodOfCombination");
static const XMLCh * s_acqnumber = xercesc::XMLString::transcode("acqNumber");
static const XMLCh * s_mslevel = xercesc::XMLString::transcode("msLevel");
static const XMLCh * s_mzrangestart = xercesc::XMLString::transcode("mzRangeStart");
static const XMLCh * s_mzrangestop = xercesc::XMLString::transcode("mzRangeStop");
static const XMLCh * s_supdataarrayref = xercesc::XMLString::transcode("supDataArrayRef");
static const XMLCh * s_precision = xercesc::XMLString::transcode("precision");
static const XMLCh * s_endian = xercesc::XMLString::transcode("endian");
static const XMLCh * s_length = xercesc::XMLString::transcode("length");
static const XMLCh * s_comment = xercesc::XMLString::transcode("comment");
static const XMLCh * s_accessionnumber = xercesc::XMLString::transcode("accessionNumber");
String tag = sm_.convert(qname);
open_tags_.push_back(tag);
//std::cout << "Start: '" << tag << "'" << std::endl;
//determine the parent tag
String parent_tag;
if (open_tags_.size() > 1)
{
parent_tag = *(open_tags_.end() - 2);
}
//do nothing until a new spectrum is reached
if (tag != "spectrum" && skip_spectrum_)
{
return;
}
// Do something depending on the tag
if (tag == "sourceFile")
{
exp_->getSourceFiles().emplace_back();
}
if (tag == "contact")
{
exp_->getContacts().resize(exp_->getContacts().size() + 1);
}
else if (tag == "source")
{
exp_->getInstrument().getIonSources().resize(1);
}
else if (tag == "detector")
{
exp_->getInstrument().getIonDetectors().resize(1);
}
else if (tag == "analyzer")
{
exp_->getInstrument().getMassAnalyzers().resize(exp_->getInstrument().getMassAnalyzers().size() + 1);
}
else if (tag == "software")
{
data_processing_ = DataProcessingPtr(new DataProcessing);
if (attributes.getIndex(sm_.convert("completionTime").c_str()) != -1)
{
data_processing_->setCompletionTime(asDateTime_(sm_.convert(attributes.getValue(sm_.convert("completionTime").c_str())).c_str()));
}
}
else if (tag == "precursor")
{
spec_.getPrecursors().emplace_back();
}
else if (tag == "cvParam")
{
String accession = attributeAsString_(attributes, s_accession);
String value = "";
optionalAttributeAsString_(value, attributes, s_value);
cvParam_(accession, value);
}
else if (tag == "supDataDesc")
{
String comment;
if (optionalAttributeAsString_(comment, attributes, s_comment))
{
meta_id_descs_.back().second.setMetaValue("comment", comment);
}
}
else if (tag == "userParam")
{
String name = attributeAsString_(attributes, s_name);
String value = "";
optionalAttributeAsString_(value, attributes, s_value);
if (parent_tag == "spectrumInstrument")
{
spec_.getInstrumentSettings().setMetaValue(name, value);
}
else if (parent_tag == "acquisition")
{
spec_.getAcquisitionInfo().back().setMetaValue(name, value);
}
else if (parent_tag == "ionSelection")
{
spec_.getPrecursors().back().setMetaValue(name, value);
}
else if (parent_tag == "activation")
{
spec_.getPrecursors().back().setMetaValue(name, value);
}
else if (parent_tag == "supDataDesc")
{
meta_id_descs_.back().second.setMetaValue(name, value);
}
else if (parent_tag == "detector")
{
exp_->getInstrument().getIonDetectors().back().setMetaValue(name, value);
}
else if (parent_tag == "source")
{
exp_->getInstrument().getIonSources().back().setMetaValue(name, value);
}
else if (parent_tag == "sampleDescription")
{
exp_->getSample().setMetaValue(name, value);
}
else if (parent_tag == "analyzer")
{
exp_->getInstrument().getMassAnalyzers().back().setMetaValue(name, value);
}
else if (parent_tag == "additional")
{
exp_->getInstrument().setMetaValue(name, value);
}
else if (parent_tag == "processingMethod")
{
data_processing_->setMetaValue(name, value);
}
else
{
warning(LOAD, "Invalid userParam: name=\"" + name + ", value=\"" + value + "\"");
}
}
else if (tag == "supDataArrayBinary")
{
//create FloatDataArray
MapType::SpectrumType::FloatDataArray mda;
//Assign the right MetaInfoDescription ("supDesc" tag)
String id = attributeAsString_(attributes, s_id);
for (Size i = 0; i < meta_id_descs_.size(); ++i)
{
if (meta_id_descs_[i].first == id)
{
mda.MetaInfoDescription::operator=(meta_id_descs_[i].second);
break;
}
}
//append FloatDataArray
spec_.getFloatDataArrays().push_back(mda);
}
else if (tag == "spectrum")
{
spec_ = SpectrumType();
spec_.setNativeID(String("spectrum=") + attributeAsString_(attributes, s_id));
spec_.getDataProcessing().push_back(data_processing_);
}
else if (tag == "spectrumList")
{
if (options_.getMetadataOnly())
throw EndParsingSoftly(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
//std::cout << Date::now() << " Reserving space for spectra" << std::endl;
UInt count = attributeAsInt_(attributes, s_count);
exp_->reserve(count);
logger_.startProgress(0, count, "loading mzData file");
//std::cout << Date::now() << " done" << std::endl;
}
else if (tag == "mzData")
{
//handle file id
exp_->setIdentifier(attributeAsString_(attributes, s_accessionnumber));
}
else if (tag == "acqSpecification")
{
String tmp_type = attributeAsString_(attributes, s_spectrumtype);
if (tmp_type == "discrete")
{
spec_.setType(SpectrumSettings::SpectrumType::CENTROID);
}
else if (tmp_type == "continuous")
{
spec_.setType(SpectrumSettings::SpectrumType::PROFILE);
}
else
{
spec_.setType(SpectrumSettings::SpectrumType::UNKNOWN);
warning(LOAD, String("Invalid spectrum type '") + tmp_type + "'.");
}
spec_.getAcquisitionInfo().setMethodOfCombination(attributeAsString_(attributes, s_methodofcombination));
}
else if (tag == "acquisition")
{
spec_.getAcquisitionInfo().insert(spec_.getAcquisitionInfo().end(), Acquisition());
spec_.getAcquisitionInfo().back().setIdentifier(attributeAsString_(attributes, s_acqnumber));
}
else if (tag == "spectrumInstrument" || tag == "acqInstrument")
{
spec_.setMSLevel(attributeAsInt_(attributes, s_mslevel));
ScanWindow window;
optionalAttributeAsDouble_(window.begin, attributes, s_mzrangestart);
optionalAttributeAsDouble_(window.end, attributes, s_mzrangestop);
if (window.begin != 0.0 || window.end != 0.0)
{
spec_.getInstrumentSettings().getScanWindows().push_back(window);
}
if (options_.hasMSLevels() && !options_.containsMSLevel(spec_.getMSLevel()))
{
skip_spectrum_ = true;
}
}
else if (tag == "supDesc")
{
meta_id_descs_.emplace_back(attributeAsString_(attributes, s_supdataarrayref), MetaInfoDescription());
}
else if (tag == "data")
{
// store precision for later
precisions_.push_back(attributeAsString_(attributes, s_precision));
endians_.push_back(attributeAsString_(attributes, s_endian));
//reserve enough space in spectrum
if (parent_tag == "mzArrayBinary")
{
peak_count_ = attributeAsInt_(attributes, s_length);
}
}
else if (tag == "mzArrayBinary")
{
data_to_decode_.resize(data_to_decode_.size() + 1);
}
else if (tag == "intenArrayBinary")
{
data_to_decode_.resize(data_to_decode_.size() + 1);
}
else if (tag == "arrayName" && parent_tag == "supDataArrayBinary")
{
// Note: name is set in closing tag as it is CDATA
data_to_decode_.resize(data_to_decode_.size() + 1);
}
//std::cout << "end startelement" << std::endl;
}
void MzDataHandler::endElement(const XMLCh * const /*uri*/, const XMLCh * const /*local_name*/, const XMLCh * const qname)
{
static UInt scan_count = 0;
static const XMLCh * s_spectrum = xercesc::XMLString::transcode("spectrum");
static const XMLCh * s_mzdata = xercesc::XMLString::transcode("mzData");
open_tags_.pop_back();
//std::cout << "End: '" << sm_.convert(qname) << "'" << std::endl;
if (equal_(qname, s_spectrum))
{
if (!skip_spectrum_)
{
fillData_();
exp_->addSpectrum(spec_);
}
skip_spectrum_ = false;
logger_.setProgress(++scan_count);
decoded_list_.clear();
decoded_double_list_.clear();
data_to_decode_.clear();
precisions_.clear();
endians_.clear();
meta_id_descs_.clear();
}
else if (equal_(qname, s_mzdata))
{
logger_.endProgress();
scan_count = 0;
}
}
void MzDataHandler::fillData_()
{
std::vector<float> decoded;
std::vector<double> decoded_double;
// data_to_decode is an encoded spectrum, represented as
// vector of base64-encoded strings:
// Each string represents one property (e.g. mzData) and decodes
// to a vector of property values - one value for every peak in the spectrum.
for (Size i = 0; i < data_to_decode_.size(); ++i)
{
//remove whitespaces from binary data
//this should not be necessary, but line breaks inside the base64 data are unfortunately no exception
data_to_decode_[i].removeWhitespaces();
if (precisions_[i] == "64") // precision 64 Bit
{
if (endians_[i] == "big")
{
//std::cout << "nr. " << i << ": decoding as high-precision big endian" << std::endl;
Base64::decode(data_to_decode_[i], Base64::BYTEORDER_BIGENDIAN, decoded_double);
}
else
{
//std::cout << "nr. " << i << ": decoding as high-precision little endian" << std::endl;
Base64::decode(data_to_decode_[i], Base64::BYTEORDER_LITTLEENDIAN, decoded_double);
}
// push_back the decoded double data - and an empty one into
// the single-precision vector, so that we don't mess up the index
//std::cout << "list size: " << decoded_double.size() << std::endl;
decoded_double_list_.push_back(decoded_double);
decoded_list_.emplace_back();
}
else // precision 32 Bit
{
if (endians_[i] == "big")
{
//std::cout << "nr. " << i << ": decoding as low-precision big endian" << std::endl;
Base64::decode(data_to_decode_[i], Base64::BYTEORDER_BIGENDIAN, decoded);
}
else
{
//std::cout << "nr. " << i << ": decoding as low-precision little endian" << std::endl;
Base64::decode(data_to_decode_[i], Base64::BYTEORDER_LITTLEENDIAN, decoded);
}
//std::cout << "list size: " << decoded.size() << std::endl;
decoded_list_.push_back(decoded);
decoded_double_list_.emplace_back();
}
}
// this works only if MapType::PeakType is a Peak1D or derived from it
{
//store what precision is used for intensity and m/z
bool mz_precision_64 = true;
if (precisions_[0] == "32")
{
mz_precision_64 = false;
}
bool int_precision_64 = true;
if (precisions_[1] == "32")
{
int_precision_64 = false;
}
// no data was decoded?
if (data_to_decode_.size() < 2) return;
const size_t peak_count_mz = mz_precision_64 ? decoded_double_list_[0].size() : decoded_list_[0].size();
const size_t peak_count_int = int_precision_64 ? decoded_double_list_[1].size() : decoded_list_[1].size();
if (peak_count_mz != peak_count_int)
{
error(LOAD, String("Length of data array for m/z differs from length of intensity data: ") + peak_count_mz + " vs. " + peak_count_int + " . The first array starts with: '" +
data_to_decode_[0].substr(0, 10) + " ...'");
}
if (peak_count_ != peak_count_mz)
{
warning(LOAD, String("Length of data arrays (m/z and int) differs from value in attribute 'length': ") + peak_count_mz + " vs. " + peak_count_ + ".");
peak_count_ = peak_count_mz;
}
// reserve space for spectrum
spec_.reserve(peak_count_);
// reserve space for meta data arrays (peak count)
for (Size i = 0; i < spec_.getFloatDataArrays().size(); ++i)
{
spec_.getFloatDataArrays()[i].reserve(peak_count_);
}
// push_back the peaks into the container
for (Size n = 0; n < peak_count_; ++n)
{
double mz = mz_precision_64 ? decoded_double_list_[0][n] : decoded_list_[0][n];
double intensity = int_precision_64 ? decoded_double_list_[1][n] : decoded_list_[1][n];
if ((!options_.hasMZRange() || options_.getMZRange().encloses(DPosition<1>(mz)))
&& (!options_.hasIntensityRange() || options_.getIntensityRange().encloses(DPosition<1>(intensity))))
{
PeakType tmp;
tmp.setIntensity(intensity);
tmp.setMZ(mz);
spec_.push_back(tmp);
//load data from meta data arrays
for (Size i = 0; i < spec_.getFloatDataArrays().size(); ++i)
{
spec_.getFloatDataArrays()[i].push_back(precisions_[2 + i] == "64" ? decoded_double_list_[2 + i][n] : decoded_list_[2 + i][n]);
}
}
}
}
}
void MzDataHandler::writeTo(std::ostream & os)
{
logger_.startProgress(0, cexp_->size(), "storing mzData file");
os << "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"
<< R"(<mzData version="1.05" accessionNumber=")" << cexp_->getIdentifier() << "\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"http://psidev.sourceforge.net/ms/xml/mzdata/mzdata.xsd\">\n";
//---------------------------------------------------------------------------------------------------
//DESCRIPTION
const Sample & sm = cexp_->getSample();
os << "\t<description>\n"
<< "\t\t<admin>\n"
<< "\t\t\t<sampleName>"
<< sm.getName()
<< "</sampleName>\n";
if (! sm.getNumber().empty() || sm.getState() != Sample::SampleState::SAMPLENULL || sm.getMass() || sm.getVolume() || sm.getConcentration() || ! sm.isMetaEmpty())
{
os << "\t\t\t<sampleDescription>\n";
writeCVS_(os, sm.getNumber(), "1000001", "SampleNumber");
writeCVS_(os, static_cast<UInt>(sm.getState()), 0, "1000003", "SampleState");
writeCVS_(os, sm.getMass(), "1000004", "SampleMass");
writeCVS_(os, sm.getVolume(), "1000005", "SampleVolume");
writeCVS_(os, sm.getConcentration(), "1000006", "SampleConcentration");
writeUserParam_(os, cexp_->getSample());
os << "\t\t\t</sampleDescription>\n";
}
if (!cexp_->getSourceFiles().empty())
{
os << "\t\t\t<sourceFile>\n"
<< "\t\t\t\t<nameOfFile>" << cexp_->getSourceFiles()[0].getNameOfFile() << "</nameOfFile>\n"
<< "\t\t\t\t<pathToFile>" << cexp_->getSourceFiles()[0].getPathToFile() << "</pathToFile>\n";
if (!cexp_->getSourceFiles()[0].getFileType().empty())
os << "\t\t\t\t<fileType>" << cexp_->getSourceFiles()[0].getFileType() << "</fileType>\n";
os << "\t\t\t</sourceFile>\n";
}
if (cexp_->getSourceFiles().size() > 1)
{
warning(STORE, "The MzData format can store only one source file. Only the first one is stored!");
}
for (Size i = 0; i < cexp_->getContacts().size(); ++i)
{
os << "\t\t\t<contact>\n"
<< "\t\t\t\t<name>" << cexp_->getContacts()[i].getFirstName() << " " << cexp_->getContacts()[i].getLastName() << "</name>\n"
<< "\t\t\t\t<institution>" << cexp_->getContacts()[i].getInstitution() << "</institution>\n";
if (!cexp_->getContacts()[i].getContactInfo().empty())
os << "\t\t\t\t<contactInfo>" << cexp_->getContacts()[i].getContactInfo() << "</contactInfo>\n";
os << "\t\t\t</contact>\n";
}
//no contacts given => add empty entry as there must be a contact entry
if (cexp_->getContacts().empty())
{
os << "\t\t\t<contact>\n"
<< "\t\t\t\t<name></name>\n"
<< "\t\t\t\t<institution></institution>\n";
os << "\t\t\t</contact>\n";
}
os << "\t\t</admin>\n";
const Instrument & inst = cexp_->getInstrument();
os << "\t\t<instrument>\n"
<< "\t\t\t<instrumentName>" << inst.getName() << "</instrumentName>\n"
<< "\t\t\t<source>\n";
if (!inst.getIonSources().empty())
{
writeCVS_(os, static_cast<UInt>(inst.getIonSources()[0].getInletType()), 11, "1000007", "InletType");
writeCVS_(os, static_cast<UInt>(inst.getIonSources()[0].getIonizationMethod()), 10, "1000008", "IonizationType");
writeCVS_(os, static_cast<UInt>(inst.getIonSources()[0].getPolarity()), 1, "1000009", "IonizationMode");
writeUserParam_(os, inst.getIonSources()[0]);
}
if (inst.getIonSources().size() > 1)
{
warning(STORE, "The MzData format can store only one ion source. Only the first one is stored!");
}
os << "\t\t\t</source>\n";
//no analyzer given => add empty entry as there must be one entry
if (inst.getMassAnalyzers().empty())
{
os << "\t\t\t<analyzerList count=\"1\">\n"
<< "\t\t\t\t<analyzer>\n"
<< "\t\t\t\t</analyzer>\n";
}
else
{
os << "\t\t\t<analyzerList count=\"" << inst.getMassAnalyzers().size() << "\">\n";
for (Size i = 0; i < inst.getMassAnalyzers().size(); ++i)
{
os << "\t\t\t\t<analyzer>\n";
const MassAnalyzer & ana = inst.getMassAnalyzers()[i];
writeCVS_(os, static_cast<UInt>(ana.getType()), 14, "1000010", "AnalyzerType", 5);
writeCVS_(os, ana.getResolution(), "1000011", "MassResolution", 5);
writeCVS_(os, static_cast<UInt>(ana.getResolutionMethod()), 2, "1000012", "ResolutionMethod", 5);
writeCVS_(os, static_cast<UInt>(ana.getResolutionType()), 3, "1000013", "ResolutionType", 5);
writeCVS_(os, ana.getAccuracy(), "1000014", "Accuracy", 5);
writeCVS_(os, ana.getScanRate(), "1000015", "ScanRate", 5);
writeCVS_(os, ana.getScanTime(), "1000016", "ScanTime", 5);
writeCVS_(os, static_cast<UInt>(ana.getScanDirection()), 5, "1000018", "ScanDirection", 5);
writeCVS_(os, static_cast<UInt>(ana.getScanLaw()), 6, "1000019", "ScanLaw", 5);
writeCVS_(os, static_cast<UInt>(ana.getReflectronState()), 8, "1000021", "ReflectronState", 5);
writeCVS_(os, ana.getTOFTotalPathLength(), "1000022", "TOFTotalPathLength", 5);
writeCVS_(os, ana.getIsolationWidth(), "1000023", "IsolationWidth", 5);
writeCVS_(os, ana.getFinalMSExponent(), "1000024", "FinalMSExponent", 5);
writeCVS_(os, ana.getMagneticFieldStrength(), "1000025", "MagneticFieldStrength", 5);
writeUserParam_(os, ana, 5);
os << "\t\t\t\t</analyzer>\n";
}
}
os << "\t\t\t</analyzerList>\n";
os << "\t\t\t<detector>\n";
if (!inst.getIonDetectors().empty())
{
writeCVS_(os, static_cast<UInt>(inst.getIonDetectors()[0].getType()), 13, "1000026", "DetectorType");
writeCVS_(os, static_cast<UInt>(inst.getIonDetectors()[0].getAcquisitionMode()), 9, "1000027", "DetectorAcquisitionMode");
writeCVS_(os, inst.getIonDetectors()[0].getResolution(), "1000028", "DetectorResolution");
writeCVS_(os, inst.getIonDetectors()[0].getADCSamplingFrequency(), "1000029", "SamplingFrequency");
writeUserParam_(os, inst.getIonDetectors()[0]);
}
if (inst.getIonDetectors().size() > 1)
{
warning(STORE, "The MzData format can store only one ion detector. Only the first one is stored!");
}
os << "\t\t\t</detector>\n";
if (!inst.getVendor().empty() || !inst.getModel().empty() || !inst.getCustomizations().empty())
{
os << "\t\t\t<additional>\n";
writeCVS_(os, inst.getVendor(), "1000030", "Vendor");
writeCVS_(os, inst.getModel(), "1000031", "Model");
writeCVS_(os, inst.getCustomizations(), "1000032", "Customization");
writeUserParam_(os, inst);
os << "\t\t\t</additional>\n";
}
os << "\t\t</instrument>\n";
//the data processing information of the first spectrum is used for the whole file
if (cexp_->empty() || (*cexp_)[0].getDataProcessing().empty())
{
os << "\t\t<dataProcessing>\n"
<< "\t\t\t<software>\n"
<< "\t\t\t\t<name></name>\n"
<< "\t\t\t\t<version></version>\n"
<< "\t\t\t</software>\n"
<< "\t\t</dataProcessing>\n";
}
else
{
const DataProcessing & data_processing = * (*cexp_)[0].getDataProcessing()[0].get();
os << "\t\t<dataProcessing>\n"
<< "\t\t\t<software";
if (data_processing.getCompletionTime() != DateTime())
{
os << " completionTime=\"" << data_processing.getCompletionTime().get().substitute(' ', 'T') << "\"";
}
os << ">\n"
<< "\t\t\t\t<name>" << data_processing.getSoftware().getName() << "</name>\n"
<< "\t\t\t\t<version>" << data_processing.getSoftware().getVersion() << "</version>\n";
os << "\t\t\t</software>\n"
<< "\t\t\t<processingMethod>\n";
if (data_processing.getProcessingActions().count(DataProcessing::DEISOTOPING) == 1)
{
os << "\t\t\t\t<cvParam cvLabel=\"psi\" name=\"Deisotoping\" accession=\"PSI:1000033\" />\n";
}
if (data_processing.getProcessingActions().count(DataProcessing::CHARGE_DECONVOLUTION) == 1)
{
os << "\t\t\t\t<cvParam cvLabel=\"psi\" name=\"ChargeDeconvolution\" accession=\"PSI:1000034\" />\n";
}
if (data_processing.getProcessingActions().count(DataProcessing::PEAK_PICKING) == 1)
{
os << "\t\t\t\t<cvParam cvLabel=\"psi\" name=\"Centroid Mass Spectrum\" accession=\"PSI:1000127\"/>\n";
}
writeUserParam_(os, data_processing);
os << "\t\t\t</processingMethod>\n"
<< "\t\t</dataProcessing>\n";
}
os << "\t</description>\n";
//---------------------------------------------------------------------------------------------------
//ACTUAL DATA
if (!cexp_->empty())
{
//check if the nativeID of all spectra are numbers or numbers prefixed with 'spectrum='
//If not we need to renumber all spectra.
bool all_numbers = true;
bool all_empty = true;
bool all_prefixed_numbers = true;
for (Size s = 0; s < cexp_->size(); s++)
{
String native_id = (*cexp_)[s].getNativeID();
if (!native_id.hasPrefix("spectrum="))
{
all_prefixed_numbers = false;
}
else
{
native_id = native_id.substr(9);
}
try
{
native_id.toInt();
}
catch (Exception::ConversionError &)
{
all_numbers = false;
all_prefixed_numbers = false;
if (!native_id.empty())
{
all_empty = false;
}
}
}
//If we need to renumber and the nativeIDs were not empty, warn the user
if (!all_numbers && !all_empty)
{
warning(STORE, "Not all spectrum native IDs are numbers or correctly prefixed with 'spectrum='. The spectra are renumbered and the native IDs are lost!");
}
//Map to store the last spectrum ID for each MS level (needed to find precursor spectra)
std::map<Int, Size> level_id;
os << "\t<spectrumList count=\"" << cexp_->size() << "\">\n";
for (Size s = 0; s < cexp_->size(); ++s)
{
logger_.setProgress(s);
const SpectrumType & spec = (*cexp_)[s];
Size spectrum_id = s + 1;
if (all_prefixed_numbers)
{
spectrum_id = spec.getNativeID().substr(9).toInt();
}
else if (all_numbers)
{
spectrum_id = spec.getNativeID().toInt();
}
os << "\t\t<spectrum id=\"" << spectrum_id << "\">\n"
<< "\t\t\t<spectrumDesc>\n"
<< "\t\t\t\t<spectrumSettings>\n";
if (!spec.getAcquisitionInfo().empty())
{
os << "\t\t\t\t\t<acqSpecification spectrumType=\"";
if (spec.getType() == SpectrumSettings::SpectrumType::CENTROID)
{
os << "discrete";
}
else if (spec.getType() == SpectrumSettings::SpectrumType::PROFILE)
{
os << "continuous";
}
else
{
warning(STORE, "Spectrum type is unknown, assuming 'discrete'");
os << "discrete";
}
os << "\" methodOfCombination=\"" << spec.getAcquisitionInfo().getMethodOfCombination() << "\""
<< " count=\"" << spec.getAcquisitionInfo().size() << "\">\n";
for (Size i = 0; i < spec.getAcquisitionInfo().size(); ++i)
{
const Acquisition & ac = spec.getAcquisitionInfo()[i];
Int acq_number = 0;
try
{
if (!ac.getIdentifier().empty())
{
acq_number = ac.getIdentifier().toInt();
}
}
catch (...)
{
warning(STORE, String("Could not convert acquisition identifier '") + ac.getIdentifier() + "' to an integer. Using '0' instead!");
acq_number = 0;
}
os << "\t\t\t\t\t\t<acquisition acqNumber=\"" << acq_number << "\">\n";
writeUserParam_(os, ac, 7);
os << "\t\t\t\t\t\t</acquisition>\n";
}
os << "\t\t\t\t\t</acqSpecification>\n";
}
const InstrumentSettings & iset = spec.getInstrumentSettings();
os << "\t\t\t\t\t<spectrumInstrument msLevel=\"" << spec.getMSLevel() << "\"";
level_id[spec.getMSLevel()] = spectrum_id;
if (!iset.getScanWindows().empty())
{
os << " mzRangeStart=\"" << iset.getScanWindows()[0].begin << "\" mzRangeStop=\"" << iset.getScanWindows()[0].end << "\"";
}
if (iset.getScanWindows().size() > 1)
{
warning(STORE, "The MzData format can store only one scan window for each scan. Only the first one is stored!");
}
os << ">\n";
//scan mode
switch (iset.getScanMode())
{
case InstrumentSettings::ScanMode::UNKNOWN:
//do nothing here
break;
case InstrumentSettings::ScanMode::MASSSPECTRUM:
case InstrumentSettings::ScanMode::MS1SPECTRUM:
case InstrumentSettings::ScanMode::MSNSPECTRUM:
if (iset.getZoomScan())
{
os << "\t\t\t\t\t\t<cvParam cvLabel=\"psi\" accession=\"PSI:1000036\" name=\"ScanMode\" value=\"Zoom\"/>\n";
}
else
{
os << "\t\t\t\t\t\t<cvParam cvLabel=\"psi\" accession=\"PSI:1000036\" name=\"ScanMode\" value=\"MassScan\"/>\n";
}
break;
case InstrumentSettings::ScanMode::SIM:
os << "\t\t\t\t\t\t<cvParam cvLabel=\"psi\" accession=\"PSI:1000036\" name=\"ScanMode\" value=\"SelectedIonDetection\"/>\n";
break;
case InstrumentSettings::ScanMode::SRM:
os << "\t\t\t\t\t\t<cvParam cvLabel=\"psi\" accession=\"PSI:1000036\" name=\"ScanMode\" value=\"SelectedReactionMonitoring\"/>\n";
break;
case InstrumentSettings::ScanMode::CRM:
os << "\t\t\t\t\t\t<cvParam cvLabel=\"psi\" accession=\"PSI:1000036\" name=\"ScanMode\" value=\"ConsecutiveReactionMonitoring\"/>\n";
break;
case InstrumentSettings::ScanMode::CNG:
os << "\t\t\t\t\t\t<cvParam cvLabel=\"psi\" accession=\"PSI:1000036\" name=\"ScanMode\" value=\"ConstantNeutralGainScan\"/>\n";
break;
case InstrumentSettings::ScanMode::CNL:
os << "\t\t\t\t\t\t<cvParam cvLabel=\"psi\" accession=\"PSI:1000036\" name=\"ScanMode\" value=\"ConstantNeutralLossScan\"/>\n";
break;
case InstrumentSettings::ScanMode::PRECURSOR:
os << "\t\t\t\t\t\t<cvParam cvLabel=\"psi\" accession=\"PSI:1000036\" name=\"ScanMode\" value=\"PrecursorIonScan\"/>\n";
break;
case InstrumentSettings::ScanMode::ABSORPTION:
os << "\t\t\t\t\t\t<cvParam cvLabel=\"psi\" accession=\"PSI:1000036\" name=\"ScanMode\" value=\"PhotodiodeArrayDetector\"/>\n";
break;
case InstrumentSettings::ScanMode::EMC:
os << "\t\t\t\t\t\t<cvParam cvLabel=\"psi\" accession=\"PSI:1000036\" name=\"ScanMode\" value=\"EnhancedMultiplyChargedScan\"/>\n";
break;
case InstrumentSettings::ScanMode::TDF:
os << "\t\t\t\t\t\t<cvParam cvLabel=\"psi\" accession=\"PSI:1000036\" name=\"ScanMode\" value=\"TimeDelayedFragmentationScan\"/>\n";
break;
default:
os << "\t\t\t\t\t\t<cvParam cvLabel=\"psi\" accession=\"PSI:1000036\" name=\"ScanMode\" value=\"MassScan\"/>\n";
warning(STORE, String("Scan mode '") + InstrumentSettings::NamesOfScanMode[static_cast<size_t>(iset.getScanMode())] + "' not supported by mzData. Using 'MassScan' scan mode!");
}
//scan polarity
if (spec.getInstrumentSettings().getPolarity() == IonSource::Polarity::POSITIVE)
{
os << String(6, '\t') << "<cvParam cvLabel=\"psi\" accession=\"PSI:1000037\" name=\"Polarity\" value=\"Positive\"/>\n";
}
else if (spec.getInstrumentSettings().getPolarity() == IonSource::Polarity::NEGATIVE)
{
os << String(6, '\t') << "<cvParam cvLabel=\"psi\" accession=\"PSI:1000037\" name=\"Polarity\" value=\"Negative\"/>\n";
}
//Retention time already in TimeInSeconds
writeCVS_(os, spec.getRT(), "1000039", "TimeInSeconds", 6);
writeUserParam_(os, spec.getInstrumentSettings(), 6);
os << "\t\t\t\t\t</spectrumInstrument>\n\t\t\t\t</spectrumSettings>\n";
if (!spec.getPrecursors().empty())
{
Int precursor_ms_level = spec.getMSLevel() - 1;
SignedSize precursor_id = -1;
if (level_id.find(precursor_ms_level) != level_id.end())
{
precursor_id = level_id[precursor_ms_level];
}
os << "\t\t\t\t<precursorList count=\"" << spec.getPrecursors().size() << "\">\n";
for (Size i = 0; i < spec.getPrecursors().size(); ++i)
{
const Precursor & precursor = spec.getPrecursors()[i];
os << "\t\t\t\t\t<precursor msLevel=\"" << precursor_ms_level << "\" spectrumRef=\"" << precursor_id << "\">\n";
os << "\t\t\t\t\t\t<ionSelection>\n";
if (precursor != Precursor())
{
writeCVS_(os, precursor.getMZ(), "1000040", "MassToChargeRatio", 7);
writeCVS_(os, precursor.getCharge(), "1000041", "ChargeState", 7);
writeCVS_(os, precursor.getIntensity(), "1000042", "Intensity", 7);
os << "\t\t\t\t\t\t\t<cvParam cvLabel=\"psi\" accession=\"PSI:1000043\" name=\"IntensityUnit\" value=\"NumberOfCounts\"/>\n";
writeUserParam_(os, precursor, 7);
}
os << "\t\t\t\t\t\t</ionSelection>\n";
os << "\t\t\t\t\t\t<activation>\n";
if (precursor != Precursor())
{
if (!precursor.getActivationMethods().empty())
{
writeCVS_(os, static_cast<UInt>(*(precursor.getActivationMethods().begin())), 18, "1000044", "ActivationMethod", 7);
}
writeCVS_(os, precursor.getActivationEnergy(), "1000045", "CollisionEnergy", 7);
os << "\t\t\t\t\t\t\t<cvParam cvLabel=\"psi\" accession=\"PSI:1000046\" name=\"EnergyUnit\" value=\"eV\"/>\n";
}
os << "\t\t\t\t\t\t</activation>\n";
os << "\t\t\t\t\t</precursor>\n";
}
os << "\t\t\t\t</precursorList>\n";
}
os << "\t\t\t</spectrumDesc>\n";
// write the supplementary data?
if (options_.getWriteSupplementalData())
{
//write meta data array descriptions
for (Size i = 0; i < spec.getFloatDataArrays().size(); ++i)
{
const MetaInfoDescription & desc = spec.getFloatDataArrays()[i];
os << "\t\t\t<supDesc supDataArrayRef=\"" << (i + 1) << "\">\n";
if (!desc.isMetaEmpty())
{
os << "\t\t\t\t<supDataDesc>\n";
writeUserParam_(os, desc, 5);
os << "\t\t\t\t</supDataDesc>\n";
}
os << "\t\t\t</supDesc>\n";
}
}
//write m/z and intensity arrays
data_to_encode_.clear();
for (Size i = 0; i < spec.size(); i++)
{
data_to_encode_.push_back(spec[i].getPosition()[0]);
}
writeBinary_(os, spec.size(), "mzArrayBinary");
// intensity
data_to_encode_.clear();
for (Size i = 0; i < spec.size(); i++)
{
data_to_encode_.push_back(spec[i].getIntensity());
}
writeBinary_(os, spec.size(), "intenArrayBinary");
// write the supplementary data?
if (options_.getWriteSupplementalData())
{
//write supplemental data arrays
for (Size i = 0; i < spec.getFloatDataArrays().size(); ++i)
{
const MapType::SpectrumType::FloatDataArray & mda = spec.getFloatDataArrays()[i];
//check if spectrum and meta data array have the same length
if (mda.size() != spec.size())
{
error(LOAD, String("Length of meta data array (index:'") + i + "' name:'" + mda.getName() + "') differs from spectrum length. meta data array: " + mda.size() + " / spectrum: " + spec.size() + " .");
}
//encode meta data array
data_to_encode_.clear();
for (Size j = 0; j < mda.size(); j++)
{
data_to_encode_.push_back(mda[j]);
}
//write meta data array
writeBinary_(os, mda.size(), "supDataArrayBinary", mda.getName(), i + 1);
}
}
os << "\t\t</spectrum>\n";
}
}
else
{
os << "\t<spectrumList count=\"1\">\n";
os << "\t\t<spectrum id=\"1\">\n";
os << "\t\t\t<spectrumDesc>\n";
os << "\t\t\t\t<spectrumSettings>\n";
os << "\t\t\t\t\t<spectrumInstrument msLevel=\"1\"/>\n";
os << "\t\t\t\t</spectrumSettings>\n";
os << "\t\t\t</spectrumDesc>\n";
os << "\t\t\t<mzArrayBinary>\n";
os << "\t\t\t\t<data length=\"0\" endian=\"little\" precision=\"32\"></data>\n";
os << "\t\t\t</mzArrayBinary>\n";
os << "\t\t\t<intenArrayBinary>\n";
os << "\t\t\t\t<data length=\"0\" endian=\"little\" precision=\"32\"></data>\n";
os << "\t\t\t</intenArrayBinary>\n";
os << "\t\t</spectrum>\n";
}
os << "\t</spectrumList>\n</mzData>\n";
logger_.endProgress();
}
void MzDataHandler::cvParam_(const String & accession, const String & value)
{
String error = "";
//determine the parent tag
String parent_tag;
if (open_tags_.size() > 1)
{
parent_tag = *(open_tags_.end() - 2);
}
if (parent_tag == "spectrumInstrument")
{
if (accession == "PSI:1000036") //Scan Mode
{
if (value == "Zoom")
{
spec_.getInstrumentSettings().setZoomScan(true);
spec_.getInstrumentSettings().setScanMode(InstrumentSettings::ScanMode::MASSSPECTRUM);
}
else if (value == "MassScan")
{
spec_.getInstrumentSettings().setScanMode(InstrumentSettings::ScanMode::MASSSPECTRUM);
}
else if (value == "SelectedIonDetection")
{
spec_.getInstrumentSettings().setScanMode(InstrumentSettings::ScanMode::SIM);
}
else if (value == "SelectedReactionMonitoring")
{
spec_.getInstrumentSettings().setScanMode(InstrumentSettings::ScanMode::SRM);
}
else if (value == "ConsecutiveReactionMonitoring")
{
spec_.getInstrumentSettings().setScanMode(InstrumentSettings::ScanMode::CRM);
}
else if (value == "ConstantNeutralGainScan")
{
spec_.getInstrumentSettings().setScanMode(InstrumentSettings::ScanMode::CNG);
}
else if (value == "ConstantNeutralLossScan")
{
spec_.getInstrumentSettings().setScanMode(InstrumentSettings::ScanMode::CNL);
}
else if (value == "ProductIonScan")
{
spec_.getInstrumentSettings().setScanMode(InstrumentSettings::ScanMode::MSNSPECTRUM);
spec_.setMSLevel(2);
}
else if (value == "PrecursorIonScan")
{
spec_.getInstrumentSettings().setScanMode(InstrumentSettings::ScanMode::PRECURSOR);
}
else if (value == "EnhancedResolutionScan")
{
spec_.getInstrumentSettings().setZoomScan(true);
spec_.getInstrumentSettings().setScanMode(InstrumentSettings::ScanMode::MASSSPECTRUM);
}
else
{
if (spec_.getMSLevel() >= 2)
{
exp_->getSpectra().back().getInstrumentSettings().setScanMode(InstrumentSettings::ScanMode::MSNSPECTRUM);
}
else
{
spec_.getInstrumentSettings().setScanMode(InstrumentSettings::ScanMode::MASSSPECTRUM);
warning(LOAD, String("Unknown scan mode '") + value + "'. Assuming full scan");
}
}
}
else if (accession == "PSI:1000038") //Time in minutes
{
spec_.setRT(asDouble_(value) * 60); //Minutes to seconds
if (options_.hasRTRange() && !options_.getRTRange().encloses(DPosition<1>(spec_.getRT())))
{
skip_spectrum_ = true;
}
}
else if (accession == "PSI:1000039") //Time in seconds
{
spec_.setRT(asDouble_(value));
if (options_.hasRTRange() && !options_.getRTRange().encloses(DPosition<1>(spec_.getRT())))
{
skip_spectrum_ = true;
}
}
else if (accession == "PSI:1000037") //Polarity
{
if (value == "Positive" || value == "positive" || value == "+") //be flexible here, actually only the first one is correct
{
spec_.getInstrumentSettings().setPolarity(IonSource::Polarity::POSITIVE);
}
else if (value == "Negative" || value == "negative" || value == "-") //be flexible here, actually only the first one is correct
{
spec_.getInstrumentSettings().setPolarity(IonSource::Polarity::NEGATIVE);
}
else
{
warning(LOAD, String("Invalid scan polarity (PSI:1000037) detected: \"") + value + "\". Valid are 'Positive' or 'Negative'.");
}
}
else
{
error = "SpectrumDescription.SpectrumSettings.SpectrumInstrument";
}
}
else if (parent_tag == "ionSelection")
{
if (accession == "PSI:1000040") //m/z
{
double mz = asDouble_(value);
spec_.getPrecursors().back().setMZ(mz);
// Check if precursor m/z is within specified range
if (options_.hasPrecursorMZRange() &&
!options_.getPrecursorMZRange().encloses(DPosition<1>(mz)))
{
skip_spectrum_ = true;
}
}
else if (accession == "PSI:1000041") //Charge
{
if (spec_.getPrecursors().back().getCharge() != 0)
{
warning(LOAD, String("Multiple precursor charges detected, expected only one! Ignoring this charge settings! accession=\"") + accession + "\", value=\"" + value + "\"");
spec_.getPrecursors().back().setCharge(0);
}
else
{
spec_.getPrecursors().back().setCharge(asInt_(value));
}
}
else if (accession == "PSI:1000042") //Intensity
{
spec_.getPrecursors().back().setIntensity(asDouble_(value));
}
else if (accession == "PSI:1000043") //Intensity unit
{
//ignored
}
else
{
error = "PrecursorList.Precursor.IonSelection.UserParam";
}
}
else if (parent_tag == "activation")
{
if (accession == "PSI:1000044") //activationmethod
{
spec_.getPrecursors().back().getActivationMethods().insert((Precursor::ActivationMethod)cvStringToEnum_(18, value, "activation method"));
}
else if (accession == "PSI:1000045") //Energy
{
spec_.getPrecursors().back().setActivationEnergy(asDouble_(value));
}
else if (accession == "PSI:1000046") //Energy unit
{
//ignored - we assume electronvolt
}
else
{
error = "PrecursorList.Precursor.Activation.UserParam";
}
}
else if (parent_tag == "supDataDesc")
{
//no terms defined in ontology
error = "supDataDesc.UserParam";
}
else if (parent_tag == "acquisition")
{
//no terms defined in ontology
error = "spectrumDesc.spectrumSettings.acquisitionSpecification.acquisition.UserParam";
}
else if (parent_tag == "detector")
{
if (accession == "PSI:1000026")
{
exp_->getInstrument().getIonDetectors().back().setType((IonDetector::Type)cvStringToEnum_(13, value, "detector type"));
}
else if (accession == "PSI:1000028")
{
exp_->getInstrument().getIonDetectors().back().setResolution(asDouble_(value));
}
else if (accession == "PSI:1000029")
{
exp_->getInstrument().getIonDetectors().back().setADCSamplingFrequency(asDouble_(value));
}
else if (accession == "PSI:1000027")
{
exp_->getInstrument().getIonDetectors().back().setAcquisitionMode((IonDetector::AcquisitionMode)cvStringToEnum_(9, value, "acquisition mode"));
}
else
{
error = "Description.Instrument.Detector.UserParam";
}
}
else if (parent_tag == "source")
{
if (accession == "PSI:1000008")
{
exp_->getInstrument().getIonSources().back().setIonizationMethod((IonSource::IonizationMethod)cvStringToEnum_(10, value, "ion source"));
}
else if (accession == "PSI:1000007")
{
exp_->getInstrument().getIonSources().back().setInletType((IonSource::InletType)cvStringToEnum_(11, value, "inlet type"));
}
else if (accession == "PSI:1000009")
{
exp_->getInstrument().getIonSources().back().setPolarity((IonSource::Polarity)cvStringToEnum_(1, value, "polarity"));
}
else
{
error = "Description.Instrument.Source.UserParam";
}
}
else if (parent_tag == "sampleDescription")
{
if (accession == "PSI:1000001")
{
exp_->getSample().setNumber(value);
}
else if (accession == "PSI:1000003")
{
exp_->getSample().setState((Sample::SampleState)cvStringToEnum_(0, value, "sample state"));
}
else if (accession == "PSI:1000004")
{
exp_->getSample().setMass(asDouble_(value));
}
else if (accession == "PSI:1000005")
{
exp_->getSample().setVolume(asDouble_(value));
}
else if (accession == "PSI:1000006")
{
exp_->getSample().setConcentration(asDouble_(value));
}
else
{
error = "Description.Admin.SampleDescription.UserParam";
}
}
else if (parent_tag == "analyzer")
{
if (accession == "PSI:1000010")
{
exp_->getInstrument().getMassAnalyzers().back().setType((MassAnalyzer::AnalyzerType)cvStringToEnum_(14, value, "analyzer type"));
}
else if (accession == "PSI:1000011")
{
exp_->getInstrument().getMassAnalyzers().back().setResolution(asDouble_(value));
}
else if (accession == "PSI:1000012")
{
exp_->getInstrument().getMassAnalyzers().back().setResolutionMethod((MassAnalyzer::ResolutionMethod)cvStringToEnum_(2, value, "resolution method"));
}
else if (accession == "PSI:1000013")
{
exp_->getInstrument().getMassAnalyzers().back().setResolutionType((MassAnalyzer::ResolutionType)cvStringToEnum_(3, value, "resolution type"));
}
else if (accession == "PSI:1000014")
{
exp_->getInstrument().getMassAnalyzers().back().setAccuracy(asDouble_(value));
}
else if (accession == "PSI:1000015")
{
exp_->getInstrument().getMassAnalyzers().back().setScanRate(asDouble_(value));
}
else if (accession == "PSI:1000016")
{
exp_->getInstrument().getMassAnalyzers().back().setScanTime(asDouble_(value));
}
else if (accession == "PSI:1000018")
{
exp_->getInstrument().getMassAnalyzers().back().setScanDirection((MassAnalyzer::ScanDirection)cvStringToEnum_(5, value, "scan direction"));
}
else if (accession == "PSI:1000019")
{
exp_->getInstrument().getMassAnalyzers().back().setScanLaw((MassAnalyzer::ScanLaw)cvStringToEnum_(6, value, "scan law"));
}
else if (accession == "PSI:1000020")
{
// ignored
}
else if (accession == "PSI:1000021")
{
exp_->getInstrument().getMassAnalyzers().back().setReflectronState((MassAnalyzer::ReflectronState)cvStringToEnum_(8, value, "reflectron state"));
}
else if (accession == "PSI:1000022")
{
exp_->getInstrument().getMassAnalyzers().back().setTOFTotalPathLength(asDouble_(value));
}
else if (accession == "PSI:1000023")
{
exp_->getInstrument().getMassAnalyzers().back().setIsolationWidth(asDouble_(value));
}
else if (accession == "PSI:1000024")
{
exp_->getInstrument().getMassAnalyzers().back().setFinalMSExponent(asInt_(value));
}
else if (accession == "PSI:1000025")
{
exp_->getInstrument().getMassAnalyzers().back().setMagneticFieldStrength(asDouble_(value));
}
else if (accession == "PSI:1000017")
{
//ignored
}
else
{
error = "AnalyzerList.Analyzer.UserParam";
}
}
else if (parent_tag == "additional")
{
if (accession == "PSI:1000030")
{
exp_->getInstrument().setVendor(value);
}
else if (accession == "PSI:1000031")
{
exp_->getInstrument().setModel(value);
}
else if (accession == "PSI:1000032")
{
exp_->getInstrument().setCustomizations(value);
}
else
{
error = "Description.Instrument.Additional";
}
}
else if (parent_tag == "processingMethod")
{
if (accession == "PSI:1000033")
{
data_processing_->getProcessingActions().insert(DataProcessing::DEISOTOPING);
}
else if (accession == "PSI:1000034")
{
data_processing_->getProcessingActions().insert(DataProcessing::CHARGE_DECONVOLUTION);
}
else if (accession == "PSI:1000127")
{
data_processing_->getProcessingActions().insert(DataProcessing::PEAK_PICKING);
}
else if (accession == "PSI:1000035")
{
//ignored
}
else
{
error = "DataProcessing.DataProcessing.UserParam";
}
}
else
{
warning(LOAD, String("Unexpected cvParam: accession=\"") + accession + "\" value=\"" + value + "\" in tag " + parent_tag);
}
if (!error.empty())
{
warning(LOAD, String("Invalid cvParam: accession=\"") + accession + "\" value=\"" + value + "\" in " + error);
}
//std::cout << "End of MzDataHander::cvParam_" << std::endl;
}
inline void MzDataHandler::writeCVS_(std::ostream & os, double value, const String & acc, const String & name, UInt indent) const
{
if (value != 0.0)
{
os << String(indent, '\t') << R"(<cvParam cvLabel="psi" accession="PSI:)" << acc << "\" name=\"" << name << "\" value=\"" << value << "\"/>\n";
}
}
inline void MzDataHandler::writeCVS_(std::ostream & os, const String & value, const String & acc, const String & name, UInt indent) const
{
if (!value.empty())
{
os << String(indent, '\t') << R"(<cvParam cvLabel="psi" accession="PSI:)" << acc << "\" name=\"" << name << "\" value=\"" << value << "\"/>\n";
}
}
inline void MzDataHandler::writeCVS_(std::ostream & os, UInt value, UInt map, const String & acc, const String & name, UInt indent)
{
//abort when receiving a wrong map index
if (map >= cv_terms_.size())
{
warning(STORE, String("Cannot find map '") + map + "' needed to write CV term '" + name + "' with accession '" + acc + "'.");
return;
}
//abort when receiving a wrong term index
if (value >= cv_terms_[map].size())
{
warning(STORE, String("Cannot find value '") + value + "' needed to write CV term '" + name + "' with accession '" + acc + "'.");
return;
}
writeCVS_(os, cv_terms_[map][value], acc, name, indent);
}
inline void MzDataHandler::writeUserParam_(std::ostream & os, const MetaInfoInterface & meta, UInt indent)
{
std::vector<String> keys;
meta.getKeys(keys);
for (std::vector<String>::const_iterator it = keys.begin(); it != keys.end(); ++it)
{
if ((*it)[0] != '#') // internally used meta info start with '#'
{
os << String(indent, '\t') << "<userParam name=\"" << *it << "\" value=\"" << meta.getMetaValue(*it) << "\"/>\n";
}
}
}
inline void MzDataHandler::writeBinary_(std::ostream & os, Size size, const String & tag, const String & name, SignedSize id)
{
os << "\t\t\t<" << tag;
if (tag == "supDataArrayBinary" || tag == "supDataArray")
{
os << " id=\"" << id << "\"";
}
os << ">\n";
if (tag == "supDataArrayBinary" || tag == "supDataArray")
{
os << "\t\t\t\t<arrayName>" << name << "</arrayName>\n";
}
String str;
Base64::encode(data_to_encode_, Base64::BYTEORDER_LITTLEENDIAN, str);
data_to_encode_.clear();
os << "\t\t\t\t<data precision=\"32\" endian=\"little\" length=\""
<< size << "\">"
<< str
<< "</data>\n\t\t\t</" << tag << ">\n";
}
} // namespace OpenMS //namespace Internal
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/HANDLERS/PTMXMLHandler.cpp | .cpp | 2,409 | 72 | // 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/HANDLERS/PTMXMLHandler.h>
using namespace std;
using namespace xercesc;
namespace OpenMS::Internal
{
PTMXMLHandler::PTMXMLHandler(map<String, pair<String, String> > & ptm_informations, const String & filename) :
XMLHandler(filename, ""),
ptm_informations_(ptm_informations)
{
}
PTMXMLHandler::~PTMXMLHandler()
= default;
void PTMXMLHandler::writeTo(std::ostream & os)
{
os << "<PTMs>" << "\n";
for (map<String, pair<String, String> >::const_iterator ptm_i = ptm_informations_.begin(); ptm_i != ptm_informations_.end(); ++ptm_i)
{
os << "\t<PTM>" << "\n";
os << "\t\t<name>" << ptm_i->first << "</name>" << "\n"; // see header
os << "\t\t<composition>" << ptm_i->second.first << "</composition>" << "\n";
os << "\t\t<possible_amino_acids>" << ptm_i->second.second << "</possible_amino_acids>" << "\n";
os << "\t</PTM>" << "\n";
}
os << "</PTMs>" << "\n";
}
void PTMXMLHandler::startElement(const XMLCh * const /*uri*/, const XMLCh * const /*local_name*/, const XMLCh * const qname, const Attributes & /*attributes*/)
{
tag_ = String(sm_.convert(qname)).trim();
open_tag_ = true;
}
void PTMXMLHandler::endElement(const XMLCh * const /*uri*/, const XMLCh * const /*local_name*/, const XMLCh * const /*qname*/)
{
// tag_ = String(sm_.convert(qname)).trim();
tag_ = "";
open_tag_ = false;
}
void PTMXMLHandler::characters(const XMLCh * const chars, const XMLSize_t /*length*/)
{
if (open_tag_)
{
if (tag_ == "name")
{
name_ = String(sm_.convert(chars)).trim();
}
else if (tag_ == "composition")
{
composition_ = String(sm_.convert(chars)).trim();
}
else if (tag_ == "possible_amino_acids")
{
ptm_informations_[name_] = make_pair(composition_, String(sm_.convert(chars)).trim());
}
}
}
} // namespace OpenMS // namespace Internal
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/HANDLERS/MascotXMLHandler.cpp | .cpp | 25,851 | 654 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Nico Pfeifer, Chris Bielow, Hendrik Weisser, Petra Gutenbrunner $
// --------------------------------------------------------------------------
#include <OpenMS/FORMAT/HANDLERS/MascotXMLHandler.h>
#include <OpenMS/CHEMISTRY/ProteaseDB.h>
using namespace std;
using namespace xercesc;
namespace OpenMS::Internal
{
MascotXMLHandler::MascotXMLHandler(ProteinIdentification& protein_identification, PeptideIdentificationList& id_data, const String& filename, map<String, vector<AASequence> >& modified_peptides, const SpectrumMetaDataLookup& lookup):
XMLHandler(filename, ""), protein_identification_(protein_identification),
id_data_(id_data), peptide_identification_index_(0), actual_title_(""),
modified_peptides_(modified_peptides), lookup_(lookup),
no_rt_error_(false)
{
}
MascotXMLHandler::~MascotXMLHandler()
= default;
void MascotXMLHandler::startElement(const XMLCh* const /*uri*/, const XMLCh* const /*local_name*/, const XMLCh* const qname, const Attributes& attributes)
{
static const XMLCh* s_protein_accession = xercesc::XMLString::transcode("accession");
static const XMLCh* s_queries_query_number = xercesc::XMLString::transcode("number");
static const XMLCh* s_peptide_query = xercesc::XMLString::transcode("query");
tag_ = String(sm_.convert(qname));
// cerr << "open: " << tag_ << endl;
tags_open_.push_back(tag_);
if (tag_ == "mascot_search_results")
{
major_version_ = this->attributeAsString_(attributes, "majorVersion");
minor_version_ = this->attributeAsString_(attributes, "minorVersion");
no_rt_error_ = false; // reset for every new file
}
else if (tag_ == "protein")
{
String attribute_value = attributeAsString_(attributes, s_protein_accession);
actual_protein_hit_.setAccession(attribute_value);
}
else if (tag_ == "query")
{
actual_query_ = attributeAsInt_(attributes, s_queries_query_number);
}
else if (tag_ == "peptide" || tag_ == "u_peptide" || tag_ == "q_peptide")
{
Int attribute_value = attributeAsInt_(attributes, s_peptide_query);
peptide_identification_index_ = attribute_value - 1;
if (peptide_identification_index_ > id_data_.size())
{
fatalError(LOAD, "No or conflicting header information present (make sure to use the 'show_header=1' option in the ./export_dat.pl script)");
}
}
}
void MascotXMLHandler::endElement(const XMLCh* const /*uri*/, const XMLCh* const /*local_name*/, const XMLCh* const qname)
{
tag_ = String(sm_.convert(qname)).trim();
// cerr << "close: " << tag_ << endl;
if (tags_open_.empty())
{
fatalError(LOAD, String("Closing tag ") + tag_ + " not matched by opening tag", __LINE__);
}
tags_open_.pop_back();
if (tag_ == "NumQueries")
{
id_data_.resize(character_buffer_.trim().toInt());
}
else if (tag_ == "prot_score")
{
actual_protein_hit_.setScore(character_buffer_.trim().toInt());
}
else if (tag_ == "pep_exp_mz")
{
id_data_[peptide_identification_index_].setMZ(
character_buffer_.trim().toDouble());
}
else if (tag_ == "pep_scan_title")
{
// extract RT (and possibly m/z, if not already set) from title:
String title = character_buffer_.trim();
SpectrumMetaDataLookup::SpectrumMetaData meta;
SpectrumMetaDataLookup::MetaDataFlags flags = SpectrumMetaDataLookup::MDF_RT;
if (!id_data_[peptide_identification_index_].hasMZ())
{
flags |= SpectrumMetaDataLookup::MDF_PRECURSORMZ;
}
try
{
lookup_.getSpectrumMetaData(title, meta, flags);
id_data_[peptide_identification_index_].setRT(meta.rt);
// have we looked up the m/z value?
if ((flags & SpectrumMetaDataLookup::MDF_PRECURSORMZ) == SpectrumMetaDataLookup::MDF_PRECURSORMZ)
{
id_data_[peptide_identification_index_].setMZ(meta.precursor_mz);
}
}
catch (...)
{
String msg = "<pep_scan_title> element has unexpected format '" + title + "'. Could not extract spectrum meta data.";
error(LOAD, msg);
}
// did it work?
if (!id_data_[peptide_identification_index_].getRT())
{
if (!no_rt_error_) // report the error only the first time
{
String msg = "Could not extract RT value ";
if (!lookup_.empty())
{
msg += "or a matching spectrum reference ";
}
msg += "from <pep_scan_title> element with format '" + title + "'. Try adjusting the 'scan_regex' parameter.";
error(LOAD, msg);
}
no_rt_error_ = true;
}
}
else if (tag_ == "pep_exp_z")
{
actual_peptide_hit_.setCharge(character_buffer_.trim().toInt());
}
else if (tag_ == "pep_score")
{
actual_peptide_hit_.setScore(character_buffer_.trim().toDouble());
}
else if (tag_ == "pep_expect")
{
// @todo what E-value flag? (andreas)
actual_peptide_hit_.metaRegistry().registerName("EValue", "E-value of e.g. Mascot searches", "");
actual_peptide_hit_.setMetaValue("EValue", character_buffer_.trim().toDouble());
}
else if (tag_ == "pep_homol")
{
id_data_[peptide_identification_index_].setSignificanceThreshold(character_buffer_.trim().toDouble());
}
else if (tag_ == "pep_ident")
{
double temp_homology = 0;
double temp_identity = 0;
// According to Matrix Science the homology threshold is only used if it
// exists and is smaller than the identity threshold.
temp_homology = id_data_[peptide_identification_index_].getSignificanceThreshold();
temp_identity = character_buffer_.trim().toDouble();
actual_peptide_hit_.setMetaValue("homology_threshold", temp_homology);
actual_peptide_hit_.setMetaValue("identity_threshold", temp_identity);
if (temp_homology > temp_identity || temp_homology == 0)
{
id_data_[peptide_identification_index_].setSignificanceThreshold(temp_identity);
}
}
else if (tag_ == "pep_seq")
{
AASequence temp_aa_sequence = AASequence::fromString(character_buffer_.trim());
// if everything is just read from the MascotXML file
if (modified_peptides_.empty())
{
// fixed modifications
for (vector<String>::const_iterator it = search_parameters_.fixed_modifications.begin(); it != search_parameters_.fixed_modifications.end(); ++it)
{
vector<String> mod_split;
it->split(' ', mod_split);
if (mod_split.size() < 2 || mod_split.size() > 3)
{
error(LOAD, String("Cannot parse fixed modification '") + *it + "'");
}
else
{
// C-term modification without specification or protein terminus
if (mod_split[1] == "(C-term)" || (mod_split[1] == "(Protein" && mod_split[2] == "C-term)"))
{
temp_aa_sequence.setCTerminalModification(mod_split[0]);
}
// N-term modification without specification or protein terminus
else if (mod_split[1] == "(N-term)" || (mod_split[1] == "(Protein" && mod_split[2] == "N-term)"))
{
temp_aa_sequence.setNTerminalModification(mod_split[0]);
}
// C-term modification for specific amino acid; e.g. <Modification> (N-term C)
else if ((mod_split[1] == "(C-term") && (mod_split.size() == 3))
{
if ((temp_aa_sequence.end() - 1)->getOneLetterCode() == mod_split[2].remove(')'))
{
temp_aa_sequence.setCTerminalModification(mod_split[0]);
}
}
// N-term modification for specific amino acid; e.g. <Modification> (N-term C)
else if ((mod_split[1] == "(N-term") && (mod_split.size() == 3))
{
if (temp_aa_sequence.begin()->getOneLetterCode() == mod_split[2].remove(')'))
{
temp_aa_sequence.setNTerminalModification(mod_split[0]);
}
}
else
{ // e.g. Carboxymethyl (C)
String AA = mod_split[1];
AA.remove(')');
AA.remove('(');
for (Size i = 0; i != temp_aa_sequence.size(); ++i)
{
if (AA == temp_aa_sequence[i].getOneLetterCode())
{
temp_aa_sequence.setModification(i, mod_split[0]);
}
}
}
}
}
}
actual_peptide_hit_.setSequence(temp_aa_sequence);
}
else if (tag_ == "pep_res_before")
{
String temp_string = character_buffer_.trim();
if (!temp_string.empty())
{
actual_peptide_evidence_.setAABefore(temp_string[0]);
}
}
else if (tag_ == "pep_res_after")
{
String temp_string = character_buffer_.trim();
if (!temp_string.empty())
{
actual_peptide_evidence_.setAAAfter(temp_string[0]);
}
}
else if (tag_ == "pep_var_mod_pos")
{
AASequence temp_aa_sequence = actual_peptide_hit_.getSequence();
String temp_string = character_buffer_.trim();
vector<String> parts;
// E.g. seq: QKAAGSK, pos: 4.0000000.0 -> mod at position 4 in var_mods vector is n-terminal
// therefore it is not possible to split Phospho (ST) to Phospho (S), Phospho (T) before this,
// because the original order is required
temp_string.split('.', parts);
if (parts.size() == 3)
{
// handle internal modifications
temp_string = parts[1];
for (Size i = 0; i < temp_string.size(); ++i)
{
if (temp_string[i] != '0')
{
UInt temp_modification_index = String(temp_string[i]).toInt() - 1;
OPENMS_PRECONDITION(temp_modification_index < search_parameters_.variable_modifications.size(), "Error when parsing variable modification string in <pep_var_mod_pos> (index too large)!");
String& temp_modification = search_parameters_.variable_modifications.at(temp_modification_index);
// e.g. "Carboxymethyl (C)"
vector<String> mod_split;
temp_modification.split(' ', mod_split);
if (mod_split.size() >= 2)
{
// search this mod, if not directly use a general one
temp_aa_sequence.setModification(i, mod_split[0]);
}
else
{
error(LOAD, String("Cannot parse variable modification '") + temp_modification + "'");
}
}
}
temp_string = parts[0]; // N-term
if (temp_string[0] != '0')
{
UInt temp_modification_index = String(temp_string[0]).toInt() - 1;
String& temp_modification = search_parameters_.variable_modifications.at(temp_modification_index);
vector<String> mod_split;
temp_modification.split(' ', mod_split);
if (mod_split.size() >= 2)
{
temp_aa_sequence.setNTerminalModification(mod_split[0]);
}
else
{
error(LOAD, String("Cannot parse variable N-term modification '") + temp_modification + "'");
}
}
temp_string = parts[2]; // C-term
if (temp_string[0] != '0')
{
UInt temp_modification_index = String(temp_string[0]).toInt() - 1;
String& temp_modification = search_parameters_.variable_modifications.at(temp_modification_index);
vector<String> mod_split;
temp_modification.split(' ', mod_split);
if (mod_split.size() >= 2)
{
temp_aa_sequence.setCTerminalModification(mod_split[0]);
}
else
{
error(LOAD, String("Cannot parse variable C-term modification '") + temp_modification + "'");
}
}
actual_peptide_hit_.setSequence(temp_aa_sequence);
}
}
else if (tag_ == "Date")
{
vector<String> parts;
character_buffer_.trim().split('T', parts);
if (parts.size() == 2)
{
date_.set(parts[0] + ' ' + parts[1].prefix('Z'));
date_time_string_ = parts[0] + ' ' + parts[1].prefix('Z');
identifier_ = "Mascot_" + date_time_string_;
}
protein_identification_.setDateTime(date_);
}
else if (tag_ == "StringTitle")
{
String title = character_buffer_.trim();
vector<String> parts;
actual_title_ = title;
if (modified_peptides_.find(title) != modified_peptides_.end())
{
vector<AASequence>& temp_hits = modified_peptides_[title];
vector<PeptideHit> temp_peptide_hits = id_data_[actual_query_ - 1].getHits();
if (temp_hits.size() != temp_peptide_hits.size())
{
warning(LOAD, "pepXML hits and Mascot hits are not the same");
}
// pepXML can contain more hits than MascotXML; hence we try to match all of them...
// run-time is O(n^2) in the number of peptide hits; should be a very small number
for (Size i = 0; i < temp_peptide_hits.size(); ++i)
{
for (Size j = 0; j < temp_hits.size(); ++j)
{
if (temp_hits[j].isModified() && temp_hits[j].toUnmodifiedString() == temp_peptide_hits[i].getSequence().toUnmodifiedString())
{
temp_peptide_hits[i].setSequence(temp_hits[j]);
break;
}
}
}
id_data_[actual_query_ - 1].setHits(temp_peptide_hits);
}
if (!id_data_[actual_query_ - 1].hasRT())
{
title.split('_', parts);
if (parts.size() == 2)
{
id_data_[actual_query_ - 1].setRT(parts[1].toDouble());
}
}
}
else if (tag_ == "RTINSECONDS")
{
id_data_[actual_query_ - 1].setRT(character_buffer_.trim().toDouble());
}
else if (tag_ == "MascotVer")
{
protein_identification_.setSearchEngineVersion(character_buffer_.trim());
}
else if (tag_ == "DB")
{
search_parameters_.db = (character_buffer_.trim());
}
else if (tag_ == "FastaVer")
{
search_parameters_.db_version = (character_buffer_.trim());
}
else if (tag_ == "TAXONOMY")
{
search_parameters_.taxonomy = (character_buffer_.trim());
}
else if (tag_ == "CHARGE")
{
search_parameters_.charges = (character_buffer_.trim());
}
else if (tag_ == "PFA")
{
search_parameters_.missed_cleavages = character_buffer_.trim().toInt();
}
else if (tag_ == "MASS")
{
String temp_string = (character_buffer_.trim());
if (temp_string == "Monoisotopic")
{
search_parameters_.mass_type = ProteinIdentification::PeakMassType::MONOISOTOPIC;
}
else if (temp_string == "Average")
{
search_parameters_.mass_type = ProteinIdentification::PeakMassType::AVERAGE;
}
}
else if (tag_ == "MODS")
{
// if the modifications are listed in the "fixed_mods" section,
// read from there; if <fixed_mods> was present it was already read
if (search_parameters_.fixed_modifications.empty())
{
String temp_string = (character_buffer_.trim());
vector<String> tmp_mods;
temp_string.split(',', tmp_mods);
for (vector<String>::const_iterator it = tmp_mods.begin(); it != tmp_mods.end(); ++it)
{
// check if modification is not on the remove list
if (std::find(remove_fixed_mods_.begin(), remove_fixed_mods_.end(), *it) == remove_fixed_mods_.end())
{
// split because e.g. Phospho (ST)
vector<String> mods_split = splitModificationBySpecifiedAA(*it);
search_parameters_.fixed_modifications.insert(search_parameters_.fixed_modifications.end(), mods_split.begin(), mods_split.end());
}
}
}
}
else if (tag_ == "IT_MODS")
{
// if the modifications are listed in the "variable_mods" section,
// read from there, because sometimes mods are forced to be variable
// (from user set fixed); if <variable_mods> was present it was already
// read
if (search_parameters_.variable_modifications.empty())
{
String temp_string = (character_buffer_.trim());
vector<String> tmp_mods;
temp_string.split(',', tmp_mods);
for (vector<String>::const_iterator it = tmp_mods.begin(); it != tmp_mods.end(); ++it)
{
// split because e.g. Phospho (ST)
vector<String> mods_split = splitModificationBySpecifiedAA(*it);
search_parameters_.variable_modifications.insert(search_parameters_.variable_modifications.end(), mods_split.begin(), mods_split.end());
}
}
}
else if (tag_ == "CLE")
{
String temp_string = (character_buffer_.trim());
if (ProteaseDB::getInstance()->hasEnzyme(temp_string))
{
search_parameters_.digestion_enzyme = *(ProteaseDB::getInstance()->getEnzyme(temp_string));
}
}
else if (tag_ == "TOL")
{
search_parameters_.precursor_mass_tolerance = (character_buffer_.trim()).toDouble();
}
else if (tag_ == "ITOL")
{
search_parameters_.fragment_mass_tolerance = (character_buffer_.trim()).toDouble();
}
else if (tag_ == "TOLU")
{
search_parameters_.precursor_mass_tolerance_ppm = (character_buffer_.trim()) == "ppm";
}
else if (tag_ == "ITOLU")
{
search_parameters_.fragment_mass_tolerance_ppm = (character_buffer_.trim()) == "ppm";
}
else if (tag_ == "name")
{
// cerr << "name tag: " << character_buffer_.trim() << "\n";
if ((major_version_ == "1")
// new since Mascot XML version 2.1 (at least): <fixed_mods> also have a subtag called <name>, thus we need to ensure we are in <variable_mods>
|| (tags_open_.size() >= 2 &&
tags_open_[tags_open_.size() - 2] == "variable_mods"))
{
// e.g. Phospho (ST) cannot be split for variable modifications at this point, because the order of
// variable modifications needs to be preserved. Split before search parameters are set.
search_parameters_.variable_modifications.push_back(character_buffer_.trim());
// cerr << "var. mod. added: " << search_parameters_.variable_modifications.back() << "\n";
}
else if (tags_open_.size() >= 2 &&
tags_open_[tags_open_.size() - 2] == "fixed_mods")
{
// check if modification is not on the remove list
String fixed_mod = character_buffer_.trim();
if (std::find(remove_fixed_mods_.begin(), remove_fixed_mods_.end(), fixed_mod) == remove_fixed_mods_.end())
{
// split because e.g. Phospho (ST)
vector<String> mods_split = splitModificationBySpecifiedAA(character_buffer_.trim());
search_parameters_.fixed_modifications.insert(search_parameters_.fixed_modifications.end(), mods_split.begin(), mods_split.end());
// cerr << "fixed mod. added: " << search_parameters_.fixed_modifications.back() << "\n";
}
else
{
warning(LOAD, String("Modification removed as fixed modification: '") + character_buffer_.trim() + String("'"));
}
}
}
else if (tag_ == "warning")
{
warning(LOAD, String("Warnings were present: '") + character_buffer_ + String("'"));
// check if fixed modification can only be used as variable modification
if (character_buffer_.trim().hasSubstring("can only be used as a variable modification"))
{
vector<String> warn_split;
character_buffer_.trim().split(';', warn_split);
if (warn_split[0].hasPrefix("'"))
{
Size end_pos = warn_split[0].find("'", 1);
if (end_pos < warn_split[0].size())
{
warn_split[0] = warn_split[0].substr(1, end_pos - 1);
remove_fixed_mods_.push_back(warn_split[0]);
}
}
}
}
else if (tag_ == "protein")
{
protein_identification_.setScoreType("Mascot");
protein_identification_.insertHit(actual_protein_hit_);
actual_protein_hit_ = ProteinHit();
}
else if (tag_ == "peptide")
{
bool already_stored(false);
vector<PeptideHit> temp_peptide_hits = id_data_[peptide_identification_index_].getHits();
vector<PeptideHit>::iterator it = temp_peptide_hits.begin();
while (it != temp_peptide_hits.end())
{
if (it->getSequence() == actual_peptide_hit_.getSequence())
{
already_stored = true;
break;
}
++it;
}
if (!already_stored)
{
id_data_[peptide_identification_index_].setIdentifier(identifier_);
id_data_[peptide_identification_index_].setScoreType("Mascot");
actual_peptide_evidence_.setProteinAccession(actual_protein_hit_.getAccession());
actual_peptide_hit_.addPeptideEvidence(actual_peptide_evidence_);
id_data_[peptide_identification_index_].insertHit(actual_peptide_hit_);
}
else
{
actual_peptide_evidence_.setProteinAccession(actual_protein_hit_.getAccession());
it->addPeptideEvidence(actual_peptide_evidence_);
id_data_[peptide_identification_index_].setHits(temp_peptide_hits);
}
actual_peptide_evidence_ = PeptideEvidence();
actual_peptide_hit_ = PeptideHit();
}
else if (tag_ == "u_peptide" || tag_ == "q_peptide")
{
id_data_[peptide_identification_index_].setIdentifier(identifier_);
id_data_[peptide_identification_index_].setScoreType("Mascot");
id_data_[peptide_identification_index_].insertHit(actual_peptide_hit_);
actual_peptide_evidence_ = PeptideEvidence();
actual_peptide_hit_ = PeptideHit();
}
else if (tag_ == "mascot_search_results")
{
protein_identification_.setSearchEngine("Mascot");
protein_identification_.setIdentifier(identifier_);
// split variable modifications e.g. Phospho (ST)
//vector<String> var_mods;
vector<String> var_mods;
for (vector<String>::iterator it = search_parameters_.variable_modifications.begin(); it != search_parameters_.variable_modifications.end(); ++it)
{
vector<String> mods_split = splitModificationBySpecifiedAA(*it);
var_mods.insert(var_mods.end(), mods_split.begin(), mods_split.end());
}
search_parameters_.variable_modifications = var_mods;
protein_identification_.setSearchParameters(search_parameters_);
}
tag_ = ""; // reset tag, for the following characters() call (due to line break) of the parent tag
character_buffer_.clear();
}
void MascotXMLHandler::characters(const XMLCh* const chars, const XMLSize_t /*length*/)
{
// do not care about chars after internal tags, e.g.
// <header>
// <COM>OpenMS_search</COM>
// <Date>
// will trigger a characters() between </COM> and <Date>, which should be ignored
if (tag_.empty())
{
return;
}
character_buffer_ += String(sm_.convert(chars));
}
vector<String> MascotXMLHandler::splitModificationBySpecifiedAA(const String& mod)
{
vector<String> mods;
vector<String> parts;
mod.split(' ', parts);
// either format "Modification (Protein C-term)" or "Modification (C-term X)"
if (parts.size() != 2)
{
mods.push_back(mod);
return mods;
}
if (parts[1].hasPrefix("(N-term") || parts[1].hasPrefix("(C-term"))
{
mods.push_back(mod);
return mods;
}
// format e.g. Phospho (ST)
ModificationsDB* mod_db = ModificationsDB::getInstance();
String AAs = parts[1];
AAs.remove(')');
AAs.remove('(');
for (String::const_iterator it = AAs.begin(); it != AAs.end(); ++it)
{
String tmp_mod = parts[0] + " (" + *it + ")";
if (mod_db->has(tmp_mod))
{
mods.push_back(tmp_mod);
}
else
{
throw Exception::ElementNotFound(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, tmp_mod);
}
}
return mods;
}
} // namespace OpenMS // namespace Internal
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/HANDLERS/CachedMzMLHandler.cpp | .cpp | 19,790 | 570 | // 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/HANDLERS/CachedMzMLHandler.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/FORMAT/MzMLFile.h>
#include <OpenMS/SYSTEM/File.h>
namespace OpenMS::Internal
{
CachedMzMLHandler::CachedMzMLHandler() = default;
CachedMzMLHandler::~CachedMzMLHandler() = default;
CachedMzMLHandler& CachedMzMLHandler::operator=(const CachedMzMLHandler& rhs)
{
if (&rhs == this)
{
return *this;
}
spectra_index_ = rhs.spectra_index_;
chrom_index_ = rhs.chrom_index_;
return *this;
}
void CachedMzMLHandler::writeMemdump(const MapType& exp, const String& out) const
{
std::ofstream ofs(out.c_str(), std::ios::binary);
Size exp_size = exp.size();
Size chrom_size = exp.getChromatograms().size();
int file_identifier = CACHED_MZML_FILE_IDENTIFIER;
ofs.write((char*)&file_identifier, sizeof(file_identifier));
startProgress(0, exp.size() + exp.getChromatograms().size(), "storing binary data");
for (Size i = 0; i < exp.size(); i++)
{
setProgress(i);
writeSpectrum_(exp[i], ofs);
}
for (Size i = 0; i < exp.getChromatograms().size(); i++)
{
setProgress(i);
writeChromatogram_(exp.getChromatograms()[i], ofs);
}
ofs.write((char*)&exp_size, sizeof(exp_size));
ofs.write((char*)&chrom_size, sizeof(chrom_size));
ofs.close();
endProgress();
}
void CachedMzMLHandler::readMemdump(MapType& exp_reading, const String& filename) const
{
std::ifstream ifs(filename.c_str(), std::ios::binary);
if (ifs.fail())
{
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);
}
}
Size exp_size, chrom_size;
int file_identifier;
ifs.read((char*)&file_identifier, sizeof(file_identifier));
if (file_identifier != CACHED_MZML_FILE_IDENTIFIER)
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"File might not be a cached mzML file (wrong file magic number). Aborting!", filename);
}
ifs.seekg(0, ifs.end); // set file pointer to end
ifs.seekg(ifs.tellg(), ifs.beg); // set file pointer to end, in forward direction
ifs.seekg(- static_cast<int>(sizeof(exp_size) + sizeof(chrom_size)), ifs.cur); // move two fields to the left, start reading
ifs.read((char*)&exp_size, sizeof(exp_size));
ifs.read((char*)&chrom_size, sizeof(chrom_size));
ifs.seekg(sizeof(file_identifier), ifs.beg); // set file pointer to beginning (after identifier), start reading
exp_reading.reserve(exp_size);
startProgress(0, exp_size + chrom_size, "reading binary data");
for (Size i = 0; i < exp_size; i++)
{
setProgress(i);
SpectrumType spectrum;
readSpectrum(spectrum, ifs);
exp_reading.addSpectrum(spectrum);
}
std::vector<ChromatogramType> chromatograms;
for (Size i = 0; i < chrom_size; i++)
{
setProgress(i);
ChromatogramType chromatogram;
readChromatogram(chromatogram, ifs);
chromatograms.push_back(chromatogram);
}
exp_reading.setChromatograms(chromatograms);
ifs.close();
endProgress();
}
const std::vector<std::streampos>& CachedMzMLHandler::getSpectraIndex() const
{
return spectra_index_;
}
const std::vector<std::streampos>& CachedMzMLHandler::getChromatogramIndex() const
{
return chrom_index_;
}
void CachedMzMLHandler::createMemdumpIndex(const String& filename)
{
std::ifstream ifs(filename.c_str(), std::ios::binary);
if (ifs.fail())
{
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);
}
}
Size exp_size, chrom_size;
ifs.seekg(0, ifs.beg); // set file pointer to beginning, start reading
spectra_index_.clear();
chrom_index_.clear();
int file_identifier;
int extra_offset = sizeof(DoubleType) + sizeof(IntType);
int chrom_offset = 0;
ifs.read((char*)&file_identifier, sizeof(file_identifier));
if (file_identifier != CACHED_MZML_FILE_IDENTIFIER)
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"File might not be a cached mzML file (wrong file magic number). Aborting!", filename);
}
// For spectra and chromatograms go through file, read the size of the
// spectrum/chromatogram and record the starting index of the element, then
// skip ahead to the next spectrum/chromatogram.
ifs.seekg(0, ifs.end); // set file pointer to end
ifs.seekg(ifs.tellg(), ifs.beg); // set file pointer to end, in forward direction
ifs.seekg(- static_cast<int>(sizeof(exp_size) + sizeof(chrom_size)), ifs.cur); // move two fields to the left, start reading
ifs.read((char*)&exp_size, sizeof(exp_size));
ifs.read((char*)&chrom_size, sizeof(chrom_size));
ifs.seekg(sizeof(file_identifier), ifs.beg); // set file pointer to beginning (after identifier), start reading
startProgress(0, exp_size + chrom_size, "Creating index for binary spectra");
for (Size i = 0; i < exp_size; i++)
{
setProgress(i);
Size spec_size;
Size float_arr;
spectra_index_.push_back(ifs.tellg());
ifs.read((char*)&spec_size, sizeof(spec_size));
ifs.read((char*)&float_arr, sizeof(float_arr));
ifs.seekg(extra_offset + (sizeof(DatumSingleton)) * 2 * (spec_size), ifs.cur);
// Read the extra data arrays
for (Size k = 0; k < float_arr; k++)
{
Size len, len_name;
ifs.read((char*)&len, sizeof(len));
ifs.read((char*)&len_name, sizeof(len_name));
ifs.seekg(len_name * sizeof(char), ifs.cur);
ifs.seekg(sizeof(DatumSingleton) * len, ifs.cur);
}
}
for (Size i = 0; i < chrom_size; i++)
{
setProgress(i);
Size ch_size;
Size float_arr;
chrom_index_.push_back(ifs.tellg());
ifs.read((char*)&ch_size, sizeof(ch_size));
ifs.read((char*)&float_arr, sizeof(float_arr));
ifs.seekg(chrom_offset + (sizeof(DatumSingleton)) * 2 * (ch_size), ifs.cur);
// Read the extra data arrays
for (Size k = 0; k < float_arr; k++)
{
Size len, len_name;
ifs.read((char*)&len, sizeof(len));
ifs.read((char*)&len_name, sizeof(len_name));
ifs.seekg(len_name * sizeof(char), ifs.cur);
ifs.seekg(sizeof(DatumSingleton) * len, ifs.cur);
}
}
ifs.close();
endProgress();
}
void CachedMzMLHandler::writeMetadata(MapType exp, const String& out_meta, bool addCacheMetaValue)
{
// delete the actual data for all spectra and chromatograms, leave only metadata
// TODO : remove copy
std::vector<MSChromatogram > chromatograms = exp.getChromatograms(); // copy
for (Size i = 0; i < exp.size(); i++)
{
exp[i].clear(false);
}
for (Size i = 0; i < exp.getChromatograms().size(); i++)
{
chromatograms[i].clear(false);
}
exp.setChromatograms(chromatograms);
if (addCacheMetaValue)
{
// set dataprocessing on each spectrum/chromatogram
std::shared_ptr< DataProcessing > dp = std::shared_ptr< DataProcessing >(new DataProcessing);
std::set<DataProcessing::ProcessingAction> actions;
actions.insert(DataProcessing::FORMAT_CONVERSION);
dp->setProcessingActions(actions);
dp->setMetaValue("cached_data", "true");
for (Size i=0; i<exp.size(); ++i)
{
exp[i].getDataProcessing().push_back(dp);
}
std::vector<MSChromatogram > l_chromatograms = exp.getChromatograms();
for (Size i=0; i<l_chromatograms.size(); ++i)
{
l_chromatograms[i].getDataProcessing().push_back(dp);
}
exp.setChromatograms(l_chromatograms);
}
// store the meta data using the regular MzMLFile
MzMLFile().store(out_meta, exp);
}
void CachedMzMLHandler::writeMetadata_x(const MapType& exp, const String& out_meta, const bool addCacheMetaValue)
{
// delete the actual data for all spectra and chromatograms, leave only metadata
// TODO : remove copy
const ExperimentalSettings& qq = exp;
MSExperiment out_exp;
out_exp = qq;
// std::vector<MSChromatogram > chromatograms = exp.getChromatograms(); // copy
for (const auto& s: exp)
{
out_exp.addSpectrum(s);
out_exp.getSpectra().back().clear(false);
}
for (const auto& c: exp.getChromatograms())
{
out_exp.addChromatogram(c);
out_exp.getChromatograms().back().clear(false);
}
if (addCacheMetaValue)
{
// set dataprocessing on each spectrum/chromatogram
std::shared_ptr< DataProcessing > dp = std::shared_ptr< DataProcessing >(new DataProcessing);
std::set<DataProcessing::ProcessingAction> actions;
actions.insert(DataProcessing::FORMAT_CONVERSION);
dp->setProcessingActions(actions);
dp->setMetaValue("cached_data", "true");
for (Size i=0; i<out_exp.size(); ++i)
{
out_exp[i].getDataProcessing().push_back(dp);
}
std::vector<MSChromatogram > l_chromatograms = out_exp.getChromatograms();
for (Size i=0; i<l_chromatograms.size(); ++i)
{
l_chromatograms[i].getDataProcessing().push_back(dp);
}
out_exp.setChromatograms(l_chromatograms);
}
// store the meta data using the regular MzMLFile
MzMLFile().store(out_meta, out_exp);
}
std::vector<OpenSwath::BinaryDataArrayPtr> CachedMzMLHandler::readSpectrumFast(std::ifstream& ifs, int& ms_level, double& rt)
{
std::vector<OpenSwath::BinaryDataArrayPtr> data;
data.push_back(OpenSwath::BinaryDataArrayPtr(new OpenSwath::BinaryDataArray));
data.push_back(OpenSwath::BinaryDataArrayPtr(new OpenSwath::BinaryDataArray));
Size spec_size = -1;
Size nr_float_arrays = -1;
ifs.read((char*) &spec_size, sizeof(spec_size));
ifs.read((char*) &nr_float_arrays, sizeof(nr_float_arrays));
ifs.read((char*) &ms_level, sizeof(ms_level));
ifs.read((char*) &rt, sizeof(rt));
if (static_cast<int>(spec_size) < 0)
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Read an invalid spectrum length, something is wrong here. Aborting.", "filestream");
}
readDataFast_(ifs, data, spec_size, nr_float_arrays);
return data;
}
void CachedMzMLHandler::readDataFast_(std::ifstream& ifs,
std::vector<OpenSwath::BinaryDataArrayPtr>& data,
const Size& data_size,
const Size& nr_float_arrays)
{
OPENMS_PRECONDITION(data.size() == 2, "Input data needs to have 2 slots.")
data[0]->data.resize(data_size);
data[1]->data.resize(data_size);
if (data_size > 0)
{
ifs.read((char*) &(data[0]->data)[0], data_size * sizeof(DatumSingleton));
ifs.read((char*) &(data[1]->data)[0], data_size * sizeof(DatumSingleton));
}
if (nr_float_arrays == 0)
{
return;
}
char* buffer = new(std::nothrow) char[1024];
for (Size k = 0; k < nr_float_arrays; k++)
{
data.push_back(OpenSwath::BinaryDataArrayPtr(new OpenSwath::BinaryDataArray));
Size len, len_name;
ifs.read((char*)&len, sizeof(len));
ifs.read((char*)&len_name, sizeof(len_name));
// We will not read data longer than 1024 bytes as this will not fit into
// our buffer (and is user-generated input data)
if (len_name > 1023)
{
ifs.seekg(len_name * sizeof(char), ifs.cur);
}
else
{
ifs.read(buffer, len_name);
buffer[len_name] = '\0';
}
data.back()->data.resize(len);
data.back()->description = buffer;
ifs.read((char*)&(data.back()->data)[0], len * sizeof(DatumSingleton));
}
delete[] buffer;
return;
}
std::vector<OpenSwath::BinaryDataArrayPtr> CachedMzMLHandler::readChromatogramFast(std::ifstream& ifs)
{
std::vector<OpenSwath::BinaryDataArrayPtr> data;
data.push_back(OpenSwath::BinaryDataArrayPtr(new OpenSwath::BinaryDataArray));
data.push_back(OpenSwath::BinaryDataArrayPtr(new OpenSwath::BinaryDataArray));
Size chrom_size = -1;
Size nr_float_arrays = -1;
ifs.read((char*) &chrom_size, sizeof(chrom_size));
ifs.read((char*) &nr_float_arrays, sizeof(nr_float_arrays));
if (static_cast<int>(chrom_size) < 0)
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Read an invalid chromatogram length, something is wrong here. Aborting.", "filestream");
}
readDataFast_(ifs, data, chrom_size, nr_float_arrays);
return data;
}
void CachedMzMLHandler::readSpectrum(SpectrumType& spectrum, std::ifstream& ifs)
{
int ms_level;
double rt;
std::vector<OpenSwath::BinaryDataArrayPtr> data = readSpectrumFast(ifs, ms_level, rt);
spectrum.reserve(data[0]->data.size());
spectrum.setMSLevel(ms_level);
spectrum.setRT(rt);
for (Size j = 0; j < data[0]->data.size(); j++)
{
Peak1D p;
p.setMZ(data[0]->data[j]);
p.setIntensity(data[1]->data[j]);
spectrum.push_back(p);
}
for (Size j = 2; j < data.size(); j++)
{
spectrum.getFloatDataArrays().push_back(MSSpectrum::FloatDataArray());
spectrum.getFloatDataArrays().back().reserve(data[j]->data.size());
spectrum.getFloatDataArrays().back().setName(data[j]->description);
for (const auto& k : data[j]->data) spectrum.getFloatDataArrays().back().push_back(k);
}
}
void CachedMzMLHandler::readChromatogram(ChromatogramType& chromatogram, std::ifstream& ifs)
{
std::vector<OpenSwath::BinaryDataArrayPtr> data = readChromatogramFast(ifs);
chromatogram.reserve(data[0]->data.size());
for (Size j = 0; j < data[0]->data.size(); j++)
{
ChromatogramPeak p;
p.setRT(data[0]->data[j]);
p.setIntensity(data[1]->data[j]);
chromatogram.push_back(p);
}
MSChromatogram::FloatDataArrays fdas;
for (Size j = 2; j < data.size(); j++)
{
MSChromatogram::FloatDataArray fda;
fda.reserve(data[j]->data.size());
for (const auto& k : fda) fda.push_back(k);
fda.setName(data[j]->description);
fdas.push_back(fda);
}
chromatogram.setFloatDataArrays(fdas);
}
void CachedMzMLHandler::writeSpectrum_(const SpectrumType& spectrum, std::ofstream& ofs) const
{
Size exp_size = spectrum.size();
ofs.write((char*)&exp_size, sizeof(exp_size));
Size arr_s = spectrum.getFloatDataArrays().size() + spectrum.getIntegerDataArrays().size();
ofs.write((char*)&arr_s, sizeof(arr_s));
IntType int_field_ = spectrum.getMSLevel();
ofs.write((char*)&int_field_, sizeof(int_field_));
DoubleType dbl_field_ = spectrum.getRT();
ofs.write((char*)&dbl_field_, sizeof(dbl_field_));
// Catch empty spectrum: we do not write any data and since the "size" we
// just wrote is zero, no data will be read
if (spectrum.empty())
{
return;
}
Datavector mz_data;
Datavector int_data;
mz_data.reserve(spectrum.size());
int_data.reserve(spectrum.size());
for (Size j = 0; j < spectrum.size(); j++)
{
mz_data.push_back(spectrum[j].getMZ());
int_data.push_back(static_cast<double>(spectrum[j].getIntensity()));
}
ofs.write((char*)&mz_data.front(), mz_data.size() * sizeof(mz_data.front()));
ofs.write((char*)&int_data.front(), int_data.size() * sizeof(int_data.front()));
Datavector tmp;
for (const auto& fda : spectrum.getFloatDataArrays() )
{
Size len = fda.size();
ofs.write((char*)&len, sizeof(len));
Size len_name = fda.getName().size();
ofs.write((char*)&len_name, sizeof(len_name));
ofs.write((char*)&fda.getName().front(), len_name * sizeof(fda.getName().front()));
// now go to the actual data
tmp.clear();
tmp.reserve(fda.size());
for (const auto& val : fda) {tmp.push_back(val);}
ofs.write((char*)&tmp.front(), tmp.size() * sizeof(tmp.front()));
}
for (const auto& ida : spectrum.getIntegerDataArrays() )
{
Size len = ida.size();
ofs.write((char*)&len, sizeof(len));
Size len_name = ida.getName().size();
ofs.write((char*)&len_name, sizeof(len_name));
ofs.write((char*)&ida.getName().front(), len_name * sizeof(ida.getName().front()));
// now go to the actual data
tmp.clear();
tmp.reserve(ida.size());
for (const auto& val : ida) {tmp.push_back(val);}
ofs.write((char*)&tmp.front(), tmp.size() * sizeof(tmp.front()));
}
}
void CachedMzMLHandler::writeChromatogram_(const ChromatogramType& chromatogram, std::ofstream& ofs) const
{
Size exp_size = chromatogram.size();
ofs.write((char*)&exp_size, sizeof(exp_size));
Size arr_s = chromatogram.getFloatDataArrays().size() + chromatogram.getIntegerDataArrays().size();
ofs.write((char*)&arr_s, sizeof(arr_s));
// Catch empty chromatogram: we do not write any data and since the "size" we
// just wrote is zero, no data will be read
if (chromatogram.empty())
{
return;
}
Datavector rt_data;
Datavector int_data;
rt_data.reserve(chromatogram.size());
int_data.reserve(chromatogram.size());
for (Size j = 0; j < chromatogram.size(); j++)
{
rt_data.push_back(chromatogram[j].getRT());
int_data.push_back(chromatogram[j].getIntensity());
}
ofs.write((char*)&rt_data.front(), rt_data.size() * sizeof(rt_data.front()));
ofs.write((char*)&int_data.front(), int_data.size() * sizeof(int_data.front()));
Datavector tmp;
for (const auto& fda : chromatogram.getFloatDataArrays() )
{
Size len = fda.size();
ofs.write((char*)&len, sizeof(len));
Size len_name = fda.getName().size();
ofs.write((char*)&len_name, sizeof(len_name));
ofs.write((char*)&fda.getName().front(), len_name * sizeof(fda.getName().front()));
// now go to the actual data
tmp.clear();
tmp.reserve(fda.size());
for (const auto& val : fda)
{
tmp.push_back(val);
}
ofs.write((char*)&tmp.front(), tmp.size() * sizeof(tmp.front()));
}
for (const auto& ida : chromatogram.getIntegerDataArrays() )
{
Size len = ida.size();
ofs.write((char*)&len, sizeof(len));
Size len_name = ida.getName().size();
ofs.write((char*)&len_name, sizeof(len_name));
ofs.write((char*)&ida.getName().front(), len_name * sizeof(ida.getName().front()));
// now go to the actual data
tmp.clear();
tmp.reserve(ida.size());
for (const auto& val : ida)
{
tmp.push_back(val);
}
ofs.write((char*)&tmp.front(), tmp.size() * sizeof(tmp.front()));
}
}
}//namespace OpenMS //namespace Internal
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/HANDLERS/FeatureXMLHandler.cpp | .cpp | 39,440 | 1,115 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Marc Sturm, Chris Bielow, Clemens Groepl $
// --------------------------------------------------------------------------
#include <OpenMS/FORMAT/HANDLERS/FeatureXMLHandler.h>
#include <OpenMS/CHEMISTRY/ProteaseDB.h>
#include <OpenMS/CONCEPT/UniqueIdGenerator.h>
#include <OpenMS/FORMAT/FileHandler.h>
#include <OpenMS/FORMAT/IdXMLFile.h>
#include <OpenMS/KERNEL/FeatureMap.h>
#include <OpenMS/METADATA/DataProcessing.h>
#include <fstream>
#include <map>
using namespace std;
namespace OpenMS::Internal
{
FeatureXMLHandler::FeatureXMLHandler(FeatureMap& map, const String& filename) :
Internal::XMLHandler("", "1.9")
{
resetMembers_();
map_ = ↦
file_ = filename;
}
FeatureXMLHandler::FeatureXMLHandler(const FeatureMap& map, const String& filename) :
Internal::XMLHandler("", "1.9")
{
resetMembers_();
cmap_ = ↦
file_ = filename;
}
FeatureXMLHandler::~FeatureXMLHandler() = default;
void FeatureXMLHandler::resetMembers_()
{
disable_parsing_ = 0;
current_feature_ = nullptr;
map_ = nullptr;
//options_ = FeatureFileOptions(); do NOT reset this, since we need to preserve options!
size_only_ = false;
expected_size_ = 0;
param_ = Param();
current_chull_ = ConvexHull2D::PointArrayType();
hull_position_ = DPosition<2>();
dim_ = 0;
in_description_ = false;
subordinate_feature_level_ = 0;
last_meta_ = nullptr;
prot_id_ = ProteinIdentification();
pep_id_ = PeptideIdentification();
prot_hit_ = ProteinHit();
pep_hit_ = PeptideHit();
proteinid_to_accession_.clear();
accession_to_id_.clear();
identifier_id_.clear();
id_identifier_.clear();
search_param_ = ProteinIdentification::SearchParameters();
}
void FeatureXMLHandler::writeTo(std::ostream& os)
{
const FeatureMap& feature_map = *(cmap_);
os << "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"
<< "<featureMap version=\"" << version_ << "\"";
// file id
if (!feature_map.getIdentifier().empty())
{
os << " document_id=\"" << feature_map.getIdentifier() << "\"";
}
// unique id
if (feature_map.hasValidUniqueId())
{
os << " id=\"fm_" << feature_map.getUniqueId() << "\"";
}
os << " xsi:noNamespaceSchemaLocation=\"https://raw.githubusercontent.com/OpenMS/OpenMS/develop/share/OpenMS/SCHEMAS/FeatureXML_1_9.xsd\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n";
// user param
writeUserParam_("UserParam", os, feature_map, 1);
// write data processing
for (Size i = 0; i < feature_map.getDataProcessing().size(); ++i)
{
const DataProcessing& processing = feature_map.getDataProcessing()[i];
os << "\t<dataProcessing completion_time=\"" << processing.getCompletionTime().getDate() << 'T' << processing.getCompletionTime().getTime() << "\">\n";
os << "\t\t<software name=\"" << processing.getSoftware().getName() << "\" version=\"" << processing.getSoftware().getVersion() << "\" />\n";
for (set<DataProcessing::ProcessingAction>::const_iterator it = processing.getProcessingActions().begin(); it != processing.getProcessingActions().end(); ++it)
{
os << "\t\t<processingAction name=\"" << DataProcessing::NamesOfProcessingAction[*it] << "\" />\n";
}
writeUserParam_("UserParam", os, processing, 2);
os << "\t</dataProcessing>\n";
}
// throws if protIDs are not unique, i.e. PeptideIDs will be randomly assigned (bad!)
checkUniqueIdentifiers_(feature_map.getProteinIdentifications());
// write identification runs
Size prot_count = 0;
for (Size i = 0; i < feature_map.getProteinIdentifications().size(); ++i)
{
const ProteinIdentification& current_prot_id = feature_map.getProteinIdentifications()[i];
os << "\t<IdentificationRun ";
os << "id=\"PI_" << i << "\" ";
identifier_id_[current_prot_id.getIdentifier()] = String("PI_") + i;
os << "date=\"" << current_prot_id.getDateTime().getDate() << "T" << current_prot_id.getDateTime().getTime() << "\" ";
os << "search_engine=\"" << writeXMLEscape(current_prot_id.getSearchEngine()) << "\" ";
os << "search_engine_version=\"" << writeXMLEscape(current_prot_id.getSearchEngineVersion()) << "\">\n";
//write search parameters
const ProteinIdentification::SearchParameters& search_param = current_prot_id.getSearchParameters();
os << "\t\t<SearchParameters "
<< "db=\"" << writeXMLEscape(search_param.db) << "\" "
<< "db_version=\"" << writeXMLEscape(search_param.db_version) << "\" "
<< "taxonomy=\"" << writeXMLEscape(search_param.taxonomy) << "\" ";
if (search_param.mass_type == ProteinIdentification::PeakMassType::MONOISOTOPIC)
{
os << "mass_type=\"monoisotopic\" ";
}
else if (search_param.mass_type == ProteinIdentification::PeakMassType::AVERAGE)
{
os << "mass_type=\"average\" ";
}
os << "charges=\"" << search_param.charges << "\" ";
String enzyme_name = search_param.digestion_enzyme.getName();
os << "enzyme=\"" << enzyme_name.toLower() << "\" ";
String precursor_unit = search_param.precursor_mass_tolerance_ppm ? "true" : "false";
String peak_unit = search_param.fragment_mass_tolerance_ppm ? "true" : "false";
os << "missed_cleavages=\"" << search_param.missed_cleavages << "\" "
<< "precursor_peak_tolerance=\"" << search_param.precursor_mass_tolerance << "\" ";
os << "precursor_peak_tolerance_ppm=\"" << precursor_unit << "\" ";
os << "peak_mass_tolerance=\"" << search_param.fragment_mass_tolerance << "\" ";
os << "peak_mass_tolerance_ppm=\"" << peak_unit << "\" ";
os << ">\n";
//modifications
for (Size j = 0; j != search_param.fixed_modifications.size(); ++j)
{
os << "\t\t\t<FixedModification name=\"" << writeXMLEscape(search_param.fixed_modifications[j]) << "\" />\n";
//Add MetaInfo, when modifications has it (Andreas)
}
for (Size j = 0; j != search_param.variable_modifications.size(); ++j)
{
os << "\t\t\t<VariableModification name=\"" << writeXMLEscape(search_param.variable_modifications[j]) << "\" />\n";
//Add MetaInfo, when modifications has it (Andreas)
}
writeUserParam_("UserParam", os, search_param, 3);
os << "\t\t</SearchParameters>\n";
//write protein identifications
os << "\t\t<ProteinIdentification";
os << " score_type=\"" << writeXMLEscape(current_prot_id.getScoreType()) << "\"";
os << " higher_score_better=\"" << (current_prot_id.isHigherScoreBetter() ? "true" : "false") << "\"";
os << " significance_threshold=\"" << current_prot_id.getSignificanceThreshold() << "\">\n";
// write protein hits
for (Size j = 0; j < current_prot_id.getHits().size(); ++j)
{
os << "\t\t\t<ProteinHit";
// prot_count
os << " id=\"PH_" << prot_count << "\"";
accession_to_id_[current_prot_id.getIdentifier() + "_" + current_prot_id.getHits()[j].getAccession()] = prot_count;
++prot_count;
os << " accession=\"" << writeXMLEscape(current_prot_id.getHits()[j].getAccession()) << "\"";
os << " score=\"" << current_prot_id.getHits()[j].getScore() << "\"";
double coverage = current_prot_id.getHits()[j].getCoverage();
if (coverage != ProteinHit::COVERAGE_UNKNOWN)
{
os << " coverage=\"" << coverage << "\"";
}
os << " sequence=\"" << writeXMLEscape(current_prot_id.getHits()[j].getSequence()) << "\">\n";
writeUserParam_("UserParam", os, current_prot_id.getHits()[j], 4);
os << "\t\t\t</ProteinHit>\n";
}
writeUserParam_("UserParam", os, current_prot_id, 3);
os << "\t\t</ProteinIdentification>\n";
os << "\t</IdentificationRun>\n";
}
//write unassigned peptide identifications
for (Size i = 0; i < feature_map.getUnassignedPeptideIdentifications().size(); ++i)
{
writePeptideIdentification_(file_, os, feature_map.getUnassignedPeptideIdentifications()[i], "UnassignedPeptideIdentification", 1);
}
// write features with their corresponding attributes
os << "\t<featureList count=\"" << feature_map.size() << "\">\n";
startProgress(0, feature_map.size(), "Storing featureXML file");
for (Size s = 0; s < feature_map.size(); s++)
{
writeFeature_(file_, os, feature_map[s], "f_", feature_map[s].getUniqueId(), 0);
setProgress(s);
// writeFeature_(file_, os, feature_map[s], "f_", s, 0);
}
endProgress();
os << "\t</featureList>\n";
os << "</featureMap>\n";
//Clear members
accession_to_id_.clear();
identifier_id_.clear();
}
FeatureFileOptions& FeatureXMLHandler::getOptions()
{
return options_;
}
const FeatureFileOptions& FeatureXMLHandler::getOptions() const
{
return options_;
}
void FeatureXMLHandler::setOptions(const FeatureFileOptions& options)
{
options_ = options;
}
void FeatureXMLHandler::startElement(const XMLCh* const /*uri*/, const XMLCh* const /*local_name*/, const XMLCh* const qname, const xercesc::Attributes& attributes)
{
static const XMLCh* s_dim = xercesc::XMLString::transcode("dim");
static const XMLCh* s_name = xercesc::XMLString::transcode("name");
static const XMLCh* s_version = xercesc::XMLString::transcode("version");
static const XMLCh* s_value = xercesc::XMLString::transcode("value");
static const XMLCh* s_type = xercesc::XMLString::transcode("type");
static const XMLCh* s_completion_time = xercesc::XMLString::transcode("completion_time");
static const XMLCh* s_document_id = xercesc::XMLString::transcode("document_id");
static const XMLCh* s_id = xercesc::XMLString::transcode("id");
// TODO The next line should be removed in OpenMS 1.7 or so!
static const XMLCh* s_unique_id = xercesc::XMLString::transcode("unique_id");
String tag = sm_.convert(qname);
// handle skipping of whole sections
// IMPORTANT: check parent tags first (i.e. tags higher in the tree), since otherwise sections might be enabled/disabled too early/late
// disable_parsing_ is an Int, since subordinates might be chained, thus at SO-level 2, the endelement() would switch on parsing again
// , even though the end of the parent SO was not reached
if ((!options_.getLoadSubordinates()) && tag == "subordinate")
{
++disable_parsing_;
}
else if ((!options_.getLoadConvexHull()) && tag == "convexhull")
{
++disable_parsing_;
}
if (disable_parsing_)
{
return;
}
// do the actual parsing:
String parent_tag;
if (!open_tags_.empty())
{
parent_tag = open_tags_.back();
}
open_tags_.push_back(tag);
//for downward compatibility, all tags in the old description must be ignored
if (in_description_)
{
return;
}
if (tag == "description")
{
in_description_ = true;
}
else if (tag == "feature")
{
// create new feature at appropriate level
updateCurrentFeature_(true);
current_feature_->setUniqueId(attributeAsString_(attributes, s_id));
}
else if (tag == "subordinate") // this is not safe towards malformed xml!
{
++subordinate_feature_level_;
}
else if (tag == "featureList")
{
if (options_.getMetadataOnly())
{
throw EndParsingSoftly(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
Size count = attributeAsInt_(attributes, "count");
if (size_only_) // true if loadSize() was used instead of load()
{
expected_size_ = count;
throw EndParsingSoftly(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
map_->reserve(std::min(Size(1e5), count)); // reserve vector for faster push_back, but with upper boundary of 1e5 (as >1e5 is most likely an invalid feature count)
startProgress(0, count, "Loading featureXML file");
}
else if (tag == "quality" || tag == "hposition" || tag == "position")
{
dim_ = attributeAsInt_(attributes, s_dim);
}
else if (tag == "pt")
{
hull_position_[0] = attributeAsDouble_(attributes, "x");
hull_position_[1] = attributeAsDouble_(attributes, "y");
}
else if (tag == "convexhull")
{
current_chull_.clear();
}
else if (tag == "hullpoint")
{
hull_position_ = DPosition<2>::zero();
}
else if (tag == "param")
{
String name = attributeAsString_(attributes, s_name);
String value = attributeAsString_(attributes, s_value);
if (!name.empty() && !value.empty())
param_.setValue(name, value);
}
else if (tag == "userParam" || tag == "UserParam") // correct: "UserParam". Test for backwards compatibility.
{
if (last_meta_ == nullptr)
{
fatalError(LOAD, String("Unexpected UserParam in tag '") + parent_tag + "'");
}
String name = attributeAsString_(attributes, s_name);
String type = attributeAsString_(attributes, s_type);
if (type == "int")
{
last_meta_->setMetaValue(name, attributeAsInt_(attributes, s_value));
}
else if (type == "float")
{
last_meta_->setMetaValue(name, attributeAsDouble_(attributes, s_value));
}
else if (type == "string")
{
last_meta_->setMetaValue(name, (String)attributeAsString_(attributes, s_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 + "'");
}
}
else if (tag == "featureMap")
{
//check file version against schema version
String file_version = "";
optionalAttributeAsString_(file_version, attributes, s_version);
if (file_version.empty())
{
file_version = "1.0"; //default version is 1.0
}
if (file_version.toDouble() > version_.toDouble())
{
warning(LOAD, String("The XML file (") + file_version + ") is newer than the parser (" + version_ + "). This might lead to undefined program behavior.");
}
//handle document id
String document_id;
if (optionalAttributeAsString_(document_id, attributes, s_document_id))
{
map_->setIdentifier(document_id);
}
//handle unique id
String unique_id;
if (optionalAttributeAsString_(unique_id, attributes, s_id))
{
map_->setUniqueId(unique_id);
}
// TODO The next four lines should be removed in OpenMS 1.7 or so!
if (optionalAttributeAsString_(unique_id, attributes, s_unique_id))
{
map_->setUniqueId(unique_id);
}
last_meta_ = map_;
}
else if (tag == "dataProcessing")
{
DataProcessing tmp;
tmp.setCompletionTime(asDateTime_(attributeAsString_(attributes, s_completion_time)));
map_->getDataProcessing().push_back(tmp);
last_meta_ = &(map_->getDataProcessing().back());
}
else if (tag == "software" && parent_tag == "dataProcessing")
{
map_->getDataProcessing().back().getSoftware().setName(attributeAsString_(attributes, s_name));
map_->getDataProcessing().back().getSoftware().setVersion(attributeAsString_(attributes, s_version));
}
else if (tag == "processingAction" && parent_tag == "dataProcessing")
{
String name = attributeAsString_(attributes, s_name);
for (Size i = 0; i < DataProcessing::SIZE_OF_PROCESSINGACTION; ++i)
{
if (name == DataProcessing::NamesOfProcessingAction[i])
{
map_->getDataProcessing().back().getProcessingActions().insert((DataProcessing::ProcessingAction)i);
}
}
}
else if (tag == "IdentificationRun")
{
prot_id_.setSearchEngine(attributeAsString_(attributes, "search_engine"));
prot_id_.setSearchEngineVersion(attributeAsString_(attributes, "search_engine_version"));
prot_id_.setDateTime(DateTime::fromString(attributeAsString_(attributes, "date")));
// set identifier
// always generate a unique id to link a ProteinIdentification and the corresponding PeptideIdentifications
// , since any FeatureLinker might just carelessly concatenate PepIDs from different FeatureMaps.
// If these FeatureMaps have identical identifiers (SearchEngine time + type match exactly), then ALL PepIDs would be falsely attributed
// to a single ProtID...
String id = attributeAsString_(attributes, "id");
while (true)
{ // loop until the identifier is unique (should be on the first iteration -- very(!) unlikely it will not be unique)
// 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)
String identifier = prot_id_.getSearchEngine() + '_' + attributeAsString_(attributes, "date") + '_' + String(UniqueIdGenerator::getUniqueId());
if (id_identifier_.find(id) == id_identifier_.end())
{
prot_id_.setIdentifier(identifier);
id_identifier_[id] = identifier;
break;
}
}
}
else if (tag == "SearchParameters")
{
//load parameters
search_param_.db = attributeAsString_(attributes, "db");
search_param_.db_version = attributeAsString_(attributes, "db_version");
optionalAttributeAsString_(search_param_.taxonomy, attributes, "taxonomy");
search_param_.charges = attributeAsString_(attributes, "charges");
optionalAttributeAsUInt_(search_param_.missed_cleavages, attributes, "missed_cleavages");
search_param_.fragment_mass_tolerance = attributeAsDouble_(attributes, "peak_mass_tolerance");
String peak_unit;
optionalAttributeAsString_(peak_unit, attributes, "peak_mass_tolerance_ppm");
search_param_.fragment_mass_tolerance_ppm = peak_unit == "true" ? true : false;
search_param_.precursor_mass_tolerance = attributeAsDouble_(attributes, "precursor_peak_tolerance");
String precursor_unit;
optionalAttributeAsString_(precursor_unit, attributes, "precursor_peak_tolerance_ppm");
search_param_.precursor_mass_tolerance_ppm = precursor_unit == "true" ? true : false;
//mass type
String mass_type = attributeAsString_(attributes, "mass_type");
if (mass_type == "monoisotopic")
{
search_param_.mass_type = ProteinIdentification::PeakMassType::MONOISOTOPIC;
}
else if (mass_type == "average")
{
search_param_.mass_type = ProteinIdentification::PeakMassType::AVERAGE;
}
//enzyme
String enzyme;
optionalAttributeAsString_(enzyme, attributes, "enzyme");
if (ProteaseDB::getInstance()->hasEnzyme(enzyme))
{
search_param_.digestion_enzyme = *(ProteaseDB::getInstance()->getEnzyme(enzyme));
}
last_meta_ = &search_param_;
}
else if (tag == "FixedModification")
{
search_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")
{
search_param_.variable_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 == "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(tmp);
last_meta_ = &prot_hit_;
//insert id and accession to map
proteinid_to_accession_[attributeAsString_(attributes, "id")] = accession;
}
else if (tag == "PeptideIdentification" || tag == "UnassignedPeptideIdentification")
{
String id = attributeAsString_(attributes, "identification_run_ref");
if (id_identifier_.find(id) == id_identifier_.end())
{
warning(LOAD, String("Peptide identification without ProteinIdentification found (id: '") + id + "')!");
}
pep_id_.setIdentifier(id_identifier_[id]);
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 = -numeric_limits<double>::max();
optionalAttributeAsDouble_(tmp2, attributes, "MZ");
if (tmp2 != -numeric_limits<double>::max())
{
pep_id_.setMZ(tmp2);
}
//RT
tmp2 = -numeric_limits<double>::max();
optionalAttributeAsDouble_(tmp2, attributes, "RT");
if (tmp2 != -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();
vector<PeptideEvidence> peptide_evidences_;
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();
vector<String> accessions;
accession_string.split(' ', accessions);
if (!accession_string.empty() && accessions.empty())
{
accessions.push_back(accession_string);
}
for (vector<String>::const_iterator it = accessions.begin(); it != accessions.end(); ++it)
{
std::map<String, String>::const_iterator it2 = proteinid_to_accession_.find(*it);
if (it2 != proteinid_to_accession_.end())
{
PeptideEvidence pe;
pe.setProteinAccession(it2->second);
peptide_evidences_.push_back(pe);
}
else
{
fatalError(LOAD, String("Invalid protein reference '") + *it + "'");
}
}
}
//aa_before
String tmp = "";
optionalAttributeAsString_(tmp, attributes, "aa_before");
if (!tmp.empty())
{
std::vector<String> splitted;
tmp.split(' ', splitted);
for (Size i = 0; i != splitted.size(); ++i)
{
if (peptide_evidences_.size() < i + 1)
{
peptide_evidences_.emplace_back();
}
peptide_evidences_[i].setAABefore(splitted[i][0]);
}
}
//aa_after
tmp = "";
optionalAttributeAsString_(tmp, attributes, "aa_after");
if (!tmp.empty())
{
std::vector<String> splitted;
tmp.split(' ', splitted);
for (Size i = 0; i != splitted.size(); ++i)
{
if (peptide_evidences_.size() < i + 1)
{
peptide_evidences_.emplace_back();
}
peptide_evidences_[i].setAAAfter(splitted[i][0]);
}
}
//start
tmp = "";
optionalAttributeAsString_(tmp, attributes, "start");
if (!tmp.empty())
{
std::vector<String> splitted;
tmp.split(' ', splitted);
for (Size i = 0; i != splitted.size(); ++i)
{
if (peptide_evidences_.size() < i + 1)
{
peptide_evidences_.emplace_back();
}
peptide_evidences_[i].setStart(splitted[i].toInt());
}
}
//end
tmp = "";
optionalAttributeAsString_(tmp, attributes, "end");
if (!tmp.empty())
{
std::vector<String> splitted;
tmp.split(' ', splitted);
for (Size i = 0; i != splitted.size(); ++i)
{
if (peptide_evidences_.size() < i + 1)
{
peptide_evidences_.emplace_back();
}
peptide_evidences_[i].setEnd(splitted[i].toInt());
}
}
pep_hit_.setPeptideEvidences(peptide_evidences_);
last_meta_ = &pep_hit_;
}
}
void FeatureXMLHandler::endElement(const XMLCh* const /*uri*/, const XMLCh* const /*local_name*/, const XMLCh* const qname)
{
String tag = sm_.convert(qname);
// handle skipping of whole sections
// IMPORTANT: check parent tags first (i.e. tags higher in the tree), since otherwise sections might be enabled/disabled too early/late
if (((!options_.getLoadSubordinates()) && tag == "subordinate")
|| ((!options_.getLoadConvexHull()) && tag == "convexhull"))
{
--disable_parsing_;
return; // even if disable_parsing is false now, we still exit (since this endelement() should be ignored)
}
if (disable_parsing_)
{
return;
}
// do the actual parsing:
open_tags_.pop_back();
//for downward compatibility, all tags in the old description must be ignored
if (tag == "description")
{
in_description_ = false;
}
if (in_description_)
{
return;
}
if (tag == "feature")
{
if ((!options_.hasRTRange() || options_.getRTRange().encloses(current_feature_->getRT()))
&& (!options_.hasMZRange() || options_.getMZRange().encloses(current_feature_->getMZ()))
&& (!options_.hasIntensityRange() || options_.getIntensityRange().encloses(current_feature_->getIntensity())))
{
}
else
{
// this feature does not pass the restrictions --> remove it
if (subordinate_feature_level_ == 0)
{
map_->pop_back();
}
else
{
Feature* f1(nullptr);
if (!map_->empty())
{
f1 = &(map_->back());
}
else
{
fatalError(LOAD, "Feature with unexpected location.");
}
for (Int level = 1; level < subordinate_feature_level_; ++level)
{
f1 = &(f1->getSubordinates().back());
}
// delete the offending feature
f1->getSubordinates().pop_back();
}
}
updateCurrentFeature_(false);
}
else if (tag == "model")
{
warning(LOAD, String("The featureXML file contains a 'model' description, but the internal datastructure has no model support since OpenMS 1.12. Model will be ignored!"));
}
else if (tag == "hullpoint" || tag == "pt")
{
current_chull_.push_back(hull_position_);
}
else if (tag == "convexhull")
{
ConvexHull2D hull;
hull.setHullPoints(current_chull_);
current_feature_->getConvexHulls().push_back(hull);
}
else if (tag == "subordinate")
{
--subordinate_feature_level_;
// reset current_feature
updateCurrentFeature_(false);
}
else if (tag == "IdentificationRun")
{
map_->getProteinIdentifications().push_back(prot_id_);
prot_id_ = ProteinIdentification();
last_meta_ = nullptr;
}
else if (tag == "SearchParameters")
{
prot_id_.setSearchParameters(search_param_);
search_param_ = ProteinIdentification::SearchParameters();
}
else if (tag == "FixedModification")
{
last_meta_ = &search_param_;
}
else if (tag == "VariableModification")
{
last_meta_ = &search_param_;
}
else if (tag == "ProteinHit")
{
prot_id_.insertHit(prot_hit_);
last_meta_ = &prot_id_;
}
else if (tag == "PeptideIdentification")
{
current_feature_->getPeptideIdentifications().push_back(pep_id_);
pep_id_ = PeptideIdentification();
last_meta_ = &map_->back();
}
else if (tag == "UnassignedPeptideIdentification")
{
map_->getUnassignedPeptideIdentifications().push_back(pep_id_);
pep_id_ = PeptideIdentification();
last_meta_ = nullptr;
}
else if (tag == "PeptideHit")
{
pep_id_.insertHit(pep_hit_);
last_meta_ = &pep_id_;
}
else if (tag == "featureList")
{
endProgress();
}
}
void FeatureXMLHandler::characters(const XMLCh* const chars, const XMLSize_t /*length*/)
{
// handle skipping of whole sections
if (disable_parsing_)
{
return;
}
// do the actual parsing:
//for downward compatibility, all tags in the old description must be ignored
if (in_description_)
{
return;
}
// we are before first tag or beyond last tag
if (open_tags_.empty())
{
return;
}
String& current_tag = open_tags_.back();
if (current_tag == "intensity")
{
current_feature_->setIntensity(asDouble_(sm_.convert(chars)));
}
else if (current_tag == "position")
{
current_feature_->getPosition()[dim_] = asDouble_(sm_.convert(chars));
}
else if (current_tag == "quality")
{
current_feature_->setQuality(dim_, asDouble_(sm_.convert(chars)));
}
else if (current_tag == "overallquality")
{
current_feature_->setOverallQuality(asDouble_(sm_.convert(chars)));
}
else if (current_tag == "charge")
{
current_feature_->setCharge(asInt_(chars));
}
else if (current_tag == "hposition")
{
hull_position_[dim_] = asDouble_(sm_.convert(chars));
}
}
void FeatureXMLHandler::writeFeature_(const String& filename, ostream& os, const Feature& feat, const String& identifier_prefix, UInt64 identifier, UInt indentation_level)
{
String indent = String(indentation_level, '\t');
os << indent << "\t\t<feature id=\"" << identifier_prefix << identifier << "\">\n";
for (Size i = 0; i < 2; i++)
{
os << indent << "\t\t\t<position dim=\"" << i << "\">" << precisionWrapper(feat.getPosition()[i]) << "</position>\n";
}
os << indent << "\t\t\t<intensity>" << precisionWrapper(feat.getIntensity()) << "</intensity>\n";
for (Size i = 0; i < 2; i++)
{
os << indent << "\t\t\t<quality dim=\"" << i << "\">" << precisionWrapper(feat.getQuality(i)) << "</quality>\n";
}
os << indent << "\t\t\t<overallquality>" << precisionWrapper(feat.getOverallQuality()) << "</overallquality>\n";
os << indent << "\t\t\t<charge>" << feat.getCharge() << "</charge>\n";
// write convex hull
vector<ConvexHull2D> hulls = feat.getConvexHulls();
Size hulls_count = hulls.size();
for (Size i = 0; i < hulls_count; i++)
{
os << indent << "\t\t\t<convexhull nr=\"" << i << "\">\n";
ConvexHull2D current_hull = hulls[i];
current_hull.compress();
Size hull_size = current_hull.getHullPoints().size();
for (Size j = 0; j < hull_size; j++)
{
DPosition<2> pos = current_hull.getHullPoints()[j];
/*Size pos_size = pos.size();
os << indent << "\t\t\t\t<hullpoint>\n";
for (Size k=0; k<pos_size; k++)
{
os << indent << "\t\t\t\t\t<hposition dim=\"" << k << "\">" << precisionWrapper(pos[k]) << "</hposition>\n";
}
os << indent << "\t\t\t\t</hullpoint>\n";*/
os << indent << "\t\t\t\t<pt x=\"" << precisionWrapper(pos[0]) << "\" y=\"" << precisionWrapper(pos[1]) << "\" />\n";
}
os << indent << "\t\t\t</convexhull>\n";
}
if (!feat.getSubordinates().empty())
{
os << indent << "\t\t\t<subordinate>\n";
for (size_t i = 0; i < feat.getSubordinates().size(); ++i)
{
// These subordinate identifiers are a bit long, but who cares about subordinates anyway? :-P
// This way the parent stands out clearly. However,
// note that only the portion after the last '_' is parsed when this is read back.
writeFeature_(filename, os, feat.getSubordinates()[i], identifier_prefix + identifier + "_", feat.getSubordinates()[i].getUniqueId(), indentation_level + 2);
}
os << indent << "\t\t\t</subordinate>\n";
}
// write PeptideIdentification
for (Size i = 0; i < feat.getPeptideIdentifications().size(); ++i)
{
writePeptideIdentification_(filename, os, feat.getPeptideIdentifications()[i], "PeptideIdentification", 3);
}
writeUserParam_("UserParam", os, feat, indentation_level + 3);
os << indent << "\t\t</feature>\n";
}
void FeatureXMLHandler::writePeptideIdentification_(const String& filename, std::ostream& os, const PeptideIdentification& id, const String& tag_name, UInt indentation_level)
{
String indent = String(indentation_level, '\t');
if (identifier_id_.find(id.getIdentifier()) == identifier_id_.end())
{
warning(STORE, String("Omitting peptide identification because of missing ProteinIdentification with identifier '") + id.getIdentifier() + "' while writing '" + filename + "'!");
return;
}
os << indent << "<" << tag_name << " ";
os << "identification_run_ref=\"" << identifier_id_[id.getIdentifier()] << "\" ";
os << "score_type=\"" << writeXMLEscape(id.getScoreType()) << "\" ";
os << "higher_score_better=\"" << (id.isHigherScoreBetter() ? "true" : "false") << "\" ";
os << "significance_threshold=\"" << id.getSignificanceThreshold() << "\" ";
//mz
if (id.hasMZ())
{
os << "MZ=\"" << id.getMZ() << "\" ";
}
// rt
if (id.hasRT())
{
os << "RT=\"" << id.getRT() << "\" ";
}
// spectrum_reference
DataValue dv = id.getMetaValue("spectrum_reference");
if (dv != DataValue::EMPTY)
{
os << "spectrum_reference=\"" << writeXMLEscape(dv.toString()) << "\" ";
}
os << ">\n";
// write peptide hits
for (Size j = 0; j < id.getHits().size(); ++j)
{
const PeptideHit& h = id.getHits()[j];
os << indent << "\t<PeptideHit";
os << " score=\"" << h.getScore() << "\"";
os << " sequence=\"" << writeXMLEscape(h.getSequence().toString()) << "\"";
os << " charge=\"" << h.getCharge() << "\"";
const vector<PeptideEvidence>& pes = id.getHits()[j].getPeptideEvidences();
IdXMLFile::createFlankingAAXMLString_(pes, os);
IdXMLFile::createPositionXMLString_(pes, os);
String accs;
for (vector<PeptideEvidence>::const_iterator pe = pes.begin(); pe != pes.end(); ++pe)
{
if (!accs.empty())
{
accs += " ";
}
String protein_accession = pe->getProteinAccession();
// empty accessions are not written out (legacy code)
if (!protein_accession.empty())
{
accs += "PH_";
accs += String(accession_to_id_[id.getIdentifier() + "_" + protein_accession]);
}
}
// don't write protein_refs if no peptide evidences present
if (!accs.empty())
{
os << " protein_refs=\"" << accs << "\"";
}
os << ">\n";
writeUserParam_("UserParam", os, id.getHits()[j], indentation_level + 2);
os << indent << "\t</PeptideHit>\n";
}
//do not write "spectrum_reference" and Constants::UserParam::SIGNIFICANCE_THRESHOLD since it is written as attribute already
MetaInfoInterface tmp = id;
tmp.removeMetaValue("spectrum_reference");
tmp.removeMetaValue(Constants::UserParam::SIGNIFICANCE_THRESHOLD);
writeUserParam_("UserParam", os, tmp, indentation_level + 1);
os << indent << "</" << tag_name << ">\n";
}
void FeatureXMLHandler::updateCurrentFeature_(bool create)
{
if (subordinate_feature_level_ == 0)
{
if (create)
{
setProgress(map_->size());
map_->push_back(Feature());
current_feature_ = &map_->back();
last_meta_ = &map_->back();
}
else
{
if (map_->empty())
{
current_feature_ = nullptr;
last_meta_ = nullptr;
}
else
{
current_feature_ = &map_->back();
last_meta_ = &map_->back();
}
}
return;
}
Feature* f1 = nullptr;
if (map_->empty())
{
// do NOT throw an exception here. this is a valid case! e.g. the
// only one feature in a map was discarded during endElement(), thus
// the map_ is empty() now and we cannot assign a current_feature,
// because there is none!
current_feature_ = nullptr;
last_meta_ = nullptr;
return;
}
else
{
f1 = &map_->back();
}
for (Int level = 1; level < subordinate_feature_level_; ++level)
{
// if all features of the current level are discarded (due to
// range-restrictions etc), then the current feature is the one which
// is one level up
if (f1->getSubordinates().empty())
{
current_feature_ = f1;
last_meta_ = f1;
return;
}
f1 = &f1->getSubordinates().back();
}
if (create)
{
f1->getSubordinates().emplace_back();
current_feature_ = &f1->getSubordinates().back();
last_meta_ = &f1->getSubordinates().back();
return;
}
else
{
if (f1->getSubordinates().empty())
{
current_feature_ = nullptr;
last_meta_ = nullptr;
return;
}
else
{
current_feature_ = &f1->getSubordinates().back();
last_meta_ = &f1->getSubordinates().back();
return;
}
}
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/HANDLERS/ConsensusXMLHandler.cpp | .cpp | 36,826 | 973 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Clemens Groepl, Marc Sturm, Mathias Walzer $
// --------------------------------------------------------------------------
#include <OpenMS/FORMAT/HANDLERS/ConsensusXMLHandler.h>
#include <OpenMS/CHEMISTRY/ProteaseDB.h>
#include <OpenMS/CONCEPT/UniqueIdGenerator.h>
#include <OpenMS/FORMAT/IdXMLFile.h>
#include <OpenMS/METADATA/DataProcessing.h>
#include <OpenMS/SYSTEM/File.h>
#include <map>
#include <fstream>
using namespace std;
namespace OpenMS::Internal
{
ConsensusXMLHandler::ConsensusXMLHandler(ConsensusMap& map, const String& filename) :
XMLHandler("", "1.7"),
ProgressLogger(),
act_cons_element_(),
last_meta_(nullptr)
{
consensus_map_ = ↦
file_ = filename;
}
ConsensusXMLHandler::ConsensusXMLHandler(const ConsensusMap& map, const String& filename) :
XMLHandler("", "1.7"),
ProgressLogger(),
act_cons_element_(),
last_meta_(nullptr)
{
cconsensus_map_ = ↦
file_ = filename;
}
ConsensusXMLHandler::~ConsensusXMLHandler() = default;
PeakFileOptions& ConsensusXMLHandler::getOptions()
{
return options_;
}
void ConsensusXMLHandler::setOptions(const PeakFileOptions& options)
{
options_ = options;
}
const PeakFileOptions& ConsensusXMLHandler::getOptions() const
{
return options_;
}
void ConsensusXMLHandler::endElement(const XMLCh* const /*uri*/, const XMLCh* const /*local_name*/, const XMLCh* const qname)
{
String tag = sm_.convert(qname);
open_tags_.pop_back();
if (tag == "consensusElement")
{
if ((!options_.hasRTRange() || options_.getRTRange().encloses(act_cons_element_.getRT())) && (!options_.hasMZRange() || options_.getMZRange().encloses(
act_cons_element_.getMZ())) && (!options_.hasIntensityRange() || options_.getIntensityRange().encloses(act_cons_element_.getIntensity())))
{
consensus_map_->push_back(act_cons_element_);
act_cons_element_.getPeptideIdentifications().clear();
}
last_meta_ = nullptr;
}
else if (tag == "IdentificationRun")
{
// post processing of ProteinGroups (hack)
getProteinGroups_(prot_id_.getProteinGroups(), "protein_group");
getProteinGroups_(prot_id_.getIndistinguishableProteins(),
"indistinguishable_proteins");
consensus_map_->getProteinIdentifications().emplace_back(std::move(prot_id_));
prot_id_ = ProteinIdentification();
last_meta_ = nullptr;
}
else if (tag == "SearchParameters")
{
prot_id_.setSearchParameters(search_param_);
search_param_ = ProteinIdentification::SearchParameters();
}
else if (tag == "FixedModification")
{
last_meta_ = &search_param_;
}
else if (tag == "VariableModification")
{
last_meta_ = &search_param_;
}
else if (tag == "ProteinHit")
{
prot_id_.insertHit(prot_hit_);
last_meta_ = &prot_id_;
}
else if (tag == "PeptideIdentification")
{
act_cons_element_.getPeptideIdentifications().emplace_back(std::move(pep_id_));
pep_id_ = PeptideIdentification();
last_meta_ = &act_cons_element_;
}
else if (tag == "UnassignedPeptideIdentification")
{
consensus_map_->getUnassignedPeptideIdentifications().emplace_back(std::move(pep_id_));
pep_id_ = PeptideIdentification();
last_meta_ = consensus_map_;
}
else if (tag == "PeptideHit")
{
pep_hit_.setPeptideEvidences(peptide_evidences_);
pep_id_.insertHit(pep_hit_);
last_meta_ = &pep_id_;
}
else if (tag == "consensusXML")
{
endProgress();
}
}
void ConsensusXMLHandler::characters(const XMLCh* const /*chars*/, const XMLSize_t /*length*/)
{
}
void ConsensusXMLHandler::startElement(const XMLCh* const /*uri*/, const XMLCh* const /*local_name*/, const XMLCh* const qname, const xercesc::Attributes& attributes)
{
const String& parent_tag = (open_tags_.empty() ? "" : open_tags_.back());
open_tags_.push_back(sm_.convert(qname));
const String& tag = open_tags_.back();
String tmp_str;
if (tag == "map")
{
setProgress(++progress_);
Size last_map = attributeAsInt_(attributes, "id");
last_meta_ = &consensus_map_->getColumnHeaders()[last_map];
consensus_map_->getColumnHeaders()[last_map].filename = attributeAsString_(attributes, "name");
String unique_id;
if (XMLHandler::optionalAttributeAsString_(unique_id, attributes, "unique_id"))
{
UniqueIdInterface tmp;
tmp.setUniqueId(unique_id);
consensus_map_->getColumnHeaders()[last_map].unique_id = tmp.getUniqueId();
}
String label;
if (XMLHandler::optionalAttributeAsString_(label, attributes, "label"))
{
consensus_map_->getColumnHeaders()[last_map].label = label;
}
UInt size;
if (XMLHandler::optionalAttributeAsUInt_(size, attributes, "size"))
{
consensus_map_->getColumnHeaders()[last_map].size = size;
}
}
else if (tag == "consensusElement")
{
setProgress(++progress_);
act_cons_element_ = ConsensusFeature();
last_meta_ = &act_cons_element_;
// quality
if (double quality; optionalAttributeAsDouble_(quality, attributes, "quality"))
{
act_cons_element_.setQuality(quality);
}
// charge
if (Int charge; optionalAttributeAsInt_(charge, attributes, "charge"))
{
act_cons_element_.setCharge(charge);
}
// unique id
act_cons_element_.setUniqueId(attributeAsString_(attributes, "id"));
last_meta_ = &act_cons_element_;
}
else if (tag == "centroid")
{
tmp_str = attributeAsString_(attributes, "rt");
if (!tmp_str.empty())
{
pos_[Peak2D::RT] = asDouble_(tmp_str);
}
tmp_str = attributeAsString_(attributes, "mz");
if (!tmp_str.empty())
{
pos_[Peak2D::MZ] = asDouble_(tmp_str);
}
tmp_str = attributeAsString_(attributes, "it");
if (!tmp_str.empty())
{
it_ = asDouble_(tmp_str);
}
}
else if (tag == "element")
{
FeatureHandle act_index_tuple;
UniqueIdInterface tmp_unique_id_interface;
tmp_str = attributeAsString_(attributes, "map");
if (!tmp_str.empty())
{
tmp_unique_id_interface.setUniqueId(tmp_str);
UInt64 map_index = tmp_unique_id_interface.getUniqueId();
tmp_str = attributeAsString_(attributes, "id");
if (!tmp_str.empty())
{
tmp_unique_id_interface.setUniqueId(tmp_str);
UInt64 unique_id = tmp_unique_id_interface.getUniqueId();
act_index_tuple.setMapIndex(map_index);
act_index_tuple.setUniqueId(unique_id);
tmp_str = attributeAsString_(attributes, "rt");
DPosition<2> pos;
pos[0] = asDouble_(tmp_str);
tmp_str = attributeAsString_(attributes, "mz");
pos[1] = asDouble_(tmp_str);
act_index_tuple.setPosition(pos);
act_index_tuple.setIntensity(attributeAsDouble_(attributes, "it"));
Int charge = 0;
if (optionalAttributeAsInt_(charge, attributes, "charge"))
{
act_index_tuple.setCharge(charge);
}
act_cons_element_.insert(std::move(act_index_tuple));
}
}
act_cons_element_.getPosition() = pos_;
act_cons_element_.setIntensity(it_);
}
else if (tag == "consensusXML")
{
startProgress(0, 0, "loading consensusXML file");
progress_ = 0;
setProgress(++progress_);
//check file version against schema version
String file_version = "";
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.");
}
// handle document id
String document_id;
if (optionalAttributeAsString_(document_id, attributes, "document_id"))
{
consensus_map_->setIdentifier(document_id);
}
// handle unique id
String unique_id;
if (optionalAttributeAsString_(unique_id, attributes, "id"))
{
consensus_map_->setUniqueId(unique_id);
}
// TODO The next four lines should be removed in OpenMS 1.7 or so!
if (optionalAttributeAsString_(unique_id, attributes, "unique_id"))
{
consensus_map_->setUniqueId(unique_id);
}
//handle experiment type
String experiment_type;
if (optionalAttributeAsString_(experiment_type, attributes, "experiment_type"))
{
consensus_map_->setExperimentType(experiment_type);
}
last_meta_ = consensus_map_;
}
else if (tag == "userParam" || tag == "UserParam") // remain backwards compatible. Correct is "UserParam"
{
if (last_meta_ == nullptr)
{
fatalError(LOAD, String("Unexpected UserParam in tag '") + parent_tag + "'");
}
String name = attributeAsString_(attributes, "name");
String type = attributeAsString_(attributes, "type");
if (type == "int")
{
last_meta_->setMetaValue(name, attributeAsInt_(attributes, "value"));
}
else if (type == "float")
{
last_meta_->setMetaValue(name, attributeAsDouble_(attributes, "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 if (type == "string")
{
last_meta_->setMetaValue(name, (String) attributeAsString_(attributes, "value"));
}
else
{
fatalError(LOAD, String("Invalid UserParam type '") + type + "'");
}
}
else if (tag == "IdentificationRun")
{
setProgress(++progress_);
prot_id_.setSearchEngine(attributeAsString_(attributes, "search_engine"));
prot_id_.setSearchEngineVersion(attributeAsString_(attributes, "search_engine_version"));
prot_id_.setDateTime(DateTime::fromString(attributeAsString_(attributes, "date")));
// set identifier
// always generate a unique id to link a ProteinIdentification and the corresponding PeptideIdentifications
// , since any FeatureLinker might just carelessly concatenate PepIDs from different FeatureMaps.
// If these FeatureMaps have identical identifiers (SearchEngine time + type match exactly), then ALL PepIDs would be falsely attributed
// to a single ProtID...
String id = attributeAsString_(attributes, "id");
while (true)
{ // loop until the identifier is unique (should be on the first iteration -- very(!) unlikely it will not be unique)
// 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)
String identifier = prot_id_.getSearchEngine() + '_' + attributeAsString_(attributes, "date") + '_' + String(UniqueIdGenerator::getUniqueId());
if (id_identifier_.find(id) == id_identifier_.end())
{
prot_id_.setIdentifier(identifier);
id_identifier_[id] = identifier;
break;
}
}
}
else if (tag == "SearchParameters")
{
//load parameters
search_param_.db = attributeAsString_(attributes, "db");
search_param_.db_version = attributeAsString_(attributes, "db_version");
optionalAttributeAsString_(search_param_.taxonomy, attributes, "taxonomy");
search_param_.charges = attributeAsString_(attributes, "charges");
optionalAttributeAsUInt_(search_param_.missed_cleavages, attributes, "missed_cleavages");
search_param_.fragment_mass_tolerance = attributeAsDouble_(attributes, "peak_mass_tolerance");
String peak_unit;
optionalAttributeAsString_(peak_unit, attributes, "peak_mass_tolerance_ppm");
search_param_.fragment_mass_tolerance_ppm = peak_unit == "true" ? true : false;
search_param_.precursor_mass_tolerance = attributeAsDouble_(attributes, "precursor_peak_tolerance");
String precursor_unit;
optionalAttributeAsString_(precursor_unit, attributes, "precursor_peak_tolerance_ppm");
search_param_.precursor_mass_tolerance_ppm = precursor_unit == "true" ? true : false;
//mass type
String mass_type = attributeAsString_(attributes, "mass_type");
if (mass_type == "monoisotopic")
{
search_param_.mass_type = ProteinIdentification::PeakMassType::MONOISOTOPIC;
}
else if (mass_type == "average")
{
search_param_.mass_type = ProteinIdentification::PeakMassType::AVERAGE;
}
//enzyme
String enzyme;
optionalAttributeAsString_(enzyme, attributes, "enzyme");
if (ProteaseDB::getInstance()->hasEnzyme(enzyme))
{
search_param_.digestion_enzyme = *(ProteaseDB::getInstance()->getEnzyme(enzyme));
}
last_meta_ = &search_param_;
}
else if (tag == "FixedModification")
{
search_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")
{
search_param_.variable_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 == "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")
{
setProgress(++progress_);
prot_hit_ = ProteinHit();
String accession = attributeAsString_(attributes, "accession");
prot_hit_.setAccession(accession);
prot_hit_.setScore(attributeAsDouble_(attributes, "score"));
// coverage
if (double coverage; optionalAttributeAsDouble_(coverage, attributes, "coverage"))
{
prot_hit_.setCoverage(coverage);
}
//sequence
String tmp = "";
optionalAttributeAsString_(tmp, attributes, "sequence");
prot_hit_.setSequence(tmp);
last_meta_ = &prot_hit_;
//insert id and accession to map
proteinid_to_accession_[attributeAsString_(attributes, "id")] = accession;
}
else if (tag == "PeptideIdentification" || tag == "UnassignedPeptideIdentification")
{
String id = attributeAsString_(attributes, "identification_run_ref");
if (id_identifier_.find(id) == id_identifier_.end())
{
warning(LOAD, String("Peptide identification without ProteinIdentification found (id: '") + id + "')!");
}
pep_id_.setIdentifier(id_identifier_[id]);
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
if (double mz; optionalAttributeAsDouble_(mz, attributes, "MZ"))
{
pep_id_.setMZ(mz);
}
//RT
if (double rt; optionalAttributeAsDouble_(rt, attributes, "RT"))
{
pep_id_.setRT(rt);
}
if (String ref; optionalAttributeAsString_(ref, attributes, "spectrum_reference"))
{
pep_id_.setSpectrumReference( ref);
}
last_meta_ = &pep_id_;
}
else if (tag == "PeptideHit")
{
setProgress(++progress_);
pep_hit_ = PeptideHit();
peptide_evidences_ = vector<PeptideEvidence>();
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();
vector<String> accessions;
accession_string.split(' ', accessions);
if (!accession_string.empty() && accessions.empty())
{
accessions.push_back(std::move(accession_string));
}
for (vector<String>::const_iterator it = accessions.begin(); it != accessions.end(); ++it)
{
std::map<String, String>::const_iterator 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;
std::vector<String> splitted;
if (optionalAttributeAsString_(tmp, attributes, "aa_before"))
{
tmp.split(' ', splitted);
for (Size i = 0; i != splitted.size(); ++i)
{
if (peptide_evidences_.size() < i + 1)
{
peptide_evidences_.emplace_back();
}
peptide_evidences_[i].setAABefore(splitted[i][0]);
}
}
//aa_after
if (optionalAttributeAsString_(tmp, attributes, "aa_after"))
{
tmp.split(' ', splitted);
for (Size i = 0; i != splitted.size(); ++i)
{
if (peptide_evidences_.size() < i + 1)
{
peptide_evidences_.emplace_back();
}
peptide_evidences_[i].setAAAfter(splitted[i][0]);
}
}
//start
if (optionalAttributeAsString_(tmp, attributes, "start"))
{
tmp.split(' ', splitted);
for (Size i = 0; i != splitted.size(); ++i)
{
if (peptide_evidences_.size() < i + 1)
{
peptide_evidences_.emplace_back();
}
peptide_evidences_[i].setStart(splitted[i].toInt());
}
}
//end
if (optionalAttributeAsString_(tmp, attributes, "end"))
{
tmp.split(' ', splitted);
for (Size i = 0; i != splitted.size(); ++i)
{
if (peptide_evidences_.size() < i + 1)
{
peptide_evidences_.emplace_back();
}
peptide_evidences_[i].setEnd(splitted[i].toInt());
}
}
last_meta_ = &pep_hit_;
}
else if (tag == "dataProcessing")
{
setProgress(++progress_);
DataProcessing tmp;
tmp.setCompletionTime(asDateTime_(attributeAsString_(attributes, "completion_time")));
consensus_map_->getDataProcessing().push_back(std::move(tmp));
last_meta_ = &(consensus_map_->getDataProcessing().back());
}
else if (tag == "software" && parent_tag == "dataProcessing")
{
consensus_map_->getDataProcessing().back().getSoftware().setName(attributeAsString_(attributes, "name"));
consensus_map_->getDataProcessing().back().getSoftware().setVersion(attributeAsString_(attributes, "version"));
}
else if (tag == "processingAction" && parent_tag == "dataProcessing")
{
String name = attributeAsString_(attributes, "name");
for (Size i = 0; i < DataProcessing::SIZE_OF_PROCESSINGACTION; ++i)
{
if (name == DataProcessing::NamesOfProcessingAction[i])
{
consensus_map_->getDataProcessing().back().getProcessingActions().insert((DataProcessing::ProcessingAction) i);
}
}
}
}
void ConsensusXMLHandler::writeTo(std::ostream& os)
{
const ConsensusMap& consensus_map = *(cconsensus_map_);
startProgress(0, 0, "storing consensusXML file");
progress_ = 0;
setProgress(++progress_);
setProgress(++progress_);
os << "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n";
os << "<?xml-stylesheet type=\"text/xsl\" href=\"https://www.openms.de/xml-stylesheet/ConsensusXML.xsl\" ?>\n";
setProgress(++progress_);
os << "<consensusXML version=\"" << version_ << "\"";
// file id
if (!consensus_map.getIdentifier().empty())
{
os << " document_id=\"" << consensus_map.getIdentifier() << "\"";
}
// unique id
if (consensus_map.hasValidUniqueId())
{
os << " id=\"cm_" << consensus_map.getUniqueId() << "\"";
}
if (!consensus_map.getExperimentType().empty())
{
os << " experiment_type=\"" << consensus_map.getExperimentType() << "\"";
}
os
<< " xsi:noNamespaceSchemaLocation=\"https://raw.githubusercontent.com/OpenMS/OpenMS/develop/share/OpenMS/SCHEMAS/ConsensusXML_1_7.xsd\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n";
// user param
writeUserParam_("UserParam", os, consensus_map, 1);
setProgress(++progress_);
// write data processing
for (Size i = 0; i < consensus_map.getDataProcessing().size(); ++i)
{
const DataProcessing& processing = consensus_map.getDataProcessing()[i];
os << "\t<dataProcessing completion_time=\"" << processing.getCompletionTime().getDate() << 'T' << processing.getCompletionTime().getTime() << "\">\n";
os << "\t\t<software name=\"" << processing.getSoftware().getName() << "\" version=\"" << processing.getSoftware().getVersion() << "\" />\n";
for (set<DataProcessing::ProcessingAction>::const_iterator it = processing.getProcessingActions().begin(); it != processing.getProcessingActions().end(); ++it)
{
os << "\t\t<processingAction name=\"" << DataProcessing::NamesOfProcessingAction[*it] << "\" />\n";
}
writeUserParam_("UserParam", os, processing, 2);
os << "\t</dataProcessing>\n";
}
setProgress(++progress_);
// write identification run
UInt prot_count = 0;
// throws if protIDs are not unique, i.e. PeptideIDs will be randomly assigned (bad!)
checkUniqueIdentifiers_(consensus_map.getProteinIdentifications());
for (UInt i = 0; i < consensus_map.getProteinIdentifications().size(); ++i)
{
setProgress(++progress_);
const ProteinIdentification& current_prot_id = consensus_map.getProteinIdentifications()[i];
os << "\t<IdentificationRun ";
os << "id=\"PI_" << i << "\" ";
identifier_id_[current_prot_id.getIdentifier()] = String("PI_") + i;
os << "date=\"" << current_prot_id.getDateTime().getDate() << "T" << current_prot_id.getDateTime().getTime() << "\" ";
os << "search_engine=\"" << writeXMLEscape(current_prot_id.getSearchEngine()) << "\" ";
os << "search_engine_version=\"" << writeXMLEscape(current_prot_id.getSearchEngineVersion()) << "\">\n";
//write search parameters
const ProteinIdentification::SearchParameters& search_param = current_prot_id.getSearchParameters();
os << "\t\t<SearchParameters " << "db=\"" << search_param.db << "\" " << "db_version=\"" << search_param.db_version << "\" " << "taxonomy=\""
<< search_param.taxonomy << "\" ";
if (search_param.mass_type == ProteinIdentification::PeakMassType::MONOISOTOPIC)
{
os << "mass_type=\"monoisotopic\" ";
}
else if (search_param.mass_type == ProteinIdentification::PeakMassType::AVERAGE)
{
os << "mass_type=\"average\" ";
}
os << "charges=\"" << search_param.charges << "\" ";
String enzyme_name = search_param.digestion_enzyme.getName();
os << "enzyme=\"" << enzyme_name.toLower() << "\" ";
String precursor_unit = search_param.precursor_mass_tolerance_ppm ? "true" : "false";
String peak_unit = search_param.fragment_mass_tolerance_ppm ? "true" : "false";
os << "missed_cleavages=\"" << search_param.missed_cleavages << "\" "
<< "precursor_peak_tolerance=\"" << search_param.precursor_mass_tolerance << "\" ";
os << "precursor_peak_tolerance_ppm=\"" << precursor_unit << "\" ";
os << "peak_mass_tolerance=\"" << search_param.fragment_mass_tolerance << "\" ";
os << "peak_mass_tolerance_ppm=\"" << peak_unit << "\" ";
os << ">\n";
//modifications
for (Size j = 0; j != search_param.fixed_modifications.size(); ++j)
{
os << "\t\t\t<FixedModification name=\"" << writeXMLEscape(search_param.fixed_modifications[j]) << "\" />\n";
}
for (Size j = 0; j != search_param.variable_modifications.size(); ++j)
{
os << "\t\t\t<VariableModification name=\"" << writeXMLEscape(search_param.variable_modifications[j]) << "\" />\n";
}
writeUserParam_("UserParam", os, search_param, 4);
os << "\t\t</SearchParameters>\n";
//write protein identifications
os << "\t\t<ProteinIdentification";
os << " score_type=\"" << writeXMLEscape(current_prot_id.getScoreType()) << "\"";
os << " higher_score_better=\"" << (current_prot_id.isHigherScoreBetter() ? "true" : "false") << "\"";
os << " significance_threshold=\"" << current_prot_id.getSignificanceThreshold() << "\">\n";
//TODO @julianus @timo IMPLEMENT PROTEIN GROUP SUPPORT!!
// write protein hits
for (Size j = 0; j < current_prot_id.getHits().size(); ++j)
{
os << "\t\t\t<ProteinHit";
// prot_count
os << " id=\"PH_" << prot_count << "\"";
accession_to_id_[current_prot_id.getIdentifier() + "_" + current_prot_id.getHits()[j].getAccession()] = prot_count;
++prot_count;
os << " accession=\"" << writeXMLEscape(current_prot_id.getHits()[j].getAccession()) << "\"";
os << " score=\"" << current_prot_id.getHits()[j].getScore() << "\"";
double coverage = current_prot_id.getHits()[j].getCoverage();
if (coverage != ProteinHit::COVERAGE_UNKNOWN)
{
os << " coverage=\"" << coverage << "\"";
}
os << " sequence=\"" << writeXMLEscape(current_prot_id.getHits()[j].getSequence()) << "\">\n";
writeUserParam_("UserParam", os, current_prot_id.getHits()[j], 4);
os << "\t\t\t</ProteinHit>\n";
}
// add ProteinGroup info to metavalues (hack)
MetaInfoInterface meta = current_prot_id;
addProteinGroups_(meta, current_prot_id.getProteinGroups(),
"protein_group", accession_to_id_, current_prot_id.getIdentifier(), STORE);
addProteinGroups_(meta, current_prot_id.getIndistinguishableProteins(),
"indistinguishable_proteins", accession_to_id_, current_prot_id.getIdentifier(), STORE);
writeUserParam_("UserParam", os, meta, 3);
os << "\t\t</ProteinIdentification>\n";
os << "\t</IdentificationRun>\n";
}
//write unassigned peptide identifications
for (UInt i = 0; i < consensus_map.getUnassignedPeptideIdentifications().size(); ++i)
{
writePeptideIdentification_(file_, os, consensus_map.getUnassignedPeptideIdentifications()[i], "UnassignedPeptideIdentification", 1);
}
//file descriptions
const ConsensusMap::ColumnHeaders& description_vector = consensus_map.getColumnHeaders();
os << "\t<mapList count=\"" << description_vector.size() << "\">\n";
for (ConsensusMap::ColumnHeaders::const_iterator it = description_vector.begin(); it != description_vector.end(); ++it)
{
setProgress(++progress_);
os << "\t\t<map id=\"" << it->first;
os << "\" name=\"" << it->second.filename;
if (UniqueIdInterface::isValid(it->second.unique_id))
{
os << "\" unique_id=\"" << it->second.unique_id;
}
os << "\" label=\"" << it->second.label;
os << "\" size=\"" << it->second.size << "\">\n";
writeUserParam_("UserParam", os, it->second, 3);
os << "\t\t</map>\n";
}
os << "\t</mapList>\n";
// write all consensus elements
os << "\t<consensusElementList>\n";
for (Size i = 0; i < consensus_map.size(); ++i)
{
setProgress(++progress_);
// write a consensusElement
const ConsensusFeature& elem = consensus_map[i];
os << "\t\t<consensusElement id=\"e_" << elem.getUniqueId() << "\" quality=\"" << precisionWrapper(elem.getQuality()) << "\"";
if (elem.getCharge() != 0)
{
os << " charge=\"" << elem.getCharge() << "\"";
}
os << ">\n";
// write centroid
os << "\t\t\t<centroid rt=\"" << precisionWrapper(elem.getRT()) << "\" mz=\"" << precisionWrapper(elem.getMZ()) << "\" it=\"" << precisionWrapper(
elem.getIntensity()) << "\"/>\n";
// write groupedElementList
os << "\t\t\t<groupedElementList>\n";
for (ConsensusFeature::HandleSetType::const_iterator it = elem.begin(); it != elem.end(); ++it)
{
os << "\t\t\t\t<element"
" map=\"" << it->getMapIndex() << "\""
" id=\"" << it->getUniqueId() << "\""
" rt=\"" << precisionWrapper(it->getRT()) << "\""
" mz=\"" << precisionWrapper(it->getMZ()) << "\""
" it=\"" << precisionWrapper(it->getIntensity()) << "\"";
if (it->getCharge() != 0)
{
os << " charge=\"" << it->getCharge() << "\"";
}
os << "/>\n";
}
os << "\t\t\t</groupedElementList>\n";
// write PeptideIdentification
for (UInt j = 0; j < elem.getPeptideIdentifications().size(); ++j)
{
writePeptideIdentification_(file_, os, elem.getPeptideIdentifications()[j], "PeptideIdentification", 3);
}
writeUserParam_("UserParam", os, elem, 3);
os << "\t\t</consensusElement>\n";
}
os << "\t</consensusElementList>\n";
os << "</consensusXML>\n";
//Clear members
identifier_id_.clear();
accession_to_id_.clear();
endProgress();
}
void ConsensusXMLHandler::writePeptideIdentification_(const String& filename, std::ostream& os, const PeptideIdentification& id, const String& tag_name,
UInt indentation_level)
{
String indent = String(indentation_level, '\t');
if (identifier_id_.find(id.getIdentifier()) == identifier_id_.end())
{
warning(STORE, String("Omitting peptide identification because of missing ProteinIdentification with identifier '") + id.getIdentifier()
+ "' while writing '" + filename + "'!");
return;
}
os << indent << "<" << tag_name << " ";
os << "identification_run_ref=\"" << identifier_id_[id.getIdentifier()] << "\" ";
os << "score_type=\"" << writeXMLEscape(id.getScoreType()) << "\" ";
os << "higher_score_better=\"" << (id.isHigherScoreBetter() ? "true" : "false") << "\" ";
os << "significance_threshold=\"" << id.getSignificanceThreshold() << "\" ";
//mz
if (id.hasMZ())
{
os << "MZ=\"" << id.getMZ() << "\" ";
}
// rt
if (id.hasRT())
{
os << "RT=\"" << id.getRT() << "\" ";
}
// spectrum_reference
DataValue dv = id.getMetaValue("spectrum_reference");
if (dv != DataValue::EMPTY)
{
os << "spectrum_reference=\"" << writeXMLEscape(dv.toString()) << "\" ";
}
os << ">\n";
// write peptide hits
for (Size j = 0; j < id.getHits().size(); ++j)
{
os << indent << "\t<PeptideHit";
os << " score=\"" << id.getHits()[j].getScore() << "\"";
os << " sequence=\"" << writeXMLEscape(id.getHits()[j].getSequence().toString()) << "\"";
os << " charge=\"" << id.getHits()[j].getCharge() << "\"";
vector<PeptideEvidence> pes = id.getHits()[j].getPeptideEvidences();
IdXMLFile::createFlankingAAXMLString_(pes, os);
IdXMLFile::createPositionXMLString_(pes, os);
String accs;
for (vector<PeptideEvidence>::const_iterator pe = pes.begin(); pe != pes.end(); ++pe)
{
if (!accs.empty())
{
accs += " ";
}
String protein_accession = pe->getProteinAccession();
// empty accessions are not written out (legacy code)
if (!protein_accession.empty())
{
accs += "PH_";
accs += String(accession_to_id_[id.getIdentifier() + "_" + protein_accession]);
}
}
// don't write protein_refs if no peptide evidences present
if (!accs.empty())
{
os << " protein_refs=\"" << accs << "\"";
}
os << ">\n";
writeUserParam_("UserParam", os, id.getHits()[j], indentation_level + 2);
os << indent << "\t</PeptideHit>\n";
}
// do not write "spectrum_reference" and Constants::UserParam::SIGNIFICANCE_THRESHOLD since it is written as attribute already
MetaInfoInterface tmp = id;
tmp.removeMetaValue("spectrum_reference");
tmp.removeMetaValue(Constants::UserParam::SIGNIFICANCE_THRESHOLD);
writeUserParam_("UserParam", os, tmp, indentation_level + 1);
os << indent << "</" << tag_name << ">\n";
}
void ConsensusXMLHandler::addProteinGroups_(
MetaInfoInterface& meta, const std::vector<ProteinIdentification::ProteinGroup>& groups,
const String& group_name, const std::unordered_map<string, UInt>& accession_to_id, const String& runid,
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(runid + "_" + *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 ConsensusXMLHandler::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);
}
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/HANDLERS/MzMLHandler.cpp | .cpp | 265,546 | 5,753 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm, Chris Bielow, Hannes Roest $
// --------------------------------------------------------------------------
#include <OpenMS/FORMAT/HANDLERS/MzMLHandler.h>
#include <OpenMS/CONCEPT/Exception.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/CONCEPT/VersionInfo.h>
#include <OpenMS/FORMAT/Base64.h>
#include <OpenMS/FORMAT/CVMappingFile.h>
#include <OpenMS/FORMAT/MSNumpressCoder.h>
#include <OpenMS/FORMAT/VALIDATORS/MzMLValidator.h>
#include <OpenMS/INTERFACES/IMSDataConsumer.h>
#include <OpenMS/SYSTEM/File.h>
#include <atomic>
#include <map>
namespace OpenMS::Internal
{
thread_local ProgressLogger pg_outer; ///< an extra logger for nested logging
/// Constructor for a read-only handler
MzMLHandler::MzMLHandler(MapType& exp, const String& filename, const String& version, const ProgressLogger& logger)
: MzMLHandler(filename, version, logger)
{
exp_ = &exp;
}
/// Constructor for a write-only handler
MzMLHandler::MzMLHandler(const MapType& exp, const String& filename, const String& version, const ProgressLogger& logger)
: MzMLHandler(filename, version, logger)
{
cexp_ = &exp;
}
/// delegated c'tor for the common things
MzMLHandler::MzMLHandler(const String& filename, const String& version, const ProgressLogger& logger)
: XMLHandler(filename, version),
logger_(logger),
cv_(ControlledVocabulary::getPSIMSCV())
{
CVMappingFile().load(File::find("/MAPPING/ms-mapping.xml"), mapping_);
// check the version number of the mzML handler
if (VersionInfo::VersionDetails::create(version_) == VersionInfo::VersionDetails::EMPTY)
{
OPENMS_LOG_ERROR << "MzMLHandler was initialized with an invalid version number: " << version_ << std::endl;
}
pg_outer = logger; // inherit the logtype etc
}
/// Destructor
MzMLHandler::~MzMLHandler() = default;
/// Set the peak file options
void MzMLHandler::setOptions(const PeakFileOptions& opt)
{
options_ = opt;
spectrum_data_.reserve(options_.getMaxDataPoolSize());
// Reserve memory for chromatogram data based on the maximum data pool size if chromatograms are to be skipped.
skip_chromatogram_ = options_.getSkipChromatograms();
if (!skip_chromatogram_)
{
chromatogram_data_.reserve(options_.getMaxDataPoolSize());
}
}
/// Get the peak file options
PeakFileOptions& MzMLHandler::getOptions()
{
return options_;
}
/// handler which support partial loading, implement this method
XMLHandler::LOADDETAIL MzMLHandler::getLoadDetail() const
{
return load_detail_;
}
/// handler which support partial loading, implement this method
void MzMLHandler::setLoadDetail(const XMLHandler::LOADDETAIL d)
{
load_detail_ = d;
}
//@}
/// Get the spectra and chromatogram counts of a file
void MzMLHandler::getCounts(Size& spectra_counts, Size& chromatogram_counts)
{
if (load_detail_ == XMLHandler::LD_RAWCOUNTS)
{
spectra_counts = std::max(scan_count_total_, 0); // default is -1; if no specs were found, report 0
chromatogram_counts = std::max(chrom_count_total_, 0);
}
else
{
spectra_counts = scan_count_;
chromatogram_counts = chromatogram_count_;
}
}
/// Set the IMSDataConsumer consumer which will consume the read data
void MzMLHandler::setMSDataConsumer(Interfaces::IMSDataConsumer* consumer)
{
consumer_ = consumer;
}
void MzMLHandler::populateSpectraWithData_()
{
// Whether spectrum should be populated with data
if (options_.getFillData())
{
std::atomic<int> errCount = 0;
String error_message;
#pragma omp parallel for
for (SignedSize i = 0; i < (SignedSize)spectrum_data_.size(); i++)
{
// parallel exception catching and re-throwing business
if (!errCount) // no need to parse further if already an error was encountered
{
try
{
populateSpectraWithData_(spectrum_data_[i].data,
spectrum_data_[i].default_array_length,
options_,
spectrum_data_[i].spectrum);
if (options_.getSortSpectraByMZ() && !spectrum_data_[i].spectrum.isSorted())
{
spectrum_data_[i].spectrum.sortByPosition();
}
}
catch (OpenMS::Exception::BaseException& e)
{
#pragma omp critical(MZMLErrorHandling)
{
++errCount;
error_message = e.what();
}
}
catch (...)
{
++errCount;
error_message = "Unknown exception during spectrum data population";
}
}
}
if (errCount != 0)
{
std::cerr << " Parsing error: '" << error_message << "'" << std::endl;
std::cerr << " You could try to disable sorting spectra while loading." << std::endl;
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, file_, "Error during parsing of binary data: '" + error_message + "'");
}
}
// Append all spectra to experiment / consumer
for (Size i = 0; i < spectrum_data_.size(); i++)
{
if (consumer_ != nullptr)
{
consumer_->consumeSpectrum(spectrum_data_[i].spectrum);
if (options_.getAlwaysAppendData())
{
exp_->addSpectrum(std::move(spectrum_data_[i].spectrum));
}
}
else
{
exp_->addSpectrum(std::move(spectrum_data_[i].spectrum));
}
}
// Delete batch
spectrum_data_.clear();
}
void MzMLHandler::populateChromatogramsWithData_()
{
// Whether chromatogram should be populated with data
if (options_.getFillData())
{
size_t errCount = 0;
String error_message;
#ifdef _OPENMP
#pragma omp parallel for
#endif
for (SignedSize i = 0; i < (SignedSize)chromatogram_data_.size(); i++)
{
// parallel exception catching and re-throwing business
try
{
populateChromatogramsWithData_(chromatogram_data_[i].data,
chromatogram_data_[i].default_array_length,
options_,
chromatogram_data_[i].chromatogram);
if (options_.getSortChromatogramsByRT() && !chromatogram_data_[i].chromatogram.isSorted())
{
chromatogram_data_[i].chromatogram.sortByPosition();
}
}
catch (OpenMS::Exception::BaseException& e)
{
#pragma omp critical
{
++errCount;
error_message = e.what();
}
}
catch (...)
{
#pragma omp atomic
++errCount;
}
}
if (errCount != 0)
{
// throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, file_, "Error during parsing of binary data.");
std::cerr << " Parsing error: '" << error_message << "'" << std::endl;
std::cerr << " You could try to disable sorting spectra while loading." << std::endl;
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, file_, "Error during parsing of binary data: '" + error_message + "'");
}
}
// Append all chromatograms to experiment / consumer
for (Size i = 0; i < chromatogram_data_.size(); i++)
{
if (consumer_ != nullptr)
{
consumer_->consumeChromatogram(chromatogram_data_[i].chromatogram);
if (options_.getAlwaysAppendData())
{
exp_->addChromatogram(std::move(chromatogram_data_[i].chromatogram));
}
}
else
{
exp_->addChromatogram(std::move(chromatogram_data_[i].chromatogram));
}
}
// Delete batch
chromatogram_data_.clear();
}
void MzMLHandler::populateSpectraWithData_(std::vector<MzMLHandlerHelper::BinaryData>& input_data,
Size& default_arr_length,
const PeakFileOptions& peak_file_options,
SpectrumType& spectrum)
{
typedef SpectrumType::PeakType PeakType;
// decode all base64 arrays
MzMLHandlerHelper::decodeBase64Arrays(input_data, options_.getSkipXMLChecks());
//look up the precision and the index of the intensity and m/z array
bool mz_precision_64 = true;
bool int_precision_64 = true;
SignedSize mz_index = -1;
SignedSize int_index = -1;
MzMLHandlerHelper::computeDataProperties_(input_data, mz_precision_64, mz_index, "m/z array");
MzMLHandlerHelper::computeDataProperties_(input_data, int_precision_64, int_index, "intensity array");
//Abort if no m/z or intensity array is present
if (int_index == -1 || mz_index == -1)
{
//if defaultArrayLength > 0 : warn that no m/z or int arrays is present
if (default_arr_length != 0)
{
warning(LOAD, String("The m/z or intensity array of spectrum '") + spectrum.getNativeID() + "' is missing and default_arr_length is " + default_arr_length + ".");
}
return;
}
// Error if intensity or m/z is encoded as int32|64 - they should be float32|64!
if ((!input_data[mz_index].ints_32.empty()) || (!input_data[mz_index].ints_64.empty()))
{
fatalError(LOAD, "Encoding m/z array as integer is not allowed!");
}
if ((!input_data[int_index].ints_32.empty()) || (!input_data[int_index].ints_64.empty()))
{
fatalError(LOAD, "Encoding intensity array as integer is not allowed!");
}
// Warn if the decoded data has a different size than the defaultArrayLength
Size mz_size = mz_precision_64 ? input_data[mz_index].floats_64.size() : input_data[mz_index].floats_32.size();
Size int_size = int_precision_64 ? input_data[int_index].floats_64.size() : input_data[int_index].floats_32.size();
// Check if int-size and mz-size are equal
if (mz_size != int_size)
{
fatalError(LOAD, String("The length of m/z and integer values of spectrum '") + spectrum.getNativeID() + "' differ (mz-size: " + mz_size + ", int-size: " + int_size + "! Not reading spectrum!");
}
bool repair_array_length = false;
if (default_arr_length != mz_size)
{
warning(LOAD, String("The m/z array of spectrum '") + spectrum.getNativeID() + "' has the size " + mz_size + ", but it should have size " + default_arr_length + " (defaultArrayLength).");
repair_array_length = true;
}
if (default_arr_length != int_size)
{
warning(LOAD, String("The intensity array of spectrum '") + spectrum.getNativeID() + "' has the size " + int_size + ", but it should have size " + default_arr_length + " (defaultArrayLength).");
repair_array_length = true;
}
if (repair_array_length)
{
default_arr_length = int_size;
warning(LOAD, String("Fixing faulty defaultArrayLength to ") + default_arr_length + ".");
}
// Copy meta data from m/z and intensity binary
// We don't have this as a separate location => store it in spectrum
spectrum.addMetaValues(input_data[mz_index].meta);
spectrum.addMetaValues(input_data[int_index].meta);
//add the peaks and the meta data to the container (if they pass the restrictions)
PeakType tmp;
spectrum.reserve(default_arr_length);
// Optimized code paths for different scenarios
bool has_mz_range = peak_file_options.hasMZRange();
bool has_intensity_range = peak_file_options.hasIntensityRange();
bool has_metadata = input_data.size() > 2;
// Pre-identify metadata arrays and create spectrum arrays for efficient access
struct MetaArrayInfo {
Size input_index;
Size spectrum_index;
MzMLHandlerHelper::BinaryData::DATA_TYPE data_type;
MzMLHandlerHelper::BinaryData::PRECISION precision;
};
std::vector<MetaArrayInfo> meta_arrays;
meta_arrays.reserve(input_data.size() - 2); // reserve space for all but m/z and intensity arrays
if (has_metadata)
{
Size meta_float_idx = 0, meta_int_idx = 0, meta_string_idx = 0;
for (Size i = 0; i < input_data.size(); i++)
{
if (static_cast<SignedSize>(i) == int_index || static_cast<SignedSize>(i) == mz_index) continue; // Skip m/z and intensity arrays
MetaArrayInfo info;
info.input_index = i;
info.data_type = input_data[i].data_type;
info.precision = input_data[i].precision;
if (input_data[i].data_type == MzMLHandlerHelper::BinaryData::DT_FLOAT)
{
info.spectrum_index = meta_float_idx++;
//create new array
spectrum.getFloatDataArrays().resize(spectrum.getFloatDataArrays().size() + 1);
//reserve space in the array
spectrum.getFloatDataArrays().back().reserve(input_data[i].size);
//copy meta info into MetaInfoDescription
spectrum.getFloatDataArrays().back().MetaInfoDescription::operator=(input_data[i].meta);
}
else if (input_data[i].data_type == MzMLHandlerHelper::BinaryData::DT_INT)
{
info.spectrum_index = meta_int_idx++;
//create new array
spectrum.getIntegerDataArrays().resize(spectrum.getIntegerDataArrays().size() + 1);
//reserve space in the array
spectrum.getIntegerDataArrays().back().reserve(input_data[i].size);
//copy meta info into MetaInfoDescription
spectrum.getIntegerDataArrays().back().MetaInfoDescription::operator=(input_data[i].meta);
}
else if (input_data[i].data_type == MzMLHandlerHelper::BinaryData::DT_STRING)
{
info.spectrum_index = meta_string_idx++;
//create new array
spectrum.getStringDataArrays().resize(spectrum.getStringDataArrays().size() + 1);
//reserve space in the array
spectrum.getStringDataArrays().back().reserve(input_data[i].decoded_char.size());
//copy meta info into MetaInfoDescription
spectrum.getStringDataArrays().back().MetaInfoDescription::operator=(input_data[i].meta);
}
meta_arrays.push_back(info);
}
}
// Most common case: no ranges, 64/32 precision, no metadata
if (mz_precision_64 && !int_precision_64 && !has_metadata && !has_mz_range && !has_intensity_range)
{
std::vector<double>::const_iterator mz_it = input_data[mz_index].floats_64.begin();
std::vector<float>::const_iterator int_it = input_data[int_index].floats_32.begin();
for (Size n = 0; n < default_arr_length; n++) {
tmp.setIntensity(*int_it);
tmp.setMZ(*mz_it);
++mz_it;
++int_it;
spectrum.push_back(tmp);
}
return;
}
// Optimized case: no filtering, but with metadata
if (!has_mz_range && !has_intensity_range)
{
// Copy all peaks first using direct array access
if (mz_precision_64 && int_precision_64) {
const auto& mz_data = input_data[mz_index].floats_64;
const auto& int_data = input_data[int_index].floats_64;
for (Size n = 0; n < default_arr_length; n++) {
tmp.setMZ(mz_data[n]);
tmp.setIntensity(int_data[n]);
spectrum.push_back(tmp);
}
} else if (mz_precision_64 && !int_precision_64) {
const auto& mz_data = input_data[mz_index].floats_64;
const auto& int_data = input_data[int_index].floats_32;
for (Size n = 0; n < default_arr_length; n++) {
tmp.setMZ(mz_data[n]);
tmp.setIntensity(int_data[n]);
spectrum.push_back(tmp);
}
} else if (!mz_precision_64 && int_precision_64) {
const auto& mz_data = input_data[mz_index].floats_32;
const auto& int_data = input_data[int_index].floats_64;
for (Size n = 0; n < default_arr_length; n++) {
tmp.setMZ(mz_data[n]);
tmp.setIntensity(int_data[n]);
spectrum.push_back(tmp);
}
} else {
const auto& mz_data = input_data[mz_index].floats_32;
const auto& int_data = input_data[int_index].floats_32;
for (Size n = 0; n < default_arr_length; n++) {
tmp.setMZ(mz_data[n]);
tmp.setIntensity(int_data[n]);
spectrum.push_back(tmp);
}
}
// Copy all metadata arrays in bulk
if (has_metadata) {
for (const auto& meta : meta_arrays) {
const auto& data = input_data[meta.input_index];
Size copy_length = std::min(default_arr_length, data.size);
// no warning if size mismatched required; done while converting from base64
if (meta.data_type == MzMLHandlerHelper::BinaryData::DT_FLOAT) {
auto& target_array = spectrum.getFloatDataArrays()[meta.spectrum_index];
target_array.reserve(copy_length);
if (meta.precision == MzMLHandlerHelper::BinaryData::PRE_64) {
target_array.insert(target_array.end(), data.floats_64.begin(), data.floats_64.begin() + copy_length);
} else {
target_array.insert(target_array.end(), data.floats_32.begin(), data.floats_32.begin() + copy_length);
}
} else if (meta.data_type == MzMLHandlerHelper::BinaryData::DT_INT) {
auto& target_array = spectrum.getIntegerDataArrays()[meta.spectrum_index];
target_array.reserve(copy_length);
if (meta.precision == MzMLHandlerHelper::BinaryData::PRE_64) {
target_array.insert(target_array.end(), data.ints_64.begin(), data.ints_64.begin() + copy_length);
} else {
target_array.insert(target_array.end(), data.ints_32.begin(), data.ints_32.begin() + copy_length);
}
} else if (meta.data_type == MzMLHandlerHelper::BinaryData::DT_STRING) {
auto& target_array = spectrum.getStringDataArrays()[meta.spectrum_index];
Size string_copy_length = std::min(copy_length, data.decoded_char.size());
target_array.reserve(string_copy_length);
target_array.insert(target_array.end(), data.decoded_char.begin(), data.decoded_char.begin() + string_copy_length);
}
}
}
return;
}
// General case with filtering (rare case - keep simple)
for (Size n = 0; n < default_arr_length; n++) {
double mz = mz_precision_64 ? input_data[mz_index].floats_64[n] : input_data[mz_index].floats_32[n];
double intensity = int_precision_64 ? input_data[int_index].floats_64[n] : input_data[int_index].floats_32[n];
if ((!has_mz_range || peak_file_options.getMZRange().encloses(DPosition<1>(mz))) &&
(!has_intensity_range || peak_file_options.getIntensityRange().encloses(DPosition<1>(intensity)))) {
tmp.setIntensity(intensity);
tmp.setMZ(mz);
spectrum.push_back(tmp);
// Add metadata efficiently for filtered peaks
if (has_metadata) {
for (const auto& meta : meta_arrays) {
const auto& data = input_data[meta.input_index];
if (n < data.size) {
if (meta.data_type == MzMLHandlerHelper::BinaryData::DT_FLOAT) {
double value = (meta.precision == MzMLHandlerHelper::BinaryData::PRE_64) ?
data.floats_64[n] : data.floats_32[n];
spectrum.getFloatDataArrays()[meta.spectrum_index].push_back(value);
} else if (meta.data_type == MzMLHandlerHelper::BinaryData::DT_INT) {
Int64 value = (meta.precision == MzMLHandlerHelper::BinaryData::PRE_64) ?
data.ints_64[n] : data.ints_32[n];
spectrum.getIntegerDataArrays()[meta.spectrum_index].push_back(value);
} else if (meta.data_type == MzMLHandlerHelper::BinaryData::DT_STRING) {
if (n < data.decoded_char.size()) {
spectrum.getStringDataArrays()[meta.spectrum_index].push_back(data.decoded_char[n]);
}
}
}
}
}
}
}
}
void MzMLHandler::populateChromatogramsWithData_(std::vector<MzMLHandlerHelper::BinaryData>& input_data,
Size& default_arr_length,
const PeakFileOptions& peak_file_options,
ChromatogramType& inp_chromatogram)
{
typedef ChromatogramType::PeakType ChromatogramPeakType;
//decode all base64 arrays
MzMLHandlerHelper::decodeBase64Arrays(input_data, options_.getSkipXMLChecks());
//look up the precision and the index of the intensity and m/z array
bool int_precision_64 = true;
bool rt_precision_64 = true;
SignedSize int_index = -1;
SignedSize rt_index = -1;
MzMLHandlerHelper::computeDataProperties_(input_data, rt_precision_64, rt_index, "time array");
MzMLHandlerHelper::computeDataProperties_(input_data, int_precision_64, int_index, "intensity array");
//Abort if no m/z or intensity array is present
if (int_index == -1 || rt_index == -1)
{
//if defaultArrayLength > 0 : warn that no time or int arrays is present
if (default_arr_length != 0)
{
warning(LOAD, String("The time or intensity array of chromatogram '") +
inp_chromatogram.getNativeID() + "' is missing and default_arr_length is " + default_arr_length + ".");
}
return;
}
// Warn if the decoded data has a different size than the defaultArrayLength
Size rt_size = rt_precision_64 ? input_data[rt_index].floats_64.size() : input_data[rt_index].floats_32.size();
Size int_size = int_precision_64 ? input_data[int_index].floats_64.size() : input_data[int_index].floats_32.size();
// Check if int-size and rt-size are equal
if (rt_size != int_size)
{
fatalError(LOAD, String("The length of RT and intensity values of chromatogram '") + inp_chromatogram.getNativeID() + "' differ (rt-size: " + rt_size + ", int-size: " + int_size + "! Not reading chromatogram!");
}
bool repair_array_length = false;
if (default_arr_length != rt_size)
{
warning(LOAD, String("The base64-decoded rt array of chromatogram '") + inp_chromatogram.getNativeID() + "' has the size " + rt_size + ", but it should have size " + default_arr_length + " (defaultArrayLength).");
repair_array_length = true;
}
if (default_arr_length != int_size)
{
warning(LOAD, String("The base64-decoded intensity array of chromatogram '") + inp_chromatogram.getNativeID() + "' has the size " + int_size + ", but it should have size " + default_arr_length + " (defaultArrayLength).");
repair_array_length = true;
}
// repair size of array, accessing memory that is beyond int_size will lead to segfaults later
if (repair_array_length)
{
default_arr_length = int_size; // set to length of actual data (int_size and rt_size are equal, s.a.)
warning(LOAD, String("Fixing faulty defaultArrayLength to ") + default_arr_length + ".");
}
// Create meta data arrays and reserve enough space for the content
if (input_data.size() > 2)
{
for (Size i = 0; i < input_data.size(); i++)
{
if (input_data[i].meta.getName() != "intensity array" && input_data[i].meta.getName() != "time array")
{
if (input_data[i].data_type == MzMLHandlerHelper::BinaryData::DT_FLOAT)
{
//create new array
inp_chromatogram.getFloatDataArrays().resize(inp_chromatogram.getFloatDataArrays().size() + 1);
//reserve space in the array
inp_chromatogram.getFloatDataArrays().back().reserve(input_data[i].size);
//copy meta info into MetaInfoDescription
inp_chromatogram.getFloatDataArrays().back().MetaInfoDescription::operator=(input_data[i].meta);
}
else if (input_data[i].data_type == MzMLHandlerHelper::BinaryData::DT_INT)
{
//create new array
inp_chromatogram.getIntegerDataArrays().resize(inp_chromatogram.getIntegerDataArrays().size() + 1);
//reserve space in the array
inp_chromatogram.getIntegerDataArrays().back().reserve(input_data[i].size);
//copy meta info into MetaInfoDescription
inp_chromatogram.getIntegerDataArrays().back().MetaInfoDescription::operator=(input_data[i].meta);
}
else if (input_data[i].data_type == MzMLHandlerHelper::BinaryData::DT_STRING)
{
//create new array
inp_chromatogram.getStringDataArrays().resize(inp_chromatogram.getStringDataArrays().size() + 1);
//reserve space in the array
inp_chromatogram.getStringDataArrays().back().reserve(input_data[i].decoded_char.size());
//copy meta info into MetaInfoDescription
inp_chromatogram.getStringDataArrays().back().MetaInfoDescription::operator=(input_data[i].meta);
}
}
}
}
// Copy meta data from time and intensity binary
// We don't have this as a separate location => store it directly in spectrum meta data
for (Size i = 0; i < input_data.size(); i++)
{
if (input_data[i].meta.getName() == "time array" || input_data[i].meta.getName() == "intensity array")
{
std::vector<UInt> keys;
input_data[i].meta.getKeys(keys);
for (Size k = 0; k < keys.size(); ++k)
{
inp_chromatogram.setMetaValue(keys[k], input_data[i].meta.getMetaValue(keys[k]));
}
}
}
// Add the peaks and the meta data to the container (if they pass the restrictions)
inp_chromatogram.reserve(default_arr_length);
ChromatogramPeakType tmp;
for (Size n = 0; n < default_arr_length; n++)
{
double rt = rt_precision_64 ? input_data[rt_index].floats_64[n] : input_data[rt_index].floats_32[n];
double intensity = int_precision_64 ? input_data[int_index].floats_64[n] : input_data[int_index].floats_32[n];
if ((!peak_file_options.hasRTRange() || peak_file_options.getRTRange().encloses(DPosition<1>(rt)))
&& (!peak_file_options.hasIntensityRange() || peak_file_options.getIntensityRange().encloses(DPosition<1>(intensity))))
{
//add peak
tmp.setIntensity(intensity);
tmp.setRT(rt);
inp_chromatogram.push_back(tmp);
//add meta data
UInt meta_float_array_index = 0;
UInt meta_int_array_index = 0;
UInt meta_string_array_index = 0;
for (Size i = 0; i < input_data.size(); i++) //loop over all binary data arrays
{
if (input_data[i].meta.getName() != "intensity array" && input_data[i].meta.getName() != "time array") // is meta data array?
{
if (input_data[i].data_type == MzMLHandlerHelper::BinaryData::DT_FLOAT)
{
if (n < input_data[i].size)
{
double value = (input_data[i].precision == MzMLHandlerHelper::BinaryData::PRE_64) ? input_data[i].floats_64[n] : input_data[i].floats_32[n];
inp_chromatogram.getFloatDataArrays()[meta_float_array_index].push_back(value);
}
++meta_float_array_index;
}
else if (input_data[i].data_type == MzMLHandlerHelper::BinaryData::DT_INT)
{
if (n < input_data[i].size)
{
Int64 value = (input_data[i].precision == MzMLHandlerHelper::BinaryData::PRE_64) ? input_data[i].ints_64[n] : input_data[i].ints_32[n];
inp_chromatogram.getIntegerDataArrays()[meta_int_array_index].push_back(value);
}
++meta_int_array_index;
}
else if (input_data[i].data_type == MzMLHandlerHelper::BinaryData::DT_STRING)
{
if (n < input_data[i].decoded_char.size())
{
String value = input_data[i].decoded_char[n];
inp_chromatogram.getStringDataArrays()[meta_string_array_index].push_back(value);
}
++meta_string_array_index;
}
}
}
}
}
}
void MzMLHandler::characters(const XMLCh* const chars, const XMLSize_t length)
{
if (skip_spectrum_ || skip_chromatogram_)
{
return;
}
const String& current_tag = open_tags_.back();
if (current_tag == "binary")
{
// Since we convert a Base64 string here, it can only contain plain ASCII
sm_.appendASCII(chars, length, bin_data_.back().base64);
}
else if (current_tag == "offset" || current_tag == "indexListOffset" || current_tag == "fileChecksum")
{
//do nothing for
// - index
// - checksum
// - binary chromatogram data
}
else
{
/*String transcoded_chars2 = sm_.convert(chars);
transcoded_chars2.trim();
if (transcoded_chars2 != "")
{
warning(LOAD, String("Unhandled character content in tag '") + current_tag + "': " +
transcoded_chars2);
}
*/
}
}
void MzMLHandler::startElement(const XMLCh* const /*uri*/, const XMLCh* const /*local_name*/, const XMLCh* const qname, const xercesc::Attributes& attributes)
{
constexpr XMLCh s_count[] = {'c','o','u','n','t', 0};
constexpr XMLCh s_default_array_length[] = { 'd','e','f','a','u','l','t','A','r','r','a','y','L','e','n','g','t','h' , 0};
constexpr XMLCh s_array_length[] = { 'a','r','r','a','y','L','e','n','g','t','h' , 0};
constexpr XMLCh s_accession[] = { 'a','c','c','e','s','s','i','o','n' , 0};
constexpr XMLCh s_name[] = { 'n','a','m','e' , 0};
constexpr XMLCh s_type[] = { 't','y','p','e' , 0};
constexpr XMLCh s_value[] = { 'v','a','l','u','e' , 0};
constexpr XMLCh s_unit_accession[] = { 'u','n','i','t','A','c','c','e','s','s','i','o','n' , 0};
constexpr XMLCh s_id[] = { 'i','d' , 0};
constexpr XMLCh s_ref[] = { 'r','e','f' , 0};
constexpr XMLCh s_version[] = { 'v','e','r','s','i','o','n' , 0};
constexpr XMLCh s_version_mzml[] = { 'm','z','M','L',':','v','e','r','s','i','o','n' , 0};
constexpr XMLCh s_order[] = { 'o','r','d','e','r' , 0};
constexpr XMLCh s_location[] = { 'l','o','c','a','t','i','o','n' , 0};
constexpr XMLCh s_sample_ref[] = { 's','a','m','p','l','e','R','e','f' , 0};
constexpr XMLCh s_software_ref[] = { 's','o','f','t','w','a','r','e','R','e','f' , 0};
constexpr XMLCh s_source_file_ref[] = { 's','o','u','r','c','e','F','i','l','e','R','e','f' , 0};
constexpr XMLCh s_spectrum_ref[] = { 's','p','e','c','t','r','u','m','R','e','f' , 0};
constexpr XMLCh s_default_instrument_configuration_ref[] = { 'd','e','f','a','u','l','t','I','n','s','t','r','u','m','e','n','t','C','o','n','f','i','g','u','r','a','t','i','o','n','R','e','f' , 0};
constexpr XMLCh s_instrument_configuration_ref[] = { 'i','n','s','t','r','u','m','e','n','t','C','o','n','f','i','g','u','r','a','t','i','o','n','R','e','f' , 0};
constexpr XMLCh s_default_data_processing_ref[] = { 'd','e','f','a','u','l','t','D','a','t','a','P','r','o','c','e','s','s','i','n','g','R','e','f' , 0};
constexpr XMLCh s_data_processing_ref[] = { 'd','a','t','a','P','r','o','c','e','s','s','i','n','g','R','e','f' , 0};
constexpr XMLCh s_start_time_stamp[] = { 's','t','a','r','t','T','i','m','e','S','t','a','m','p' , 0};
constexpr XMLCh s_external_spectrum_id[] = { 'e','x','t','e','r','n','a','l','S','p','e','c','t','r','u','m','I','D' , 0};
// constexpr XMLCh s_default_source_file_ref[] = { 'd','e','f','a','u','l','t','S','o','u','r','c','e','F','i','l','e','R','e','f' , 0};
constexpr XMLCh s_scan_settings_ref[] = { 's','c','a','n','S','e','t','t','i','n','g','s','R','e','f' , 0};
open_tags_.push_back(sm_.convert(qname));
const String& tag = open_tags_.back();
// do nothing until a spectrum/chromatogram/spectrumList ends
if (skip_spectrum_ || skip_chromatogram_)
{
return;
}
// determine parent tag
const String* parent_tag = &tag; // set to some valid string
if (open_tags_.size() > 1)
{
parent_tag = &(*(open_tags_.end() - 2));
}
const String* parent_parent_tag = &tag; // set to some valid string
if (open_tags_.size() > 2)
{
parent_parent_tag = &(*(open_tags_.end() - 3));
}
if (tag == "spectrum")
{
// for cppcheck
constexpr XMLCh s_spot_id[] = { 's','p','o','t','I','D', 0 };
//number of peaks
spec_ = SpectrumType();
default_array_length_ = attributeAsInt_(attributes, s_default_array_length);
//spectrum source file
String source_file_ref;
if (optionalAttributeAsString_(source_file_ref, attributes, s_source_file_ref))
{
if (source_files_.find(source_file_ref) != source_files_.end())
{
spec_.setSourceFile(source_files_[source_file_ref]);
}
else
{
OPENMS_LOG_WARN << "Error: unregistered source file reference " << source_file_ref << "." << std::endl;
}
}
//native id
spec_.setNativeID(attributeAsString_(attributes, s_id));
//maldi spot id
String maldi_spot_id;
if (optionalAttributeAsString_(maldi_spot_id, attributes, s_spot_id))
{
spec_.setMetaValue("maldi_spot_id", maldi_spot_id);
}
//data processing
String data_processing_ref;
if (optionalAttributeAsString_(data_processing_ref, attributes, s_data_processing_ref))
{
spec_.setDataProcessing(processing_[data_processing_ref]);
}
else
{
spec_.setDataProcessing(processing_[default_processing_]);
}
}
else if (tag == "chromatogram")
{
if (load_detail_ == XMLHandler::LD_COUNTS_WITHOPTIONS)
{ //, but we only want to count
skip_chromatogram_ = true; // skip the remaining chrom, until endElement(chromatogram)
++chromatogram_count_;
}
chromatogram_ = ChromatogramType();
default_array_length_ = attributeAsInt_(attributes, s_default_array_length);
String source_file_ref;
if (optionalAttributeAsString_(source_file_ref, attributes, s_source_file_ref))
{
chromatogram_.setSourceFile(source_files_[source_file_ref]);
}
// native id
chromatogram_.setNativeID(attributeAsString_(attributes, s_id));
// data processing
String data_processing_ref;
if (optionalAttributeAsString_(data_processing_ref, attributes, s_data_processing_ref))
{
chromatogram_.setDataProcessing(processing_[data_processing_ref]);
}
else
{
chromatogram_.setDataProcessing(processing_[default_processing_]);
}
}
else if (tag == "spectrumList")
{
//default data processing
default_processing_ = attributeAsString_(attributes, s_default_data_processing_ref);
//Abort if we need meta data only
if (options_.getMetadataOnly())
{
throw EndParsingSoftly(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
scan_count_total_ = attributeAsInt_(attributes, s_count);
logger_.startProgress(0, scan_count_total_, "loading spectra list");
in_spectrum_list_ = true;
// we only want total scan count and chrom count
if (load_detail_ == XMLHandler::LD_RAWCOUNTS)
{ // in case chromatograms came before spectra, we have all information --> end parsing
if (chrom_count_total_ != -1) throw EndParsingSoftly(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
// or skip the remaining spectra until </spectrumList>
skip_spectrum_ = true;
}
else
{
exp_->reserveSpaceSpectra(scan_count_total_);
}
}
else if (tag == "chromatogramList")
{
// return if skip_chromatogram_ true
if (skip_chromatogram_)
{
return;
}
// default data processing
default_processing_ = attributeAsString_(attributes, s_default_data_processing_ref);
//Abort if we need meta data only
if (options_.getMetadataOnly())
{
throw EndParsingSoftly(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
chrom_count_total_ = attributeAsInt_(attributes, s_count);
logger_.startProgress(0, chrom_count_total_, "loading chromatogram list");
in_spectrum_list_ = false;
// we only want total scan count and chrom count
if (load_detail_ == XMLHandler::LD_RAWCOUNTS)
{ // in case spectra came before chroms, we have all information --> end parsing
if (scan_count_total_ != -1)
{
throw EndParsingSoftly(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
// or skip the remaining chroms until </chromatogramList>
skip_chromatogram_ = true;
}
else
{
exp_->reserveSpaceChromatograms(chrom_count_total_);
}
}
else if (tag == "binaryDataArrayList" /* && in_spectrum_list_*/)
{
bin_data_.reserve(attributeAsInt_(attributes, s_count));
}
else if (tag == "binaryDataArray" /* && in_spectrum_list_*/)
{
bin_data_.emplace_back();
bin_data_.back().np_compression = MSNumpressCoder::NONE; // ensure that numpress compression is initially set to none ...
bin_data_.back().compression = false; // ensure that zlib compression is initially set to none ...
// array length
Int array_length = (Int) default_array_length_;
optionalAttributeAsInt_(array_length, attributes, s_array_length);
bin_data_.back().size = array_length;
// data processing
String data_processing_ref;
if (optionalAttributeAsString_(data_processing_ref, attributes, s_data_processing_ref))
{
bin_data_.back().meta.setDataProcessing(processing_[data_processing_ref]);
}
}
else if (tag == "cvParam")
{
String value;
optionalAttributeAsString_(value, attributes, s_value);
String unit_accession;
optionalAttributeAsString_(unit_accession, attributes, s_unit_accession);
handleCVParam_(*parent_parent_tag, *parent_tag, attributeAsString_(attributes, s_accession), attributeAsString_(attributes, s_name), value, unit_accession);
}
else if (tag == "userParam")
{
String type;
optionalAttributeAsString_(type, attributes, s_type);
String value;
optionalAttributeAsString_(value, attributes, s_value);
String unit_accession;
optionalAttributeAsString_(unit_accession, attributes, s_unit_accession);
handleUserParam_(*parent_parent_tag, *parent_tag, attributeAsString_(attributes, s_name), type, value, unit_accession);
}
else if (tag == "referenceableParamGroup")
{
current_id_ = attributeAsString_(attributes, s_id);
}
else if (tag == "sourceFile")
{
current_id_ = attributeAsString_(attributes, s_id);
// Name of the source file, without reference to location (either URI or local path). e.g. "control.mzML"
String name_of_file = attributeAsString_(attributes, s_name);
//URI-formatted location where the file was retrieved.
String path_to_file = attributeAsString_(attributes, s_location);
// mzML files often deviate from the specification by storing e.g. the full path in the name attribute etc.
// error: whole path is stored in file name. fix: split into path and file name
if (path_to_file.empty() && !name_of_file.empty())
{
path_to_file = File::path(name_of_file);
name_of_file = File::basename(name_of_file);
if (path_to_file == ".")
{
path_to_file = "file://./";
}
}
// format URI prefix as in mzML spec.
if (path_to_file.hasPrefix("File://"))
{
path_to_file.substitute("File://", "file://");
}
if (path_to_file.hasPrefix("FILE://"))
{
path_to_file.substitute("FILE://", "file://");
}
if (path_to_file.hasPrefix("file:///."))
{
path_to_file.substitute("file:///.", "file://./");
}
bool is_relative_path = path_to_file.hasPrefix("file://./") || path_to_file.hasPrefix("file://../");
// ill formed absolute or relative path
if (!is_relative_path && path_to_file.hasPrefix("file://") && !path_to_file.hasPrefix("file:///"))
{
warning(LOAD, "Ill formed absolute or relative sourceFile path: " + path_to_file);
}
// if possible convert relative path to absolute path
if (is_relative_path && File::isDirectory(path_to_file))
{
String normal_path = String(path_to_file).substitute("file://", ""); // remove URI prefix
path_to_file = String("file://") + File::absolutePath(normal_path); // on linux this e.g. file:///home... on win: file://C:/...
}
// absolute path to the root: remove additional / otherwise we will get file://// on concatenation
if (!is_relative_path && path_to_file == "file:///")
{
path_to_file = "file://";
}
source_files_[current_id_].setNameOfFile(name_of_file);
source_files_[current_id_].setPathToFile(path_to_file);
}
else if (tag == "referenceableParamGroupRef")
{
//call handleCVParam_ with the parent tag for each parameter in the group
String ref = attributeAsString_(attributes, s_ref);
for (Size i = 0; i < ref_param_[ref].size(); ++i)
{
handleCVParam_(*parent_parent_tag, *parent_tag, ref_param_[ref][i].accession, ref_param_[ref][i].name, ref_param_[ref][i].value, ref_param_[ref][i].unit_accession);
}
}
else if (tag == "scan")
{
Acquisition tmp;
//source file => meta data
String source_file_ref;
if (optionalAttributeAsString_(source_file_ref, attributes, s_source_file_ref))
{
tmp.setMetaValue("source_file_name", source_files_[source_file_ref].getNameOfFile());
tmp.setMetaValue("source_file_path", source_files_[source_file_ref].getPathToFile());
}
//external spectrum id => meta data
String external_spectrum_id;
if (optionalAttributeAsString_(external_spectrum_id, attributes, s_external_spectrum_id))
{
tmp.setIdentifier(external_spectrum_id);
}
//spectrumRef - not really needed
//instrumentConfigurationRef - not really needed: why should a scan have a different instrument?
String instrument_configuration_ref;
if (optionalAttributeAsString_(instrument_configuration_ref, attributes, s_instrument_configuration_ref))
{
warning(LOAD, "Unhandled attribute 'instrumentConfigurationRef' in 'scan' tag.");
}
spec_.getAcquisitionInfo().push_back(std::move(tmp));
}
else if (tag == "mzML")
{
scan_count_ = 0;
chromatogram_count_ = 0;
scan_count_total_ = -1;
chrom_count_total_ = -1;
//check file version against schema version
String file_version;
if (!(optionalAttributeAsString_(file_version, attributes, s_version) || optionalAttributeAsString_(file_version, attributes, s_version_mzml)) )
{
warning(LOAD, "No version attribute in mzML");
}
VersionInfo::VersionDetails current_version = VersionInfo::VersionDetails::create(file_version);
static VersionInfo::VersionDetails mzML_min_version = VersionInfo::VersionDetails::create("1.1.0");
if (current_version == VersionInfo::VersionDetails::EMPTY)
{
warning(LOAD, String("Invalid mzML version string '") + file_version + "'. Assuming mzML version " + version_ + "!");
}
else
{
if (current_version < mzML_min_version)
{
fatalError(LOAD, String("Only mzML 1.1.0 or higher is supported! This file has version '") + file_version + "'.");
}
else if (current_version > VersionInfo::VersionDetails::create(version_))
{
warning(LOAD, "The mzML file version (" + file_version + ") is newer than the parser version (" + version_ + "). This might lead to undefined behavior.");
}
}
//handle file accession
String accession;
if (optionalAttributeAsString_(accession, attributes, s_accession))
{
exp_->setIdentifier(accession);
}
//handle file id
String id;
if (optionalAttributeAsString_(id, attributes, s_id))
{
exp_->setMetaValue("mzml_id", id);
}
pg_outer.startProgress(0, 1, "loading mzML");
}
else if (tag == "contact")
{
exp_->getContacts().emplace_back();
}
else if (tag == "sample")
{
current_id_ = attributeAsString_(attributes, s_id);
String name;
if (optionalAttributeAsString_(name, attributes, s_name))
{
samples_[current_id_].setName(name);
}
}
else if (tag == "run")
{
//sample
String sample_ref;
if (optionalAttributeAsString_(sample_ref, attributes, s_sample_ref))
{
exp_->setSample(samples_[sample_ref]);
}
//instrument
String instrument_ref = attributeAsString_(attributes, s_default_instrument_configuration_ref);
exp_->setInstrument(instruments_[instrument_ref]);
//start time
String start_time;
if (optionalAttributeAsString_(start_time, attributes, s_start_time_stamp))
{
exp_->setDateTime(asDateTime_(start_time));
}
/*
//defaultSourceFileRef
String default_source_file_ref;
if (optionalAttributeAsString_(default_source_file_ref, attributes, s_default_source_file_ref))
{
exp_->getSourceFiles().push_back(source_files_[default_source_file_ref]);
}
*/
}
else if (tag == "software")
{
current_id_ = attributeAsString_(attributes, s_id);
software_[current_id_].setVersion(attributeAsString_(attributes, s_version));
}
else if (tag == "dataProcessing")
{
current_id_ = attributeAsString_(attributes, s_id);
}
else if (tag == "processingMethod")
{
DataProcessingPtr dp(new DataProcessing);
// See ticket 452: Do NOT remove this try/catch block until foreign
// software (e.g. ProteoWizard msconvert.exe) produces valid mzML.
try
{
dp->setSoftware(software_[attributeAsString_(attributes, s_software_ref)]);
}
catch (Exception::ParseError& /*e*/)
{
OPENMS_LOG_ERROR << "Warning: Parsing error, \"processingMethod\" is missing the required attribute \"softwareRef\".\n" <<
"The software tool which generated this mzML should be fixed. Please notify the maintainers." << std::endl;
}
processing_[current_id_].push_back(dp);
//The order of processing methods is currently ignored
}
else if (tag == "instrumentConfiguration")
{
current_id_ = attributeAsString_(attributes, s_id);
//scan settings
String scan_settings_ref;
if (optionalAttributeAsString_(scan_settings_ref, attributes, s_scan_settings_ref))
{
warning(LOAD, "Unhandled attribute 'scanSettingsRef' in 'instrumentConfiguration' tag.");
}
}
else if (tag == "softwareRef")
{
//Set the software of the instrument
instruments_[current_id_].setSoftware(software_[attributeAsString_(attributes, s_ref)]);
}
else if (tag == "source")
{
instruments_[current_id_].getIonSources().emplace_back();
instruments_[current_id_].getIonSources().back().setOrder(attributeAsInt_(attributes, s_order));
}
else if (tag == "analyzer")
{
instruments_[current_id_].getMassAnalyzers().emplace_back();
instruments_[current_id_].getMassAnalyzers().back().setOrder(attributeAsInt_(attributes, s_order));
}
else if (tag == "detector")
{
instruments_[current_id_].getIonDetectors().emplace_back();
instruments_[current_id_].getIonDetectors().back().setOrder(attributeAsInt_(attributes, s_order));
}
else if (tag == "precursor")
{
if (in_spectrum_list_)
{
//initialize
spec_.getPrecursors().emplace_back();
//source file => meta data
String source_file_ref;
if (optionalAttributeAsString_(source_file_ref, attributes, s_source_file_ref))
{
spec_.getPrecursors().back().setMetaValue("source_file_name", source_files_[source_file_ref].getNameOfFile());
spec_.getPrecursors().back().setMetaValue("source_file_path", source_files_[source_file_ref].getPathToFile());
}
//external spectrum id => meta data
String external_spectrum_id;
if (optionalAttributeAsString_(external_spectrum_id, attributes, s_external_spectrum_id))
{
spec_.getPrecursors().back().setMetaValue("external_spectrum_id", external_spectrum_id);
}
//spectrum_ref => meta data
String spectrum_ref;
if (optionalAttributeAsString_(spectrum_ref, attributes, s_spectrum_ref))
{
spec_.getPrecursors().back().setMetaValue("spectrum_ref", spectrum_ref);
}
//reset selected ion count
selected_ion_count_ = 0;
}
else
{
chromatogram_.setPrecursor(Precursor());
String source_file_ref;
if (optionalAttributeAsString_(source_file_ref, attributes, s_source_file_ref))
{
chromatogram_.getPrecursor().setMetaValue("source_file_name", source_files_[source_file_ref].getNameOfFile());
chromatogram_.getPrecursor().setMetaValue("source_file_path", source_files_[source_file_ref].getPathToFile());
}
String external_spectrum_id;
if (optionalAttributeAsString_(external_spectrum_id, attributes, s_external_spectrum_id))
{
chromatogram_.getPrecursor().setMetaValue("external_spectrum_id", external_spectrum_id);
}
selected_ion_count_ = 0;
}
}
else if (tag == "product")
{
//initialize
if (in_spectrum_list_)
{
spec_.getProducts().emplace_back();
}
else
{
chromatogram_.setProduct(Product());
}
}
else if (tag == "selectedIon")
{
//increase selected ion count
++selected_ion_count_;
}
else if (tag == "selectedIonList")
{
//Warn if more than one selected ion is present
if (attributeAsInt_(attributes, s_count) > 1)
{
warning(LOAD, "OpenMS can currently handle only one selection ion per precursor! Only the first ion is loaded!");
}
}
else if (tag == "scanWindow")
{
spec_.getInstrumentSettings().getScanWindows().emplace_back();
}
}
void MzMLHandler::endElement(const XMLCh* const /*uri*/, const XMLCh* const /*local_name*/, const XMLCh* const qname)
{
constexpr XMLCh s_spectrum[] = { 's','p','e','c','t','r','u','m' , 0};
constexpr XMLCh s_chromatogram[] = { 'c','h','r','o','m','a','t','o','g','r','a','m' , 0};
constexpr XMLCh s_spectrum_list[] = { 's','p','e','c','t','r','u','m','L','i','s','t' , 0};
constexpr XMLCh s_chromatogram_list[] = { 'c','h','r','o','m','a','t','o','g','r','a','m','L','i','s','t' , 0};
constexpr XMLCh s_mzml[] = { 'm','z','M','L' , 0};
constexpr XMLCh s_sourceFileList[] = { 's','o','u','r','c','e','F','i','l','e','L','i','s','t', 0};
open_tags_.pop_back();
if (equal_(qname, s_spectrum))
{
if (!skip_spectrum_)
{
// catch errors stemming from confusion about elution time and scan time
if (!rt_set_ && spec_.metaValueExists("elution time (seconds)"))
{
spec_.setRT(spec_.getMetaValue("elution time (seconds)"));
}
/* this is too hot (could be SRM as well? -- check!):
// correct spectrum type if possible (i.e., make it more specific)
if (spec_.getInstrumentSettings().getScanMode() == InstrumentSettings::ScanMode::MASSSPECTRUM)
{
if (spec_.getMSLevel() <= 1) spec_.getInstrumentSettings().setScanMode(InstrumentSettings::ScanMode::MS1SPECTRUM);
else spec_.getInstrumentSettings().setScanMode(InstrumentSettings::ScanMode::MSNSPECTRUM);
}
*/
// Move current data to (temporary) spectral data object
SpectrumData tmp;
tmp.spectrum = std::move(spec_);
tmp.default_array_length = default_array_length_;
if (options_.getFillData())
{
tmp.data = std::move(bin_data_);
}
// append current spectral data to buffer
spectrum_data_.push_back(std::move(tmp));
if (spectrum_data_.size() >= options_.getMaxDataPoolSize())
{
populateSpectraWithData_();
}
}
switch (load_detail_)
{
case XMLHandler::LD_ALLDATA:
case XMLHandler::LD_COUNTS_WITHOPTIONS:
skip_spectrum_ = false; // don't skip the next spectrum (unless via options later)
break;
case XMLHandler::LD_RAWCOUNTS:
skip_spectrum_ = true; // we always skip spectra; we only need the outer <spectrumList/chromatogramList count=...>
break;
}
rt_set_ = false;
logger_.nextProgress();
bin_data_.clear();
default_array_length_ = 0;
}
else if (equal_(qname, s_chromatogram))
{
if (!skip_chromatogram_)
{
// Move current data to (temporary) spectral data object
ChromatogramData tmp;
tmp.default_array_length = default_array_length_;
tmp.chromatogram = std::move(chromatogram_);
if (options_.getFillData())
{
tmp.data = std::move(bin_data_);
}
// append current spectral data to buffer
chromatogram_data_.push_back(std::move(tmp));
if (chromatogram_data_.size() >= options_.getMaxDataPoolSize())
{
populateChromatogramsWithData_();
}
}
switch (load_detail_)
{
case XMLHandler::LD_ALLDATA:
case XMLHandler::LD_COUNTS_WITHOPTIONS:
if (!options_.getSkipChromatograms())
{
skip_chromatogram_ = false; // don't skip the next chrom
}
break;
case XMLHandler::LD_RAWCOUNTS:
skip_chromatogram_ = true; // we always skip chroms; we only need the outer <spectrumList/chromatogramList count=...>
break;
}
logger_.nextProgress();
bin_data_.clear();
default_array_length_ = 0;
}
else if (equal_(qname, s_spectrum_list))
{
skip_spectrum_ = false; // no more spectra to come, so stop skipping (for the LD_RAWCOUNTS case)
in_spectrum_list_ = false;
logger_.endProgress();
}
else if (equal_(qname, s_chromatogram_list))
{
skip_chromatogram_ = false; // no more chromatograms to come, so stop skipping
in_spectrum_list_ = false;
logger_.endProgress();
}
else if (equal_(qname, s_sourceFileList ))
{
for (auto const& ref_sourcefile : source_files_)
{
auto& sfs = exp_->getSourceFiles();
// only store source files once
if (std::find(sfs.begin(), sfs.end(), ref_sourcefile.second) == sfs.end())
{
exp_->getSourceFiles().push_back(ref_sourcefile.second);
}
}
}
else if (equal_(qname, s_mzml))
{
ref_param_.clear();
current_id_ = "";
source_files_.clear();
samples_.clear();
software_.clear();
instruments_.clear();
processing_.clear();
// Flush the remaining data
populateSpectraWithData_();
populateChromatogramsWithData_();
pg_outer.endProgress(File::fileSize(file_)); // we cannot query the offset within the file when SAX'ing it (Xerces does not support that)
// , so we can only report I/O at the very end
}
}
void MzMLHandler::handleCVParam_(const String& parent_parent_tag,
const String& parent_tag,
const String& accession,
const String& name,
const String& value,
const String& unit_accession)
{
// the actual value stored in the CVParam
DataValue termValue = XMLHandler::cvParamToValue(cv_, parent_tag, accession, name, value, unit_accession);
if (termValue == DataValue::EMPTY) return; // conversion failed (warning message was emitted in cvParamToValue())
//------------------------- run ----------------------------
if (parent_tag == "run")
{
//MS:1000857 ! run attribute
if (accession == "MS:1000858") //fraction identifier
{
exp_->setFractionIdentifier(value);
}
else
{
warning(LOAD, String("Unhandled cvParam '") + accession + "' in tag '" + parent_tag + "'.");
}
}
//------------------------- binaryDataArray ----------------------------
else if (parent_tag == "binaryDataArray")
{
// store name for all non-default arrays
if (cv_.isChildOf(accession, "MS:1000513")) // other array names as string
{
bin_data_.back().meta.setName(cv_.getTerm(accession).name);
}
if (!MzMLHandlerHelper::handleBinaryDataArrayCVParam(bin_data_, accession, value, name, unit_accession))
{
if (!cv_.isChildOf(accession, "MS:1000513")) //other array names as string
{
warning(LOAD, String("Unhandled cvParam '") + accession + "' in tag '" + parent_tag + "'.");
}
}
}
//------------------------- spectrum ----------------------------
else if (parent_tag == "spectrum")
{
//spectrum type
if (accession == "MS:1000294") //mass spectrum
{
spec_.getInstrumentSettings().setScanMode(InstrumentSettings::ScanMode::MASSSPECTRUM);
}
else if (accession == "MS:1000579") //MS1 spectrum
{
spec_.getInstrumentSettings().setScanMode(InstrumentSettings::ScanMode::MS1SPECTRUM);
}
else if (accession == "MS:1000580") //MSn spectrum
{
spec_.getInstrumentSettings().setScanMode(InstrumentSettings::ScanMode::MSNSPECTRUM);
}
else if (accession == "MS:1000581") //CRM spectrum
{
spec_.getInstrumentSettings().setScanMode(InstrumentSettings::ScanMode::CRM);
}
else if (accession == "MS:1000582") //SIM spectrum
{
spec_.getInstrumentSettings().setScanMode(InstrumentSettings::ScanMode::SIM);
}
else if (accession == "MS:1000583") //SRM spectrum
{
spec_.getInstrumentSettings().setScanMode(InstrumentSettings::ScanMode::SRM);
}
else if (accession == "MS:1000804") //electromagnetic radiation spectrum
{
spec_.getInstrumentSettings().setScanMode(InstrumentSettings::ScanMode::EMR);
}
else if (accession == "MS:1000805") //emission spectrum
{
spec_.getInstrumentSettings().setScanMode(InstrumentSettings::ScanMode::EMISSION);
}
else if (accession == "MS:1000806") //absorption spectrum
{
spec_.getInstrumentSettings().setScanMode(InstrumentSettings::ScanMode::ABSORPTION);
}
else if (accession == "MS:1000325") //constant neutral gain spectrum
{
spec_.getInstrumentSettings().setScanMode(InstrumentSettings::ScanMode::CNG);
}
else if (accession == "MS:1000326") //constant neutral loss spectrum
{
spec_.getInstrumentSettings().setScanMode(InstrumentSettings::ScanMode::CNL);
}
else if (accession == "MS:1000341") //precursor ion spectrum
{
spec_.getInstrumentSettings().setScanMode(InstrumentSettings::ScanMode::PRECURSOR);
}
else if (accession == "MS:1000789") //enhanced multiply charged spectrum
{
spec_.getInstrumentSettings().setScanMode(InstrumentSettings::ScanMode::EMC);
}
else if (accession == "MS:1000790") //time-delayed fragmentation spectrum
{
spec_.getInstrumentSettings().setScanMode(InstrumentSettings::ScanMode::TDF);
}
//spectrum representation
else if (accession == "MS:1000127") //centroid spectrum
{
spec_.setType(SpectrumSettings::SpectrumType::CENTROID);
}
else if (accession == "MS:1000128") //profile spectrum
{
spec_.setType(SpectrumSettings::SpectrumType::PROFILE);
}
else if (accession == "MS:1000525") //spectrum representation
{
spec_.setType(SpectrumSettings::SpectrumType::UNKNOWN);
}
else if (accession == "MS:1003441") //ion mobility centroid frame
{
spec_.setIMFormat(IMFormat::CENTROIDED);
}
// spectrum attribute
else if (accession == "MS:1000511") //ms level
{
spec_.setMSLevel(value.toInt());
if (options_.hasMSLevels() && !options_.containsMSLevel(spec_.getMSLevel()))
{
skip_spectrum_ = true;
}
else
{ // MS level is ok
if (load_detail_ == XMLHandler::LD_COUNTS_WITHOPTIONS)
{ //, and we only want to count
// , but do not skip the spectrum yet if (load_detail_ == XMLHandler::LD_COUNTS_WITHOPTIONS), since it might be outside the RT range (so should not count)
//skip_spectrum_ = false; // it is false right now... keep it that way
}
}
}
else if (accession == "MS:1000497") // deprecated: zoom scan is now a scan attribute
{
OPENMS_LOG_DEBUG << "MS:1000497 - zoom scan is now a scan attribute. Reading it for backwards compatibility reasons as spectrum attribute."
<< " You can make this warning go away by converting this file using FileConverter to a newer version of the PSI ontology."
<< " Or by using a recent converter that supports the newest PSI ontology."
<< std::endl;
spec_.getInstrumentSettings().setZoomScan(true);
}
else if (accession == "MS:1000285") //total ion current
{
//No member => meta data
spec_.setMetaValue("total ion current", termValue);
}
else if (accession == "MS:1000504") //base peak m/z
{
//No member => meta data
spec_.setMetaValue("base peak m/z", termValue);
}
else if (accession == "MS:1000505") //base peak intensity
{
//No member => meta data
spec_.setMetaValue("base peak intensity", termValue);
}
else if (accession == "MS:1000527") //highest observed m/z
{
//No member => meta data
spec_.setMetaValue("highest observed m/z", termValue);
}
else if (accession == "MS:1000528") //lowest observed m/z
{
//No member => meta data
spec_.setMetaValue("lowest observed m/z", termValue);
}
else if (accession == "MS:1000618") //highest observed wavelength
{
//No member => meta data
spec_.setMetaValue("highest observed wavelength", termValue);
}
else if (accession == "MS:1000619") //lowest observed wavelength
{
//No member => meta data
spec_.setMetaValue("lowest observed wavelength", termValue);
}
else if (accession == "MS:1000796") //spectrum title
{
//No member => meta data
spec_.setMetaValue("spectrum title", termValue);
}
else if (accession == "MS:1000797") //peak list scans
{
//No member => meta data
spec_.setMetaValue("peak list scans", termValue);
}
else if (accession == "MS:1000798") //peak list raw scans
{
//No member => meta data
spec_.setMetaValue("peak list raw scans", termValue);
}
else if (accession == "MS:1001581") //FAIMS compensation voltage
{
// According to the PSI-MS ontology this term should be stored below the "scan" and not "spectrum" parent.
// Some pwiz version put this term on the "spectrum" level so we also read it here.
//TODO CV term is wrongly annotated without an xref data type -> cast to double
spec_.setDriftTime(value.toDouble());
spec_.setDriftTimeUnit(DriftTimeUnit::FAIMS_COMPENSATION_VOLTAGE);
}
//scan polarity
else if (accession == "MS:1000129") //negative scan
{
spec_.getInstrumentSettings().setPolarity(IonSource::Polarity::NEGATIVE);
}
else if (accession == "MS:1000130") //positive scan
{
spec_.getInstrumentSettings().setPolarity(IonSource::Polarity::POSITIVE);
}
else
warning(LOAD, String("Unhandled cvParam '") + accession + "' in tag '" + parent_tag + "'.");
}
//------------------------- scanWindow ----------------------------
else if (parent_tag == "scanWindow")
{
if (accession == "MS:1000501") //scan window lower limit
{
spec_.getInstrumentSettings().getScanWindows().back().begin = value.toDouble();
}
else if (accession == "MS:1000500") //scan window upper limit
{
spec_.getInstrumentSettings().getScanWindows().back().end = value.toDouble();
}
else
warning(LOAD, String("Unhandled cvParam '") + accession + "' in tag '" + parent_tag + "'.");
}
//------------------------- referenceableParamGroup ----------------------------
else if (parent_tag == "referenceableParamGroup")
{
SemanticValidator::CVTerm term;
term.accession = accession;
term.name = name;
term.value = value;
term.unit_accession = unit_accession;
ref_param_[current_id_].push_back(std::move(term));
}
//------------------------- selectedIon ----------------------------
else if (parent_tag == "selectedIon")
{
//parse only the first selected ion
if (selected_ion_count_ > 1)
{
return;
}
if (accession == "MS:1000744") //selected ion m/z
{
double this_mz = value.toDouble();
Precursor& precursor = in_spectrum_list_ ?
spec_.getPrecursors().back() : chromatogram_.getPrecursor();
if (this_mz != precursor.getMZ())
{
if (options_.getPrecursorMZSelectedIon())
{
// overwrite the m/z of the isolation window:
precursor.setMetaValue("isolation window target m/z",
precursor.getMZ());
precursor.setMZ(this_mz);
// Check if precursor m/z is within specified range (when using selected ion m/z)
if (in_spectrum_list_ && options_.hasPrecursorMZRange() &&
!options_.getPrecursorMZRange().encloses(DPosition<1>(this_mz)))
{
skip_spectrum_ = true;
}
}
else // keep precursor m/z from isolation window
{
precursor.setMetaValue("selected ion m/z", this_mz);
}
}
// don't need to do anything if the two m/z values are the same
}
else if (accession == "MS:1000041") //charge state
{
if (in_spectrum_list_)
{
spec_.getPrecursors().back().setCharge(value.toInt());
}
else
{
chromatogram_.getPrecursor().setCharge(value.toInt());
}
}
else if (accession == "MS:1000042") //peak intensity
{
if (in_spectrum_list_)
{
spec_.getPrecursors().back().setIntensity(value.toDouble());
}
else
{
chromatogram_.getPrecursor().setIntensity(value.toDouble());
}
}
else if (accession == "MS:1000633") //possible charge state
{
if (in_spectrum_list_)
{
spec_.getPrecursors().back().getPossibleChargeStates().push_back(value.toInt());
}
else
{
chromatogram_.getPrecursor().getPossibleChargeStates().push_back(value.toInt());
}
}
else if (accession == "MS:1002476" || accession == "MS:1002815" || accession == "MS:1001581") //ion mobility drift time or FAIM compensation voltage
{
// Drift time may be a property of the precursor (in case we are
// acquiring a fragment ion spectrum) or of the spectrum itself.
// According to the updated OBO, it can be a precursor or a scan
// attribute.
//
// If we find here, this relates to a particular precursor. We still
// also store it in MSSpectrum in case a client only checks there.
// In most cases, there is a single precursor with a single drift
// time.
//
// Note that only milliseconds and VSSC are valid units
auto unit = DriftTimeUnit::MILLISECOND;
if (accession == "MS:1002476")
{
unit = DriftTimeUnit::MILLISECOND;
}
else if (accession == "MS:1002815")
{
unit = DriftTimeUnit::VSSC;
}
else if (accession == "MS:1001581")
{
unit = DriftTimeUnit::FAIMS_COMPENSATION_VOLTAGE;
}
if (in_spectrum_list_)
{
spec_.getPrecursors().back().setDriftTime(value.toDouble());
spec_.setDriftTime(value.toDouble());
spec_.setDriftTimeUnit(unit);
spec_.getPrecursors().back().setDriftTimeUnit(unit);
}
else
{
chromatogram_.getPrecursor().setDriftTime(value.toDouble());
chromatogram_.getPrecursor().setDriftTimeUnit(unit);
}
}
else
{
warning(LOAD, String("Unhandled cvParam '") + accession + "' in tag '" + parent_tag + "'.");
}
}
//------------------------- activation ----------------------------
else if (parent_tag == "activation")
{
//precursor activation attribute
if (in_spectrum_list_)
{
if (accession == "MS:1000245") //charge stripping
{
//No member => meta data
spec_.getPrecursors().back().setMetaValue("charge stripping", String("true"));
}
else if (accession == "MS:1000045") //collision energy (ev)
{
//No member => meta data
spec_.getPrecursors().back().setMetaValue("collision energy", termValue);
}
else if (accession == "MS:1000412") //buffer gas
{
//No member => meta data
spec_.getPrecursors().back().setMetaValue("buffer gas", termValue);
}
else if (accession == "MS:1000419") //collision gas
{
//No member => meta data
spec_.getPrecursors().back().setMetaValue("collision gas", termValue);
}
else if (accession == "MS:1000509") //activation energy (ev)
{
spec_.getPrecursors().back().setActivationEnergy(value.toDouble());
}
else if (accession == "MS:1000138") //percent collision energy
{
//No member => meta data
spec_.getPrecursors().back().setMetaValue("percent collision energy", termValue);
}
else if (accession == "MS:1000869") //collision gas pressure
{
//No member => meta data
spec_.getPrecursors().back().setMetaValue("collision gas pressure", termValue);
}
//dissociation method
else if (accession == "MS:1000044") //dissociation method
{
//nothing to do here
}
else if (accession == "MS:1000133") //collision-induced dissociation
{
spec_.getPrecursors().back().getActivationMethods().insert(Precursor::ActivationMethod::CID);
}
else if (accession == "MS:1000134") //plasma desorption
{
spec_.getPrecursors().back().getActivationMethods().insert(Precursor::ActivationMethod::PD);
}
else if (accession == "MS:1000135") //post-source decay
{
spec_.getPrecursors().back().getActivationMethods().insert(Precursor::ActivationMethod::PSD);
}
else if (accession == "MS:1000136") //surface-induced dissociation
{
spec_.getPrecursors().back().getActivationMethods().insert(Precursor::ActivationMethod::SID);
}
else if (accession == "MS:1000242") //blackbody infrared radiative dissociation
{
spec_.getPrecursors().back().getActivationMethods().insert(Precursor::ActivationMethod::BIRD);
}
else if (accession == "MS:1000250") //electron capture dissociation
{
spec_.getPrecursors().back().getActivationMethods().insert(Precursor::ActivationMethod::ECD);
}
else if (accession == "MS:1000262") //infrared multiphoton dissociation
{
spec_.getPrecursors().back().getActivationMethods().insert(Precursor::ActivationMethod::IMD);
}
else if (accession == "MS:1000282") //sustained off-resonance irradiation
{
spec_.getPrecursors().back().getActivationMethods().insert(Precursor::ActivationMethod::SORI);
}
else if (accession == "MS:1000422") //beam-type collision-induced dissociation / HCD
{
spec_.getPrecursors().back().getActivationMethods().insert(Precursor::ActivationMethod::HCD);
}
else if (accession == "MS:1002472") //trap-type collision-induced dissociation
{
spec_.getPrecursors().back().getActivationMethods().insert(Precursor::ActivationMethod::TRAP);
}
else if (accession == "MS:1002481") //high-energy collision-induced dissociation
{
spec_.getPrecursors().back().getActivationMethods().insert(Precursor::ActivationMethod::HCID);
}
else if (accession == "MS:1000433") //low-energy collision-induced dissociation
{
spec_.getPrecursors().back().getActivationMethods().insert(Precursor::ActivationMethod::LCID);
}
else if (accession == "MS:1000435") //photodissociation
{
spec_.getPrecursors().back().getActivationMethods().insert(Precursor::ActivationMethod::PHD);
}
else if (accession == "MS:1000598") //electron transfer dissociation
{
spec_.getPrecursors().back().getActivationMethods().insert(Precursor::ActivationMethod::ETD);
}
else if (accession == "MS:1003182" //electron transfer and collision-induced dissociation
|| accession == "MS:1002679") // workaround: supplemental collision-induced dissociation (see https://github.com/compomics/ThermoRawFileParser/issues/182)
{
spec_.getPrecursors().back().getActivationMethods().insert(Precursor::ActivationMethod::ETciD);
}
else if (accession == "MS:1002631" //electron transfer and higher-energy collision dissociation
|| accession == "MS:1002678") // workaround: supplemental beam-type collision-induced dissociation (see https://github.com/compomics/ThermoRawFileParser/issues/182)
{
spec_.getPrecursors().back().getActivationMethods().insert(Precursor::ActivationMethod::EThcD);
}
else if (accession == "MS:1000599") //pulsed q dissociation
{
spec_.getPrecursors().back().getActivationMethods().insert(Precursor::ActivationMethod::PQD);
}
else if (accession == "MS:1001880") //in-source collision-induced dissociation
{
spec_.getPrecursors().back().getActivationMethods().insert(Precursor::ActivationMethod::INSOURCE);
}
else if (accession == "MS:1002000") //LIFT
{
spec_.getPrecursors().back().getActivationMethods().insert(Precursor::ActivationMethod::LIFT);
}
else
warning(LOAD, String("Unhandled cvParam '") + accession + "' in tag '" + parent_tag + "'.");
}
else
{
if (accession == "MS:1000245") //charge stripping
{
//No member => meta data
chromatogram_.getPrecursor().setMetaValue("charge stripping", String("true"));
}
else if (accession == "MS:1000045") //collision energy (ev)
{
//No member => meta data
chromatogram_.getPrecursor().setMetaValue("collision energy", termValue);
}
else if (accession == "MS:1000412") //buffer gas
{
//No member => meta data
chromatogram_.getPrecursor().setMetaValue("buffer gas", termValue);
}
else if (accession == "MS:1000419") //collision gas
{
//No member => meta data
chromatogram_.getPrecursor().setMetaValue("collision gas", termValue);
}
else if (accession == "MS:1000509") //activation energy (ev)
{
chromatogram_.getPrecursor().setActivationEnergy(value.toDouble());
}
else if (accession == "MS:1000138") //percent collision energy
{
//No member => meta data
chromatogram_.getPrecursor().setMetaValue("percent collision energy", termValue);
}
else if (accession == "MS:1000869") //collision gas pressure
{
//No member => meta data
chromatogram_.getPrecursor().setMetaValue("collision gas pressure", termValue);
}
//dissociation method
else if (accession == "MS:1000044") //dissociation method
{
//nothing to do here
}
else if (accession == "MS:1000133") //collision-induced dissociation
{
chromatogram_.getPrecursor().getActivationMethods().insert(Precursor::ActivationMethod::CID);
}
else if (accession == "MS:1000134") //plasma desorption
{
chromatogram_.getPrecursor().getActivationMethods().insert(Precursor::ActivationMethod::PD);
}
else if (accession == "MS:1000135") //post-source decay
{
chromatogram_.getPrecursor().getActivationMethods().insert(Precursor::ActivationMethod::PSD);
}
else if (accession == "MS:1000136") //surface-induced dissociation
{
chromatogram_.getPrecursor().getActivationMethods().insert(Precursor::ActivationMethod::SID);
}
else if (accession == "MS:1000242") //blackbody infrared radiative dissociation
{
chromatogram_.getPrecursor().getActivationMethods().insert(Precursor::ActivationMethod::BIRD);
}
else if (accession == "MS:1000250") //electron capture dissociation
{
chromatogram_.getPrecursor().getActivationMethods().insert(Precursor::ActivationMethod::ECD);
}
else if (accession == "MS:1000262") //infrared multiphoton dissociation
{
chromatogram_.getPrecursor().getActivationMethods().insert(Precursor::ActivationMethod::IMD);
}
else if (accession == "MS:1000282") //sustained off-resonance irradiation
{
chromatogram_.getPrecursor().getActivationMethods().insert(Precursor::ActivationMethod::SORI);
}
else if (accession == "MS:1000422") //beam-type collision-induced dissociation / HCD
{
chromatogram_.getPrecursor().getActivationMethods().insert(Precursor::ActivationMethod::HCD);
}
else if (accession == "MS:1002472") //trap-type collision-induced dissociation
{
chromatogram_.getPrecursor().getActivationMethods().insert(Precursor::ActivationMethod::TRAP);
}
else if (accession == "MS:1002481") //high-energy collision-induced dissociation
{
chromatogram_.getPrecursor().getActivationMethods().insert(Precursor::ActivationMethod::HCID);
}
else if (accession == "MS:1000433") //low-energy collision-induced dissociation
{
chromatogram_.getPrecursor().getActivationMethods().insert(Precursor::ActivationMethod::LCID);
}
else if (accession == "MS:1000435") //photodissociation
{
chromatogram_.getPrecursor().getActivationMethods().insert(Precursor::ActivationMethod::PHD);
}
else if (accession == "MS:1000598") //electron transfer dissociation
{
chromatogram_.getPrecursor().getActivationMethods().insert(Precursor::ActivationMethod::ETD);
}
else if (accession == "MS:1003182") //electron transfer and collision-induced dissociation
{
chromatogram_.getPrecursor().getActivationMethods().insert(Precursor::ActivationMethod::ETciD);
}
else if (accession == "MS:1002631") //electron transfer and higher-energy collision dissociation
{
chromatogram_.getPrecursor().getActivationMethods().insert(Precursor::ActivationMethod::EThcD);
}
else if (accession == "MS:1000599") //pulsed q dissociation
{
chromatogram_.getPrecursor().getActivationMethods().insert(Precursor::ActivationMethod::PQD);
}
else if (accession == "MS:1001880") //in-source collision-induced dissociation
{
chromatogram_.getPrecursor().getActivationMethods().insert(Precursor::ActivationMethod::INSOURCE);
}
else if (accession == "MS:1002000") //LIFT
{
chromatogram_.getPrecursor().getActivationMethods().insert(Precursor::ActivationMethod::LIFT);
}
else
{
warning(LOAD, String("Unhandled cvParam '") + accession + "' in tag '" + parent_tag + "'.");
}
}
}
//------------------------- isolationWindow ----------------------------
else if (parent_tag == "isolationWindow")
{
if (parent_parent_tag == "precursor")
{
if (accession == "MS:1000827") //isolation window target m/z
{
if (in_spectrum_list_)
{
spec_.getPrecursors().back().setMZ(value.toDouble());
// Check if precursor m/z is within specified range (only if not using selected ion m/z as precursor)
if (!options_.getPrecursorMZSelectedIon() && options_.hasPrecursorMZRange() &&
!options_.getPrecursorMZRange().encloses(DPosition<1>(value.toDouble())))
{
skip_spectrum_ = true;
}
}
else
{
chromatogram_.getPrecursor().setMZ(value.toDouble());
}
}
else if (accession == "MS:1000828") //isolation window lower offset
{
double offset_value = value.toDouble();
if (offset_value >= 0) // Skip negative values (indicate null/invalid)
{
if (in_spectrum_list_)
{
spec_.getPrecursors().back().setIsolationWindowLowerOffset(offset_value);
}
else
{
chromatogram_.getPrecursor().setIsolationWindowLowerOffset(offset_value);
}
}
}
else if (accession == "MS:1000829") //isolation window upper offset
{
double offset_value = value.toDouble();
if (offset_value >= 0) // Skip negative values (indicate null/invalid)
{
if (in_spectrum_list_)
{
spec_.getPrecursors().back().setIsolationWindowUpperOffset(offset_value);
}
else
{
chromatogram_.getPrecursor().setIsolationWindowUpperOffset(offset_value);
}
}
}
else
warning(LOAD, String("Unhandled cvParam '") + accession + "' in tag '" + parent_tag + "'.");
}
else if (parent_parent_tag == "product")
{
if (accession == "MS:1000827") //isolation window target m/z
{
if (in_spectrum_list_)
{
spec_.getProducts().back().setMZ(value.toDouble());
}
else
{
chromatogram_.getProduct().setMZ(value.toDouble());
}
}
else if (accession == "MS:1000829") //isolation window upper offset
{
double offset_value = value.toDouble();
if (offset_value >= 0) // Skip negative values (indicate null/invalid)
{
if (in_spectrum_list_)
{
spec_.getProducts().back().setIsolationWindowUpperOffset(offset_value);
}
else
{
chromatogram_.getProduct().setIsolationWindowUpperOffset(offset_value);
}
}
}
else if (accession == "MS:1000828") //isolation window lower offset
{
double offset_value = value.toDouble();
if (offset_value >= 0) // Skip negative values (indicate null/invalid)
{
if (in_spectrum_list_)
{
spec_.getProducts().back().setIsolationWindowLowerOffset(offset_value);
}
else
{
chromatogram_.getProduct().setIsolationWindowLowerOffset(offset_value);
}
}
}
else
warning(LOAD, String("Unhandled cvParam '") + accession + "' in tag '" + parent_tag + "'.");
}
}
//------------------------- scanList ----------------------------
else if (parent_tag == "scanList")
{
if (cv_.isChildOf(accession, "MS:1000570")) //method of combination as string
{
spec_.getAcquisitionInfo().setMethodOfCombination(cv_.getTerm(accession).name);
}
else
{
warning(LOAD, String("Unhandled cvParam '") + accession + "' in tag '" + parent_tag + "'.");
}
}
//------------------------- scan ----------------------------
else if (parent_tag == "scan")
{
//scan attributes
if (accession == "MS:1000502") //dwell time
{
//No member => meta data
spec_.setMetaValue("dwell time", termValue);
}
else if (accession == "MS:1002476" || accession == "MS:1002815" || accession == "MS:1001581") //ion mobility drift time or FAIMS compensation voltage
{
// Drift time may be a property of the precursor (in case we are
// acquiring a fragment ion spectrum) or of the spectrum itself.
// According to the updated OBO, it can be a precursor or a scan
// attribute.
//
// If we find it here, it relates to the scan or spectrum itself and
// not to a particular precursor.
//
// Note: this is where pwiz stores the ion mobility for a spectrum
auto unit = DriftTimeUnit::MILLISECOND;
if (accession == "MS:1002476")
{
unit = DriftTimeUnit::MILLISECOND;
}
else if (accession == "MS:1002815")
{
unit = DriftTimeUnit::VSSC;
}
else if (accession == "MS:1001581")
{
unit = DriftTimeUnit::FAIMS_COMPENSATION_VOLTAGE;
}
spec_.setDriftTime(value.toDouble());
spec_.setDriftTimeUnit(unit);
}
else if (accession == "MS:1000011") //mass resolution
{
//No member => meta data
spec_.setMetaValue("mass resolution", termValue);
}
else if (accession == "MS:1000015") //scan rate
{
//No member => meta data
spec_.setMetaValue("scan rate", termValue);
}
else if (accession == "MS:1000016") //scan start time
{
if (unit_accession == "UO:0000031") //minutes
{
spec_.setRT(60.0 * value.toDouble());
}
else //seconds
{
spec_.setRT(value.toDouble());
}
rt_set_ = true;
if (options_.hasRTRange())
{
if (!options_.getRTRange().encloses(DPosition<1>(spec_.getRT())))
{
skip_spectrum_ = true;
}
else
{ // we are within RT range
if (load_detail_ == XMLHandler::LD_COUNTS_WITHOPTIONS)
{ //, but we only want to count
skip_spectrum_ = true;
++scan_count_;
}
}
}
else if (load_detail_ == XMLHandler::LD_COUNTS_WITHOPTIONS)
{ // all RTs are valid, and the MS level of the current spectrum is in our MSLevels (otherwise we would not be here)
skip_spectrum_ = true;
++scan_count_;
}
}
else if (accession == "MS:1000826") //elution time
{
if (unit_accession == "UO:0000031") //minutes
{
spec_.setMetaValue("elution time (seconds)", 60.0 * value.toDouble());
}
else //seconds
{
spec_.setMetaValue("elution time (seconds)", value.toDouble());
}
}
else if (accession == "MS:1000512") //filter string
{
//No member => meta data
spec_.setMetaValue("filter string", termValue);
}
else if (accession == "MS:1000803") //analyzer scan offset
{
//No member => meta data
spec_.setMetaValue("analyzer scan offset", termValue); // used in SpectraIDViewTab()
}
else if (accession == "MS:1000616") //preset scan configuration
{
//No member => meta data
spec_.setMetaValue("preset scan configuration", termValue);
}
else if (accession == "MS:1000800") //mass resolving power
{
//No member => meta data
spec_.setMetaValue("mass resolving power", termValue);
}
else if (accession == "MS:1000880") //interchannel delay
{
//No member => meta data
spec_.setMetaValue("interchannel delay", termValue);
}
//scan direction
else if (accession == "MS:1000092") //decreasing m/z scan
{
//No member => meta data
spec_.setMetaValue("scan direction", String("decreasing"));
}
else if (accession == "MS:1000093") //increasing m/z scan
{
//No member => meta data
spec_.setMetaValue("scan direction", String("increasing"));
}
//scan law
else if (accession == "MS:1000094") //scan law: exponential
{
//No member => meta data
spec_.setMetaValue("scan law", String("exponential"));
}
else if (accession == "MS:1000095") //scan law: linear
{
//No member => meta data
spec_.setMetaValue("scan law", String("linear"));
}
else if (accession == "MS:1000096") //scan law: quadratic
{
//No member => meta data
spec_.setMetaValue("scan law", String("quadratic"));
}
else if (accession == "MS:1000497") // zoom scan
{
spec_.getInstrumentSettings().setZoomScan(true);
}
else
{
//warning(LOAD, String("Unhandled cvParam '") + accession + "' in tag '" + parent_tag + "'."); //of course just pops up with debug flag set ...
spec_.getAcquisitionInfo().back().setMetaValue(accession, termValue);
}
}
//------------------------- contact ----------------------------
else if (parent_tag == "contact")
{
if (accession == "MS:1000586") //contact name
{
exp_->getContacts().back().setName(value);
}
else if (accession == "MS:1000587") //contact address
{
exp_->getContacts().back().setAddress(value);
}
else if (accession == "MS:1000588") //contact URL
{
exp_->getContacts().back().setURL(value);
}
else if (accession == "MS:1000589") //contact email
{
exp_->getContacts().back().setEmail(value);
}
else if (accession == "MS:1000590") //contact organization
{
exp_->getContacts().back().setInstitution(value);
}
else
warning(LOAD, String("Unhandled cvParam '") + accession + "' in tag '" + parent_tag + "'.");
}
//------------------------- sourceFile ----------------------------
else if (parent_tag == "sourceFile")
{
if (accession == "MS:1000569") //SHA-1 checksum
{
source_files_[current_id_].setChecksum(value, SourceFile::ChecksumType::SHA1);
}
else if (accession == "MS:1000568") //MD5 checksum
{
source_files_[current_id_].setChecksum(value, SourceFile::ChecksumType::MD5);
}
else if (cv_.isChildOf(accession, "MS:1000560")) //source file type as string
{
source_files_[current_id_].setFileType(cv_.getTerm(accession).name);
}
else if (cv_.isChildOf(accession, "MS:1000767")) //native spectrum identifier format as string
{
source_files_[current_id_].setNativeIDType(cv_.getTerm(accession).name);
source_files_[current_id_].setNativeIDTypeAccession(cv_.getTerm(accession).id);
}
else
warning(LOAD, String("Unhandled cvParam '") + accession + "' in tag '" + parent_tag + "'.");
}
//------------------------- sample ----------------------------
else if (parent_tag == "sample")
{
if (accession == "MS:1000004") //sample mass (gram)
{
samples_[current_id_].setMass(value.toDouble());
}
else if (accession == "MS:1000001") //sample number
{
samples_[current_id_].setNumber(value);
}
else if (accession == "MS:1000005") //sample volume (milliliter)
{
samples_[current_id_].setVolume(value.toDouble());
}
else if (accession == "MS:1000006") //sample concentration (gram per liter)
{
samples_[current_id_].setConcentration(value.toDouble());
}
else if (accession == "MS:1000053") //sample batch
{
//No member => meta data
samples_[current_id_].setMetaValue("sample batch", termValue);
}
else if (accession == "MS:1000047") //emulsion
{
samples_[current_id_].setState(Sample::SampleState::EMULSION);
}
else if (accession == "MS:1000048") //gas
{
samples_[current_id_].setState(Sample::SampleState::GAS);
}
else if (accession == "MS:1000049") //liquid
{
samples_[current_id_].setState(Sample::SampleState::LIQUID);
}
else if (accession == "MS:1000050") //solid
{
samples_[current_id_].setState(Sample::SampleState::SOLID);
}
else if (accession == "MS:1000051") //solution
{
samples_[current_id_].setState(Sample::SampleState::SOLUTION);
}
else if (accession == "MS:1000052") //suspension
{
samples_[current_id_].setState(Sample::SampleState::SUSPENSION);
}
else if (accession.hasPrefix("PATO:")) //quality of an object
{
//No member => meta data
samples_[current_id_].setMetaValue(String(name), termValue);
}
else if (accession.hasPrefix("GO:")) //cellular_component
{
//No member => meta data
samples_[current_id_].setMetaValue("GO cellular component", String(name));
}
else if (accession.hasPrefix("BTO:")) //brenda source tissue ontology
{
//No member => meta data
samples_[current_id_].setMetaValue("brenda source tissue", String(name));
}
else
warning(LOAD, String("Unhandled cvParam '") + accession + "' in tag '" + parent_tag + "'.");
}
//------------------------- instrumentConfiguration ----------------------------
else if (parent_tag == "instrumentConfiguration")
{
//instrument model
if (accession == "MS:1000031")
{
//unknown instrument => nothing to do
}
else if (cv_.isChildOf(accession, "MS:1000031")) //instrument name as string
{
instruments_[current_id_].setName(cv_.getTerm(accession).name);
}
//instrument attribute
else if (accession == "MS:1000529") //instrument serial number
{
//No member => meta data
instruments_[current_id_].setMetaValue("instrument serial number", termValue);
}
else if (accession == "MS:1000032") //customization
{
instruments_[current_id_].setCustomizations(value);
}
else if (accession == "MS:1000236") //transmission
{
//No member => metadata
instruments_[current_id_].setMetaValue("transmission", termValue);
}
//ion optics type
else if (accession == "MS:1000246") //delayed extraction
{
instruments_[current_id_].setIonOptics(Instrument::IonOpticsType::DELAYED_EXTRACTION);
}
else if (accession == "MS:1000221") //magnetic deflection
{
instruments_[current_id_].setIonOptics(Instrument::IonOpticsType::MAGNETIC_DEFLECTION);
}
else if (accession == "MS:1000275") //collision quadrupole
{
instruments_[current_id_].setIonOptics(Instrument::IonOpticsType::COLLISION_QUADRUPOLE);
}
else if (accession == "MS:1000281") //selected ion flow tube
{
instruments_[current_id_].setIonOptics(Instrument::IonOpticsType::SELECTED_ION_FLOW_TUBE);
}
else if (accession == "MS:1000286") //time lag focusing
{
instruments_[current_id_].setIonOptics(Instrument::IonOpticsType::TIME_LAG_FOCUSING);
}
else if (accession == "MS:1000300") //reflectron
{
instruments_[current_id_].setIonOptics(Instrument::IonOpticsType::REFLECTRON);
}
else if (accession == "MS:1000307") //einzel lens
{
instruments_[current_id_].setIonOptics(Instrument::IonOpticsType::EINZEL_LENS);
}
else if (accession == "MS:1000309") //first stability region
{
instruments_[current_id_].setIonOptics(Instrument::IonOpticsType::FIRST_STABILITY_REGION);
}
else if (accession == "MS:1000310") //fringing field
{
instruments_[current_id_].setIonOptics(Instrument::IonOpticsType::FRINGING_FIELD);
}
else if (accession == "MS:1000311") //kinetic energy analyzer
{
instruments_[current_id_].setIonOptics(Instrument::IonOpticsType::KINETIC_ENERGY_ANALYZER);
}
else if (accession == "MS:1000320") //static field
{
instruments_[current_id_].setIonOptics(Instrument::IonOpticsType::STATIC_FIELD);
}
//ion optics attribute
else if (accession == "MS:1000304") //accelerating voltage
{
//No member => metadata
instruments_[current_id_].setMetaValue("accelerating voltage", termValue);
}
else if (accession == "MS:1000216") //field-free region
{
//No member => metadata
instruments_[current_id_].setMetaValue("field-free region", String("true"));
}
else if (accession == "MS:1000308") //electric field strength
{
//No member => metadata
instruments_[current_id_].setMetaValue("electric field strength", termValue);
}
else if (accession == "MS:1000319") //space charge effect
{
//No member => metadata
instruments_[current_id_].setMetaValue("space charge effect", String("true"));
}
else
warning(LOAD, String("Unhandled cvParam '") + accession + "' in tag '" + parent_tag + "'.");
}
else if (parent_tag == "source")
{
//inlet type
if (accession == "MS:1000055") //continuous flow fast atom bombardment
{
instruments_[current_id_].getIonSources().back().setInletType(IonSource::InletType::CONTINUOUSFLOWFASTATOMBOMBARDMENT);
}
else if (accession == "MS:1000056") //direct inlet
{
instruments_[current_id_].getIonSources().back().setInletType(IonSource::InletType::DIRECT);
}
else if (accession == "MS:1000057") //electrospray inlet
{
instruments_[current_id_].getIonSources().back().setInletType(IonSource::InletType::ELECTROSPRAYINLET);
}
else if (accession == "MS:1000058") //flow injection analysis
{
instruments_[current_id_].getIonSources().back().setInletType(IonSource::InletType::FLOWINJECTIONANALYSIS);
}
else if (accession == "MS:1000059") //inductively coupled plasma
{
instruments_[current_id_].getIonSources().back().setInletType(IonSource::InletType::INDUCTIVELYCOUPLEDPLASMA);
}
else if (accession == "MS:1000060") //infusion
{
instruments_[current_id_].getIonSources().back().setInletType(IonSource::InletType::INFUSION);
}
else if (accession == "MS:1000061") //jet separator
{
instruments_[current_id_].getIonSources().back().setInletType(IonSource::InletType::JETSEPARATOR);
}
else if (accession == "MS:1000062") //membrane separator
{
instruments_[current_id_].getIonSources().back().setInletType(IonSource::InletType::MEMBRANESEPARATOR);
}
else if (accession == "MS:1000063") //moving belt
{
instruments_[current_id_].getIonSources().back().setInletType(IonSource::InletType::MOVINGBELT);
}
else if (accession == "MS:1000064") //moving wire
{
instruments_[current_id_].getIonSources().back().setInletType(IonSource::InletType::MOVINGWIRE);
}
else if (accession == "MS:1000065") //open split
{
instruments_[current_id_].getIonSources().back().setInletType(IonSource::InletType::OPENSPLIT);
}
else if (accession == "MS:1000066") //particle beam
{
instruments_[current_id_].getIonSources().back().setInletType(IonSource::InletType::PARTICLEBEAM);
}
else if (accession == "MS:1000067") //reservoir
{
instruments_[current_id_].getIonSources().back().setInletType(IonSource::InletType::RESERVOIR);
}
else if (accession == "MS:1000068") //septum
{
instruments_[current_id_].getIonSources().back().setInletType(IonSource::InletType::SEPTUM);
}
else if (accession == "MS:1000069") //thermospray inlet
{
instruments_[current_id_].getIonSources().back().setInletType(IonSource::InletType::THERMOSPRAYINLET);
}
else if (accession == "MS:1000248") //direct insertion probe
{
instruments_[current_id_].getIonSources().back().setInletType(IonSource::InletType::BATCH);
}
else if (accession == "MS:1000249") //direct liquid introduction
{
instruments_[current_id_].getIonSources().back().setInletType(IonSource::InletType::CHROMATOGRAPHY);
}
else if (accession == "MS:1000396") //membrane inlet
{
instruments_[current_id_].getIonSources().back().setInletType(IonSource::InletType::MEMBRANE);
}
else if (accession == "MS:1000485") //nanospray inlet
{
instruments_[current_id_].getIonSources().back().setInletType(IonSource::InletType::NANOSPRAY);
}
//ionization type
else if (accession == "MS:1000071") //chemical ionization
{
instruments_[current_id_].getIonSources().back().setIonizationMethod(IonSource::IonizationMethod::CI);
}
else if (accession == "MS:1000073") //electrospray ionization
{
instruments_[current_id_].getIonSources().back().setIonizationMethod(IonSource::IonizationMethod::ESI);
}
else if (accession == "MS:1000074") //fast atom bombardment ionization
{
instruments_[current_id_].getIonSources().back().setIonizationMethod(IonSource::IonizationMethod::FAB);
}
else if (accession == "MS:1000227") //multiphoton ionization
{
instruments_[current_id_].getIonSources().back().setIonizationMethod(IonSource::IonizationMethod::MPI);
}
else if (accession == "MS:1000240") //atmospheric pressure ionization
{
instruments_[current_id_].getIonSources().back().setIonizationMethod(IonSource::IonizationMethod::API);
}
else if (accession == "MS:1000247") //desorption ionization
{
instruments_[current_id_].getIonSources().back().setIonizationMethod(IonSource::IonizationMethod::DI);
}
else if (accession == "MS:1000255") //flowing afterglow
{
instruments_[current_id_].getIonSources().back().setIonizationMethod(IonSource::IonizationMethod::FA);
}
else if (accession == "MS:1000258") //field ionization
{
instruments_[current_id_].getIonSources().back().setIonizationMethod(IonSource::IonizationMethod::FII);
}
else if (accession == "MS:1000259") //glow discharge ionization
{
instruments_[current_id_].getIonSources().back().setIonizationMethod(IonSource::IonizationMethod::GD_MS);
}
else if (accession == "MS:1000271") //Negative ion chemical ionization
{
instruments_[current_id_].getIonSources().back().setIonizationMethod(IonSource::IonizationMethod::NICI);
}
else if (accession == "MS:1000272") //neutralization reionization mass spectrometry
{
instruments_[current_id_].getIonSources().back().setIonizationMethod(IonSource::IonizationMethod::NRMS);
}
else if (accession == "MS:1000273") //photoionization
{
instruments_[current_id_].getIonSources().back().setIonizationMethod(IonSource::IonizationMethod::PI);
}
else if (accession == "MS:1000274") //pyrolysis mass spectrometry
{
instruments_[current_id_].getIonSources().back().setIonizationMethod(IonSource::IonizationMethod::PYMS);
}
else if (accession == "MS:1000276") //resonance enhanced multiphoton ionization
{
instruments_[current_id_].getIonSources().back().setIonizationMethod(IonSource::IonizationMethod::REMPI);
}
else if (accession == "MS:1000380") //adiabatic ionization
{
instruments_[current_id_].getIonSources().back().setIonizationMethod(IonSource::IonizationMethod::AI);
}
else if (accession == "MS:1000381") //associative ionization
{
instruments_[current_id_].getIonSources().back().setIonizationMethod(IonSource::IonizationMethod::ASI);
}
else if (accession == "MS:1000383") //autodetachment
{
instruments_[current_id_].getIonSources().back().setIonizationMethod(IonSource::IonizationMethod::AD);
}
else if (accession == "MS:1000384") //autoionization
{
instruments_[current_id_].getIonSources().back().setIonizationMethod(IonSource::IonizationMethod::AUI);
}
else if (accession == "MS:1000385") //charge exchange ionization
{
instruments_[current_id_].getIonSources().back().setIonizationMethod(IonSource::IonizationMethod::CEI);
}
else if (accession == "MS:1000386") //chemi-ionization
{
instruments_[current_id_].getIonSources().back().setIonizationMethod(IonSource::IonizationMethod::CHEMI);
}
else if (accession == "MS:1000388") //dissociative ionization
{
instruments_[current_id_].getIonSources().back().setIonizationMethod(IonSource::IonizationMethod::DISSI);
}
else if (accession == "MS:1000389") //electron ionization
{
instruments_[current_id_].getIonSources().back().setIonizationMethod(IonSource::IonizationMethod::EI);
}
else if (accession == "MS:1000395") //liquid secondary ionization
{
instruments_[current_id_].getIonSources().back().setIonizationMethod(IonSource::IonizationMethod::LSI);
}
else if (accession == "MS:1000399") //penning ionization
{
instruments_[current_id_].getIonSources().back().setIonizationMethod(IonSource::IonizationMethod::PEI);
}
else if (accession == "MS:1000400") //plasma desorption ionization
{
instruments_[current_id_].getIonSources().back().setIonizationMethod(IonSource::IonizationMethod::PD);
}
else if (accession == "MS:1000402") //secondary ionization
{
instruments_[current_id_].getIonSources().back().setIonizationMethod(IonSource::IonizationMethod::SI);
}
else if (accession == "MS:1000403") //soft ionization
{
instruments_[current_id_].getIonSources().back().setIonizationMethod(IonSource::IonizationMethod::SOI);
}
else if (accession == "MS:1000404") //spark ionization
{
instruments_[current_id_].getIonSources().back().setIonizationMethod(IonSource::IonizationMethod::SPI);
}
else if (accession == "MS:1000406") //surface ionization
{
instruments_[current_id_].getIonSources().back().setIonizationMethod(IonSource::IonizationMethod::SUI);
}
else if (accession == "MS:1000407") //thermal ionization
{
instruments_[current_id_].getIonSources().back().setIonizationMethod(IonSource::IonizationMethod::TI);
}
else if (accession == "MS:1000408") //vertical ionization
{
instruments_[current_id_].getIonSources().back().setIonizationMethod(IonSource::IonizationMethod::VI);
}
else if (accession == "MS:1000446") //fast ion bombardment
{
instruments_[current_id_].getIonSources().back().setIonizationMethod(IonSource::IonizationMethod::FIB);
}
else if (accession == "MS:1000070") //atmospheric pressure chemical ionization
{
instruments_[current_id_].getIonSources().back().setIonizationMethod(IonSource::IonizationMethod::APCI);
}
else if (accession == "MS:1000239") //atmospheric pressure matrix-assisted laser desorption ionization
{
instruments_[current_id_].getIonSources().back().setIonizationMethod(IonSource::IonizationMethod::AP_MALDI);
}
else if (accession == "MS:1000382") //atmospheric pressure photoionization
{
instruments_[current_id_].getIonSources().back().setIonizationMethod(IonSource::IonizationMethod::APPI);
}
else if (accession == "MS:1000075") //matrix-assisted laser desorption ionization
{
instruments_[current_id_].getIonSources().back().setIonizationMethod(IonSource::IonizationMethod::MALDI);
}
else if (accession == "MS:1000257") //field desorption
{
instruments_[current_id_].getIonSources().back().setIonizationMethod(IonSource::IonizationMethod::FD);
}
else if (accession == "MS:1000387") //desorption/ionization on silicon
{
instruments_[current_id_].getIonSources().back().setIonizationMethod(IonSource::IonizationMethod::SILI);
}
else if (accession == "MS:1000393") //laser desorption ionization
{
instruments_[current_id_].getIonSources().back().setIonizationMethod(IonSource::IonizationMethod::LD);
}
else if (accession == "MS:1000405") //surface-assisted laser desorption ionization
{
instruments_[current_id_].getIonSources().back().setIonizationMethod(IonSource::IonizationMethod::SALDI);
}
else if (accession == "MS:1000397") //microelectrospray
{
instruments_[current_id_].getIonSources().back().setIonizationMethod(IonSource::IonizationMethod::MESI);
}
else if (accession == "MS:1000398") //nanoelectrospray
{
instruments_[current_id_].getIonSources().back().setIonizationMethod(IonSource::IonizationMethod::NESI);
}
else if (accession == "MS:1000278") //surface enhanced laser desorption ionization
{
instruments_[current_id_].getIonSources().back().setIonizationMethod(IonSource::IonizationMethod::SELDI);
}
else if (accession == "MS:1000279") //surface enhanced neat desorption
{
instruments_[current_id_].getIonSources().back().setIonizationMethod(IonSource::IonizationMethod::SEND);
}
else if (accession == "MS:1000008") //ionization type (base term)
{
instruments_[current_id_].getIonSources().back().setIonizationMethod(IonSource::IonizationMethod::IONMETHODNULL);
}
//source attribute
else if (accession == "MS:1000392") //ionization efficiency
{
//No member => meta data
instruments_[current_id_].getIonSources().back().setMetaValue("ionization efficiency", termValue);
}
else if (accession == "MS:1000486") //source potential
{
//No member => meta data
instruments_[current_id_].getIonSources().back().setMetaValue("source potential", termValue);
}
else if (accession == "MS:1000875") // declustering potential
{
//No member => meta data
instruments_[current_id_].getIonSources().back().setMetaValue("declustering potential", termValue);
}
else if (accession == "MS:1000876") // cone voltage
{
//No member => meta data
instruments_[current_id_].getIonSources().back().setMetaValue("cone voltage", termValue);
}
else if (accession == "MS:1000877") // tube lens
{
//No member => meta data
instruments_[current_id_].getIonSources().back().setMetaValue("tube lens", termValue);
}
//laser attribute
else if (accession == "MS:1000843") // wavelength
{
//No member => meta data
instruments_[current_id_].getIonSources().back().setMetaValue("wavelength", termValue);
}
else if (accession == "MS:1000844") // focus diameter x
{
//No member => meta data
instruments_[current_id_].getIonSources().back().setMetaValue("focus diameter x", termValue);
}
else if (accession == "MS:1000845") // focus diameter y
{
//No member => meta data
instruments_[current_id_].getIonSources().back().setMetaValue("focus diameter y", termValue);
}
else if (accession == "MS:1000846") // pulse energy
{
//No member => meta data
instruments_[current_id_].getIonSources().back().setMetaValue("pulse energy", termValue);
}
else if (accession == "MS:1000847") // pulse duration
{
//No member => meta data
instruments_[current_id_].getIonSources().back().setMetaValue("pulse duration", termValue);
}
else if (accession == "MS:1000848") // attenuation
{
//No member => meta data
instruments_[current_id_].getIonSources().back().setMetaValue("attenuation", termValue);
}
else if (accession == "MS:1000849") // impact angle
{
//No member => meta data
instruments_[current_id_].getIonSources().back().setMetaValue("impact angle", termValue);
}
//laser type
else if (accession == "MS:1000850") // gas laser
{
//No member => meta data
instruments_[current_id_].getIonSources().back().setMetaValue("laser type", "gas laser");
}
else if (accession == "MS:1000851") // solid-state laser
{
//No member => meta data
instruments_[current_id_].getIonSources().back().setMetaValue("laser type", "solid-state laser");
}
else if (accession == "MS:1000852") // dye-laser
{
//No member => meta data
instruments_[current_id_].getIonSources().back().setMetaValue("laser type", "dye-laser");
}
else if (accession == "MS:1000853") // free electron laser
{
//No member => meta data
instruments_[current_id_].getIonSources().back().setMetaValue("laser type", "free electron laser");
}
//MALDI matrix application
else if (accession == "MS:1000834") // matrix solution
{
//No member => meta data
instruments_[current_id_].getIonSources().back().setMetaValue("matrix solution", termValue);
}
else if (accession == "MS:1000835") // matrix solution concentration
{
//No member => meta data
instruments_[current_id_].getIonSources().back().setMetaValue("matrix solution concentration", termValue);
}
// matrix application type
else if (accession == "MS:1000836") // dried dropplet
{
//No member => meta data
instruments_[current_id_].getIonSources().back().setMetaValue("matrix application type", "dried dropplet");
}
else if (accession == "MS:1000837") // printed
{
//No member => meta data
instruments_[current_id_].getIonSources().back().setMetaValue("matrix application type", "printed");
}
else if (accession == "MS:1000838") // sprayed
{
//No member => meta data
instruments_[current_id_].getIonSources().back().setMetaValue("matrix application type", "sprayed");
}
else if (accession == "MS:1000839") // precoated plate
{
//No member => meta data
instruments_[current_id_].getIonSources().back().setMetaValue("matrix application type", " precoated plate");
}
else
warning(LOAD, String("Unhandled cvParam '") + accession + "' in tag '" + parent_tag + "'.");
}
else if (parent_tag == "analyzer")
{
//mass analyzer type
if (accession == "MS:1000079") //fourier transform ion cyclotron resonance mass spectrometer
{
instruments_[current_id_].getMassAnalyzers().back().setType(MassAnalyzer::AnalyzerType::FOURIERTRANSFORM);
}
else if (accession == "MS:1000080") //magnetic sector
{
instruments_[current_id_].getMassAnalyzers().back().setType(MassAnalyzer::AnalyzerType::SECTOR);
}
else if (accession == "MS:1000081") //quadrupole
{
instruments_[current_id_].getMassAnalyzers().back().setType(MassAnalyzer::AnalyzerType::QUADRUPOLE);
}
else if (accession == "MS:1000084") //time-of-flight
{
instruments_[current_id_].getMassAnalyzers().back().setType(MassAnalyzer::AnalyzerType::TOF);
}
else if (accession == "MS:1000254") //electrostatic energy analyzer
{
instruments_[current_id_].getMassAnalyzers().back().setType(MassAnalyzer::AnalyzerType::ESA);
}
else if (accession == "MS:1000264") //ion trap
{
instruments_[current_id_].getMassAnalyzers().back().setType(MassAnalyzer::AnalyzerType::IT);
}
else if (accession == "MS:1000284") //stored waveform inverse fourier transform
{
instruments_[current_id_].getMassAnalyzers().back().setType(MassAnalyzer::AnalyzerType::SWIFT);
}
else if (accession == "MS:1000288") //cyclotron
{
instruments_[current_id_].getMassAnalyzers().back().setType(MassAnalyzer::AnalyzerType::CYCLOTRON);
}
else if (accession == "MS:1000484") //orbitrap
{
instruments_[current_id_].getMassAnalyzers().back().setType(MassAnalyzer::AnalyzerType::ORBITRAP);
}
else if (accession == "MS:1000078") //axial ejection linear ion trap
{
instruments_[current_id_].getMassAnalyzers().back().setType(MassAnalyzer::AnalyzerType::AXIALEJECTIONLINEARIONTRAP);
}
else if (accession == "MS:1000082") //quadrupole ion trap
{
instruments_[current_id_].getMassAnalyzers().back().setType(MassAnalyzer::AnalyzerType::PAULIONTRAP);
}
else if (accession == "MS:1000083") //radial ejection linear ion trap
{
instruments_[current_id_].getMassAnalyzers().back().setType(MassAnalyzer::AnalyzerType::RADIALEJECTIONLINEARIONTRAP);
}
else if (accession == "MS:1000291") //linear ion trap
{
instruments_[current_id_].getMassAnalyzers().back().setType(MassAnalyzer::AnalyzerType::LIT);
}
else if (accession == "MS:1000443") //mass analyzer type (base term)
{
instruments_[current_id_].getMassAnalyzers().back().setType(MassAnalyzer::AnalyzerType::ANALYZERNULL);
}
//mass analyzer attribute
else if (accession == "MS:1000014") //accuracy (ppm)
{
instruments_[current_id_].getMassAnalyzers().back().setAccuracy(value.toDouble());
}
else if (accession == "MS:1000022") //TOF Total Path Length (meter)
{
instruments_[current_id_].getMassAnalyzers().back().setTOFTotalPathLength(value.toDouble());
}
else if (accession == "MS:1000024") //final MS exponent
{
instruments_[current_id_].getMassAnalyzers().back().setFinalMSExponent(value.toInt());
}
else if (accession == "MS:1000025") //magnetic field strength (tesla)
{
instruments_[current_id_].getMassAnalyzers().back().setMagneticFieldStrength(value.toDouble());
}
else if (accession == "MS:1000105") //reflectron off
{
instruments_[current_id_].getMassAnalyzers().back().setReflectronState(MassAnalyzer::ReflectronState::OFF);
}
else if (accession == "MS:1000106") //reflectron on
{
instruments_[current_id_].getMassAnalyzers().back().setReflectronState(MassAnalyzer::ReflectronState::ON);
}
else
warning(LOAD, String("Unhandled cvParam '") + accession + "' in tag '" + parent_tag + "'.");
}
else if (parent_tag == "detector")
{
//detector type
if (accession == "MS:1000107") //channeltron
{
instruments_[current_id_].getIonDetectors().back().setType(IonDetector::Type::CHANNELTRON);
}
else if (accession == "MS:1000110") //daly detector
{
instruments_[current_id_].getIonDetectors().back().setType(IonDetector::Type::DALYDETECTOR);
}
else if (accession == "MS:1000112") //faraday cup
{
instruments_[current_id_].getIonDetectors().back().setType(IonDetector::Type::FARADAYCUP);
}
else if (accession == "MS:1000114") //microchannel plate detector
{
instruments_[current_id_].getIonDetectors().back().setType(IonDetector::Type::MICROCHANNELPLATEDETECTOR);
}
else if (accession == "MS:1000115") //multi-collector
{
instruments_[current_id_].getIonDetectors().back().setType(IonDetector::Type::MULTICOLLECTOR);
}
else if (accession == "MS:1000116") //photomultiplier
{
instruments_[current_id_].getIonDetectors().back().setType(IonDetector::Type::PHOTOMULTIPLIER);
}
else if (accession == "MS:1000253") //electron multiplier
{
instruments_[current_id_].getIonDetectors().back().setType(IonDetector::Type::ELECTRONMULTIPLIER);
}
else if (accession == "MS:1000345") //array detector
{
instruments_[current_id_].getIonDetectors().back().setType(IonDetector::Type::ARRAYDETECTOR);
}
else if (accession == "MS:1000346") //conversion dynode
{
instruments_[current_id_].getIonDetectors().back().setType(IonDetector::Type::CONVERSIONDYNODE);
}
else if (accession == "MS:1000347") //dynode
{
instruments_[current_id_].getIonDetectors().back().setType(IonDetector::Type::DYNODE);
}
else if (accession == "MS:1000348") //focal plane collector
{
instruments_[current_id_].getIonDetectors().back().setType(IonDetector::Type::FOCALPLANECOLLECTOR);
}
else if (accession == "MS:1000349") //ion-to-photon detector
{
instruments_[current_id_].getIonDetectors().back().setType(IonDetector::Type::IONTOPHOTONDETECTOR);
}
else if (accession == "MS:1000350") //point collector
{
instruments_[current_id_].getIonDetectors().back().setType(IonDetector::Type::POINTCOLLECTOR);
}
else if (accession == "MS:1000351") //postacceleration detector
{
instruments_[current_id_].getIonDetectors().back().setType(IonDetector::Type::POSTACCELERATIONDETECTOR);
}
else if (accession == "MS:1000621") //photodiode array detector
{
instruments_[current_id_].getIonDetectors().back().setType(IonDetector::Type::PHOTODIODEARRAYDETECTOR);
}
else if (accession == "MS:1000624") //inductive detector
{
instruments_[current_id_].getIonDetectors().back().setType(IonDetector::Type::INDUCTIVEDETECTOR);
}
else if (accession == "MS:1000108") //conversion dynode electron multiplier
{
instruments_[current_id_].getIonDetectors().back().setType(IonDetector::Type::CONVERSIONDYNODEELECTRONMULTIPLIER);
}
else if (accession == "MS:1000109") //conversion dynode photomultiplier
{
instruments_[current_id_].getIonDetectors().back().setType(IonDetector::Type::CONVERSIONDYNODEPHOTOMULTIPLIER);
}
else if (accession == "MS:1000111") //electron multiplier tube
{
instruments_[current_id_].getIonDetectors().back().setType(IonDetector::Type::ELECTRONMULTIPLIERTUBE);
}
else if (accession == "MS:1000113") //focal plane array
{
instruments_[current_id_].getIonDetectors().back().setType(IonDetector::Type::FOCALPLANEARRAY);
}
else if (accession == "MS:1000026") //detector type (base term)
{
instruments_[current_id_].getIonDetectors().back().setType(IonDetector::Type::TYPENULL);
}
//detector attribute
else if (accession == "MS:1000028") //detector resolution
{
instruments_[current_id_].getIonDetectors().back().setResolution(value.toDouble());
}
else if (accession == "MS:1000029") //sampling frequency
{
instruments_[current_id_].getIonDetectors().back().setADCSamplingFrequency(value.toDouble());
}
//detector acquisition mode
else if (accession == "MS:1000117") //analog-digital converter
{
instruments_[current_id_].getIonDetectors().back().setAcquisitionMode(IonDetector::AcquisitionMode::ADC);
}
else if (accession == "MS:1000118") //pulse counting
{
instruments_[current_id_].getIonDetectors().back().setAcquisitionMode(IonDetector::AcquisitionMode::PULSECOUNTING);
}
else if (accession == "MS:1000119") //time-digital converter
{
instruments_[current_id_].getIonDetectors().back().setAcquisitionMode(IonDetector::AcquisitionMode::TDC);
}
else if (accession == "MS:1000120") //transient recorder
{
instruments_[current_id_].getIonDetectors().back().setAcquisitionMode(IonDetector::AcquisitionMode::TRANSIENTRECORDER);
}
else
warning(LOAD, String("Unhandled cvParam '") + accession + "' in tag '" + parent_tag + "'.");
}
else if (parent_tag == "processingMethod")
{
//data processing parameter
if (accession == "MS:1000629") //low intensity threshold (ion count)
{
processing_[current_id_].back()->setMetaValue("low_intensity_threshold", termValue);
}
else if (accession == "MS:1000631") //high intensity threshold (ion count)
{
processing_[current_id_].back()->setMetaValue("high_intensity_threshold", termValue);
}
else if (accession == "MS:1000787") //inclusive low intensity threshold
{
processing_[current_id_].back()->setMetaValue("inclusive_low_intensity_threshold", termValue);
}
else if (accession == "MS:1000788") //inclusive high intensity threshold
{
processing_[current_id_].back()->setMetaValue("inclusive_high_intensity_threshold", termValue);
}
else if (accession == "MS:1000747") //completion time
{
processing_[current_id_].back()->setCompletionTime(asDateTime_(value));
}
//file format conversion
else if (accession == "MS:1000530") //file format conversion
{
processing_[current_id_].back()->getProcessingActions().insert(DataProcessing::FORMAT_CONVERSION);
}
else if (accession == "MS:1000544") //Conversion to mzML
{
processing_[current_id_].back()->getProcessingActions().insert(DataProcessing::CONVERSION_MZML);
}
else if (accession == "MS:1000545") //Conversion to mzXML
{
processing_[current_id_].back()->getProcessingActions().insert(DataProcessing::CONVERSION_MZXML);
}
else if (accession == "MS:1000546") //Conversion to mzData
{
processing_[current_id_].back()->getProcessingActions().insert(DataProcessing::CONVERSION_MZDATA);
}
else if (accession == "MS:1000741") //Conversion to DTA
{
processing_[current_id_].back()->getProcessingActions().insert(DataProcessing::CONVERSION_DTA);
}
//data processing action
else if (accession == "MS:1000543") //data processing action
{
processing_[current_id_].back()->getProcessingActions().insert(DataProcessing::DATA_PROCESSING);
}
else if (accession == "MS:1000033") //deisotoping
{
processing_[current_id_].back()->getProcessingActions().insert(DataProcessing::DEISOTOPING);
}
else if (accession == "MS:1000034") //charge deconvolution
{
processing_[current_id_].back()->getProcessingActions().insert(DataProcessing::CHARGE_DECONVOLUTION);
}
else if (accession == "MS:1000035" || cv_.isChildOf(accession, "MS:1000035")) //peak picking (or child terms, we make no difference)
{
processing_[current_id_].back()->getProcessingActions().insert(DataProcessing::PEAK_PICKING);
}
else if (accession == "MS:1000592" || cv_.isChildOf(accession, "MS:1000592")) //smoothing (or child terms, we make no difference)
{
processing_[current_id_].back()->getProcessingActions().insert(DataProcessing::SMOOTHING);
}
else if (accession == "MS:1000778" || cv_.isChildOf(accession, "MS:1000778")) //charge state calculation (or child terms, we make no difference)
{
processing_[current_id_].back()->getProcessingActions().insert(DataProcessing::CHARGE_CALCULATION);
}
else if (accession == "MS:1000780" || cv_.isChildOf(accession, "MS:1000780")) //precursor recalculation (or child terms, we make no difference)
{
processing_[current_id_].back()->getProcessingActions().insert(DataProcessing::PRECURSOR_RECALCULATION);
}
else if (accession == "MS:1000593") //baseline reduction
{
processing_[current_id_].back()->getProcessingActions().insert(DataProcessing::BASELINE_REDUCTION);
}
else if (accession == "MS:1000745") //retention time alignment
{
processing_[current_id_].back()->getProcessingActions().insert(DataProcessing::ALIGNMENT);
}
else if (accession == "MS:1001484") //intensity normalization
{
processing_[current_id_].back()->getProcessingActions().insert(DataProcessing::NORMALIZATION);
}
else if (accession == "MS:1001485") //m/z calibration
{
processing_[current_id_].back()->getProcessingActions().insert(DataProcessing::CALIBRATION);
}
else if (accession == "MS:1001486" || cv_.isChildOf(accession, "MS:1001486")) //data filtering (or child terms, we make no difference)
{
processing_[current_id_].back()->getProcessingActions().insert(DataProcessing::FILTERING);
}
else
warning(LOAD, String("Unhandled cvParam '") + accession + "' in tag '" + parent_tag + "'.");
}
else if (parent_tag == "fileContent")
{
if (cv_.isChildOf(accession, "MS:1000524")) //data file content
{
//ignored
//exp_->setMetaValue(name, termValue);
}
else if (cv_.isChildOf(accession, "MS:1000525")) //spectrum representation
{
//ignored
//exp_->setMetaValue(name, termValue);
}
else
warning(LOAD, String("Unhandled cvParam '") + accession + "' in tag '" + parent_tag + "'.");
}
else if (parent_tag == "software")
{
if (cv_.isChildOf(accession, "MS:1000531")) //software as string
{
if (accession == "MS:1000799") //custom unreleased software tool => use value as name
{
software_[current_id_].setName(value);
}
else //use name as name
{
software_[current_id_].setName(name);
}
}
else
{
warning(LOAD, String("Unhandled cvParam '") + accession + "' in tag '" + parent_tag + "'.");
}
//~ software_[current_id_].addCVTerm( CVTerm (accession, value, const String &cv_identifier_ref, const String &value, const Unit &unit) ); TODO somthing like that
}
else if (parent_tag == "chromatogram")
{
if (accession == "MS:1000810")
{
chromatogram_.setChromatogramType(ChromatogramSettings::ChromatogramType::MASS_CHROMATOGRAM);
}
else if (accession == "MS:1000235")
{
chromatogram_.setChromatogramType(ChromatogramSettings::ChromatogramType::TOTAL_ION_CURRENT_CHROMATOGRAM);
}
else if (accession == "MS:1000627")
{
chromatogram_.setChromatogramType(ChromatogramSettings::ChromatogramType::SELECTED_ION_CURRENT_CHROMATOGRAM);
}
else if (accession == "MS:1000628")
{
chromatogram_.setChromatogramType(ChromatogramSettings::ChromatogramType::BASEPEAK_CHROMATOGRAM);
}
else if (accession == "MS:1001472")
{
chromatogram_.setChromatogramType(ChromatogramSettings::ChromatogramType::SELECTED_ION_MONITORING_CHROMATOGRAM);
}
else if (accession == "MS:1001473")
{
chromatogram_.setChromatogramType(ChromatogramSettings::ChromatogramType::SELECTED_REACTION_MONITORING_CHROMATOGRAM);
}
else if (accession == "MS:1001474")
{
chromatogram_.setChromatogramType(ChromatogramSettings::ChromatogramType::SELECTED_REACTION_MONITORING_CHROMATOGRAM);
}
else if (accession == "MS:1000811")
{
chromatogram_.setChromatogramType(ChromatogramSettings::ChromatogramType::ELECTROMAGNETIC_RADIATION_CHROMATOGRAM);
}
else if (accession == "MS:1000812")
{
chromatogram_.setChromatogramType(ChromatogramSettings::ChromatogramType::ABSORPTION_CHROMATOGRAM);
}
else if (accession == "MS:1000813")
{
chromatogram_.setChromatogramType(ChromatogramSettings::ChromatogramType::EMISSION_CHROMATOGRAM);
}
else if (accession == "MS:1000809")
{
chromatogram_.setName(value);
}
else
warning(LOAD, String("Unhandled cvParam '") + accession + "' in tag '" + parent_tag + "'.");
}
else if (parent_tag == "target")
{
//allowed but, not needed
}
else
warning(LOAD, String("Unhandled cvParam '") + accession + "' in tag '" + parent_tag + "'.");
}
void MzMLHandler::handleUserParam_(const String& parent_parent_tag,
const String& parent_tag,
const String& name,
const String& type,
const String& value,
const String& unit_accession)
{
// create a DataValue that contains the data in the right type
DataValue data_value = fromXSDString(type, value);
if (!unit_accession.empty())
{
if (unit_accession.hasPrefix("UO:"))
{
data_value.setUnit(unit_accession.suffix(unit_accession.size() - 3).toInt());
data_value.setUnitType(DataValue::UnitType::UNIT_ONTOLOGY);
}
else if (unit_accession.hasPrefix("MS:"))
{
data_value.setUnit(unit_accession.suffix(unit_accession.size() - 3).toInt());
data_value.setUnitType(DataValue::UnitType::MS_ONTOLOGY);
}
else
{
warning(LOAD, String("Unhandled unit '") + unit_accession + "' in tag '" + parent_tag + "'.");
}
}
//find the right MetaInfoInterface
if (parent_tag == "run")
{
exp_->setMetaValue(name, data_value);
}
else if (parent_tag == "instrumentConfiguration")
{
instruments_[current_id_].setMetaValue(name, data_value);
}
else if (parent_tag == "source")
{
instruments_[current_id_].getIonSources().back().setMetaValue(name, data_value);
}
else if (parent_tag == "analyzer")
{
instruments_[current_id_].getMassAnalyzers().back().setMetaValue(name, data_value);
}
else if (parent_tag == "detector")
{
instruments_[current_id_].getIonDetectors().back().setMetaValue(name, data_value);
}
else if (parent_tag == "sample")
{
samples_[current_id_].setMetaValue(name, data_value);
}
else if (parent_tag == "software")
{
software_[current_id_].setMetaValue(name, data_value);
}
else if (parent_tag == "contact")
{
exp_->getContacts().back().setMetaValue(name, data_value);
}
else if (parent_tag == "sourceFile")
{
source_files_[current_id_].setMetaValue(name, data_value);
}
else if (parent_tag == "binaryDataArray")
{
bin_data_.back().meta.setMetaValue(name, data_value);
}
else if (parent_tag == "spectrum")
{
spec_.setMetaValue(name, data_value);
}
else if (parent_tag == "chromatogram")
{
chromatogram_.setMetaValue(name, data_value);
}
else if (parent_tag == "scanList")
{
spec_.getAcquisitionInfo().setMetaValue(name, data_value);
}
else if (parent_tag == "scan")
{
spec_.getAcquisitionInfo().back().setMetaValue(name, data_value);
}
else if (parent_tag == "scanWindow")
{
spec_.getInstrumentSettings().getScanWindows().back().setMetaValue(name, data_value);
}
else if (parent_tag == "isolationWindow")
{
//We don't have this as a separate location => store it in the precursor
if (parent_parent_tag == "precursor")
{
if (in_spectrum_list_)
{
spec_.getPrecursors().back().setMetaValue(name, data_value);
}
else
{
chromatogram_.getPrecursor().setMetaValue(name, data_value);
}
}
else if (parent_parent_tag == "product")
{
if (in_spectrum_list_)
{
spec_.getProducts().back().setMetaValue(name, data_value);
}
else
{
chromatogram_.getProduct().setMetaValue(name, data_value);
}
}
}
else if (parent_tag == "selectedIon")
{
//parse only the first selected ion
if (selected_ion_count_ > 1)
return;
//We don't have this as a separate location => store it in the precursor
if (in_spectrum_list_)
{
spec_.getPrecursors().back().setMetaValue(name, data_value);
}
else
{
chromatogram_.getPrecursor().setMetaValue(name, data_value);
}
}
else if (parent_tag == "activation")
{
//We don't have this as a separate location => store it in the precursor
if (in_spectrum_list_)
{
spec_.getPrecursors().back().setMetaValue(name, data_value);
}
else
{
chromatogram_.getPrecursor().setMetaValue(name, data_value);
}
}
else if (parent_tag == "processingMethod")
{
processing_[current_id_].back()->setMetaValue(name, data_value);
}
else if (parent_tag == "fileContent")
{
//exp_->setMetaValue(name, data_value);
}
else
{
warning(LOAD, String("Unhandled userParam '") + name + "' in tag '" + parent_tag + "'.");
}
}
bool MzMLHandler::validateCV_(const ControlledVocabulary::CVTerm& c, const String& path, const Internal::MzMLValidator& validator) const
{
// We remember already validated path-term-combinations in cached_terms_
// This avoids recomputing SemanticValidator::locateTerm() multiple times for the same terms and paths
// validateCV_() is called very often for the same path-term-combinations, so we save lots of repetitive computations
// By caching these combinations we save about 99% of the runtime of validateCV_()
const auto it = cached_terms_.find(std::make_pair(path, c.id));
if (it != cached_terms_.end())
{
return it->second;
}
SemanticValidator::CVTerm sc;
sc.accession = c.id;
sc.name = c.name;
sc.has_unit_accession = false;
sc.has_unit_name = false;
bool isValid = validator.SemanticValidator::locateTerm(path, sc);
cached_terms_[std::make_pair(path, c.id)] = isValid;
return isValid;
}
String MzMLHandler::writeCV_(const ControlledVocabulary::CVTerm& c, const DataValue& metaValue) const
{
String cvTerm = "<cvParam cvRef=\"" + c.id.prefix(':') + "\" accession=\"" + c.id + "\" name=\"" + c.name;
if (!metaValue.isEmpty())
{
cvTerm += "\" value=\"" + writeXMLEscape(metaValue.toString());
if (metaValue.hasUnit())
{
// unitAccession="UO:0000021" unitName="gram" unitCvRef="UO"
//
// We need to identify the correct CV term for the *unit* by
// retrieving the identifier and looking up the term within the
// correct ontology in our cv_ object.
char s[8];
snprintf(s, sizeof(s), "%07d", metaValue.getUnit()); // all CV use 7 digit identifiers padded with zeros
String unitstring = String(s);
if (metaValue.getUnitType() == DataValue::UnitType::UNIT_ONTOLOGY)
{
unitstring = "UO:" + unitstring;
}
else if (metaValue.getUnitType() == DataValue::UnitType::MS_ONTOLOGY)
{
unitstring = "MS:" + unitstring;
}
else
{
warning(LOAD, String("Unhandled unit ontology '") );
}
ControlledVocabulary::CVTerm unit = cv_.getTerm(unitstring);
cvTerm += "\" unitAccession=\"" + unit.id + "\" unitName=\"" + unit.name + "\" unitCvRef=\"" + unit.id.prefix(2);
}
}
cvTerm += "\"/>\n";
return cvTerm;
}
void MzMLHandler::writeUserParam_(std::ostream& os, const MetaInfoInterface& meta, UInt indent, const String& path, const Internal::MzMLValidator& validator, const std::set<String>& exclude) const
{
std::vector<String> cvParams;
std::vector<String> userParams;
std::vector<String> keys;
meta.getKeys(keys);
for (std::vector<String>::iterator key = keys.begin(); key != keys.end(); ++key)
{
if (exclude.count(*key)) continue; // skip excluded entries
// special treatment of GO and BTO terms
// <cvParam cvRef="BTO" accession="BTO:0000199" name="cardiac muscle"/>
if (*key == "GO cellular component" || *key == "brenda source tissue")
{
// the CVTerm info is in the meta value
const ControlledVocabulary::CVTerm* c = cv_.checkAndGetTermByName(meta.getMetaValue(*key));
if (c != nullptr)
{
// TODO: validate CV, we currently cannot do this as the relations in the BTO and GO are not captured by our CV impl
cvParams.push_back(writeCV_(*c, DataValue::EMPTY));
}
}
else
{
bool writtenAsCVTerm = false;
const ControlledVocabulary::CVTerm* c = cv_.checkAndGetTermByName(*key);
if (c != nullptr)
{
if (validateCV_(*c, path, validator))
{
// write CV
cvParams.push_back(writeCV_(*c, meta.getMetaValue(*key)));
writtenAsCVTerm = true;
}
}
// if we could not write it as CVTerm we will store it at least as userParam
if (!writtenAsCVTerm)
{
String userParam = "<userParam name=\"" + *key + "\" type=\"";
const DataValue& d = meta.getMetaValue(*key);
//determine type
if (d.valueType() == DataValue::INT_VALUE)
{
userParam += "xsd:integer";
}
else if (d.valueType() == DataValue::DOUBLE_VALUE)
{
userParam += "xsd:double";
}
else //string or lists are converted to string
{
userParam += "xsd:string";
}
userParam += "\" value=\"" + writeXMLEscape(d.toString());
if (d.hasUnit())
{
// unitAccession="UO:0000021" unitName="gram" unitCvRef="UO"
//
// We need to identify the correct CV term for the *unit* by
// retrieving the identifier and looking up the term within the
// correct ontology in our cv_ object.
char s[8];
snprintf(s, sizeof(s), "%07d", d.getUnit()); // all CV use 7 digit identifiers padded with zeros
String unitstring = String(s);
if (d.getUnitType() == DataValue::UnitType::UNIT_ONTOLOGY)
{
unitstring = "UO:" + unitstring;
}
else if (d.getUnitType() == DataValue::UnitType::MS_ONTOLOGY)
{
unitstring = "MS:" + unitstring;
}
else
{
warning(LOAD, String("Unhandled unit ontology '") );
}
ControlledVocabulary::CVTerm unit = cv_.getTerm(unitstring);
userParam += "\" unitAccession=\"" + unit.id + "\" unitName=\"" + unit.name + "\" unitCvRef=\"" + unit.id.prefix(2);
}
userParam += "\"/>\n";
userParams.push_back(std::move(userParam));
}
}
}
// write out all the cvParams and userParams in correct order
for (const auto& p : cvParams)
{
os << String(indent, '\t') << p;
}
for (const auto& p : userParams)
{
os << String(indent, '\t') << p;
}
}
ControlledVocabulary::CVTerm MzMLHandler::getChildWithName_(const String& parent_accession, const String& name) const
{
ControlledVocabulary::CVTerm res;
auto searcher = [&res, &name, this] (const String& child)
{
const ControlledVocabulary::CVTerm& current = this->cv_.getTerm(child);
if (current.name == name)
{
res = current;
return true;
}
return false;
};
cv_.iterateAllChildren(parent_accession, searcher);
return res;
}
void MzMLHandler::writeSoftware_(std::ostream& os, const String& id, const Software& software, const Internal::MzMLValidator& validator)
{
os << "\t\t<software id=\"" << id << "\" version=\"" << software.getVersion() << "\" >\n";
ControlledVocabulary::CVTerm so_term = getChildWithName_("MS:1000531", software.getName());
if (so_term.id.empty())
{
so_term = getChildWithName_("MS:1000531", software.getName() + " software"); //act of desperation to find the right cv and keep compatible with older cv mzmls
}
if (so_term.id.empty())
{
so_term = getChildWithName_("MS:1000531", "TOPP " + software.getName()); //act of desperation to find the right cv and keep compatible with older cv mzmls
}
if (so_term.id == "MS:1000799")
{
os << "\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000799\" name=\"custom unreleased software tool\" value=\"\" />\n";
}
else if (!so_term.id.empty())
{
os << "\t\t\t<cvParam cvRef=\"MS\" accession=\"" << so_term.id << "\" name=\"" << writeXMLEscape(so_term.name) << "\" />\n";
}
else
{
os << "\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000799\" name=\"custom unreleased software tool\" value=\"" << writeXMLEscape(software.getName()) << "\" />\n";
}
writeUserParam_(os, software, 3, "/mzML/Software/cvParam/@accession", validator);
os << "\t\t</software>\n";
}
void MzMLHandler::writeSourceFile_(std::ostream& os, const String& id, const SourceFile& source_file, const Internal::MzMLValidator& validator)
{
os << "\t\t\t<sourceFile id=\"" << id << "\" name=\"" << writeXMLEscape(source_file.getNameOfFile()) << "\" location=\"" << writeXMLEscape(source_file.getPathToFile()) << "\">\n";
//checksum
if (source_file.getChecksumType() == SourceFile::ChecksumType::SHA1)
{
os << "\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000569\" name=\"SHA-1\" value=\"" << source_file.getChecksum() << "\" />\n";
}
else if (source_file.getChecksumType() == SourceFile::ChecksumType::MD5)
{
os << "\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000568\" name=\"MD5\" value=\"" << source_file.getChecksum() << "\" />\n";
}
else //FORCED
{
os << "\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000569\" name=\"SHA-1\" value=\"\" />\n";
}
//file type
ControlledVocabulary::CVTerm ft_term = getChildWithName_("MS:1000560", source_file.getFileType());
if (ft_term.id.empty() && source_file.getFileType().hasSuffix("file"))
{
ft_term = getChildWithName_("MS:1000560", source_file.getFileType().chop(4) + "format"); // this is born out of desperation that sourcefile has a string interface for its filetype and not the enum, which could have been easily manipulated to the updated cv
}
if (!ft_term.id.empty())
{
os << "\t\t\t\t<cvParam cvRef=\"MS\" accession=\"" << ft_term.id << "\" name=\"" << ft_term.name << "\" />\n";
}
else //FORCED
{
os << "\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000564\" name=\"PSI mzData format\" />\n";
}
//native ID format
ControlledVocabulary::CVTerm id_term = getChildWithName_("MS:1000767", source_file.getNativeIDType());
if (!id_term.id.empty())
{
os << "\t\t\t\t<cvParam cvRef=\"MS\" accession=\"" << id_term.id << "\" name=\"" << id_term.name << "\" />\n";
}
else //FORCED
{
os << "\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000777\" name=\"spectrum identifier nativeID format\" />\n";
}
writeUserParam_(os, source_file, 4, "/mzML/fileDescription/sourceFileList/sourceFile/cvParam/@accession", validator);
os << "\t\t\t</sourceFile>\n";
}
void MzMLHandler::writeDataProcessing_(std::ostream& os, const String& id, const std::vector< ConstDataProcessingPtr >& dps, const Internal::MzMLValidator& validator)
{
os << "\t\t<dataProcessing id=\"" << id << "\">\n";
//FORCED
if (dps.empty())
{
os << "\t\t\t<processingMethod order=\"0\" softwareRef=\"so_default\">\n";
os << "\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000544\" name=\"Conversion to mzML\" />\n";
os << "\t\t\t\t<userParam name=\"warning\" type=\"xsd:string\" value=\"fictional processing method used to fulfill format requirements\" />\n";
os << "\t\t\t</processingMethod>\n";
}
bool written = false;
for (Size i = 0; i < dps.size(); ++i)
{
//data processing action
os << "\t\t\t<processingMethod order=\"0\" softwareRef=\"so_" << id << "_pm_" << i << "\">\n";
if (dps[i]->getProcessingActions().count(DataProcessing::DATA_PROCESSING) == 1)
{
os << "\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000543\" name=\"data processing action\" />\n";
written = true;
}
if (dps[i]->getProcessingActions().count(DataProcessing::CHARGE_DECONVOLUTION) == 1)
{
os << "\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000034\" name=\"charge deconvolution\" />\n";
written = true;
}
if (dps[i]->getProcessingActions().count(DataProcessing::DEISOTOPING) == 1)
{
os << "\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000033\" name=\"deisotoping\" />\n";
written = true;
}
if (dps[i]->getProcessingActions().count(DataProcessing::SMOOTHING) == 1)
{
os << "\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000592\" name=\"smoothing\" />\n";
written = true;
}
if (dps[i]->getProcessingActions().count(DataProcessing::CHARGE_CALCULATION) == 1)
{
os << "\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000778\" name=\"charge state calculation\" />\n";
written = true;
}
if (dps[i]->getProcessingActions().count(DataProcessing::PRECURSOR_RECALCULATION) == 1)
{
os << "\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000780\" name=\"precursor recalculation\" />\n";
written = true;
}
if (dps[i]->getProcessingActions().count(DataProcessing::BASELINE_REDUCTION) == 1)
{
os << "\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000593\" name=\"baseline reduction\" />\n";
written = true;
}
if (dps[i]->getProcessingActions().count(DataProcessing::PEAK_PICKING) == 1)
{
os << "\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000035\" name=\"peak picking\" />\n";
written = true;
}
if (dps[i]->getProcessingActions().count(DataProcessing::ALIGNMENT) == 1)
{
os << "\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000745\" name=\"retention time alignment\" />\n";
written = true;
}
if (dps[i]->getProcessingActions().count(DataProcessing::CALIBRATION) == 1)
{
os << "\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1001485\" name=\"m/z calibration\" />\n";
written = true;
}
if (dps[i]->getProcessingActions().count(DataProcessing::NORMALIZATION) == 1)
{
os << "\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1001484\" name=\"intensity normalization\" />\n";
written = true;
}
if (dps[i]->getProcessingActions().count(DataProcessing::FILTERING) == 1)
{
os << "\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1001486\" name=\"data filtering\" />\n";
written = true;
}
//file format conversion
if (dps[i]->getProcessingActions().count(DataProcessing::FORMAT_CONVERSION) == 1)
{
os << "\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000530\" name=\"file format conversion\" />\n";
written = true;
}
if (dps[i]->getProcessingActions().count(DataProcessing::CONVERSION_MZDATA) == 1)
{
os << "\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000546\" name=\"Conversion to mzData\" />\n";
written = true;
}
if (dps[i]->getProcessingActions().count(DataProcessing::CONVERSION_MZML) == 1)
{
os << "\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000544\" name=\"Conversion to mzML\" />\n";
written = true;
}
if (dps[i]->getProcessingActions().count(DataProcessing::CONVERSION_MZXML) == 1)
{
os << "\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000545\" name=\"Conversion to mzXML\" />\n";
written = true;
}
if (dps[i]->getProcessingActions().count(DataProcessing::CONVERSION_DTA) == 1)
{
os << "\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000741\" name=\"Conversion to dta\" />\n";
written = true;
}
if (!written)
{
os << "\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000543\" name=\"data processing action\" />\n";
}
//data processing attribute
if (dps[i]->getCompletionTime().isValid())
{
os << "\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000747\" name=\"completion time\" value=\"" << dps[i]->getCompletionTime().toString("yyyy-MM-dd+hh:mm") << "\" />\n";
}
writeUserParam_(os, *(dps[i].get()), 4, "/mzML/dataProcessingList/dataProcessing/processingMethod/cvParam/@accession", validator);
os << "\t\t\t</processingMethod>\n";
}
os << "\t\t</dataProcessing>\n";
}
void MzMLHandler::writePrecursor_(std::ostream& os, const Precursor& precursor, const Internal::MzMLValidator& validator)
{
// optional attributes
String external_spectrum_id =
precursor.metaValueExists("external_spectrum_id") ?
" externalSpectrumID=\"" + precursor.getMetaValue("external_spectrum_id").toString() + "\"" :
"";
String spectrum_ref =
precursor.metaValueExists("spectrum_ref") ?
" spectrumRef=\"" + precursor.getMetaValue("spectrum_ref").toString() + "\"":
"";
os << "\t\t\t\t\t<precursor" + external_spectrum_id + spectrum_ref + ">\n";
//--------------------------------------------------------------------------------------------
//isolation window (optional)
//--------------------------------------------------------------------------------------------
// precursor m/z may come from "selected ion":
double mz = precursor.getMetaValue("isolation window target m/z",
precursor.getMZ());
// Note that TPP parsers break when the isolation window is written out
// in mzML files and the precursorMZ gets set to zero.
if (mz > 0.0 && !options_.getForceTPPCompatability())
{
os << "\t\t\t\t\t\t<isolationWindow>\n";
os << "\t\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000827\" name=\"isolation window target m/z\" value=\"" << mz << "\" unitAccession=\"MS:1000040\" unitName=\"m/z\" unitCvRef=\"MS\" />\n";
if (precursor.getIsolationWindowLowerOffset() > 0.0)
{
os << "\t\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000828\" name=\"isolation window lower offset\" value=\"" << precursor.getIsolationWindowLowerOffset() << "\" unitAccession=\"MS:1000040\" unitName=\"m/z\" unitCvRef=\"MS\" />\n";
}
if (precursor.getIsolationWindowUpperOffset() > 0.0)
{
os << "\t\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000829\" name=\"isolation window upper offset\" value=\"" << precursor.getIsolationWindowUpperOffset() << "\" unitAccession=\"MS:1000040\" unitName=\"m/z\" unitCvRef=\"MS\" />\n";
}
os << "\t\t\t\t\t\t</isolationWindow>\n";
}
//userParam: no extra object for it => no user parameters
//--------------------------------------------------------------------------------------------
//selected ion list (optional)
//--------------------------------------------------------------------------------------------
//
if (options_.getForceTPPCompatability() ||
precursor.getCharge() != 0 ||
precursor.getIntensity() > 0.0 ||
precursor.getDriftTime() >= 0.0 ||
precursor.getDriftTimeUnit() == DriftTimeUnit::FAIMS_COMPENSATION_VOLTAGE ||
!precursor.getPossibleChargeStates().empty() ||
precursor.getMZ() > 0.0)
{
// precursor m/z may come from "isolation window":
mz = precursor.getMetaValue("selected ion m/z",
precursor.getMZ());
os << "\t\t\t\t\t\t<selectedIonList count=\"1\">\n";
os << "\t\t\t\t\t\t\t<selectedIon>\n";
os << "\t\t\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000744\" name=\"selected ion m/z\" value=\"" << mz << "\" unitAccession=\"MS:1000040\" unitName=\"m/z\" unitCvRef=\"MS\" />\n";
if (options_.getForceTPPCompatability() || precursor.getCharge() != 0)
{
os << "\t\t\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000041\" name=\"charge state\" value=\"" << precursor.getCharge() << "\" />\n";
}
if ( precursor.getIntensity() > 0.0)
{
os << "\t\t\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000042\" name=\"peak intensity\" value=\"" << precursor.getIntensity() << "\" unitAccession=\"MS:1000132\" unitName=\"percent of base peak\" unitCvRef=\"MS\" />\n";
}
for (Size j = 0; j < precursor.getPossibleChargeStates().size(); ++j)
{
os << "\t\t\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000633\" name=\"possible charge state\" value=\"" << precursor.getPossibleChargeStates()[j] << "\" />\n";
}
if (precursor.getDriftTime() != IMTypes::DRIFTTIME_NOT_SET)
{
switch (precursor.getDriftTimeUnit())
{
default:
// assume milliseconds, but warn
warning(STORE, String("Precursor drift time unit not set, assume milliseconds"));
[[fallthrough]];
case DriftTimeUnit::MILLISECOND:
os << "\t\t\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1002476\" name=\"ion mobility drift time\" value=\"" << precursor.getDriftTime()
<< "\" unitAccession=\"UO:0000028\" unitName=\"millisecond\" unitCvRef=\"UO\" />\n";
break;
case DriftTimeUnit::VSSC:
os << "\t\t\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1002815\" name=\"inverse reduced ion mobility\" value=\"" << precursor.getDriftTime()
<< "\" unitAccession=\"MS:1002814\" unitName=\"volt-second per square centimeter\" unitCvRef=\"MS\" />\n";
break;
}
}
//userParam: no extra object for it => no user parameters
os << "\t\t\t\t\t\t\t</selectedIon>\n";
os << "\t\t\t\t\t\t</selectedIonList>\n";
}
//--------------------------------------------------------------------------------------------
//activation (mandatory)
//--------------------------------------------------------------------------------------------
os << "\t\t\t\t\t\t<activation>\n";
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wfloat-equal"
#endif
if (precursor.getActivationEnergy() != 0)
#ifdef __clang__
#pragma clang diagnostic pop
#endif
{
os << "\t\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000509\" name=\"activation energy\" value=\"" << precursor.getActivationEnergy() << "\" unitAccession=\"UO:0000266\" unitName=\"electronvolt\" unitCvRef=\"UO\" />\n";
}
if (precursor.getActivationMethods().count(Precursor::ActivationMethod::CID) != 0)
{
os << "\t\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000133\" name=\"collision-induced dissociation\" />\n";
}
if (precursor.getActivationMethods().count(Precursor::ActivationMethod::PD) != 0)
{
os << "\t\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000134\" name=\"plasma desorption\" />\n";
}
if (precursor.getActivationMethods().count(Precursor::ActivationMethod::PSD) != 0)
{
os << "\t\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000135\" name=\"post-source decay\" />\n";
}
if (precursor.getActivationMethods().count(Precursor::ActivationMethod::SID) != 0)
{
os << "\t\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000136\" name=\"surface-induced dissociation\" />\n";
}
if (precursor.getActivationMethods().count(Precursor::ActivationMethod::BIRD) != 0)
{
os << "\t\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000242\" name=\"blackbody infrared radiative dissociation\" />\n";
}
if (precursor.getActivationMethods().count(Precursor::ActivationMethod::ECD) != 0)
{
os << "\t\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000250\" name=\"electron capture dissociation\" />\n";
}
if (precursor.getActivationMethods().count(Precursor::ActivationMethod::IMD) != 0)
{
os << "\t\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000262\" name=\"infrared multiphoton dissociation\" />\n";
}
if (precursor.getActivationMethods().count(Precursor::ActivationMethod::SORI) != 0)
{
os << "\t\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000282\" name=\"sustained off-resonance irradiation\" />\n";
}
if (precursor.getActivationMethods().count(Precursor::ActivationMethod::HCID) != 0)
{
os << "\t\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1002481\" name=\"high-energy collision-induced dissociation\" />\n";
}
if (precursor.getActivationMethods().count(Precursor::ActivationMethod::HCD) != 0)
{
os << "\t\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000422\" name=\"beam-type collision-induced dissociation\" />\n";
}
if (precursor.getActivationMethods().count(Precursor::ActivationMethod::TRAP) != 0)
{
os << "\t\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1002472\" name=\"trap-type collision-induced dissociation\" />\n";
}
if (precursor.getActivationMethods().count(Precursor::ActivationMethod::LCID) != 0)
{
os << "\t\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000433\" name=\"low-energy collision-induced dissociation\" />\n";
}
if (precursor.getActivationMethods().count(Precursor::ActivationMethod::PHD) != 0)
{
os << "\t\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000435\" name=\"photodissociation\" />\n";
}
if (precursor.getActivationMethods().count(Precursor::ActivationMethod::ETD) != 0)
{
os << "\t\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000598\" name=\"electron transfer dissociation\" />\n";
}
if (precursor.getActivationMethods().count(Precursor::ActivationMethod::ETciD) != 0)
{
os << "\t\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1003182\" name=\"electron transfer and collision-induced dissociation\" />\n";
}
if (precursor.getActivationMethods().count(Precursor::ActivationMethod::EThcD) != 0)
{
os << "\t\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1002631\" name=\"electron transfer and higher-energy collision dissociation\" />\n";
}
if (precursor.getActivationMethods().count(Precursor::ActivationMethod::PQD) != 0)
{
os << "\t\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000599\" name=\"pulsed q dissociation\" />\n";
}
if (precursor.getActivationMethods().count(Precursor::ActivationMethod::INSOURCE) != 0)
{
os << "\t\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1001880\" name=\"in-source collision-induced dissociation\" />\n";
}
if (precursor.getActivationMethods().count(Precursor::ActivationMethod::LIFT) != 0)
{
os << "\t\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1002000\" name=\"LIFT\" />\n";
}
if (precursor.getActivationMethods().empty())
{
os << "\t\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000044\" name=\"dissociation method\" />\n";
}
// as "precursor" has no own user param its userParam is stored here;
// don't write out parameters that are used internally to distinguish
// between precursor m/z values from different sources:
writeUserParam_(os, precursor, 7, "/mzML/run/spectrumList/spectrum/precursorList/precursor/activation/cvParam/@accession", validator, {"isolation window target m/z", "selected ion m/z", "external_spectrum_id", "spectrum_ref"});
os << "\t\t\t\t\t\t</activation>\n";
os << "\t\t\t\t\t</precursor>\n";
}
void MzMLHandler::writeProduct_(std::ostream& os, const Product& product, const Internal::MzMLValidator& validator)
{
os << "\t\t\t\t\t<product>\n";
os << "\t\t\t\t\t\t<isolationWindow>\n";
os << "\t\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000827\" name=\"isolation window target m/z\" value=\"" << product.getMZ() << "\" unitAccession=\"MS:1000040\" unitName=\"m/z\" unitCvRef=\"MS\" />\n";
if ( product.getIsolationWindowLowerOffset() > 0.0)
{
os << "\t\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000828\" name=\"isolation window lower offset\" value=\"" << product.getIsolationWindowLowerOffset() << "\" unitAccession=\"MS:1000040\" unitName=\"m/z\" unitCvRef=\"MS\" />\n";
}
if ( product.getIsolationWindowUpperOffset() > 0.0)
{
os << "\t\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000829\" name=\"isolation window upper offset\" value=\"" << product.getIsolationWindowUpperOffset() << "\" unitAccession=\"MS:1000040\" unitName=\"m/z\" unitCvRef=\"MS\" />\n";
}
writeUserParam_(os, product, 7, "/mzML/run/spectrumList/spectrum/productList/product/isolationWindow/cvParam/@accession", validator);
os << "\t\t\t\t\t\t</isolationWindow>\n";
os << "\t\t\t\t\t</product>\n";
}
void MzMLHandler::writeTo(std::ostream& os)
{
const MapType& exp = *(cexp_);
logger_.startProgress(0, exp.size() + exp.getChromatograms().size(), "storing mzML file");
int progress = 0;
UInt stored_spectra = 0;
UInt stored_chromatograms = 0;
Internal::MzMLValidator validator(mapping_, cv_);
std::vector<std::vector< ConstDataProcessingPtr > > dps;
//--------------------------------------------------------------------------------------------
//header
//--------------------------------------------------------------------------------------------
writeHeader_(os, exp, dps, validator);
//--------------------------------------------------------------------------------------------
// spectra
//--------------------------------------------------------------------------------------------
if (!exp.empty())
{
// INFO : do not try to be smart and skip empty spectra or
// chromatograms. There can be very good reasons for this (e.g. if the
// meta information needs to be stored here but the actual data is
// stored somewhere else).
os << "\t\t<spectrumList count=\"" << exp.size() << "\" defaultDataProcessingRef=\"dp_sp_0\">\n";
// check native ids
bool renew_native_ids = false;
for (Size s_idx = 0; s_idx < exp.size(); ++s_idx)
{
if (!exp[s_idx].getNativeID().has('='))
{
renew_native_ids = true;
break;
}
}
// issue warning if something is wrong
if (renew_native_ids)
{
warning(STORE, String("Invalid native IDs detected. Using spectrum identifier nativeID format (spectrum=xsd:nonNegativeInteger) for all spectra."));
}
// write actual data
for (Size s_idx = 0; s_idx < exp.size(); ++s_idx)
{
logger_.setProgress(progress++);
const SpectrumType& spec = exp[s_idx];
writeSpectrum_(os, spec, s_idx, validator, renew_native_ids, dps);
++stored_spectra;
}
os << "\t\t</spectrumList>\n";
}
//--------------------------------------------------------------------------------------------
// chromatograms
//--------------------------------------------------------------------------------------------
if (!exp.getChromatograms().empty())
{
// INFO : do not try to be smart and skip empty spectra or
// chromatograms. There can be very good reasons for this (e.g. if the
// meta information needs to be stored here but the actual data is
// stored somewhere else).
os << "\t\t<chromatogramList count=\"" << exp.getChromatograms().size() << "\" defaultDataProcessingRef=\"dp_sp_0\">\n";
for (Size c_idx = 0; c_idx != exp.getChromatograms().size(); ++c_idx)
{
logger_.setProgress(progress++);
const ChromatogramType& chromatogram = exp.getChromatograms()[c_idx];
writeChromatogram_(os, chromatogram, c_idx, validator);
++stored_chromatograms;
}
os << "\t\t</chromatogramList>" << "\n";
}
MzMLHandlerHelper::writeFooter_(os, options_, spectra_offsets_, chromatograms_offsets_);
OPENMS_LOG_INFO << stored_spectra << " spectra and " << stored_chromatograms << " chromatograms stored.\n";
logger_.endProgress(os.tellp());
}
void MzMLHandler::writeHeader_(std::ostream& os,
const MapType& exp,
std::vector<std::vector< ConstDataProcessingPtr > >& dps,
const Internal::MzMLValidator& validator)
{
os << "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n";
if (options_.getWriteIndex())
{
os << "<indexedmzML xmlns=\"http://psi.hupo.org/ms/mzml\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://psi.hupo.org/ms/mzml http://psidev.info/files/ms/mzML/xsd/mzML1.1.0_idx.xsd\">\n";
}
os << R"(<mzML xmlns="http://psi.hupo.org/ms/mzml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://psi.hupo.org/ms/mzml http://psidev.info/files/ms/mzML/xsd/mzML1.1.0.xsd" accession=")" << writeXMLEscape(exp.getIdentifier()) << "\" version=\"" << version_ << "\">\n";
//--------------------------------------------------------------------------------------------
// CV list
//--------------------------------------------------------------------------------------------
os << "\t<cvList count=\"5\">\n"
<< "\t\t<cv id=\"MS\" fullName=\"Proteomics Standards Initiative Mass Spectrometry Ontology\" URI=\"http://psidev.cvs.sourceforge.net/*checkout*/psidev/psi/psi-ms/mzML/controlledVocabulary/psi-ms.obo\"/>\n"
<< "\t\t<cv id=\"UO\" fullName=\"Unit Ontology\" URI=\"http://obo.cvs.sourceforge.net/obo/obo/ontology/phenotype/unit.obo\"/>\n"
<< "\t\t<cv id=\"BTO\" fullName=\"BrendaTissue545\" version=\"unknown\" URI=\"http://www.brenda-enzymes.info/ontology/tissue/tree/update/update_files/BrendaTissueOBO\"/>\n"
<< "\t\t<cv id=\"GO\" fullName=\"Gene Ontology - Slim Versions\" version=\"unknown\" URI=\"http://www.geneontology.org/GO_slims/goslim_goa.obo\"/>\n"
<< "\t\t<cv id=\"PATO\" fullName=\"Quality ontology\" version=\"unknown\" URI=\"http://obo.cvs.sourceforge.net/*checkout*/obo/obo/ontology/phenotype/quality.obo\"/>\n"
<< "\t</cvList>\n";
//--------------------------------------------------------------------------------------------
// file content
//--------------------------------------------------------------------------------------------
os << "\t<fileDescription>\n";
os << "\t\t<fileContent>\n";
std::map<InstrumentSettings::ScanMode, UInt> file_content;
for (Size i = 0; i < exp.size(); ++i)
{
++file_content[exp[i].getInstrumentSettings().getScanMode()];
}
if (file_content.find(InstrumentSettings::ScanMode::MASSSPECTRUM) != file_content.end())
{
os << "\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000294\" name=\"mass spectrum\" />\n";
}
if (file_content.find(InstrumentSettings::ScanMode::MS1SPECTRUM) != file_content.end())
{
os << "\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000579\" name=\"MS1 spectrum\" />\n";
}
if (file_content.find(InstrumentSettings::ScanMode::MSNSPECTRUM) != file_content.end())
{
os << "\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000580\" name=\"MSn spectrum\" />\n";
}
if (file_content.find(InstrumentSettings::ScanMode::SIM) != file_content.end())
{
os << "\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000582\" name=\"SIM spectrum\" />\n";
}
if (file_content.find(InstrumentSettings::ScanMode::SRM) != file_content.end())
{
os << "\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000583\" name=\"SRM spectrum\" />\n";
}
if (file_content.find(InstrumentSettings::ScanMode::CRM) != file_content.end())
{
os << "\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000581\" name=\"CRM spectrum\" />\n";
}
if (file_content.find(InstrumentSettings::ScanMode::PRECURSOR) != file_content.end())
{
os << "\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000341\" name=\"precursor ion spectrum\" />\n";
}
if (file_content.find(InstrumentSettings::ScanMode::CNG) != file_content.end())
{
os << "\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000325\" name=\"constant neutral gain spectrum\" />\n";
}
if (file_content.find(InstrumentSettings::ScanMode::CNL) != file_content.end())
{
os << "\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000326\" name=\"constant neutral loss spectrum\" />\n";
}
if (file_content.find(InstrumentSettings::ScanMode::EMR) != file_content.end())
{
os << "\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000804\" name=\"electromagnetic radiation spectrum\" />\n";
}
if (file_content.find(InstrumentSettings::ScanMode::EMISSION) != file_content.end())
{
os << "\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000805\" name=\"emission spectrum\" />\n";
}
if (file_content.find(InstrumentSettings::ScanMode::ABSORPTION) != file_content.end())
{
os << "\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000806\" name=\"absorption spectrum\" />\n";
}
if (file_content.find(InstrumentSettings::ScanMode::EMC) != file_content.end())
{
os << "\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000789\" name=\"enhanced multiply charged spectrum\" />\n";
}
if (file_content.find(InstrumentSettings::ScanMode::TDF) != file_content.end())
{
os << "\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000789\" name=\"time-delayed fragmentation spectrum\" />\n";
}
if (file_content.find(InstrumentSettings::ScanMode::UNKNOWN) != file_content.end() || file_content.empty())
{
os << "\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000294\" name=\"mass spectrum\" />\n";
}
// writeUserParam_(os, exp, 3, "/mzML/fileDescription/fileContent/cvParam/@accession", validator);
os << "\t\t</fileContent>\n";
//--------------------------------------------------------------------------------------------
// source file list
//--------------------------------------------------------------------------------------------
//find out how many spectra source files need to be written
UInt sf_sp_count = 0;
for (Size i = 0; i < exp.size(); ++i)
{
if (exp[i].getSourceFile() != SourceFile())
{
++sf_sp_count;
}
}
if (!exp.getSourceFiles().empty() || sf_sp_count > 0)
{
os << "\t\t<sourceFileList count=\"" << exp.getSourceFiles().size() + sf_sp_count << "\">\n";
//write source file of run
for (Size i = 0; i < exp.getSourceFiles().size(); ++i)
{
writeSourceFile_(os, String("sf_ru_") + String(i), exp.getSourceFiles()[i], validator);
}
// write source files of spectra
if (sf_sp_count > 0)
{
const SourceFile sf_default;
for (Size i = 0; i < exp.size(); ++i)
{
if (exp[i].getSourceFile() != sf_default)
{
writeSourceFile_(os, String("sf_sp_") + i, exp[i].getSourceFile(), validator);
}
}
}
os << "\t\t</sourceFileList>\n";
}
//--------------------------------------------------------------------------------------------
// contacts
//--------------------------------------------------------------------------------------------
for (Size i = 0; i < exp.getContacts().size(); ++i)
{
const ContactPerson& cp = exp.getContacts()[i];
os << "\t\t<contact>\n";
os << "\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000586\" name=\"contact name\" value=\"" << writeXMLEscape(cp.getLastName()) << ", " << writeXMLEscape(cp.getFirstName()) << "\" />\n";
os << "\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000590\" name=\"contact affiliation\" value=\"" << writeXMLEscape(cp.getInstitution()) << "\" />\n";
if (!cp.getAddress().empty())
{
os << "\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000587\" name=\"contact address\" value=\"" << writeXMLEscape(cp.getAddress()) << "\" />\n";
}
if (!cp.getURL().empty())
{
os << "\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000588\" name=\"contact URL\" value=\"" << writeXMLEscape(cp.getURL()) << "\" />\n";
}
if (!cp.getEmail().empty())
{
os << "\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000589\" name=\"contact email\" value=\"" << writeXMLEscape(cp.getEmail()) << "\" />\n";
}
if (!cp.getContactInfo().empty())
{
os << "\t\t\t<userParam name=\"contact_info\" type=\"xsd:string\" value=\"" << writeXMLEscape(cp.getContactInfo()) << "\" />\n";
}
writeUserParam_(os, cp, 3, "/mzML/fileDescription/contact/cvParam/@accession", validator);
os << "\t\t</contact>\n";
}
os << "\t</fileDescription>\n";
//--------------------------------------------------------------------------------------------
// sample
//--------------------------------------------------------------------------------------------
const Sample& sa = exp.getSample();
os << "\t<sampleList count=\"1\">\n";
os << "\t\t<sample id=\"sa_0\" name=\"" << writeXMLEscape(sa.getName()) << "\">\n";
if (!sa.getNumber().empty())
{
os << "\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000001\" name=\"sample number\" value=\"" << writeXMLEscape(sa.getNumber()) << "\" />\n";
}
os << "\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000004\" name=\"sample mass\" value=\"" << sa.getMass() << "\" unitAccession=\"UO:0000021\" unitName=\"gram\" unitCvRef=\"UO\" />\n";
os << "\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000005\" name=\"sample volume\" value=\"" << sa.getVolume() << "\" unitAccession=\"UO:0000098\" unitName=\"milliliter\" unitCvRef=\"UO\" />\n";
os << "\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000006\" name=\"sample concentration\" value=\"" << sa.getConcentration() << "\" unitAccession=\"UO:0000175\" unitName=\"gram per liter\" unitCvRef=\"UO\" />\n";
if (sa.getState() == Sample::SampleState::EMULSION)
{
os << "\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000047\" name=\"emulsion\" />\n";
}
else if (sa.getState() == Sample::SampleState::GAS)
{
os << "\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000048\" name=\"gas\" />\n";
}
else if (sa.getState() == Sample::SampleState::LIQUID)
{
os << "\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000049\" name=\"liquid\" />\n";
}
else if (sa.getState() == Sample::SampleState::SOLID)
{
os << "\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000050\" name=\"solid\" />\n";
}
else if (sa.getState() == Sample::SampleState::SOLUTION)
{
os << "\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000051\" name=\"solution\" />\n";
}
else if (sa.getState() == Sample::SampleState::SUSPENSION)
{
os << "\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000052\" name=\"suspension\" />\n";
}
if (!sa.getComment().empty())
{
os << "\t\t\t<userParam name=\"comment\" type=\"xsd:string\" value=\"" << writeXMLEscape(sa.getComment()) << "\" />\n";
}
writeUserParam_(os, sa, 3, "/mzML/sampleList/sample/cvParam/@accession", validator);
os << "\t\t</sample>\n";
os << "\t</sampleList>\n";
//--------------------------------------------------------------------------------------------
// Software
//--------------------------------------------------------------------------------------------
// instrument software and fallback software is always written (see below)
Size num_software(2);
// Create a list of all different data processings: check if the
// DataProcessing of the current spectra/chromatogram is already present
// and if not, append it to the dps vector
for (Size s = 0; s < exp.size(); ++s)
{
bool already_present = false;
for (Size j = 0; j < dps.size(); j++)
{
already_present = OpenMS::Helpers::cmpPtrContainer(
exp[s].getDataProcessing(), dps[j]);
if (already_present) break;
}
if (!already_present)
{
dps.push_back(exp[s].getDataProcessing());
num_software += exp[s].getDataProcessing().size();
}
}
for (Size s = 0; s < exp.getChromatograms().size(); ++s)
{
bool already_present = false;
for (Size j = 0; j < dps.size(); j++)
{
already_present = OpenMS::Helpers::cmpPtrContainer(
exp.getChromatograms()[s].getDataProcessing(), dps[j]);
if (already_present) break;
}
if (!already_present)
{
dps.push_back(exp.getChromatograms()[s].getDataProcessing());
num_software += exp.getChromatograms()[s].getDataProcessing().size();
}
}
// count binary data array software
Size num_bi_software(0);
for (Size s = 0; s < exp.size(); ++s)
{
for (Size m = 0; m < exp[s].getFloatDataArrays().size(); ++m)
{
for (Size i = 0; i < exp[s].getFloatDataArrays()[m].getDataProcessing().size(); ++i)
{
++num_bi_software;
}
}
}
os << "\t<softwareList count=\"" << num_software + num_bi_software << "\">\n";
// write instrument software
writeSoftware_(os, "so_in_0", exp.getInstrument().getSoftware(), validator);
// write fallback software
writeSoftware_(os, "so_default", Software(), validator);
// write the software of the dps
for (Size s1 = 0; s1 != dps.size(); ++s1)
{
for (Size s2 = 0; s2 != dps[s1].size(); ++s2)
{
writeSoftware_(os, String("so_dp_sp_") + s1 + "_pm_" + s2, dps[s1][s2]->getSoftware(), validator);
}
}
//write data processing (for each binary data array)
for (Size s = 0; s < exp.size(); ++s)
{
for (Size m = 0; m < exp[s].getFloatDataArrays().size(); ++m)
{
for (Size i = 0; i < exp[s].getFloatDataArrays()[m].getDataProcessing().size(); ++i)
{
writeSoftware_(os, String("so_dp_sp_") + s + "_bi_" + m + "_pm_" + i,
exp[s].getFloatDataArrays()[m].getDataProcessing()[i]->getSoftware(), validator);
}
}
}
os << "\t</softwareList>\n";
//--------------------------------------------------------------------------------------------
// instrument configuration (enclosing ion source, mass analyzer and detector)
//--------------------------------------------------------------------------------------------
const Instrument& in = exp.getInstrument();
os << "\t<instrumentConfigurationList count=\"1\">\n";
os << "\t\t<instrumentConfiguration id=\"ic_0\">\n";
ControlledVocabulary::CVTerm in_term = getChildWithName_("MS:1000031", in.getName());
if (!in_term.id.empty())
{
os << "\t\t\t<cvParam cvRef=\"MS\" accession=\"" << in_term.id << "\" name=\"" << writeXMLEscape(in_term.name) << "\" />\n";
}
else
{
os << "\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000031\" name=\"instrument model\" />\n";
}
if (!in.getCustomizations().empty())
{
os << "\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000032\" name=\"customization\" value=\"" << writeXMLEscape(in.getCustomizations()) << "\" />\n";
}
//ion optics
if (in.getIonOptics() == Instrument::IonOpticsType::MAGNETIC_DEFLECTION)
{
os << "\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000221\" name=\"magnetic deflection\" />\n";
}
else if (in.getIonOptics() == Instrument::IonOpticsType::DELAYED_EXTRACTION)
{
os << "\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000246\" name=\"delayed extraction\" />\n";
}
else if (in.getIonOptics() == Instrument::IonOpticsType::COLLISION_QUADRUPOLE)
{
os << "\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000275\" name=\"collision quadrupole\" />\n";
}
else if (in.getIonOptics() == Instrument::IonOpticsType::SELECTED_ION_FLOW_TUBE)
{
os << "\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000281\" name=\"selected ion flow tube\" />\n";
}
else if (in.getIonOptics() == Instrument::IonOpticsType::TIME_LAG_FOCUSING)
{
os << "\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000286\" name=\"time lag focusing\" />\n";
}
else if (in.getIonOptics() == Instrument::IonOpticsType::REFLECTRON)
{
os << "\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000300\" name=\"reflectron\" />\n";
}
else if (in.getIonOptics() == Instrument::IonOpticsType::EINZEL_LENS)
{
os << "\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000307\" name=\"einzel lens\" />\n";
}
else if (in.getIonOptics() == Instrument::IonOpticsType::FIRST_STABILITY_REGION)
{
os << "\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000309\" name=\"first stability region\" />\n";
}
else if (in.getIonOptics() == Instrument::IonOpticsType::FRINGING_FIELD)
{
os << "\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000310\" name=\"fringing field\" />\n";
}
else if (in.getIonOptics() == Instrument::IonOpticsType::KINETIC_ENERGY_ANALYZER)
{
os << "\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000311\" name=\"kinetic energy analyzer\" />\n";
}
else if (in.getIonOptics() == Instrument::IonOpticsType::STATIC_FIELD)
{
os << "\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000320\" name=\"static field\" />\n";
}
writeUserParam_(os, in, 3, "/mzML/instrumentConfigurationList/instrumentConfiguration/cvParam/@accession", validator);
Size component_count = in.getIonSources().size() + in.getMassAnalyzers().size() + in.getIonDetectors().size();
if (component_count != 0)
{
os << "\t\t\t<componentList count=\"" << (std::max)((Size)3, component_count) << "\">\n";
//--------------------------------------------------------------------------------------------
// ion source
//--------------------------------------------------------------------------------------------
for (Size i = 0; i < in.getIonSources().size(); ++i)
{
const IonSource& so = in.getIonSources()[i];
os << "\t\t\t\t<source order=\"" << so.getOrder() << "\">\n";
if (so.getInletType() == IonSource::InletType::CONTINUOUSFLOWFASTATOMBOMBARDMENT)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000055\" name=\"continuous flow fast atom bombardment\" />\n";
}
else if (so.getInletType() == IonSource::InletType::DIRECT)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000056\" name=\"direct inlet\" />\n";
}
else if (so.getInletType() == IonSource::InletType::ELECTROSPRAYINLET)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000057\" name=\"electrospray inlet\" />\n";
}
else if (so.getInletType() == IonSource::InletType::FLOWINJECTIONANALYSIS)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000058\" name=\"flow injection analysis\" />\n";
}
else if (so.getInletType() == IonSource::InletType::INDUCTIVELYCOUPLEDPLASMA)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000059\" name=\"inductively coupled plasma\" />\n";
}
else if (so.getInletType() == IonSource::InletType::INFUSION)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000060\" name=\"infusion\" />\n";
}
else if (so.getInletType() == IonSource::InletType::JETSEPARATOR)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000061\" name=\"jet separator\" />\n";
}
else if (so.getInletType() == IonSource::InletType::MEMBRANESEPARATOR)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000062\" name=\"membrane separator\" />\n";
}
else if (so.getInletType() == IonSource::InletType::MOVINGBELT)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000063\" name=\"moving belt\" />\n";
}
else if (so.getInletType() == IonSource::InletType::MOVINGWIRE)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000064\" name=\"moving wire\" />\n";
}
else if (so.getInletType() == IonSource::InletType::OPENSPLIT)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000065\" name=\"open split\" />\n";
}
else if (so.getInletType() == IonSource::InletType::PARTICLEBEAM)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000066\" name=\"particle beam\" />\n";
}
else if (so.getInletType() == IonSource::InletType::RESERVOIR)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000067\" name=\"reservoir\" />\n";
}
else if (so.getInletType() == IonSource::InletType::SEPTUM)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000068\" name=\"septum\" />\n";
}
else if (so.getInletType() == IonSource::InletType::THERMOSPRAYINLET)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000069\" name=\"thermospray inlet\" />\n";
}
else if (so.getInletType() == IonSource::InletType::BATCH)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000248\" name=\"direct insertion probe\" />\n";
}
else if (so.getInletType() == IonSource::InletType::CHROMATOGRAPHY)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000249\" name=\"direct liquid introduction\" />\n";
}
else if (so.getInletType() == IonSource::InletType::MEMBRANE)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000396\" name=\"membrane inlet\" />\n";
}
else if (so.getInletType() == IonSource::InletType::NANOSPRAY)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000485\" name=\"nanospray inlet\" />\n";
}
if (so.getIonizationMethod() == IonSource::IonizationMethod::APCI)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000070\" name=\"atmospheric pressure chemical ionization\" />\n";
}
else if (so.getIonizationMethod() == IonSource::IonizationMethod::CI)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000071\" name=\"chemical ionization\" />\n";
}
else if (so.getIonizationMethod() == IonSource::IonizationMethod::ESI)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000073\" name=\"electrospray ionization\" />\n";
}
else if (so.getIonizationMethod() == IonSource::IonizationMethod::FAB)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000074\" name=\"fast atom bombardment ionization\" />\n";
}
else if (so.getIonizationMethod() == IonSource::IonizationMethod::MALDI)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000075\" name=\"matrix-assisted laser desorption ionization\" />\n";
}
else if (so.getIonizationMethod() == IonSource::IonizationMethod::MPI)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000227\" name=\"multiphoton ionization\" />\n";
}
else if (so.getIonizationMethod() == IonSource::IonizationMethod::AP_MALDI)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000239\" name=\"atmospheric pressure matrix-assisted laser desorption ionization\" />\n";
}
else if (so.getIonizationMethod() == IonSource::IonizationMethod::API)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000240\" name=\"atmospheric pressure ionization\" />\n";
}
else if (so.getIonizationMethod() == IonSource::IonizationMethod::DI)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000247\" name=\"desorption ionization\" />\n";
}
else if (so.getIonizationMethod() == IonSource::IonizationMethod::FA)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000255\" name=\"flowing afterglow\" />\n";
}
else if (so.getIonizationMethod() == IonSource::IonizationMethod::FD)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000257\" name=\"field desorption\" />\n";
}
else if (so.getIonizationMethod() == IonSource::IonizationMethod::FII)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000258\" name=\"field ionization\" />\n";
}
else if (so.getIonizationMethod() == IonSource::IonizationMethod::GD_MS)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000259\" name=\"glow discharge ionization\" />\n";
}
else if (so.getIonizationMethod() == IonSource::IonizationMethod::NICI)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000271\" name=\"Negative ion chemical ionization\" />\n";
}
else if (so.getIonizationMethod() == IonSource::IonizationMethod::NRMS)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000272\" name=\"neutralization reionization mass spectrometry\" />\n";
}
else if (so.getIonizationMethod() == IonSource::IonizationMethod::PI)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000273\" name=\"photoionization\" />\n";
}
else if (so.getIonizationMethod() == IonSource::IonizationMethod::PYMS)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000274\" name=\"pyrolysis mass spectrometry\" />\n";
}
else if (so.getIonizationMethod() == IonSource::IonizationMethod::REMPI)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000276\" name=\"resonance enhanced multiphoton ionization\" />\n";
}
else if (so.getIonizationMethod() == IonSource::IonizationMethod::SELDI)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000278\" name=\"surface enhanced laser desorption ionization\" />\n";
}
else if (so.getIonizationMethod() == IonSource::IonizationMethod::SEND)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000279\" name=\"surface enhanced neat desorption\" />\n";
}
else if (so.getIonizationMethod() == IonSource::IonizationMethod::AI)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000380\" name=\"adiabatic ionization\" />\n";
}
else if (so.getIonizationMethod() == IonSource::IonizationMethod::ASI)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000381\" name=\"associative ionization\" />\n";
}
else if (so.getIonizationMethod() == IonSource::IonizationMethod::APPI)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000382\" name=\"atmospheric pressure photoionization\" />\n";
}
else if (so.getIonizationMethod() == IonSource::IonizationMethod::AD)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000383\" name=\"autodetachment\" />\n";
}
else if (so.getIonizationMethod() == IonSource::IonizationMethod::AUI)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000384\" name=\"autoionization\" />\n";
}
else if (so.getIonizationMethod() == IonSource::IonizationMethod::CEI)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000385\" name=\"charge exchange ionization\" />\n";
}
else if (so.getIonizationMethod() == IonSource::IonizationMethod::CHEMI)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000386\" name=\"chemi-ionization\" />\n";
}
else if (so.getIonizationMethod() == IonSource::IonizationMethod::SILI)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000387\" name=\"desorption/ionization on silicon\" />\n";
}
else if (so.getIonizationMethod() == IonSource::IonizationMethod::DISSI)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000388\" name=\"dissociative ionization\" />\n";
}
else if (so.getIonizationMethod() == IonSource::IonizationMethod::EI)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000389\" name=\"electron ionization\" />\n";
}
else if (so.getIonizationMethod() == IonSource::IonizationMethod::LD)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000393\" name=\"laser desorption ionization\" />\n";
}
else if (so.getIonizationMethod() == IonSource::IonizationMethod::LSI)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000395\" name=\"liquid secondary ionization\" />\n";
}
else if (so.getIonizationMethod() == IonSource::IonizationMethod::MESI)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000397\" name=\"microelectrospray\" />\n";
}
else if (so.getIonizationMethod() == IonSource::IonizationMethod::NESI)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000398\" name=\"nanoelectrospray\" />\n";
}
else if (so.getIonizationMethod() == IonSource::IonizationMethod::PEI)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000399\" name=\"penning ionization\" />\n";
}
else if (so.getIonizationMethod() == IonSource::IonizationMethod::PD)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000400\" name=\"plasma desorption ionization\" />\n";
}
else if (so.getIonizationMethod() == IonSource::IonizationMethod::SI)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000402\" name=\"secondary ionization\" />\n";
}
else if (so.getIonizationMethod() == IonSource::IonizationMethod::SOI)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000403\" name=\"soft ionization\" />\n";
}
else if (so.getIonizationMethod() == IonSource::IonizationMethod::SPI)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000404\" name=\"spark ionization\" />\n";
}
else if (so.getIonizationMethod() == IonSource::IonizationMethod::SALDI)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000405\" name=\"surface-assisted laser desorption ionization\" />\n";
}
else if (so.getIonizationMethod() == IonSource::IonizationMethod::SUI)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000406\" name=\"surface ionization\" />\n";
}
else if (so.getIonizationMethod() == IonSource::IonizationMethod::TI)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000407\" name=\"thermal ionization\" />\n";
}
else if (so.getIonizationMethod() == IonSource::IonizationMethod::VI)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000408\" name=\"vertical ionization\" />\n";
}
else if (so.getIonizationMethod() == IonSource::IonizationMethod::FIB)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000446\" name=\"fast ion bombardment\" />\n";
}
else if (so.getIonizationMethod() == IonSource::IonizationMethod::IONMETHODNULL)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000008\" name=\"ionization type\" />\n";
}
writeUserParam_(os, so, 5, "/mzML/instrumentConfigurationList/instrumentConfiguration/componentList/source/cvParam/@accession", validator);
os << "\t\t\t\t</source>\n";
}
//FORCED
if (component_count < 3 && in.getIonSources().empty())
{
os << "\t\t\t\t<source order=\"1234\">\n";
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000446\" name=\"fast ion bombardment\" />\n";
os << "\t\t\t\t\t<userParam name=\"warning\" type=\"xsd:string\" value=\"invented ion source, to fulfill mzML schema\" />\n";
os << "\t\t\t\t</source>\n";
}
//--------------------------------------------------------------------------------------------
// mass analyzer
//--------------------------------------------------------------------------------------------
for (Size i = 0; i < in.getMassAnalyzers().size(); ++i)
{
const MassAnalyzer& ma = in.getMassAnalyzers()[i];
os << "\t\t\t\t<analyzer order=\"" << ma.getOrder() << "\">\n";
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000014\" name=\"accuracy\" value=\"" << ma.getAccuracy() << "\" unitAccession=\"UO:0000169\" unitName=\"parts per million\" unitCvRef=\"UO\" />\n";
// @todo: the parameters below are instrument specific and should not be written every time
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000022\" name=\"TOF Total Path Length\" value=\"" << ma.getTOFTotalPathLength() << "\" unitAccession=\"UO:0000008\" unitName=\"meter\" unitCvRef=\"UO\" />\n";
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000024\" name=\"final MS exponent\" value=\"" << ma.getFinalMSExponent() << "\" />\n";
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000025\" name=\"magnetic field strength\" value=\"" << ma.getMagneticFieldStrength() << "\" unitAccession=\"UO:0000228\" unitName=\"tesla\" unitCvRef=\"UO\" />\n";
if (ma.getReflectronState() == MassAnalyzer::ReflectronState::ON)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000106\" name=\"reflectron on\" />\n";
}
else if (ma.getReflectronState() == MassAnalyzer::ReflectronState::OFF)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000105\" name=\"reflectron off\" />\n";
}
if (ma.getType() == MassAnalyzer::AnalyzerType::FOURIERTRANSFORM)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000079\" name=\"fourier transform ion cyclotron resonance mass spectrometer\" />\n";
}
else if (ma.getType() == MassAnalyzer::AnalyzerType::SECTOR)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000080\" name=\"magnetic sector\" />\n";
}
else if (ma.getType() == MassAnalyzer::AnalyzerType::QUADRUPOLE)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000081\" name=\"quadrupole\" />\n";
}
else if (ma.getType() == MassAnalyzer::AnalyzerType::TOF)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000084\" name=\"time-of-flight\" />\n";
}
else if (ma.getType() == MassAnalyzer::AnalyzerType::ESA)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000254\" name=\"electrostatic energy analyzer\" />\n";
}
else if (ma.getType() == MassAnalyzer::AnalyzerType::IT)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000264\" name=\"ion trap\" />\n";
}
else if (ma.getType() == MassAnalyzer::AnalyzerType::SWIFT)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000284\" name=\"stored waveform inverse fourier transform\" />\n";
}
else if (ma.getType() == MassAnalyzer::AnalyzerType::CYCLOTRON)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000288\" name=\"cyclotron\" />\n";
}
else if (ma.getType() == MassAnalyzer::AnalyzerType::ORBITRAP)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000484\" name=\"orbitrap\" />\n";
}
else if (ma.getType() == MassAnalyzer::AnalyzerType::AXIALEJECTIONLINEARIONTRAP)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000078\" name=\"axial ejection linear ion trap\" />\n";
}
else if (ma.getType() == MassAnalyzer::AnalyzerType::PAULIONTRAP)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000082\" name=\"quadrupole ion trap\" />\n";
}
else if (ma.getType() == MassAnalyzer::AnalyzerType::RADIALEJECTIONLINEARIONTRAP)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000083\" name=\"radial ejection linear ion trap\" />\n";
}
else if (ma.getType() == MassAnalyzer::AnalyzerType::LIT)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000291\" name=\"linear ion trap\" />\n";
}
else if (ma.getType() == MassAnalyzer::AnalyzerType::ANALYZERNULL)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000443\" name=\"mass analyzer type\" />\n";
}
writeUserParam_(os, ma, 5, "/mzML/instrumentConfigurationList/instrumentConfiguration/componentList/analyzer/cvParam/@accession", validator);
os << "\t\t\t\t</analyzer>\n";
}
//FORCED
if (component_count < 3 && in.getMassAnalyzers().empty())
{
os << "\t\t\t\t<analyzer order=\"1234\">\n";
os << "\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000288\" name=\"cyclotron\" />\n";
os << "\t\t\t\t\t<userParam name=\"warning\" type=\"xsd:string\" value=\"invented mass analyzer, to fulfill mzML schema\" />\n";
os << "\t\t\t\t</analyzer>\n";
}
//--------------------------------------------------------------------------------------------
// ion detector
//--------------------------------------------------------------------------------------------
for (Size i = 0; i < in.getIonDetectors().size(); ++i)
{
const IonDetector& id = in.getIonDetectors()[i];
os << "\t\t\t\t<detector order=\"" << id.getOrder() << "\">\n";
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000028\" name=\"detector resolution\" value=\"" << id.getResolution() << "\" />\n";
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000029\" name=\"sampling frequency\" value=\"" << id.getADCSamplingFrequency() << "\" unitAccession=\"UO:0000106\" unitName=\"hertz\" unitCvRef=\"UO\" />\n";
if (id.getAcquisitionMode() == IonDetector::AcquisitionMode::ADC)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000117\" name=\"analog-digital converter\" />\n";
}
else if (id.getAcquisitionMode() == IonDetector::AcquisitionMode::PULSECOUNTING)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000118\" name=\"pulse counting\" />\n";
}
else if (id.getAcquisitionMode() == IonDetector::AcquisitionMode::TDC)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000119\" name=\"time-digital converter\" />\n";
}
else if (id.getAcquisitionMode() == IonDetector::AcquisitionMode::TRANSIENTRECORDER)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000120\" name=\"transient recorder\" />\n";
}
if (id.getType() == IonDetector::Type::CHANNELTRON)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000107\" name=\"channeltron\" />\n";
}
else if (id.getType() == IonDetector::Type::DALYDETECTOR)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000110\" name=\"daly detector\" />\n";
}
else if (id.getType() == IonDetector::Type::FARADAYCUP)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000112\" name=\"faraday cup\" />\n";
}
else if (id.getType() == IonDetector::Type::MICROCHANNELPLATEDETECTOR)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000114\" name=\"microchannel plate detector\" />\n";
}
else if (id.getType() == IonDetector::Type::MULTICOLLECTOR)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000115\" name=\"multi-collector\" />\n";
}
else if (id.getType() == IonDetector::Type::PHOTOMULTIPLIER)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000116\" name=\"photomultiplier\" />\n";
}
else if (id.getType() == IonDetector::Type::ELECTRONMULTIPLIER)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000253\" name=\"electron multiplier\" />\n";
}
else if (id.getType() == IonDetector::Type::ARRAYDETECTOR)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000345\" name=\"array detector\" />\n";
}
else if (id.getType() == IonDetector::Type::CONVERSIONDYNODE)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000346\" name=\"conversion dynode\" />\n";
}
else if (id.getType() == IonDetector::Type::DYNODE)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000347\" name=\"dynode\" />\n";
}
else if (id.getType() == IonDetector::Type::FOCALPLANECOLLECTOR)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000348\" name=\"focal plane collector\" />\n";
}
else if (id.getType() == IonDetector::Type::IONTOPHOTONDETECTOR)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000349\" name=\"ion-to-photon detector\" />\n";
}
else if (id.getType() == IonDetector::Type::POINTCOLLECTOR)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000350\" name=\"point collector\" />\n";
}
else if (id.getType() == IonDetector::Type::POSTACCELERATIONDETECTOR)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000351\" name=\"postacceleration detector\" />\n";
}
else if (id.getType() == IonDetector::Type::PHOTODIODEARRAYDETECTOR)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000621\" name=\"photodiode array detector\" />\n";
}
else if (id.getType() == IonDetector::Type::INDUCTIVEDETECTOR)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000624\" name=\"inductive detector\" />\n";
}
else if (id.getType() == IonDetector::Type::CONVERSIONDYNODEELECTRONMULTIPLIER)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000108\" name=\"conversion dynode electron multiplier\" />\n";
}
else if (id.getType() == IonDetector::Type::CONVERSIONDYNODEPHOTOMULTIPLIER)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000109\" name=\"conversion dynode photomultiplier\" />\n";
}
else if (id.getType() == IonDetector::Type::ELECTRONMULTIPLIERTUBE)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000111\" name=\"electron multiplier tube\" />\n";
}
else if (id.getType() == IonDetector::Type::FOCALPLANEARRAY)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000113\" name=\"focal plane array\" />\n";
}
else if (id.getType() == IonDetector::Type::TYPENULL)
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000026\" name=\"detector type\" />\n";
}
writeUserParam_(os, id, 5, "/mzML/instrumentConfigurationList/instrumentConfiguration/componentList/detector/cvParam/@accession", validator);
os << "\t\t\t\t</detector>\n";
}
//FORCED
if (component_count < 3 && in.getIonDetectors().empty())
{
os << "\t\t\t\t<detector order=\"1234\">\n";
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000107\" name=\"channeltron\" />\n";
os << "\t\t\t\t\t<userParam name=\"warning\" type=\"xsd:string\" value=\"invented ion detector, to fulfill mzML schema\" />\n";
os << "\t\t\t\t</detector>\n";
}
os << "\t\t\t</componentList>\n";
}
os << "\t\t\t<softwareRef ref=\"so_in_0\" />\n";
os << "\t\t</instrumentConfiguration>\n";
os << "\t</instrumentConfigurationList>\n";
//--------------------------------------------------------------------------------------------
// data processing
//--------------------------------------------------------------------------------------------
// count number of float data array dps
Size num_bi_dps(0);
for (Size s = 0; s < exp.size(); ++s)
{
for (Size m = 0; m < exp[s].getFloatDataArrays().size(); ++m)
{
++num_bi_dps;
}
}
os << "\t<dataProcessingList count=\"" << (std::max)((Size)1, dps.size() + num_bi_dps) << "\">\n";
// default (if experiment is empty and no actual data processing is here)
if (dps.size() + num_bi_dps == 0)
{
std::vector< ConstDataProcessingPtr > dummy;
writeDataProcessing_(os, "dp_sp_0", dummy, validator);
}
for (Size s = 0; s < dps.size(); ++s)
{
writeDataProcessing_(os, String("dp_sp_") + s, dps[s], validator);
}
//for each binary data array
for (Size s = 0; s < exp.size(); ++s)
{
for (Size m = 0; m < exp[s].getFloatDataArrays().size(); ++m)
{
// if a DataArray has dataProcessing information, write it, otherwise we assume it has the
// same processing as the rest of the spectra and use the implicit referencing of mzML
// to the first entry (which is a dummy if none exists; see above)
if (!exp[s].getFloatDataArrays()[m].getDataProcessing().empty())
{
writeDataProcessing_(os, String("dp_sp_") + s + "_bi_" + m,
exp[s].getFloatDataArrays()[m].getDataProcessing(), validator);
}
}
}
os << "\t</dataProcessingList>\n";
//--------------------------------------------------------------------------------------------
// acquisitionSettings
//--------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------
// run
//--------------------------------------------------------------------------------------------
os << "\t<run id=\"ru_0\" defaultInstrumentConfigurationRef=\"ic_0\" sampleRef=\"sa_0\"";
if (exp.getDateTime().isValid())
{
os << " startTimeStamp=\"" << exp.getDateTime().get().substitute(' ', 'T') << "\"";
}
if (!exp.getSourceFiles().empty())
{
os << " defaultSourceFileRef=\"sf_ru_0\"";
}
os << ">\n";
//run attributes
if (!exp.getFractionIdentifier().empty())
{
os << "\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000858\" name=\"fraction identifier\" value=\"" << exp.getFractionIdentifier() << "\" />\n";
}
writeUserParam_(os, exp, 2, "/mzML/run/cvParam/@accession", validator);
}
void MzMLHandler::writeSpectrum_(std::ostream& os,
const SpectrumType& spec,
Size s,
const Internal::MzMLValidator& validator,
bool renew_native_ids,
std::vector<std::vector< ConstDataProcessingPtr > >& dps)
{
//native id
String native_id = spec.getNativeID();
if (renew_native_ids)
{
native_id = String("spectrum=") + s;
}
Int64 offset = os.tellp();
spectra_offsets_.emplace_back(native_id, offset + 3);
// IMPORTANT make sure the offset (above) corresponds to the start of the <spectrum tag
os << "\t\t\t<spectrum id=\"" << writeXMLEscape(native_id) << "\" index=\"" << s << "\" defaultArrayLength=\"" << spec.size() << "\"";
if (spec.getSourceFile() != SourceFile())
{
os << " sourceFileRef=\"sf_sp_" << s << "\"";
}
//the data processing info of the first spectrum is the default
//if (s==0 || spec.getDataProcessing()!=exp[0].getDataProcessing())
if (s == 0 || spec.getDataProcessing() != dps[0])
{
Size dp_ref_num = s;
if (s != 0)
{
for (Size i = 0; i < dps.size(); ++i)
{
if (spec.getDataProcessing() == dps[i])
{
dp_ref_num = i;
break;
}
}
}
os << " dataProcessingRef=\"dp_sp_" << dp_ref_num << "\"";
}
os << ">\n";
//spectrum representation
if (spec.getType() == SpectrumSettings::SpectrumType::CENTROID)
{
os << "\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000127\" name=\"centroid spectrum\" />\n";
}
else if (spec.getType() == SpectrumSettings::SpectrumType::PROFILE)
{
os << "\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000128\" name=\"profile spectrum\" />\n";
}
else
{
os << "\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000525\" name=\"spectrum representation\" />\n";
}
//ion mobility frame representation
if (spec.getIMFormat() == IMFormat::CENTROIDED)
{
os << "\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1003441\" name=\"ion mobility centroid frame\" />\n";
}
//spectrum attributes
if (spec.getMSLevel() != 0)
{
os << "\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000511\" name=\"ms level\" value=\"" << spec.getMSLevel() << "\" />\n";
}
//spectrum type
if (spec.getInstrumentSettings().getScanMode() == InstrumentSettings::ScanMode::MASSSPECTRUM)
{
os << "\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000294\" name=\"mass spectrum\" />\n";
}
else if (spec.getInstrumentSettings().getScanMode() == InstrumentSettings::ScanMode::MS1SPECTRUM)
{
os << "\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000579\" name=\"MS1 spectrum\" />\n";
}
else if (spec.getInstrumentSettings().getScanMode() == InstrumentSettings::ScanMode::MSNSPECTRUM)
{
os << "\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000580\" name=\"MSn spectrum\" />\n";
}
else if (spec.getInstrumentSettings().getScanMode() == InstrumentSettings::ScanMode::SIM)
{
os << "\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000582\" name=\"SIM spectrum\" />\n";
}
else if (spec.getInstrumentSettings().getScanMode() == InstrumentSettings::ScanMode::SRM)
{
os << "\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000583\" name=\"SRM spectrum\" />\n";
}
else if (spec.getInstrumentSettings().getScanMode() == InstrumentSettings::ScanMode::CRM)
{
os << "\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000581\" name=\"CRM spectrum\" />\n";
}
else if (spec.getInstrumentSettings().getScanMode() == InstrumentSettings::ScanMode::PRECURSOR)
{
os << "\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000341\" name=\"precursor ion spectrum\" />\n";
}
else if (spec.getInstrumentSettings().getScanMode() == InstrumentSettings::ScanMode::CNG)
{
os << "\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000325\" name=\"constant neutral gain spectrum\" />\n";
}
else if (spec.getInstrumentSettings().getScanMode() == InstrumentSettings::ScanMode::CNL)
{
os << "\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000326\" name=\"constant neutral loss spectrum\" />\n";
}
else if (spec.getInstrumentSettings().getScanMode() == InstrumentSettings::ScanMode::EMR)
{
os << "\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000804\" name=\"electromagnetic radiation spectrum\" />\n";
}
else if (spec.getInstrumentSettings().getScanMode() == InstrumentSettings::ScanMode::EMISSION)
{
os << "\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000805\" name=\"emission spectrum\" />\n";
}
else if (spec.getInstrumentSettings().getScanMode() == InstrumentSettings::ScanMode::ABSORPTION)
{
os << "\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000806\" name=\"absorption spectrum\" />\n";
}
else if (spec.getInstrumentSettings().getScanMode() == InstrumentSettings::ScanMode::EMC)
{
os << "\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000789\" name=\"enhanced multiply charged spectrum\" />\n";
}
else if (spec.getInstrumentSettings().getScanMode() == InstrumentSettings::ScanMode::TDF)
{
os << "\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000789\" name=\"time-delayed fragmentation spectrum\" />\n";
}
else //FORCED
{
os << "\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000294\" name=\"mass spectrum\" />\n";
}
//scan polarity
if (spec.getInstrumentSettings().getPolarity() == IonSource::Polarity::NEGATIVE)
{
os << "\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000129\" name=\"negative scan\" />\n";
}
else if (spec.getInstrumentSettings().getPolarity() == IonSource::Polarity::POSITIVE)
{
os << "\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000130\" name=\"positive scan\" />\n";
}
writeUserParam_(os, spec, 4, "/mzML/run/spectrumList/spectrum/cvParam/@accession", validator);
//--------------------------------------------------------------------------------------------
//scan list
//--------------------------------------------------------------------------------------------
os << "\t\t\t\t<scanList count=\"" << (std::max)((Size)1, spec.getAcquisitionInfo().size()) << "\">\n";
ControlledVocabulary::CVTerm ai_term = getChildWithName_("MS:1000570", spec.getAcquisitionInfo().getMethodOfCombination());
if (!ai_term.id.empty())
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"" << ai_term.id << "\" name=\"" << ai_term.name << "\" />\n";
}
else
{
os << "\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000795\" name=\"no combination\" />\n";
}
writeUserParam_(os, spec.getAcquisitionInfo(), 5, "/mzML/run/spectrumList/spectrum/scanList/cvParam/@accession", validator);
//--------------------------------------------------------------------------------------------
//scan
//--------------------------------------------------------------------------------------------
for (Size j = 0; j < spec.getAcquisitionInfo().size(); ++j)
{
const Acquisition& ac = spec.getAcquisitionInfo()[j];
os << "\t\t\t\t\t<scan "; // TODO
if (!ac.getIdentifier().empty())
{
os << "externalSpectrumID=\"" << ac.getIdentifier() << "\"";
}
os << ">\n";
if (j == 0)
{
os << "\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000016\" name=\"scan start time\" value=\"" << spec.getRT()
<< "\" unitAccession=\"UO:0000010\" unitName=\"second\" unitCvRef=\"UO\" />\n";
if (spec.getDriftTimeUnit() == DriftTimeUnit::FAIMS_COMPENSATION_VOLTAGE)
{
os << "\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1001581\" name=\"FAIMS compensation voltage\" value=\"" << spec.getDriftTime()
<< "\" unitAccession=\"UO:000218\" unitName=\"volt\" unitCvRef=\"UO\" />\n";
}
else if (spec.getDriftTime() != IMTypes::DRIFTTIME_NOT_SET)// if drift time was never set, don't report it
{
if (spec.getDriftTimeUnit() == DriftTimeUnit::MILLISECOND)
{
os << "\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1002476\" name=\"ion mobility drift time\" value=\"" << spec.getDriftTime()
<< "\" unitAccession=\"UO:0000028\" unitName=\"millisecond\" unitCvRef=\"UO\" />\n";
}
else if (spec.getDriftTimeUnit() == DriftTimeUnit::VSSC)
{
os << "\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1002815\" name=\"inverse reduced ion mobility\" value=\"" << spec.getDriftTime()
<< "\" unitAccession=\"MS:1002814\" unitName=\"volt-second per square centimeter\" unitCvRef=\"MS\" />\n";
}
else
{
// assume milliseconds, but warn
warning(STORE, String("Spectrum drift time unit not set, assume milliseconds"));
os << "\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1002476\" name=\"ion mobility drift time\" value=\"" << spec.getDriftTime()
<< "\" unitAccession=\"UO:0000028\" unitName=\"millisecond\" unitCvRef=\"UO\" />\n";
}
}
}
writeUserParam_(os, ac, 6, "/mzML/run/spectrumList/spectrum/scanList/scan/cvParam/@accession", validator);
if (spec.getInstrumentSettings().getZoomScan())
{
os << "\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000497\" name=\"zoom scan\" />\n";
}
//scan windows
if (j == 0 && !spec.getInstrumentSettings().getScanWindows().empty())
{
os << "\t\t\t\t\t\t<scanWindowList count=\"" << spec.getInstrumentSettings().getScanWindows().size() << "\">\n";
for (Size k = 0; k < spec.getInstrumentSettings().getScanWindows().size(); ++k)
{
os << "\t\t\t\t\t\t\t<scanWindow>\n";
os << "\t\t\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000501\" name=\"scan window lower limit\" value=\"" << spec.getInstrumentSettings().getScanWindows()[k].begin << "\" unitAccession=\"MS:1000040\" unitName=\"m/z\" unitCvRef=\"MS\" />\n";
os << "\t\t\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000500\" name=\"scan window upper limit\" value=\"" << spec.getInstrumentSettings().getScanWindows()[k].end << "\" unitAccession=\"MS:1000040\" unitName=\"m/z\" unitCvRef=\"MS\" />\n";
writeUserParam_(os, spec.getInstrumentSettings().getScanWindows()[k], 8, "/mzML/run/spectrumList/spectrum/scanList/scan/scanWindowList/scanWindow/cvParam/@accession", validator);
os << "\t\t\t\t\t\t\t</scanWindow>\n";
}
os << "\t\t\t\t\t\t</scanWindowList>\n";
}
os << "\t\t\t\t\t</scan>\n";
}
//fallback if we have no acquisition information (a dummy scan is created for RT and so on)
if (spec.getAcquisitionInfo().empty())
{
os << "\t\t\t\t\t<scan>\n";
os << "\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000016\" name=\"scan start time\" value=\"" << spec.getRT() << "\" unitAccession=\"UO:0000010\" unitName=\"second\" unitCvRef=\"UO\" />\n";
if (spec.getInstrumentSettings().getZoomScan())
{
os << "\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000497\" name=\"zoom scan\" />\n";
}
//scan windows
if (!spec.getInstrumentSettings().getScanWindows().empty())
{
os << "\t\t\t\t\t\t<scanWindowList count=\"" << spec.getInstrumentSettings().getScanWindows().size() << "\">\n";
for (Size j = 0; j < spec.getInstrumentSettings().getScanWindows().size(); ++j)
{
os << "\t\t\t\t\t\t\t<scanWindow>\n";
os << "\t\t\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000501\" name=\"scan window lower limit\" value=\"" << spec.getInstrumentSettings().getScanWindows()[j].begin << "\" unitAccession=\"MS:1000040\" unitName=\"m/z\" unitCvRef=\"MS\" />\n";
os << "\t\t\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000500\" name=\"scan window upper limit\" value=\"" << spec.getInstrumentSettings().getScanWindows()[j].end << "\" unitAccession=\"MS:1000040\" unitName=\"m/z\" unitCvRef=\"MS\" />\n";
writeUserParam_(os, spec.getInstrumentSettings().getScanWindows()[j], 8, "/mzML/run/spectrumList/spectrum/scanList/scan/scanWindowList/scanWindow/cvParam/@accession", validator);
os << "\t\t\t\t\t\t\t</scanWindow>\n";
}
os << "\t\t\t\t\t\t</scanWindowList>\n";
}
os << "\t\t\t\t\t</scan>\n";
}
os << "\t\t\t\t</scanList>\n";
//--------------------------------------------------------------------------------------------
//precursor list
//--------------------------------------------------------------------------------------------
if (!spec.getPrecursors().empty())
{
os << "\t\t\t\t<precursorList count=\"" << spec.getPrecursors().size() << "\">\n";
for (Size p = 0; p != spec.getPrecursors().size(); ++p)
{
writePrecursor_(os, spec.getPrecursors()[p], validator);
}
os << "\t\t\t\t</precursorList>\n";
}
//--------------------------------------------------------------------------------------------
//product list
//--------------------------------------------------------------------------------------------
if (!spec.getProducts().empty())
{
os << "\t\t\t\t<productList count=\"" << spec.getProducts().size() << "\">\n";
for (Size p = 0; p < spec.getProducts().size(); ++p)
{
writeProduct_(os, spec.getProducts()[p], validator);
}
os << "\t\t\t\t</productList>\n";
}
//--------------------------------------------------------------------------------------------
//binary data array list
//--------------------------------------------------------------------------------------------
if (!spec.empty())
{
String encoded_string;
os << "\t\t\t\t<binaryDataArrayList count=\"" << (2 + spec.getFloatDataArrays().size() + spec.getStringDataArrays().size() + spec.getIntegerDataArrays().size()) << "\">\n";
writeContainerData_<SpectrumType>(os, options_, spec, "mz");
writeContainerData_<SpectrumType>(os, options_, spec, "intensity");
String compression_term = MzMLHandlerHelper::getCompressionTerm_(options_, options_.getNumpressConfigurationIntensity(), "\t\t\t\t\t\t", false);
// write float data array
for (Size m = 0; m < spec.getFloatDataArrays().size(); ++m)
{
const SpectrumType::FloatDataArray& array = spec.getFloatDataArrays()[m];
writeBinaryFloatDataArray_(os, options_, array, s, m, true, validator);
}
// write integer data array
for (Size m = 0; m < spec.getIntegerDataArrays().size(); ++m)
{
const SpectrumType::IntegerDataArray& array = spec.getIntegerDataArrays()[m];
std::vector<Int64> data64_to_encode(array.size());
for (Size p = 0; p < array.size(); ++p)
{
data64_to_encode[p] = array[p];
}
Base64::encodeIntegers(data64_to_encode, Base64::BYTEORDER_LITTLEENDIAN, encoded_string, options_.getCompression());
String data_processing_ref_string ;
if (!array.getDataProcessing().empty())
{
data_processing_ref_string = String("dataProcessingRef=\"dp_sp_") + s + "_bi_" + m + "\"";
}
os << "\t\t\t\t\t<binaryDataArray arrayLength=\"" << array.size() << "\" encodedLength=\"" << encoded_string.size() << "\" " << data_processing_ref_string << ">\n";
os << "\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000522\" name=\"64-bit integer\" />\n";
os << "\t\t\t\t\t\t" << compression_term << "\n";
ControlledVocabulary::CVTerm bi_term = getChildWithName_("MS:1000513", array.getName());
if (!bi_term.id.empty())
{
os << "\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"" << bi_term.id << "\" name=\"" << bi_term.name << "\" />\n";
}
else
{
os << "\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000786\" name=\"non-standard data array\" value=\"" << array.getName() << "\" />\n";
}
writeUserParam_(os, array, 6, "/mzML/run/spectrumList/spectrum/binaryDataArrayList/binaryDataArray/cvParam/@accession", validator);
os << "\t\t\t\t\t\t<binary>" << encoded_string << "</binary>\n";
os << "\t\t\t\t\t</binaryDataArray>\n";
}
// write string data arrays
for (Size m = 0; m < spec.getStringDataArrays().size(); ++m)
{
const SpectrumType::StringDataArray& array = spec.getStringDataArrays()[m];
std::vector<String> data_to_encode;
data_to_encode.resize(array.size());
for (Size p = 0; p < array.size(); ++p)
data_to_encode[p] = array[p];
Base64::encodeStrings(data_to_encode, encoded_string, options_.getCompression());
String data_processing_ref_string ;
if (!array.getDataProcessing().empty())
{
data_processing_ref_string = String("dataProcessingRef=\"dp_sp_") + s + "_bi_" + m + "\"";
}
os << "\t\t\t\t\t<binaryDataArray arrayLength=\"" << array.size() << "\" encodedLength=\"" << encoded_string.size() << "\" " << data_processing_ref_string << ">\n";
os << "\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1001479\" name=\"null-terminated ASCII string\" />\n";
os << "\t\t\t\t\t\t" << compression_term << "\n";
os << "\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000786\" name=\"non-standard data array\" value=\"" << array.getName() << "\" />\n";
writeUserParam_(os, array, 6, "/mzML/run/spectrumList/spectrum/binaryDataArrayList/binaryDataArray/cvParam/@accession", validator);
os << "\t\t\t\t\t\t<binary>" << encoded_string << "</binary>\n";
os << "\t\t\t\t\t</binaryDataArray>\n";
}
os << "\t\t\t\t</binaryDataArrayList>\n";
}
os << "\t\t\t</spectrum>\n";
}
template <typename ContainerT>
void MzMLHandler::writeContainerData_(std::ostream& os, const PeakFileOptions& pf_options_, const ContainerT& container, const String& array_type)
{
// Intensity is the same for chromatograms and spectra, the second
// dimension is either "time" or "mz" (both of these are controlled by
// getMz32Bit)
bool is32Bit = ((array_type == "intensity" && pf_options_.getIntensity32Bit()) || pf_options_.getMz32Bit());
if (!is32Bit || pf_options_.getNumpressConfigurationMassTime().np_compression != MSNumpressCoder::NONE)
{
std::vector<double> data_to_encode(container.size());
if (array_type == "intensity")
{
for (Size p = 0; p < container.size(); ++p)
{
data_to_encode[p] = container[p].getIntensity();
}
}
else
{
for (Size p = 0; p < container.size(); ++p)
{
data_to_encode[p] = container[p].getPos();
}
}
writeBinaryDataArray_(os, pf_options_, data_to_encode, false, array_type);
}
else
{
std::vector<float> data_to_encode(container.size());
if (array_type == "intensity")
{
for (Size p = 0; p < container.size(); ++p)
{
data_to_encode[p] = container[p].getIntensity();
}
}
else
{
for (Size p = 0; p < container.size(); ++p)
{
data_to_encode[p] = container[p].getPos();
}
}
writeBinaryDataArray_(os, pf_options_, data_to_encode, true, array_type);
}
}
template <typename DataType>
void MzMLHandler::writeBinaryDataArray_(std::ostream& os,
const PeakFileOptions& pf_options_,
std::vector<DataType>& data_to_encode,
bool is32bit,
String array_type)
{
String encoded_string;
bool no_numpress = true;
// Compute the array-type and the compression CV term
String cv_term_type;
String compression_term;
String compression_term_no_np;
MSNumpressCoder::NumpressConfig np_config;
if (array_type == "mz")
{
cv_term_type = "\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000514\" name=\"m/z array\" unitAccession=\"MS:1000040\" unitName=\"m/z\" unitCvRef=\"MS\" />\n";
compression_term = MzMLHandlerHelper::getCompressionTerm_(pf_options_, pf_options_.getNumpressConfigurationMassTime(), "\t\t\t\t\t\t", true);
compression_term_no_np = MzMLHandlerHelper::getCompressionTerm_(pf_options_, pf_options_.getNumpressConfigurationMassTime(), "\t\t\t\t\t\t", false);
np_config = pf_options_.getNumpressConfigurationMassTime();
}
else if (array_type == "time")
{
cv_term_type = "\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000595\" name=\"time array\" unitAccession=\"UO:0000010\" unitName=\"second\" unitCvRef=\"MS\" />\n";
compression_term = MzMLHandlerHelper::getCompressionTerm_(pf_options_, pf_options_.getNumpressConfigurationMassTime(), "\t\t\t\t\t\t", true);
compression_term_no_np = MzMLHandlerHelper::getCompressionTerm_(pf_options_, pf_options_.getNumpressConfigurationMassTime(), "\t\t\t\t\t\t", false);
np_config = pf_options_.getNumpressConfigurationMassTime();
}
else if (array_type == "intensity")
{
cv_term_type = "\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000515\" name=\"intensity array\" unitAccession=\"MS:1000131\" unitName=\"number of detector counts\" unitCvRef=\"MS\"/>\n";
compression_term = MzMLHandlerHelper::getCompressionTerm_(pf_options_, pf_options_.getNumpressConfigurationIntensity(), "\t\t\t\t\t\t", true);
compression_term_no_np = MzMLHandlerHelper::getCompressionTerm_(pf_options_, pf_options_.getNumpressConfigurationIntensity(), "\t\t\t\t\t\t", false);
np_config = pf_options_.getNumpressConfigurationIntensity();
}
else
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Unknown array type", array_type);
}
// Try numpress encoding (if it is enabled) and fall back to regular encoding if it fails
if (np_config.np_compression != MSNumpressCoder::NONE)
{
MSNumpressCoder().encodeNP(data_to_encode, encoded_string, pf_options_.getCompression(), np_config);
if (!encoded_string.empty())
{
// numpress succeeded
no_numpress = false;
os << "\t\t\t\t\t<binaryDataArray encodedLength=\"" << encoded_string.size() << "\">\n";
os << cv_term_type;
os << "\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000523\" name=\"64-bit float\" />\n";
}
}
// Regular DataArray without numpress (either 32 or 64 bit encoded)
if (is32bit && no_numpress)
{
compression_term = compression_term_no_np; // select the no-numpress term
Base64::encode(data_to_encode, Base64::BYTEORDER_LITTLEENDIAN, encoded_string, pf_options_.getCompression());
os << "\t\t\t\t\t<binaryDataArray encodedLength=\"" << encoded_string.size() << "\">\n";
os << cv_term_type;
os << "\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000521\" name=\"32-bit float\" />\n";
}
else if (!is32bit && no_numpress)
{
compression_term = compression_term_no_np; // select the no-numpress term
Base64::encode(data_to_encode, Base64::BYTEORDER_LITTLEENDIAN, encoded_string, pf_options_.getCompression());
os << "\t\t\t\t\t<binaryDataArray encodedLength=\"" << encoded_string.size() << "\">\n";
os << cv_term_type;
os << "\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000523\" name=\"64-bit float\" />\n";
}
os << compression_term << "\n";
os << "\t\t\t\t\t\t<binary>" << encoded_string << "</binary>\n";
os << "\t\t\t\t\t</binaryDataArray>\n";
}
void MzMLHandler::writeBinaryFloatDataArray_(std::ostream& os,
const PeakFileOptions& pf_options_,
const OpenMS::DataArrays::FloatDataArray& array,
const Size spec_chrom_idx,
const Size array_idx,
bool isSpectrum,
const Internal::MzMLValidator& validator)
{
String encoded_string;
bool no_numpress = true;
std::vector<float> data_to_encode = array;
MetaInfoDescription array_metadata = array;
// bool is32bit = true;
// Compute the array-type and the compression CV term
String cv_term_type;
String compression_term;
String compression_term_no_np;
MSNumpressCoder::NumpressConfig np_config;
// if (array_type == "float_data")
{
// Try and identify whether we have a CV term for this particular array (otherwise write the array name itself)
ControlledVocabulary::CVTerm bi_term = getChildWithName_("MS:1000513", array.getName()); // name: binary data array
String unit_cv_term ;
if (array_metadata.metaValueExists("unit_accession"))
{
ControlledVocabulary::CVTerm unit = cv_.getTerm(array_metadata.getMetaValue("unit_accession"));
unit_cv_term = " unitAccession=\"" + unit.id + "\" unitName=\"" + unit.name + "\" unitCvRef=\"" + unit.id.prefix(2) + "\"";
array_metadata.removeMetaValue("unit_accession"); // prevent this from being written as userParam
}
if (!bi_term.id.empty())
{
cv_term_type = "\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"" + bi_term.id + "\" name=\"" + bi_term.name + "\"" + unit_cv_term + " />\n";
}
else
{
cv_term_type = "\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000786\" name=\"non-standard data array\" value=\"" +
array.getName() + "\"" + unit_cv_term + " />\n";
}
compression_term = MzMLHandlerHelper::getCompressionTerm_(pf_options_, pf_options_.getNumpressConfigurationFloatDataArray(), "\t\t\t\t\t\t", true);
compression_term_no_np = MzMLHandlerHelper::getCompressionTerm_(pf_options_, pf_options_.getNumpressConfigurationFloatDataArray(), "\t\t\t\t\t\t", false);
np_config = pf_options_.getNumpressConfigurationFloatDataArray();
}
String data_processing_ref_string ;
if (!array.getDataProcessing().empty())
{
data_processing_ref_string = String("dataProcessingRef=\"dp_sp_") + spec_chrom_idx + "_bi_" + array_idx + "\"";
}
// Try numpress encoding (if it is enabled) and fall back to regular encoding if it fails
if (np_config.np_compression != MSNumpressCoder::NONE)
{
MSNumpressCoder().encodeNP(data_to_encode, encoded_string, pf_options_.getCompression(), np_config);
if (!encoded_string.empty())
{
// numpress succeeded
no_numpress = false;
os << "\t\t\t\t\t<binaryDataArray arrayLength=\"" << array.size() << "\" encodedLength=\"" << encoded_string.size() << "\" " << data_processing_ref_string << ">\n";
os << cv_term_type;
os << "\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000523\" name=\"64-bit float\" />\n";
}
}
// Regular DataArray without numpress (here: only 32 bit encoded)
if (no_numpress)
{
compression_term = compression_term_no_np; // select the no-numpress term
Base64::encode(data_to_encode, Base64::BYTEORDER_LITTLEENDIAN, encoded_string, pf_options_.getCompression());
os << "\t\t\t\t\t<binaryDataArray arrayLength=\"" << array.size() << "\" encodedLength=\"" << encoded_string.size() << "\" " << data_processing_ref_string << ">\n";
os << cv_term_type;
os << "\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000521\" name=\"32-bit float\" />\n";
}
os << compression_term << "\n";
if (isSpectrum)
{
writeUserParam_(os, array_metadata, 6, "/mzML/run/spectrumList/spectrum/binaryDataArrayList/binaryDataArray/cvParam/@accession", validator);
}
else
{
writeUserParam_(os, array_metadata, 6, "/mzML/run/chromatogramList/chromatogram/binaryDataArrayList/binaryDataArray/cvParam/@accession", validator);
}
os << "\t\t\t\t\t\t<binary>" << encoded_string << "</binary>\n";
os << "\t\t\t\t\t</binaryDataArray>\n";
}
// We only ever need 2 instances for the following functions: one for Spectra / Chromatograms and one for floats / doubles
template void MzMLHandler::writeContainerData_<SpectrumType>(std::ostream& os,
const PeakFileOptions& pf_options_,
const SpectrumType& container,
const String& array_type);
template void MzMLHandler::writeContainerData_<ChromatogramType>(std::ostream& os,
const PeakFileOptions& pf_options_,
const ChromatogramType& container,
const String& array_type);
template void MzMLHandler::writeBinaryDataArray_<float>(std::ostream& os,
const PeakFileOptions& pf_options_,
std::vector<float>& data_to_encode,
bool is32bit,
String array_type);
template void MzMLHandler::writeBinaryDataArray_<double>(std::ostream& os,
const PeakFileOptions& pf_options_,
std::vector<double>& data_to_encode,
bool is32bit,
String array_type);
void MzMLHandler::writeChromatogram_(std::ostream& os,
const ChromatogramType& chromatogram,
Size c,
const Internal::MzMLValidator& validator)
{
Int64 offset = os.tellp();
chromatograms_offsets_.emplace_back(chromatogram.getNativeID(), offset + 3);
// TODO native id with chromatogram=?? prefix?
// IMPORTANT make sure the offset (above) corresponds to the start of the <chromatogram tag
os << "\t\t\t<chromatogram id=\"" << writeXMLEscape(chromatogram.getNativeID()) << "\" index=\"" << c << "\" defaultArrayLength=\"" << chromatogram.size() << "\">" << "\n";
// write cvParams (chromatogram type)
if (chromatogram.getChromatogramType() == ChromatogramSettings::ChromatogramType::MASS_CHROMATOGRAM)
{
os << "\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000810\" name=\"ion current chromatogram\" />\n";
}
else if (chromatogram.getChromatogramType() == ChromatogramSettings::ChromatogramType::TOTAL_ION_CURRENT_CHROMATOGRAM)
{
os << "\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000235\" name=\"total ion current chromatogram\" />\n";
}
else if (chromatogram.getChromatogramType() == ChromatogramSettings::ChromatogramType::SELECTED_ION_CURRENT_CHROMATOGRAM)
{
os << "\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000627\" name=\"selected ion current chromatogram\" />\n";
}
else if (chromatogram.getChromatogramType() == ChromatogramSettings::ChromatogramType::BASEPEAK_CHROMATOGRAM)
{
os << "\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000628\" name=\"basepeak chromatogram\" />\n";
}
else if (chromatogram.getChromatogramType() == ChromatogramSettings::ChromatogramType::SELECTED_ION_MONITORING_CHROMATOGRAM)
{
os << "\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1001472\" name=\"selected ion monitoring chromatogram\" />\n";
}
else if (chromatogram.getChromatogramType() == ChromatogramSettings::ChromatogramType::SELECTED_REACTION_MONITORING_CHROMATOGRAM)
{
os << "\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1001473\" name=\"selected reaction monitoring chromatogram\" />\n";
}
else if (chromatogram.getChromatogramType() == ChromatogramSettings::ChromatogramType::ELECTROMAGNETIC_RADIATION_CHROMATOGRAM)
{
os << "\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000811\" name=\"electromagnetic radiation chromatogram\" />\n";
}
else if (chromatogram.getChromatogramType() == ChromatogramSettings::ChromatogramType::ABSORPTION_CHROMATOGRAM)
{
os << "\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000812\" name=\"absorption chromatogram\" />\n";
}
else if (chromatogram.getChromatogramType() == ChromatogramSettings::ChromatogramType::EMISSION_CHROMATOGRAM)
{
os << "\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000813\" name=\"emission chromatogram\" />\n";
}
else
{
// TODO
}
writePrecursor_(os, chromatogram.getPrecursor(), validator);
writeProduct_(os, chromatogram.getProduct(), validator);
//--------------------------------------------------------------------------------------------
//binary data array list
//--------------------------------------------------------------------------------------------
String compression_term;
String encoded_string;
os << "\t\t\t\t<binaryDataArrayList count=\"" << (2 + chromatogram.getFloatDataArrays().size() + chromatogram.getStringDataArrays().size() + chromatogram.getIntegerDataArrays().size()) << "\">\n";
writeContainerData_<ChromatogramType>(os, options_, chromatogram, "time");
writeContainerData_<ChromatogramType>(os, options_, chromatogram, "intensity");
compression_term = MzMLHandlerHelper::getCompressionTerm_(options_, options_.getNumpressConfigurationIntensity(), "\t\t\t\t\t\t", false);
// write float data array
for (Size m = 0; m < chromatogram.getFloatDataArrays().size(); ++m)
{
const ChromatogramType::FloatDataArray& array = chromatogram.getFloatDataArrays()[m];
writeBinaryFloatDataArray_(os, options_, array, c, m, false, validator);
}
//write integer data array
for (Size m = 0; m < chromatogram.getIntegerDataArrays().size(); ++m)
{
const ChromatogramType::IntegerDataArray& array = chromatogram.getIntegerDataArrays()[m];
std::vector<Int64> data64_to_encode(array.size());
for (Size p = 0; p < array.size(); ++p)
{
data64_to_encode[p] = array[p];
}
Base64::encodeIntegers(data64_to_encode, Base64::BYTEORDER_LITTLEENDIAN, encoded_string, options_.getCompression());
String data_processing_ref_string ;
if (!array.getDataProcessing().empty())
{
data_processing_ref_string = String("dataProcessingRef=\"dp_sp_") + c + "_bi_" + m + "\"";
}
os << "\t\t\t\t\t<binaryDataArray arrayLength=\"" << array.size() << "\" encodedLength=\"" << encoded_string.size() << "\" " << data_processing_ref_string << ">\n";
os << "\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000522\" name=\"64-bit integer\" />\n";
os << "\t\t\t\t\t\t" << compression_term << "\n";
ControlledVocabulary::CVTerm bi_term = getChildWithName_("MS:1000513", array.getName());
if (!bi_term.id.empty())
{
os << "\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"" << bi_term.id << "\" name=\"" << bi_term.name << "\" />\n";
}
else
{
os << "\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000786\" name=\"non-standard data array\" value=\"" << array.getName() << "\" />\n";
}
writeUserParam_(os, array, 6, "/mzML/run/chromatogramList/chromatogram/binaryDataArrayList/binaryDataArray/cvParam/@accession", validator);
os << "\t\t\t\t\t\t<binary>" << encoded_string << "</binary>\n";
os << "\t\t\t\t\t</binaryDataArray>\n";
}
//write string data arrays
for (Size m = 0; m < chromatogram.getStringDataArrays().size(); ++m)
{
const ChromatogramType::StringDataArray& array = chromatogram.getStringDataArrays()[m];
std::vector<String> data_to_encode;
data_to_encode.resize(array.size());
for (Size p = 0; p < array.size(); ++p)
{
data_to_encode[p] = array[p];
}
Base64::encodeStrings(data_to_encode, encoded_string, options_.getCompression());
String data_processing_ref_string ;
if (!array.getDataProcessing().empty())
{
data_processing_ref_string = String("dataProcessingRef=\"dp_sp_") + c + "_bi_" + m + "\"";
}
os << "\t\t\t\t\t<binaryDataArray arrayLength=\"" << array.size() << "\" encodedLength=\"" << encoded_string.size() << "\" " << data_processing_ref_string << ">\n";
os << "\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1001479\" name=\"null-terminated ASCII string\" />\n";
os << "\t\t\t\t\t\t" << compression_term << "\n";
os << "\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1000786\" name=\"non-standard data array\" value=\"" << array.getName() << "\" />\n";
writeUserParam_(os, array, 6, "/mzML/run/chromatogramList/chromatogram/binaryDataArrayList/binaryDataArray/cvParam/@accession", validator);
os << "\t\t\t\t\t\t<binary>" << encoded_string << "</binary>\n";
os << "\t\t\t\t\t</binaryDataArray>\n";
}
os << "\t\t\t\t</binaryDataArrayList>\n";
os << "\t\t\t</chromatogram>" << "\n";
}
} // namespace OpenMS // namespace Internal
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/DATAACCESS/SiriusFragmentAnnotation.cpp | .cpp | 16,670 | 393 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Oliver Alka, Axel Walter $
// $Authors: Oliver Alka $
// --------------------------------------------------------------------------
#include <OpenMS/FORMAT/DATAACCESS/SiriusFragmentAnnotation.h>
#include <OpenMS/CONCEPT/Constants.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <fstream>
#include <QtCore/QDir>
#include <QtCore/QString>
using namespace std;
namespace OpenMS
{
std::vector<SiriusFragmentAnnotation::SiriusTargetDecoySpectra> SiriusFragmentAnnotation::extractAndResolveSiriusAnnotations(
const std::vector<String>& sirius_workspace_subdirs, double score_threshold, bool use_exact_mass, bool decoy_generation)
{
std::map<String, SiriusFragmentAnnotation::SiriusTargetDecoySpectra> native_ids_annotated_spectra;
std::vector<SiriusFragmentAnnotation::SiriusTargetDecoySpectra> annotated_spectra;
MSSpectrum best_annotated_spectrum;
double score = 0.0;
for (const auto& subdir : sirius_workspace_subdirs)
{
std::vector<MSSpectrum> ann_spec_tmp = extractAnnotationsFromSiriusFile(subdir, 1, false, use_exact_mass);
if (ann_spec_tmp.empty())
{
continue;
}
else
{
// max_rank 1 will get the best.
best_annotated_spectrum = extractAnnotationsFromSiriusFile(subdir, 1, false, use_exact_mass)[0];
}
// extract decoy spectra only if decoy generation is set, else clear target specs from vector
if (decoy_generation)
{
ann_spec_tmp = extractAnnotationsFromSiriusFile(subdir, 1, true, use_exact_mass);
}
else
{
ann_spec_tmp.clear();
}
// if no spectrum can be extracted we add an empty spectrum
// to the TD pair for backwards compatibility with AssayGeneratorMetabo
MSSpectrum annotated_decoy_for_best_tgt = MSSpectrum();
if (!ann_spec_tmp.empty())
{
//I ASSUME that decoys are in the same ranking order as their corresponding targets.
annotated_decoy_for_best_tgt = ann_spec_tmp[0];
}
else // fill with basics for backwards-compatibility. IMHO this should be solved differently.
{
OpenMS::String concat_native_ids = SiriusFragmentAnnotation::extractConcatNativeIDsFromSiriusMS_(subdir);
OpenMS::String concat_m_ids = SiriusFragmentAnnotation::extractConcatMIDsFromSiriusMS_(subdir);
annotated_decoy_for_best_tgt.setNativeID(concat_native_ids);
annotated_decoy_for_best_tgt.setName(concat_m_ids);
}
score = double(best_annotated_spectrum.getMetaValue(Constants::UserParam::SIRIUS_SCORE));
// only use spectra over a certain score threshold (0-1)
if (score >= score_threshold)
{
// resolve multiple use of the same concatenated nativeids based on the sirius score (used for multiple features/identifications)
map<String, SiriusFragmentAnnotation::SiriusTargetDecoySpectra>::iterator it;
it = native_ids_annotated_spectra.find(best_annotated_spectrum.getNativeID());
if (it != native_ids_annotated_spectra.end())
{
if (score >= double(it->second.target.getMetaValue(Constants::UserParam::SIRIUS_SCORE)))
{
SiriusFragmentAnnotation::SiriusTargetDecoySpectra target_decoy(best_annotated_spectrum, annotated_decoy_for_best_tgt);
it->second = target_decoy;
}
}
else
{
SiriusFragmentAnnotation::SiriusTargetDecoySpectra target_decoy(best_annotated_spectrum, annotated_decoy_for_best_tgt);
native_ids_annotated_spectra.insert(make_pair(best_annotated_spectrum.getNativeID(), target_decoy));
}
}
}
// convert to vector
annotated_spectra.reserve(native_ids_annotated_spectra.size());
for (auto& id_spec : native_ids_annotated_spectra)
{
annotated_spectra.emplace_back(std::move(id_spec.second));
}
return annotated_spectra;
}
// extract native id from SIRIUS spectrum.ms output file (workspace - compound specific)
// first native id in the spectrum.ms
OpenMS::String SiriusFragmentAnnotation::extractConcatNativeIDsFromSiriusMS_(const String& path_to_sirius_workspace)
{
vector< String > ext_n_ids;
String ext_n_id;
const String sirius_spectrum_ms = path_to_sirius_workspace + "/spectrum.ms";
ifstream spectrum_ms_file(sirius_spectrum_ms);
if (spectrum_ms_file)
{
const OpenMS::String n_id_prefix = "##n_id ";
String line;
while (getline(spectrum_ms_file, line))
{
if (line.hasPrefix(n_id_prefix))
{
String n_id = line.erase(line.find(n_id_prefix), n_id_prefix.size());
ext_n_ids.emplace_back(n_id);
}
else if (spectrum_ms_file.eof())
{
OPENMS_LOG_WARN << "No native id was found - please check your input mzML. " << std::endl;
break;
}
}
spectrum_ms_file.close();
}
ext_n_id = ListUtils::concatenate(ext_n_ids, "|");
return ext_n_id;
}
// extract native id from SIRIUS spectrum.ms output file (workspace - compound specific)
// first native id in the spectrum.ms
OpenMS::String SiriusFragmentAnnotation::extractFeatureIDFromSiriusMS_(const String& path_to_sirius_workspace)
{
String fid = "";
const String sirius_spectrum_ms = path_to_sirius_workspace + "/spectrum.ms";
ifstream spectrum_ms_file(sirius_spectrum_ms);
if (spectrum_ms_file)
{
const OpenMS::String fid_prefix = "##fid ";
String line;
while (getline(spectrum_ms_file, line))
{
if (line.hasPrefix(fid_prefix))
{
fid = line.erase(line.find(fid_prefix), fid_prefix.size());
break; // one file can only have one fid
}
else if (spectrum_ms_file.eof())
{
return ""; // fid is optional and only there if the origin of the sirius run was an OpenMS feature (not a single MS2).
}
}
spectrum_ms_file.close();
}
return fid;
}
// extract m_id from SIRIUS spectrum.ms output file (workspace - compound specific)
// and concatenates them if multiple spectra have been used in case of the compound.
OpenMS::String SiriusFragmentAnnotation::extractConcatMIDsFromSiriusMS_(const String& path_to_sirius_workspace)
{
vector< String > ext_m_ids;
String ext_m_id;
const String sirius_spectrum_ms = path_to_sirius_workspace + "/spectrum.ms";
ifstream spectrum_ms_file(sirius_spectrum_ms);
if (spectrum_ms_file)
{
const OpenMS::String m_id_prefix = "##m_id ";
String line;
while (getline(spectrum_ms_file, line))
{
if (line.hasPrefix(m_id_prefix))
{
String m_id = line.erase(line.find(m_id_prefix), m_id_prefix.size());
ext_m_ids.emplace_back(m_id);
}
else if (spectrum_ms_file.eof())
{
OPENMS_LOG_WARN << "No SiriusExport m_id was found - please check your input mzML. " << std::endl;
break;
}
}
spectrum_ms_file.close();
}
ext_m_id = ListUtils::concatenate(ext_m_ids, "|");
return ext_m_id;
}
std::map< std::string, Size > SiriusFragmentAnnotation::extract_columnname_to_columnindex(const CsvFile& csvfile)
{
StringList header_row;
std::map< std::string, Size > columnname_to_columnindex;
csvfile.getRow(0, header_row);
for (size_t i = 0; i < header_row.size(); i++)
{
columnname_to_columnindex.insert(make_pair(header_row[i], i));
}
return columnname_to_columnindex;
};
// provides a mapping of rank and the file it belongs to since this is not encoded in the directory structure/filename
std::map< Size, String > SiriusFragmentAnnotation::extractCompoundRankingAndFilename_(const String& path_to_sirius_workspace)
{
map< Size, String > rank_filename;
String line;
const String sirius_formula_candidates = path_to_sirius_workspace + "/formula_candidates.tsv"; // based on SIRIUS annotation
ifstream fcandidates(sirius_formula_candidates);
if (fcandidates)
{
CsvFile candidates(sirius_formula_candidates, '\t');
const UInt rowcount = candidates.rowCount();
std::map< std::string, Size > columnname_to_columnindex = SiriusFragmentAnnotation::extract_columnname_to_columnindex(candidates);
// i starts at 1, due to header
for (size_t i = 1; i < rowcount; i++)
{
StringList sl;
candidates.getRow(i, sl);
String adduct = sl[columnname_to_columnindex.at("adduct")];
adduct.erase(std::remove_if(adduct.begin(), adduct.end(), ::isspace), adduct.end());
rank_filename.emplace(std::make_pair(sl[columnname_to_columnindex.at("formulaRank")].toInt(),
String(sl[columnname_to_columnindex.at("molecularFormula")] + "_" + adduct + ".tsv")));
}
}
fcandidates.close();
return rank_filename;
}
// provides a mapping of rank and the TreeIsotope_Score which can be used to resolve ambiguities in mapping
// 43_Cyazofamid_[M+H]+_3 sample=1 period=1 cycle=683 experiment=3|sample=1 period=1 cycle=684 experiment=3|sample=1 period=1 cycle=685 experiment=5
// 44_Ethofumesate_[M+K]+_3 sample=1 period=1 cycle=683 experiment=3|sample=1 period=1 cycle=684 experiment=3|sample=1 period=1 cycle=685 experiment=5
// which have the same mass within 25 ppm due to their adduct in AccurateMassSearch
std::map< Size, double > SiriusFragmentAnnotation::extractCompoundRankingAndScore_(const String& path_to_sirius_workspace)
{
map< Size, double > rank_score;
String line;
const String sirius_formula_candidates = path_to_sirius_workspace + "/formula_candidates.tsv"; // based on SIRIUS annotation
ifstream fcandidates(sirius_formula_candidates);
if (fcandidates)
{
CsvFile candidates(sirius_formula_candidates, '\t');
const UInt rowcount = candidates.rowCount();
std::map< std::string, Size > columnname_to_columnindex = SiriusFragmentAnnotation::extract_columnname_to_columnindex(candidates);
// i starts at 1, due to header
for (size_t i = 1; i < rowcount; i++)
{
StringList sl;
candidates.getRow(i, sl);
rank_score.emplace(std::make_pair(sl[columnname_to_columnindex.at("formulaRank")].toInt(),
sl[columnname_to_columnindex.at("explainedIntensity")].toDouble()));
}
}
fcandidates.close();
return rank_score;
}
std::vector<MSSpectrum> SiriusFragmentAnnotation::extractAnnotationsFromSiriusFile(const String& path_to_sirius_workspace, Size max_rank, bool decoy, bool use_exact_mass)
{
if (decoy) use_exact_mass = false;
std::vector<MSSpectrum> result;
std::string subfolder = decoy ? "/decoys/" : "/spectra/";
const std::string sirius_spectra_dir = path_to_sirius_workspace + subfolder;
QDir dir(QString::fromStdString(sirius_spectra_dir));
if (dir.exists())
{
// TODO this probably can and should be extracted in one go.
OpenMS::String concat_native_ids = SiriusFragmentAnnotation::extractConcatNativeIDsFromSiriusMS_(path_to_sirius_workspace);
OpenMS::String concat_m_ids = SiriusFragmentAnnotation::extractConcatMIDsFromSiriusMS_(path_to_sirius_workspace);
OpenMS::String fid = SiriusFragmentAnnotation::extractFeatureIDFromSiriusMS_(path_to_sirius_workspace);
std::map< Size, String > rank_filename = SiriusFragmentAnnotation::extractCompoundRankingAndFilename_(path_to_sirius_workspace);
std::map< Size, double > rank_score = SiriusFragmentAnnotation::extractCompoundRankingAndScore_(path_to_sirius_workspace);
Size max_found_rank = rank_filename.rbegin()->first;
if (rank_filename.empty() || rank_score.empty())
{
OPENMS_LOG_WARN << "Extraction of the compound ranking, filename and score failed for, please check if the SIRIUS project space is correct for." << sirius_spectra_dir << std::endl;
}
else
{
result.resize(std::min(max_rank, max_found_rank));
}
String suffix = "";
for (unsigned int i = 1; i <= result.size(); ++i)
{
MSSpectrum& msspectrum_to_fill = result[i-1];
// to be backwards compatible, the best rank does not have a suffix
// TODO should be changed. But I need to figure out where.
if (i > 1)
{
suffix = "_" + String(i);
}
msspectrum_to_fill.setNativeID(concat_native_ids + suffix);
msspectrum_to_fill.setName(concat_m_ids + suffix);
String filename = rank_filename.at(i); // rank 1
double score = rank_score.at(i); // rank 1
QFileInfo sirius_result_file(dir,filename.toQString());
if (use_exact_mass)
{
msspectrum_to_fill.setMetaValue(Constants::UserParam::SIRIUS_PEAKMZ, DataValue(Constants::UserParam::SIRIUS_EXACTMASS));
}
else
{
msspectrum_to_fill.setMetaValue(Constants::UserParam::SIRIUS_PEAKMZ, DataValue(Constants::UserParam::SIRIUS_MZ));
}
// filename: sumformula_adduct.csv - save sumformula and adduct as metavalue
String current_sumformula = filename.substr(0, filename.find_last_of("_"));
String current_adduct = filename.substr(filename.find_last_of("_") + 1, filename.find_last_of(".") - filename.find_last_of("_") - 1);
msspectrum_to_fill.setMetaValue(Constants::UserParam::SIRIUS_ANNOTATED_SUMFORMULA, DataValue(current_sumformula));
msspectrum_to_fill.setMetaValue(Constants::UserParam::SIRIUS_ANNOTATED_ADDUCT, DataValue(current_adduct));
msspectrum_to_fill.setMetaValue(Constants::UserParam::SIRIUS_DECOY, decoy);
msspectrum_to_fill.setMetaValue(Constants::UserParam::SIRIUS_SCORE, DataValue(score));
if (!fid.empty())
{
msspectrum_to_fill.setMetaValue(Constants::UserParam::SIRIUS_FEATURE_ID, fid);
}
// read file and save in MSSpectrum
ifstream fragment_annotation_file(sirius_result_file.absoluteFilePath().toStdString());
if (fragment_annotation_file)
{
// Target schema
//mz intensity rel.intensity exactmass formula ionization
//51.023137 713.15 9.36 51.022927 C4H2 [M + H]+
//Decoy schema
//mz rel.intensity formula ionization
//46.994998 0.71 CH2S [M + H]+
std::vector<Peak1D> fragments_mzs_ints;
MSSpectrum::FloatDataArray fragments_extra_masses;
MSSpectrum::StringDataArray fragments_explanations;
MSSpectrum::StringDataArray fragments_ionization;
Size main_mz_col = 0;
Size extra_mz_col = 3;
// option to use the exact mass as peak MZ (e.g. for library preparation).
if (use_exact_mass)
{
main_mz_col = 3;
extra_mz_col = 0;
fragments_extra_masses.setName(Constants::UserParam::SIRIUS_MZ);
}
else
{
fragments_extra_masses.setName(Constants::UserParam::SIRIUS_EXACTMASS);
}
fragments_explanations.setName(Constants::UserParam::SIRIUS_EXPLANATION);
String line;
std::getline(fragment_annotation_file, line); // skip header
while (std::getline(fragment_annotation_file, line))
{
StringList splitted_line;
line.split("\t",splitted_line);
if (!decoy)
{
fragments_extra_masses.push_back(splitted_line[extra_mz_col].toFloat());
}
fragments_mzs_ints.emplace_back(splitted_line[main_mz_col].toDouble(), splitted_line[1].toFloat());
fragments_explanations.push_back(splitted_line[splitted_line.size() - 2]);
fragments_ionization.push_back(splitted_line[splitted_line.size() - 1]);
}
msspectrum_to_fill.setMSLevel(2);
msspectrum_to_fill.swap(fragments_mzs_ints);
msspectrum_to_fill.getFloatDataArrays().push_back(fragments_extra_masses);
msspectrum_to_fill.getStringDataArrays().push_back(fragments_explanations);
msspectrum_to_fill.getStringDataArrays().push_back(fragments_ionization);
}
}
}
else
{
OPENMS_LOG_DEBUG << "Directory '" + subfolder + "' was not found for: " << sirius_spectra_dir << std::endl;
}
return result;
}
} // namespace OpenMS
/// @endcond
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/DATAACCESS/MSDataWritingConsumer.cpp | .cpp | 5,748 | 176 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hannes Roest $
// $Authors: Hannes Roest $
// --------------------------------------------------------------------------
#include <OpenMS/FORMAT/DATAACCESS/MSDataWritingConsumer.h>
#include <OpenMS/FORMAT/VALIDATORS/MzMLValidator.h>
// TODO move getVersion to Handler
#include <OpenMS/FORMAT/MzMLFile.h>
#include <utility>
namespace OpenMS
{
MSDataWritingConsumer::MSDataWritingConsumer(const String& filename) :
Internal::MzMLHandler(MapType(), filename, MzMLFile().getVersion(), ProgressLogger()),
started_writing_(false),
writing_spectra_(false),
writing_chromatograms_(false),
spectra_written_(0),
chromatograms_written_(0),
spectra_expected_(0),
chromatograms_expected_(0),
add_dataprocessing_(false)
{
validator_ = new Internal::MzMLValidator(this->mapping_, this->cv_);
// open file in binary mode to avoid any line ending conversions
ofs_.open(filename.c_str(), std::ios::out | std::ios::binary);
ofs_.precision(writtenDigits(double()));
}
MSDataWritingConsumer::~MSDataWritingConsumer()
{
doCleanup_();
}
void MSDataWritingConsumer::setExperimentalSettings(const ExperimentalSettings& exp)
{
settings_ = exp;
}
void MSDataWritingConsumer::setExpectedSize(Size expectedSpectra, Size expectedChromatograms)
{
spectra_expected_ = expectedSpectra;
chromatograms_expected_ = expectedChromatograms;
}
void MSDataWritingConsumer::consumeSpectrum(SpectrumType & s)
{
if (writing_chromatograms_)
{
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Cannot write spectra after writing chromatograms.");
}
// Process the spectrum
SpectrumType scpy = s;
processSpectrum_(scpy);
// Add dataprocessing if required
if (add_dataprocessing_)
{
scpy.getDataProcessing().push_back(additional_dataprocessing_);
}
if (!started_writing_)
{
// This is the first data to be written -> start writing the header
// We also need to modify the map and add this dummy spectrum in
// order to write the header correctly
MapType dummy;
dummy = settings_;
dummy.addSpectrum(scpy);
//--------------------------------------------------------------------
//header
//--------------------------------------------------------------------
Internal::MzMLHandler::writeHeader_(ofs_, dummy, dps_, *validator_);
started_writing_ = true;
}
if (!writing_spectra_)
{
// This is the first spectrum, thus write the spectrumList header
ofs_ << "\t\t<spectrumList count=\"" << spectra_expected_ << "\" defaultDataProcessingRef=\"dp_sp_0\">\n";
writing_spectra_ = true;
}
bool renew_native_ids = false;
// TODO writeSpectrum assumes that dps_ has at least one value -> assert
// this here ...
Internal::MzMLHandler::writeSpectrum_(ofs_, scpy,
spectra_written_++, *validator_, renew_native_ids, dps_);
}
void MSDataWritingConsumer::consumeChromatogram(ChromatogramType & c)
{
// make sure to close an open List tag
if (writing_spectra_)
{
ofs_ << "\t\t</spectrumList>\n";
writing_spectra_ = false;
}
// Create copy and add dataprocessing if required
ChromatogramType ccpy = c;
processChromatogram_(ccpy);
if (add_dataprocessing_)
{
ccpy.getDataProcessing().push_back(additional_dataprocessing_);
}
if (!started_writing_)
{
// this is the first data to be written -> start writing the header
// We also need to modify the map and add this dummy chromatogram in
// order to write the header correctly
MapType dummy;
dummy = settings_;
dummy.addChromatogram(ccpy);
//--------------------------------------------------------------------
//header (fill also dps_ variable)
//--------------------------------------------------------------------
Internal::MzMLHandler::writeHeader_(ofs_, dummy, dps_, *validator_);
started_writing_ = true;
}
if (!writing_chromatograms_)
{
ofs_ << "\t\t<chromatogramList count=\"" << chromatograms_expected_ << "\" defaultDataProcessingRef=\"dp_sp_0\">\n";
writing_chromatograms_ = true;
}
Internal::MzMLHandler::writeChromatogram_(ofs_, ccpy,
chromatograms_written_++, *validator_);
}
void MSDataWritingConsumer::addDataProcessing(DataProcessing d)
{
additional_dataprocessing_ = DataProcessingPtr( new DataProcessing(std::move(d)) );
add_dataprocessing_ = true;
}
Size MSDataWritingConsumer::getNrSpectraWritten() {return spectra_written_;}
Size MSDataWritingConsumer::getNrChromatogramsWritten() {return chromatograms_written_;}
void MSDataWritingConsumer::doCleanup_()
{
//--------------------------------------------------------------------------------------------
//cleanup
//--------------------------------------------------------------------------------------------
// make sure to close an open List tag
if (writing_spectra_)
{
ofs_ << "\t\t</spectrumList>\n";
}
else if (writing_chromatograms_)
{
ofs_ << "\t\t</chromatogramList>\n";
}
// Only write the footer if we actually did start writing ...
if (started_writing_)
{
Internal::MzMLHandlerHelper::writeFooter_(ofs_, options_, spectra_offsets_, chromatograms_offsets_);
}
delete validator_;
ofs_.close();
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/DATAACCESS/MSDataSqlConsumer.cpp | .cpp | 2,412 | 91 | // 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/DATAACCESS/MSDataSqlConsumer.h>
#include <OpenMS/FORMAT/HANDLERS/MzMLSqliteHandler.h>
namespace OpenMS
{
MSDataSqlConsumer::MSDataSqlConsumer(const String& filename, UInt64 run_id, int flush_after, bool full_meta, bool lossy_compression, double linear_mass_acc) :
filename_(filename),
handler_(new OpenMS::Internal::MzMLSqliteHandler(filename, run_id) ),
flush_after_(flush_after),
full_meta_(full_meta)
{
spectra_.reserve(flush_after_);
chromatograms_.reserve(flush_after_);
handler_->setConfig(full_meta, lossy_compression, linear_mass_acc, flush_after_);
handler_->createTables();
}
MSDataSqlConsumer::~MSDataSqlConsumer()
{
flush();
// Write run level information into the file (e.g. run id, run name and mzML structure)
peak_meta_.setLoadedFilePath(filename_);
handler_->writeRunLevelInformation(peak_meta_, full_meta_);
delete handler_;
}
void MSDataSqlConsumer::flush()
{
if (!spectra_.empty() )
{
handler_->writeSpectra(spectra_);
spectra_.clear();
spectra_.reserve(flush_after_);
}
if (!chromatograms_.empty() )
{
handler_->writeChromatograms(chromatograms_);
chromatograms_.clear();
chromatograms_.reserve(flush_after_);
}
}
void MSDataSqlConsumer::consumeSpectrum(SpectrumType & s)
{
spectra_.push_back(s);
s.clear(false);
if (full_meta_)
{
peak_meta_.addSpectrum(s);
}
if (spectra_.size() >= flush_after_)
{
flush();
}
}
void MSDataSqlConsumer::consumeChromatogram(ChromatogramType & c)
{
chromatograms_.push_back(c);
c.clear(false);
if (full_meta_)
{
peak_meta_.addChromatogram(c);
}
if (chromatograms_.size() >= flush_after_)
{
flush();
}
}
void MSDataSqlConsumer::setExpectedSize(Size /* expectedSpectra */, Size /* expectedChromatograms */) {;}
void MSDataSqlConsumer::setExperimentalSettings(const ExperimentalSettings& /* exp */) {;}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/DATAACCESS/MSDataAggregatingConsumer.cpp | .cpp | 1,830 | 68 | // 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/DATAACCESS/MSDataAggregatingConsumer.h>
#include <OpenMS/PROCESSING/RESAMPLING/LinearResamplerAlign.h>
#include <OpenMS/ANALYSIS/OPENSWATH/SpectrumAddition.h>
#include <OpenMS/KERNEL/SpectrumHelper.h>
namespace OpenMS
{
MSDataAggregatingConsumer::~MSDataAggregatingConsumer()
{
// flush remaining spectra
if (!s_list.empty())
{
MSSpectrum tmps = SpectrumAddition::addUpSpectra(s_list, -1, true);
copySpectrumMeta(s_list[0], tmps, false);
next_consumer_->consumeSpectrum(tmps);
}
}
void MSDataAggregatingConsumer::consumeSpectrum(SpectrumType & s)
{
// aggregate by RT
double RT = s.getRT();
if (rt_initialized_ && std::fabs(RT - previous_rt_) < 1e-5)
{
// need to aggregate spectrum
s_list.push_back(s);
}
else
{
// consume the previous list
if (rt_initialized_ && !s_list.empty())
{
MSSpectrum tmps = SpectrumAddition::addUpSpectra(s_list, -1, true);
copySpectrumMeta(s_list[0], tmps, false);
next_consumer_->consumeSpectrum(tmps);
}
// start new spectrum list
int expected_size = s_list.size();
s_list.clear();
s_list.reserve(expected_size);
s_list.push_back(s);
}
previous_rt_ = RT;
rt_initialized_ = true;
}
void MSDataAggregatingConsumer::consumeChromatogram(ChromatogramType & c)
{
// NOP
next_consumer_->consumeChromatogram(c);
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/DATAACCESS/SwathFileConsumer.cpp | .cpp | 446 | 15 | // 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/DATAACCESS/SwathFileConsumer.h>
namespace OpenMS
{
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/DATAACCESS/MSDataChainingConsumer.cpp | .cpp | 1,663 | 63 | // 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/DATAACCESS/MSDataChainingConsumer.h>
#include <utility>
namespace OpenMS
{
MSDataChainingConsumer::MSDataChainingConsumer() = default;
MSDataChainingConsumer::MSDataChainingConsumer(std::vector<Interfaces::IMSDataConsumer *> consumers) :
consumers_(std::move(consumers))
{}
MSDataChainingConsumer::~MSDataChainingConsumer() = default;
void MSDataChainingConsumer::appendConsumer(Interfaces::IMSDataConsumer * consumer)
{
consumers_.push_back(consumer);
}
void MSDataChainingConsumer::setExperimentalSettings(const ExperimentalSettings & settings)
{
for (Size i = 0; i < consumers_.size(); i++)
{
consumers_[i]->setExperimentalSettings(settings);
}
}
void MSDataChainingConsumer::setExpectedSize(Size s_size, Size c_size)
{
for (Size i = 0; i < consumers_.size(); i++)
{
consumers_[i]->setExpectedSize(s_size, c_size);
}
}
void MSDataChainingConsumer::consumeSpectrum(SpectrumType & s)
{
for (Size i = 0; i < consumers_.size(); i++)
{
consumers_[i]->consumeSpectrum(s);
}
}
void MSDataChainingConsumer::consumeChromatogram(ChromatogramType & c)
{
for (Size i = 0; i < consumers_.size(); i++)
{
consumers_[i]->consumeChromatogram(c);
}
}
} //end namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/DATAACCESS/NoopMSDataConsumer.cpp | .cpp | 494 | 16 | // 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/DATAACCESS/NoopMSDataConsumer.h>
namespace OpenMS
{
NoopMSDataConsumer default_noop_consumer;
} //end namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/DATAACCESS/MSDataCachedConsumer.cpp | .cpp | 2,881 | 80 | // 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/DATAACCESS/MSDataCachedConsumer.h>
#include <OpenMS/CONCEPT/Macros.h>
#include <OpenMS/KERNEL/MSSpectrum.h>
#include <OpenMS/KERNEL/MSChromatogram.h>
namespace OpenMS
{
MSDataCachedConsumer::MSDataCachedConsumer(const String& filename, bool clearData) :
ofs_(filename.c_str(), std::ios::binary),
clearData_(clearData),
spectra_written_(0),
chromatograms_written_(0)
{
int file_identifier = CACHED_MZML_FILE_IDENTIFIER;
ofs_.write((char*)&file_identifier, sizeof(file_identifier));
}
MSDataCachedConsumer::~MSDataCachedConsumer()
{
// Write size of file (to the end of the file)
ofs_.write((char*)&spectra_written_, sizeof(spectra_written_));
ofs_.write((char*)&chromatograms_written_, sizeof(chromatograms_written_));
// Close file stream: close() _should_ call flush() but it might not in
// all cases. To be sure call flush() first.
ofs_.flush();
ofs_.close();
}
void MSDataCachedConsumer::consumeSpectrum(SpectrumType & s)
{
if (chromatograms_written_ > 0)
{
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Cannot write spectra after writing chromatograms.");
}
writeSpectrum_(s, ofs_);
spectra_written_++;
// Clear all spectral data including all float/int data arrays (but not string arrays)
if (clearData_)
{
s.clear(false);
s.setFloatDataArrays({});
s.setIntegerDataArrays({});
}
OPENMS_POSTCONDITION( (!clearData_ || s.empty() ), "clearData implies spectrum is empty")
OPENMS_POSTCONDITION( (!clearData_ || s.getFloatDataArrays().empty() ), "clearData implies spectrum is empty")
OPENMS_POSTCONDITION( (!clearData_ || s.getIntegerDataArrays().empty() ), "clearData implies spectrum is empty")
}
void MSDataCachedConsumer::consumeChromatogram(ChromatogramType & c)
{
writeChromatogram_(c, ofs_);
chromatograms_written_++;
// Clear all chromatogram data including all float/int data arrays (but not string arrays)
if (clearData_)
{
c.clear(false);
c.setFloatDataArrays({});
c.setIntegerDataArrays({});
}
OPENMS_POSTCONDITION( (!clearData_ || c.empty() ), "clearData implies chromatogram is empty")
OPENMS_POSTCONDITION( (!clearData_ || c.getFloatDataArrays().empty() ), "clearData implies chromatogram is empty")
OPENMS_POSTCONDITION( (!clearData_ || c.getIntegerDataArrays().empty() ), "clearData implies chromatogram is empty")
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/DATAACCESS/MSDataStoringConsumer.cpp | .cpp | 1,212 | 45 | // 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/DATAACCESS/MSDataStoringConsumer.h>
#include <OpenMS/KERNEL/MSSpectrum.h>
#include <OpenMS/KERNEL/MSChromatogram.h>
namespace OpenMS
{
MSDataStoringConsumer::MSDataStoringConsumer() = default;
void MSDataStoringConsumer::setExperimentalSettings(const ExperimentalSettings & settings)
{
exp_ = settings; // only override the settings, keep the data
}
void MSDataStoringConsumer::setExpectedSize(Size s_size, Size c_size)
{
exp_.reserveSpaceSpectra(s_size);
exp_.reserveSpaceChromatograms(c_size);
}
void MSDataStoringConsumer::consumeSpectrum(SpectrumType & s)
{
exp_.addSpectrum(s);
}
void MSDataStoringConsumer::consumeChromatogram(ChromatogramType & c)
{
exp_.addChromatogram(c);
}
const PeakMap& MSDataStoringConsumer::getData() const
{
return exp_;
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms/source/FORMAT/DATAACCESS/MSDataTransformingConsumer.cpp | .cpp | 2,203 | 69 | // 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, Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/FORMAT/DATAACCESS/MSDataTransformingConsumer.h>
#include <utility>
namespace OpenMS
{
/**
@brief Constructor
*/
MSDataTransformingConsumer::MSDataTransformingConsumer()
: lambda_spec_(nullptr),
lambda_chrom_(nullptr),
lambda_exp_settings_(nullptr)
{
}
/// Default destructor
MSDataTransformingConsumer::~MSDataTransformingConsumer()
= default;
void MSDataTransformingConsumer::setExpectedSize(Size /* expectedSpectra */, Size /* expectedChromatograms */)
{
}
void MSDataTransformingConsumer::consumeSpectrum(SpectrumType& s)
{
// apply the given function to it (unless nullptr)
if (lambda_spec_) lambda_spec_(s);
}
void MSDataTransformingConsumer::setSpectraProcessingFunc( std::function<void (SpectrumType&)> f_spec )
{
lambda_spec_ = std::move(f_spec);
}
void MSDataTransformingConsumer::consumeChromatogram(ChromatogramType & c)
{
// apply the given function to it (unless nullptr)
if (lambda_chrom_) lambda_chrom_(c);
}
void MSDataTransformingConsumer::setChromatogramProcessingFunc( std::function<void (ChromatogramType&)> f_chrom )
{
lambda_chrom_ = std::move(f_chrom);
}
void MSDataTransformingConsumer::setExperimentalSettingsFunc( std::function<void (const OpenMS::ExperimentalSettings&)> f_exp_settings )
{
lambda_exp_settings_ = std::move(f_exp_settings);
}
void MSDataTransformingConsumer::setExperimentalSettings(const OpenMS::ExperimentalSettings& es)
{
// apply the given function to it (unless nullptr)
if (lambda_exp_settings_)
{
lambda_exp_settings_(es);
}
}
} // namespace OpenMS
| C++ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.