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/include/OpenMS/SYSTEM/SysInfo.h | .h | 3,502 | 89 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/config.h>
#include <OpenMS/DATASTRUCTURES/String.h>
namespace OpenMS
{
/// convert bytes to a human readable unit (TiB, GiB, MiB, KiB), e.g. "45.34 MiB"
OPENMS_DLLAPI std::string bytesToHumanReadable(UInt64 bytes);
/**
@brief Some functions to get system information
Supports current memory and peak memory consumption.
*/
class OPENMS_DLLAPI SysInfo
{
public:
/// Get memory consumption in KiloBytes (KB)
/// On Windows, this is equivalent to 'Peak Working Set (Memory)' in Task Manager.
/// On other OS this might be very unreliable, depending on operating system and kernel version.
///
/// @param[out] mem_virtual Total virtual memory currently allocated by this process
/// @return True on success, false otherwise. If false is returned, then @p mem_virtual is set to 0.
static bool getProcessMemoryConsumption(size_t& mem_virtual);
/// Get peak memory consumption in KiloBytes (KB)
/// On Windows, this is equivalent to 'Working Set (Memory)' in Task Manager.
/// On other OS this might be very unreliable, depending on operating system and kernel version.
///
/// @param[out] mem_virtual Total virtual memory allocated by this process
/// @return True on success, false otherwise. If false is returned, then @p mem_virtual is set to 0.
static bool getProcessPeakMemoryConsumption(size_t& mem_virtual);
/**
@brief A convenience class to report either absolute or delta (between two timepoints) RAM usage
Working RAM and Peak RAM usage are recorded at two time points ('before' and 'after').
@note Peak RAM is only supported on WindowsOS; other OS will only report Working RAM usage
When constructed, MemUsage automatically queries the present RAM usage (first timepoint), i.e. calls @ref before().
Data for the second timepoint can be recorded using @ref after().
@ref delta() reports the difference between the timepoints (before -> after);
@ref usage() reports only the second timepoint's absolute value (after).
When @ref delta() or @ref usage() are called, and the second timepoint is not recorded yet, this will be done internally.
*/
struct OPENMS_DLLAPI MemUsage
{
size_t mem_before, mem_before_peak, mem_after, mem_after_peak;
/// C'tor, calls @ref before() automatically
MemUsage();
/// forget all data (you need to call @ref before() again)
void reset();
/// record data for the first timepoint
void before();
/// record data for the second timepoint
void after();
/// get difference in memory usage between the two timepoints
/// @ref after() will be called unless it was called earlier
String delta(const String& event = "delta");
/// get current memory usage (i.e. 'after')
/// @ref after() will be called unless it was called earlier
String usage();
private:
// convert difference to string
String diff_str_(size_t mem_before, size_t mem_after);
};
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/SYSTEM/File.h | .h | 15,441 | 369 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Andreas Bertsch, Chris Bielow, Marc Sturm $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/StringListUtils.h>
#include <OpenMS/config.h>
#include <cstdlib>
#include <mutex>
namespace OpenMS
{
class Param;
class TOPPBase;
/**
@brief Basic file handling operations.
@ingroup System
*/
class OPENMS_DLLAPI File
{
public:
/**
@brief Class representing a temporary directory
*/
class OPENMS_DLLAPI TempDir
{
public:
/// Construct temporary folder
/// If keep_dir is set to true, the folder will not be deleted on destruction of the object.
TempDir(bool keep_dir = false);
/// Destroy temporary folder (can be prohibited in Constructor)
~TempDir();
/// delete all means to copy or move a TempDir
TempDir(const TempDir&) = delete;
TempDir& operator=(const TempDir&) = delete;
TempDir(TempDir&&) = delete;
TempDir& operator=(TempDir&&) = delete;
/// Return path to temporary folder
const String& getPath() const;
private:
String temp_dir_;
bool keep_dir_;
};
/// Retrieve path of current executable (useful to find other TOPP tools)
/// The returned path is either just an EMPTY string if the call to system subroutines failed
/// or the complete path including a trailing "/", to enable usage of this function as
/// File::getExecutablePath() + "mytool"
static String getExecutablePath();
/// Method used to test if a @p file exists.
static bool exists(const String& file);
/// Return true if the file does not exist or the file is empty
static bool empty(const String& file);
/// Method used to test if a @p file is executable.
static bool executable(const String& file);
/// The filesize in bytes (or -1 on error, e.g. if the file does not exist)
static UInt64 fileSize(const String& file);
/**
@brief Rename a file
If @p from and @p to point to the same file (symlinks are resolved),
no action will be taken and true is returned.
If the target already exists (and is not identical to the source),
this function will fail unless @p overwrite_existing is true.
@param[in] from Source filename
@param[in] to Target filename
@param[in] overwrite_existing Delete already existing target, before renaming
@param[in] verbose Print message to OPENMS_LOG_ERROR if something goes wrong.
@return True on success
*/
static bool rename(const String& from, const String& to, bool overwrite_existing = true, bool verbose = true);
/**
@brief Copy directory recursively
Copies a source directory to a new target directory (recursive).
If the target directory already exists, files will be added.
If files from the source already exist in the target, @p option allows for the following behaviour:
OVERWRITE: Overwrite the file in the target directory if it already exists.
SKIP: Skip the file in the target directory if it already exists.
CANCEL: Cancel the copy process if file already exists in target directory - return false.
@param[in] from_dir Source directory
@param[in] to_dir Target directory
@param[in] option Specify the copy option (OVERWRITE, SKIP, CANCEL)
@return True on success
*/
enum class CopyOptions {OVERWRITE,SKIP,CANCEL};
static bool copyDirRecursively(const QString &from_dir, const QString &to_dir, File::CopyOptions option = CopyOptions::OVERWRITE);
/// Copy a file (if it exists). Returns true if successful.
static bool copy(const String& from, const String& to);
/**
@brief Removes a file (if it exists).
@return Returns true if the file was successfully deleted (or if it did not exist).
*/
static bool remove(const String& file);
/// Removes the subdirectories of the specified directory (absolute path). Returns true if successful.
static bool removeDirRecursively(const String& dir_name);
/// Removes the directory and all subdirectories (absolute path).
static bool removeDir(const QString& dir_name);
/// Creates a directory (absolute path or relative to the current working dir), even if subdirectories do not exist. Returns true if successful.
/// If the path already exists when this function is called, it will return true.
static bool makeDir(const String& dir_name);
/// Replaces the relative path in the argument with the absolute path.
static String absolutePath(const String& file);
/// Returns the basename of the file (without the path).
/// No checking is done on the filesystem, i.e. '/path/some_entity' will return 'some_entity', irrespective of 'some_entity' is a file or a directory.
/// However, '/path/some_entity/' will return ''.
static String basename(const String& file);
/// Returns the path of the file (without the file name and without path separator).
/// If just a filename is given without any path, then "." is returned.
/// No checking is done on the filesystem, i.e. '/path/some_entity' will return '/path', irrespective of 'some_entity' is a file or a directory.
/// However, '/path/some_entity/' will return '/path/some_entity'.
static String path(const String& file);
/// Return true if the file exists and is readable
static bool readable(const String& file);
/// Return true if the file is writable
static bool writable(const String& file);
/// Return true if the given path specifies a directory
static bool isDirectory(const String& path);
/**
@brief Looks up the location of the file @p filename
The following locations are checked in this order:
- the directories in @p directories
- the directory contained in the environment variable $OPENMS_DATA_PATH
- the 'share/OpenMS/' directory of the OpenMS install directory
@exception FileNotFound is thrown, if the file is not found
*/
static String find(const String& filename, StringList directories = StringList());
/**
@brief Retrieves a list of files matching @p file_pattern in directory
@p dir (returns filenames without paths unless @p full_path is true)
@return true => there are matching files
*/
static bool fileList(const String& dir, const String& file_pattern, StringList& output, bool full_path = false);
/**
@brief Resolves a partial file name to a documentation file in the doc-folder.
Using find() to locate the documentation file under OPENMS_DATA_PATH,
OPENMS_SOURCE_PATH, OPENMS_BINARY_PATH + "/../../doc" (or a variation for
MacOS packages)
Will return the filename with the full path to the local documentation. If
this call fails, try the web documentation
(http://www.openms.de/current_doxygen/) instead.
@param[in] filename The doc file name to find.
@return The full path to the requested file.
@exception FileNotFound is thrown, if the file is not found
*/
static String findDoc(const String& filename);
/**
@brief Returns a string, consisting of date, time, hostname, process id, and a incrementing number. This can be used for temporary files.
@param[in] include_hostname add hostname into result - potentially a long string
@return a unique name
*/
static String getUniqueName(bool include_hostname = true);
/// Returns the OpenMS data path (environment variable overwrites the default installation path)
static String getOpenMSDataPath();
/// Returns the OpenMS home path (environment variable overwrites the default home path)
static String getOpenMSHomePath();
/// The current OpenMS temporary data path (for temporary files).
/// Looks up the following locations, taking the first one which is non-null:
/// - environment variable OPENMS_TMPDIR
/// - 'temp_dir' in the ~/OpenMS.ini file
/// - System temp directory (usually defined by environment 'TMP' or 'TEMP'
static String getTempDirectory();
/// The current OpenMS user data path (for result files)
/// Tries to set the user directory in following order:
/// 1. OPENMS_HOME_DIR if environmental variable set
/// 2. "home_dir" entry in OpenMS.ini
/// 3. user home directory
static String getUserDirectory();
/// get the system's default OpenMS.ini file in the users home directory (<home>/OpenMS/OpenMS.ini)
/// or create/repair it if required
/// order:
/// 1. <OPENMS_HOME_DIR>/OpenMS/OpenMS.ini if environmental variable set
/// 2. user home directory <home>/OpenMS/OpenMS.ini
static Param getSystemParameters();
/// uses File::find() to search for a file names @p db_name
/// in the 'id_db_dir' param of the OpenMS system parameters
/// @exception FileNotFound is thrown, if the file is not found
static String findDatabase(const String& db_name);
/**
@brief Extract list of directories from a concatenated string (usually $PATH).
Depending on platform, the components are split based on ":" (Linux/Mac) or ";" (Windows).
All paths use the '/' as separator and end in '/'.
E.g. for 'PATH=/usr/bin:/home/unicorn' the result is {"/usr/bin/", "/home/unicorn/"}
or 'PATH=c:\\temp;c:\\Windows' the result is {"c:/temp/", "c:/Windows/"}
Note: the environment variable is passed as input to enable proper testing (env vars are usually read-only).
*/
static StringList getPathLocations(const String& path = std::getenv("PATH"));
/**
@brief Searches for an executable with the given name (similar to @em where (Windows) or @em which (Linux/MacOS)
This function can be used to find the full path+filename to an executable in
the PATH environment. Only the @em first hit (by order in PATH) is returned.
If the @p exe_filename has a relative or full path which points to an existing file, PATH information will not be used.
The function returns true if the filename was found (exists) and false otherwise.
Note: this does not require the file to have executable permission set (this is not tested)
The returned content of @p exe_filename is only valid if true is returned.
@param[in,out] exe_filename The executable to search for.
@return true if @p exe_filename could be resolved to a full path and it exists
*/
static bool findExecutable(OpenMS::String& exe_filename);
/**
@brief Searches for an executable with the given name.
@param[in] toolName The executable to search for.
@exception FileNotFound is thrown, if the tool executable was not found.
*/
static String findSiblingTOPPExecutable(const String& toolName);
/**
@brief Obtain a temporary filename, ensuring automatic deletion upon exit
The file is not actually created and only deleted at exit if it exists.
However, if 'alternative_file' is given and not empty, no temporary filename
is created and 'alternative_file' is returned (and not destroyed upon exit).
This is useful if you have an optional
output file, which may, or may not be requested, but you need its content regardless,
e.g. for intermediate plotting with R.
Thus you can just call this function to get a file which can be used and gets automatically
destroyed if needed.
@param[in] alternative_file If this string is not empty, no action is taken and it is used as return value
@return Full path to a temporary file
*/
static String getTemporaryFile(const String& alternative_file = "");
enum class MatchingFileListsStatus
{
MATCH = 0, // Everything matches perfectly
ORDER_MISMATCH = 1, // Same set of files but in wrong order
SET_MISMATCH = 2 // Different sets of files (including size mismatch)
};
/**
@brief Helper function to test if filenames provided in two StringLists match.
Passing several InputFilesLists is error-prone as users may provide files in a different order.
This helper function performs validation and returns one of three states:
- MATCH (0): Files match perfectly (considering basename/extension settings)
- ORDER_MISMATCH (1): Same set of files but in different order
- SET_MISMATCH (2): Different sets of files (including different counts)
@param[in] sl1 First StringList with filenames
@param[in] sl2 Second StringList with filenames
@param[in] basename If set to true, only basenames are compared
@param[in] ignore_extension If set to true, extensions are ignored (e.g., useful to compare spectra filenames to ID filenames)
@return MatchingFileListsStatus indicating the validation result
*/
static MatchingFileListsStatus validateMatchingFileNames(const StringList& sl1,
const StringList& sl2,
bool basename = true,
bool ignore_extension = true);
/**
@brief Download file from given URL into a download folder. Returns when done.
If a file with same filename already exists, continues download and appends '.\#number' to basename.
@throw FileNotFound exception if download failed.
*/
static void download(const std::string& url, const std::string& download_folder);
private:
/// get defaults for the system's Temp-path, user home directory etc.
static Param getSystemParameterDefaults_();
/// Check if the given path is a valid OPENMS_DATA_PATH
static bool isOpenMSDataPath_(const String& path);
#ifdef OPENMS_WINDOWSPLATFORM
/**
@brief Get list of file suffices to try during search on PATH (usually .exe, .bat etc)
Input could be ".COM;.EXE;.BAT;.CMD;.VBS".
If the result does not contain at least ".exe", then we assume the environment variable is broken and return a
fallback, i.e. {".exe", ".bat"}.
Note: the environment variable is passed as input to enable proper testing (env vars are usually read-only).
*/
static StringList executableExtensions_(const String& ext = std::getenv("PATHEXT"));
#endif
/**
@brief Internal helper class, which holds temporary filenames and deletes these files at program exit
*/
class TemporaryFiles_
{
public:
TemporaryFiles_(const TemporaryFiles_&) = delete; // copy is forbidden
TemporaryFiles_& operator=(const TemporaryFiles_&) = delete;
TemporaryFiles_();
/// create a new filename and queue internally for deletion
String newFile();
~TemporaryFiles_();
private:
StringList filenames_;
std::mutex mtx_;
};
/// private list of temporary filenames, which are deleted upon program exit
static TemporaryFiles_ temporary_files_;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/SYSTEM/UpdateCheck.h | .h | 685 | 30 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/config.h>
namespace OpenMS
{
class String;
/**
@brief Helper Functions to perform an update query to the OpenMS REST server
@ingroup System
*/
class OPENMS_DLLAPI UpdateCheck
{
public:
static void run(const String& tool_name, const String& version, int debug_level);
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/SYSTEM/JavaInfo.h | .h | 1,244 | 40 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Timo Sachsenberg, Chris Bielow $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/config.h>
namespace OpenMS
{
class String;
/**
@brief Detect Java and retrieve information.
Similar classes exist for other external tools, e.g. PythonInfo .
@ingroup System
*/
class OPENMS_DLLAPI JavaInfo
{
public:
/**
@brief Determine if Java is installed and reachable
The call fails if either Java is not installed or if a relative location is given and Java is not on the search PATH.
@param[in] java_executable Path to Java executable. Can be absolute, relative or just a filename
@param[in] verbose_on_error On error, should an error message be printed to OPENMS_LOG_ERROR?
@return Returns false if Java executable can not be called; true if Java executable can be executed
**/
static bool canRun(const String& java_executable, bool verbose_on_error = true);
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/SYSTEM/StopWatch.h | .h | 7,769 | 237 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/config.h>
#include <OpenMS/CONCEPT/Types.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#ifdef OPENMS_HAS_SYS_TIME_H
#include <sys/time.h>
#endif
#ifdef OPENMS_HAS_TIME_H
#include <ctime>
#endif
namespace OpenMS
{
/**
@brief This class is used to determine the current process' CPU (user and/or kernel) and wall time.
CPU time is measured as sum of all threads of the current process.
To read a time, the stopwatch must be started beforehand, but not necessarily stopped.
You can stop() the timer and resume() it later to omit intermediate steps which should not count towards
the measured times.
@ingroup System
*/
class OPENMS_DLLAPI StopWatch
{
public:
/** Starting, Stopping and Resetting the stop watch
*/
//@{
/**
@brief Start the stop watch.
If the watch holds data from previous measurements, these will be reset before starting up,
i.e. it is not possible to resume by start(), stop(), start().
Use resume(), stop(), resume() instead.
@throw Exception::Precondition if the StopWatch is already running
*/
void start();
/**
@brief Stop the stop watch (can be resumed later).
If the stop watch was not running an exception is thrown.
@throw Exception::Precondition if the StopWatch is not running
*/
void stop();
/**
@brief Resume a stopped StopWatch
@throw Exception::Precondition if the StopWatch is already running
*/
void resume();
/**
@brief Clear the stop watch but keep running.
The stop watch is reset to 0, but not stopped (if running).
@see clear
*/
void reset();
/** Clear and stop the stop watch.
This sets the stop watch to zero and stops it when running.
@see reset
*/
void clear();
//@}
/** @name Readout of the StopWatch
*/
//@{
/** Get clock time.
Return the accumulated wall clock (real) time in seconds.
*/
double getClockTime() const;
/** Get user time.
Return the accumulated user time in seconds across all threads.
*/
double getUserTime() const;
/** Get user time.
Return the accumulated system time in seconds across all threads.
*/
double getSystemTime() const;
/** Get CPU time.
Return the accumulated CPU time in seconds.
CPU time is the sum of user time and system time across all threads.
*/
double getCPUTime() const;
/** @name Predicates
*/
//@{
/** Return true if the stop watch is running.
@return bool <b>true</b> if the stop watch is running, <b>false</b> otherwise
*/
bool isRunning() const;
/** Equality operator.
Return <b>true</b> if two stop watches are equal, i.e. they contain exactly
the same time intervals for clock, user and system time and have the
same running status.
@param[in] stop_watch the stop watch to compare with
@return bool <b>true</b> on equality, <b>false</b> otherwise
*/
bool operator==(const StopWatch & stop_watch) const;
/** Inequality operator.
Return <b>false</b> if two stop watches differ in any way, i.e. they differ
in either the clock, user, or system time or have a different
running status.
@param[in] stop_watch the stop watch to compare with
@return bool <b>true</b> on inequality, <b>false</b> otherwise
*/
bool operator!=(const StopWatch & stop_watch) const;
/** Lesser than operator.
Return true, if the stop watch is in all timings lesser than the
stop watch to be compared with (clock, user and system time).
@param[in] stop_watch the stop watch to compare with
@return bool <b>true</b> if all times are lesser
*/
bool operator<(const StopWatch & stop_watch) const;
/** Lesser or equal operator.
Return true, if the stop watch is in all timings lesser or equal than the
stop watch to be compared with (clock, user and system time).
@param[in] stop_watch the stop watch to compare with
@return bool <b>true</b> if all times are lesser or equal
*/
bool operator<=(const StopWatch & stop_watch) const;
/** Greater or equal operator.
Return true, if the stop watch is in all timings greater or equal than the
stop watch to be compared with (clock, user and system time).
@param[in] stop_watch the stop watch to compare with
@return bool <b>true</b> if all times are greater or equal
*/
bool operator>=(const StopWatch & stop_watch) const;
/** Greater operator.
Return true, if the stop watch is in all timings greater than the
stop watch to be compared with (clock, user and system time).
@param[in] stop_watch the stop watch to compare with
@return bool <b>true</b> if all times are greater
*/
bool operator>(const StopWatch & stop_watch) const;
//@}
/**
@brief get a compact representation of the current time status.
The output will be something like:
2.10 s (wall), 1.67 s (CPU), 0.12 s (system), 1.54 s (user)
*/
String toString() const;
/**
custom string formatting of time, using only the minimal number of units required (e.g., does not report hours when seconds suffice).
*/
static String toString(const double time_in_seconds);
private:
#ifdef OPENMS_WINDOWSPLATFORM
typedef UInt64 TimeType; ///< do not use clock_t on Windows, since its not big enough for larger time intervals
static const long long SecondsTo100Nano_; ///< 10 million; convert from 100 nanosecond ticks to seconds (factor of 1 billion/100 = 10 million)
#else
typedef clock_t TimeType;
static const PointerSizeInt cpu_speed_; ///< POSIX API returns CPU ticks, so we need to divide by CPU speed
#endif
struct TimeDiff_
{
TimeType user_ticks{ 0 }; ///< platform dependent value (might be CPU ticks or time intervals)
TimeType kernel_ticks{ 0 }; ///< platform dependent value (might be CPU ticks or time intervals)
PointerSizeInt start_time{ 0 }; ///< time in seconds (relative or absolute, depending on usage)
PointerSizeInt start_time_usec{ 0 }; ///< time in microseconds (relative or absolute, depending on usage)
double userTime() const;
double kernelTime() const;
double getCPUTime() const;
double clockTime() const;
TimeDiff_ operator-(const TimeDiff_& earlier) const;
TimeDiff_& operator+=(const TimeDiff_& other);
bool operator==(const TimeDiff_& rhs) const;
private:
double ticksToSeconds_(TimeType in) const;
};
/// get the absolute times for current system, user and kernel times
TimeDiff_ snapShot_() const;
/// currently accumulated times between start to stop intervals (initially 0),
/// not counting the currently running interval which started at last_start_
TimeDiff_ accumulated_times_;
/// point in time of last start()
TimeDiff_ last_start_;
/// state of stop watch, either true(on) or false(off)
bool is_running_ = false;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/SYSTEM/BuildInfo.h | .h | 4,873 | 155 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/build_config.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <QtCore/QSysInfo>
#include <QtCore/QString>
#ifdef _OPENMP
#include "omp.h"
#endif
namespace OpenMS
{
namespace Internal
{
enum class OpenMS_OS {OS_UNKNOWN, OS_MACOS, OS_WINDOWS, OS_LINUX, SIZE_OF_OPENMS_OS};
inline const std::string OpenMS_OSNames[] = {"unknown", "MacOS", "Windows", "Linux"};
enum class OpenMS_Architecture {ARCH_UNKNOWN, ARCH_32BIT, ARCH_64BIT, SIZE_OF_OPENMS_ARCHITECTURE};
inline const std::string OpenMS_ArchNames[] = {"unknown", "32 bit", "64 bit"};
class OPENMS_DLLAPI OpenMSOSInfo
{
OpenMS_OS os_;
String os_version_;
OpenMS_Architecture arch_;
public:
OpenMSOSInfo() :
os_(OpenMS_OS::OS_UNKNOWN),
os_version_("unknown"),
arch_(OpenMS_Architecture::ARCH_UNKNOWN)
{}
/// @brief Get the current operating system (Windows, MacOS, Linux)
String getOSAsString() const
{
return OpenMS_OSNames[static_cast<size_t>(os_)];
}
/// @brief Get the current architecture (32-bit or 64-bit)
String getArchAsString() const
{
return OpenMS_ArchNames[static_cast<size_t>(arch_)];
}
/// @brief Get the OS version (e.g. 10.15 for macOS or 10 for Windows)
String getOSVersionAsString() const
{
return os_version_;
}
/// @brief Get Architecture of this binary (simply by looking at size of a pointer, i.e. size_t).
static String getBinaryArchitecture()
{
size_t bytes = sizeof(size_t);
switch (bytes)
{
case 4:
return OpenMS_ArchNames[static_cast<size_t>(OpenMS_Architecture::ARCH_32BIT)];
case 8:
return OpenMS_ArchNames[static_cast<size_t>(OpenMS_Architecture::ARCH_64BIT)];
default:
return OpenMS_ArchNames[static_cast<size_t>(OpenMS_Architecture::ARCH_UNKNOWN)];
}
}
/// @brief Obtain a list of SIMD extensions which are currently in use (i.e. used by the compiler during optimization, as well as for SIMDe code within OpenMS)
static String getActiveSIMDExtensions();
/// @brief Constructs and returns an OpenMSOSInfo object
static OpenMSOSInfo getOSInfo()
{
OpenMSOSInfo info;
#if defined(WIN32) // Windows
info.os_ = OpenMS_OS::OS_WINDOWS;
#elif (defined(__MACH__) && defined(__APPLE__)) // MacOS
info.os_ = OpenMS_OS::OS_MACOS;
#elif (defined(__unix__)) //Linux/FreeBSD TODO make a difference?
info.os_ = OpenMS_OS::OS_LINUX;
#endif // else stays unknown
// returns something meaningful for basically all important platforms
info.os_version_ = QSysInfo::productVersion();
// identify architecture
if (QSysInfo::WordSize == 32)
{
info.arch_ = OpenMS_Architecture::ARCH_32BIT;
}
else
{
info.arch_ = OpenMS_Architecture::ARCH_64BIT;
}
return info;
}
};
/// @brief Struct with some static methods to get informations on the build configuration
struct OpenMSBuildInfo
{
public:
/// @brief Checks if OpenMP was enabled during build, based on the _OPENMP macro
static bool isOpenMPEnabled()
{
#ifdef _OPENMP
return true;
#else
return false;
#endif
}
/// @brief Get the build type used during building the OpenMS library
static String getBuildType()
{
return OPENMS_BUILD_TYPE;
}
/// @brief Get the maximum number of threads that OpenMP will use (including hyperthreads)
/// Note: This could also be limited by the OMP_NUM_THREADS environment variable
/// Returns 1 if OpenMP was disabled.
static Size getOpenMPMaxNumThreads()
{
#ifdef _OPENMP
return omp_get_max_threads();
#else
return 1;
#endif
}
/// @brief Set the number of threads that OpenMP will use (including hyperthreads)
/// Note: Can be initialized by the OMP_NUM_THREADS environment variable. This function can overwrite this at runtime.
static void setOpenMPNumThreads(Int num_threads)
{
#ifdef _OPENMP
omp_set_num_threads(num_threads);
#endif
(void)num_threads; // avoid 'unreferenced formal parameter' C4100 on Windows
}
};
} // NS Internal
} // NS OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/SYSTEM/SIMDe.h | .h | 1,521 | 43 | // 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 $
// --------------------------------------------------------------------------
#pragma once
//
// + Use this header whenever you want to make use of SIMDe, since it ensures
// + better cross-platform experience (defining missing operators on simde__m128i etc)
// + you are only using the SIMDe features backed by the build system (i.e. compile flags, e.g. '-mssse3')
//
// + Include it only in .cpp files, never in a header, since we do not want to expose the
// SIMDe internals to the outside world
//
// if you want to upgrade to anything more advanced (e.g. SSE4, or AVX),
// add the respective compile flags to <git>/cmake/compiler_flags.cmake
#include <simde/x86/ssse3.h>
// these operators are defined for GCC/clang, but not in MSVC (TODO: maybe use SFINAE, but that is overkill for the moment)
#ifdef _MSC_VER
inline simde__m128i operator|(const simde__m128i& left, const simde__m128i& right)
{
return simde_mm_or_si128(left, right);
}
inline simde__m128i& operator|=(simde__m128i& left, const simde__m128i& right)
{
left = simde_mm_or_si128(left, right);
return left;
}
inline simde__m128i operator&(const simde__m128i left, const simde__m128i& right)
{
return simde_mm_and_si128(left, right);
}
#endif
namespace OpenMS
{
} | Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/SYSTEM/RWrapper.h | .h | 2,998 | 89 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/config.h>
#include <QtCore/QString>
#include <QtCore/qcontainerfwd.h> // for QStringList
namespace OpenMS
{
class String;
/**
@brief R-Wrapper Class.
Call R scripts from OpenMS, mainly to produce
plots.
@ingroup System
*/
class OPENMS_DLLAPI RWrapper
{
public:
/**
@brief Look for an R script in the share/OpenMS/SCRIPT folder
The script filename can be an absolute filename (in which case the filename is returned unchanged),
or a relative filename or just a filename. In the latter cases, the script will be searched
in the OpenMS 'SCRIPTS' path (share/OpenMS/SCRIPTS) and the full filename will be returned.
An exception will be thrown if the file cannot be found.
@param[in] script_file Name of the R script
@param[in] verbose Print error message to OPENMS_LOG_ERROR upon FileNotFound
@return Full filename with absolute path
@throw Exception::FileNotFound
*/
static String findScript(const String& script_file, bool verbose = true);
/**
@brief Check for presence of 'Rscript'.
@param[in] executable Name of the R interpreter
@param[in] verbose Print failure information?
@return Success status
*/
static bool findR(const QString& executable = QString("Rscript"), bool verbose = true);
/**
@brief Run an R script with certain arguments on the command line
The following checks are done before running the script:
1) [optional] 'Rscript' executable is searched (see findR() -- set @p find_R to true)
2) The script_file is searched in 'OpenMS/share/SCRIPTS' (see findScript()).
3) The script is run as $ Rscript <path/to/script> <arg1> <arg2> ...
If any of the above steps fail, an error message is printed and false is returned.
The 'cmd_args' are passed via commandline and should be read by the R script using R' commandArgs() function.
Usually, the args are input and output filenames.
@param[in] script_file Filename of the R script
@param[in] cmd_args Command line arguments to the script
@param[in] executable Name of the R interpreter
@param[in] find_R Run findR()? May be skipped if runScript() is run repeatedly
@param[in] verbose Print status information; also passed internally to findR() and findScript().
@return Success status
*/
static bool runScript(const String& script_file, const QStringList& cmd_args, const QString& executable = QString("Rscript"), bool find_R = false, bool verbose = true);
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/SpecArrayFile.h | .h | 3,298 | 111 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/CONCEPT/Exception.h>
#include <OpenMS/KERNEL/Feature.h>
#include <OpenMS/FORMAT/TextFile.h>
#include <fstream>
#include <vector>
namespace OpenMS
{
/**
@brief File adapter for SpecArray (.pepList) files.
The first line is the header and contains the column names:<br>
m/z rt(min) snr charge intensity
Every subsequent line is a feature.
Entries are separated by Tab (\\t).
@ingroup FileIO
*/
class OPENMS_DLLAPI SpecArrayFile
{
public:
/// Default constructor
SpecArrayFile();
/// Destructor
virtual ~SpecArrayFile();
/**
@brief Loads a SpecArray file into a featureXML.
The content of the file is stored in @p features.
@exception Exception::FileNotFound is thrown if the file could not be opened
@exception Exception::ParseError is thrown if an error occurs during parsing
*/
template <typename FeatureMapType>
void load(const String& filename, FeatureMapType& feature_map)
{
// load input
TextFile input(filename, false);
// reset map
FeatureMapType 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;
std::vector<String> parts;
line.split('\t', parts);
if (parts.size() < 5)
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "", String("Failed to convert line") + String((it - input.begin()) + 1) + "not enough columns (expected 5 or more, got " + String(parts.size()) + ")");
}
Feature f;
try
{
f.setMZ(parts[0].toDouble());
f.setRT(parts[1].toDouble() * 60.0);
f.setMetaValue("s/n", parts[2].toDouble());
f.setCharge(parts[3].toInt());
f.setIntensity(parts[4].toDouble());
}
catch ( Exception::BaseException& )
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "", String("Failed to convert value into a number (line '") + String((it - input.begin()) + 1) + ")");
}
feature_map.push_back(f);
}
}
/**
@brief Stores a featureXML as a SpecArray file.
NOT IMPLEMENTED
@exception Exception::UnableToCreateFile is thrown if the file could not be created
*/
template <typename SpectrumType>
void store(const String& filename, const SpectrumType& spectrum) const
{
std::cerr << "Store() for SpecArrayFile not implemented. Filename was: " << filename << ", spec of size " << spectrum.size() << "\n";
throw Exception::NotImplemented(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/XTandemXMLFile.h | .h | 4,238 | 143 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/METADATA/PeptideIdentification.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
#include <OpenMS/FORMAT/XMLFile.h>
#include <OpenMS/FORMAT/HANDLERS/XMLHandler.h>
#include <OpenMS/CHEMISTRY/ModificationDefinitionsSet.h>
#include <stack>
namespace OpenMS
{
class String;
class ProteinIdentification;
/**
@brief Used to load XTandemXML files
This class is used to load documents that implement
the schema of XTandemXML files.
@ingroup FileIO
*/
class OPENMS_DLLAPI XTandemXMLFile :
protected Internal::XMLHandler,
public Internal::XMLFile
{
public:
/// Default constructor
XTandemXMLFile();
/// Destructor
~XTandemXMLFile() override;
/**
@brief loads data from an X! Tandem XML file
@param[in] filename the file to be loaded
@param[in] protein_identification protein identifications belonging to the whole experiment
@param[in] id_data the identifications with m/z and RT
@param[in] mod_def_set Fixed and variable modifications defined for the search. May be extended with additional (X! Tandem default) modifications if those are found in the file.
This class serves to read in an X! Tandem XML file. The information can be
retrieved via the load function.
@ingroup FileIO
*/
void load(const String& filename, ProteinIdentification& protein_identification, PeptideIdentificationList& id_data, ModificationDefinitionsSet& mod_def_set);
protected:
// Docu in base class
void startElement(const XMLCh* const /*uri*/, const XMLCh* const /*local_name*/, const XMLCh* const qname, const xercesc::Attributes& attributes) override;
// Docu in base class
void endElement(const XMLCh* const /*uri*/, const XMLCh* const /*local_name*/, const XMLCh* const qname) override;
// Docu in base class
void characters(const XMLCh* const chars, const XMLSize_t /*length*/) override;
XTandemXMLFile(const XTandemXMLFile& rhs);
XTandemXMLFile& operator=(const XTandemXMLFile& rhs);
private:
ProteinIdentification* protein_identification_;
// true during "note" element containing protein accession
bool is_protein_note_;
// true during "note" element containing spectrum ID
bool is_spectrum_note_;
// true after non-new protein entries, so that with the next "protein note" the
// accession will not be updated again
bool skip_protein_acc_update_;
// peptide hits per spectrum
std::map<UInt, std::vector<PeptideHit> > peptide_hits_;
// protein hits
std::vector<ProteinHit> protein_hits_;
// protein unique IDs (assigned by X! Tandem), to keep track of which proteins were already seen
std::set<UInt> protein_uids_;
// accession of the current protein
String current_protein_;
// charge of current peptide
Int current_charge_;
// X! Tandem ID of current peptide
UInt current_id_;
// tag
String tag_;
// start position of current peptide in protein sequence
UInt current_start_;
// stop position of current peptide in protein sequence
UInt current_stop_;
// previous peptide sequence
String previous_seq_;
// mapping from X! Tandem ID to spectrum ID
std::map<UInt, String> spectrum_ids_;
// modification definitions
ModificationDefinitionsSet mod_def_set_;
// modifications used by X! Tandem by default
ModificationDefinitionsSet default_nterm_mods_;
// the possible type attributes of the group tag elements
enum class GroupType
{
MODEL,
PARAMETERS,
SUPPORT
};
// stack of types of the group elements
// they can be nested (e.g. a support group in a model group)
// parsing of child elements sometimes depends on the group type
std::stack<GroupType> group_type_stack_;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/TriqlerFile.h | .h | 6,474 | 178 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/METADATA/ExperimentalDesign.h>
#include <OpenMS/KERNEL/ConsensusMap.h>
#include <OpenMS/FORMAT/TextFile.h>
#include <map>
#include <utility>
#include <unordered_map>
#include <set>
#include <vector>
namespace OpenMS
{
using IndProtGrp = OpenMS::ProteinIdentification::ProteinGroup;
using IndProtGrps = std::vector<IndProtGrp>;
/**
@brief File adapter for Triqler files
@ingroup FileIO
*/
class OPENMS_DLLAPI TriqlerFile
{
public:
/// Default constructor
TriqlerFile() = default;
/// Destructor
~TriqlerFile() = default;
/// store label free experiment
void storeLFQ(const String& filename,
const ConsensusMap &consensus_map,
const ExperimentalDesign& design,
const StringList& reannotate_filenames,
const String& condition);
private:
typedef OpenMS::Peak2D::IntensityType Intensity;
typedef OpenMS::Peak2D::CoordinateType Coordinate;
static const String na_string_;
static const char delim_ = ',';
static const char accdelim_ = ';';
static const char quote_ = '"';
/*
* @brief: Struct to aggregate intermediate information from ConsensusFeature and ConsensusMap,
* such as filenames, intensities, retention times, labels and features (for further processing)
*/
struct AggregatedConsensusInfo
{
std::vector< std::vector< String > > consensus_feature_filenames; //< Filenames of ConsensusFeature
std::vector< std::vector< Intensity > > consensus_feature_intensities; //< Intensities of ConsensusFeature
std::vector< std::vector< Coordinate > > consensus_feature_retention_times; //< Retention times of ConsensusFeature
std::vector< std::vector< unsigned > > consensus_feature_labels; //< Labels of ConsensusFeature
std::vector<BaseFeature> features; //<s Features of ConsensusMap
};
/*
* @brief: Aggregates information from ConsensusFeature and ConsensusMap,
* such as filenames, intensities, retention times, labels and features.
* Stores them in AggregatedConsensusInfo for later processing
*/
TriqlerFile::AggregatedConsensusInfo aggregateInfo_(const ConsensusMap& consensus_map,
const std::vector<String>& spectra_paths);
/*
* @brief: Internal function to check if condition exists in Experimental Design
*/
static void checkConditionLFQ_(const ExperimentalDesign::SampleSection& sampleSection, const String& condition);
/*
* In OpenMS, a run is split into multiple fractions.
*/
static void assembleRunMap_(
std::map< std::pair< String, unsigned>, unsigned> &run_map,
const ExperimentalDesign &design);
/*
* @brief checks two vectors for same content
*/
static bool checkUnorderedContent_(const std::vector< String> &first, const std::vector< String > &second);
OpenMS::Peak2D::IntensityType sumIntensity_(const std::set< OpenMS::Peak2D::IntensityType > &intensities) const
{
OpenMS::Peak2D::IntensityType result = 0;
for (const OpenMS::Peak2D::IntensityType &intensity : intensities)
{
result += intensity;
}
return result;
}
OpenMS::Peak2D::IntensityType meanIntensity_(const std::set< OpenMS::Peak2D::IntensityType > &intensities) const
{
return sumIntensity_(intensities) / intensities.size();
}
class TriqlerLine_
{
public :
TriqlerLine_(
const String& run,
const String& condition,
const String& precursor_charge,
const String& search_score,
const String& intensity,
const String& sequence,
const String& accession
): run_(run),
condition_(condition),
precursor_charge_(precursor_charge),
search_score_(search_score),
intensity_(intensity),
sequence_(sequence),
accession_(accession)
{}
TriqlerLine_(TriqlerLine_&& m) = default;
TriqlerLine_(const TriqlerLine_& m) = default;
/// as string
String toString() const;
friend bool operator<(const TriqlerLine_ &l,
const TriqlerLine_ &r)
{
return std::tie(l.accession_, l.run_, l.condition_, l.precursor_charge_, l.intensity_, l.sequence_) <
std::tie(r.accession_, r.run_, r.condition_, r.precursor_charge_, r.intensity_, r.sequence_);
}
private:
String run_;
String condition_;
String precursor_charge_;
String search_score_;
String intensity_;
String sequence_;
String accession_;
};
using MapSequenceToLines_ = std::map<String, std::set<TriqlerLine_>>;
/*
* @brief Constructs the lines and adds them to the TextFile
* @param[out] peptideseq_quantifyable Has to be a set (only) for deterministic ordered output
*/
void constructFile_(TextFile& csv_out,
const std::set<String>& peptideseq_quantifyable,
const MapSequenceToLines_& peptideseq_to_line) const;
/*
* @brief Constructs the accession to indist. group mapping
*/
static std::unordered_map<OpenMS::String, const IndProtGrp* > getAccessionToGroupMap_(const IndProtGrps& ind_prots);
/*
* @brief Based on the evidence accession set in a PeptideHit, checks if is unique and therefore quantifyable
* in a group context.
*
*/
bool isQuantifyable_(
const std::set<String>& accs,
const std::unordered_map<String, const IndProtGrp*>& accession_to_group) const;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/MS2File.h | .h | 4,507 | 174 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/CONCEPT/Exception.h>
#include <OpenMS/SYSTEM/File.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/METADATA/DocumentIdentifier.h>
#include <vector>
#include <fstream>
namespace OpenMS
{
/**
@brief MS2 input file adapter.
For the format description take a look at:
Rapid Communications in Mass Spectrometry. 2004;18(18):2162-8.
MS1, MS2, and SQT-three unified, compact, and easily parsed file formats for the
storage of shotgun proteomic spectra and identifications.
McDonald WH, Tabb DL, Sadygov RG, MacCoss MJ, Venable J, Graumann J, Johnson JR,
Cociorva D, Yates JR 3rd.
PMID: 15317041
@ingroup FileIO
*/
class OPENMS_DLLAPI MS2File :
public ProgressLogger
{
public:
/// constructor
MS2File();
/// constructor
~MS2File() override;
template <typename MapType>
void load(const String & filename, MapType & exp)
{
//startProgress(0,0,"loading DTA2D file");
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);
}
exp.reset();
//set DocumentIdentifier
exp.setLoadedFileType(filename);
exp.setLoadedFilePath(filename);
std::ifstream in(filename.c_str());
UInt spectrum_number = 0;
typename MapType::SpectrumType spec;
typename MapType::SpectrumType::PeakType p;
String line;
bool first_spec(true);
// line number counter
Size line_number = 0;
while (getline(in, line, '\n'))
{
++line_number;
line.trim();
if (line.empty()) continue;
// header
if (line[0] == 'H')
{
continue;
}
// scan
if (line[0] == 'S')
{
if (!first_spec)
{
spec.setMSLevel(2);
spec.setNativeID(String("index=") + (spectrum_number++));
exp.addSpectrum(spec);
}
else
{
first_spec = false;
}
spec.clear(true);
line.simplify();
std::vector<String> split;
line.split(' ', split);
if (split.size() != 4)
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "line (" + String(line_number) + ") '" + line + "' should contain four values, got " + String(split.size()) + "!", "");
}
spec.getPrecursors().resize(1);
spec.getPrecursors()[0].setMZ(split[3].toDouble());
continue;
}
// charge-independent analysis
if (line[0] == 'I')
{
continue;
}
// charge specification
if (line[0] == 'Z')
{
continue;
}
// charge-dependent analysis
if (line[0] == 'D')
{
continue;
}
// yet another peak, hopefully
line.simplify();
std::vector<String> split;
line.split(' ', split);
if (split.size() != 2)
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "line (" + String(line_number) + ") '" + line + "' should contain two values, got " + String(split.size()) + "!", "");
}
try
{
p.setPosition(split[0].toDouble());
p.setIntensity(split[1].toFloat());
}
catch ( Exception::ConversionError& )
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "ConversionError: line (" + String(line_number) + ") '" + line + "' does not contain two numbers!", "");
}
spec.push_back(p);
}
if (!first_spec)
{
spec.setMSLevel(2);
spec.setNativeID(String("index=") + (spectrum_number++));
exp.addSpectrum(spec);
}
exp.updateRanges();
}
protected:
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/OMSSAXMLFile.h | .h | 4,149 | 134 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/FORMAT/HANDLERS/XMLHandler.h>
#include <OpenMS/FORMAT/XMLFile.h>
#include <OpenMS/METADATA/ProteinIdentification.h>
#include <OpenMS/METADATA/PeptideIdentification.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
#include <OpenMS/CHEMISTRY/ResidueModification.h>
#include <OpenMS/CHEMISTRY/ModificationDefinitionsSet.h>
#include <vector>
namespace OpenMS
{
class String;
class ModificationsDB;
/**
@brief Used to load OMSSAXML files
This class is used to load documents that implement
the schema of OMSSAXML files.
@ingroup FileIO
*/
class OPENMS_DLLAPI OMSSAXMLFile :
protected Internal::XMLHandler,
public Internal::XMLFile
{
public:
/// Default constructor
OMSSAXMLFile();
/// Destructor
~OMSSAXMLFile() override;
/**
@brief loads data from a OMSSAXML file
@param[in] filename The file to be loaded
@param[in] protein_identification Protein identifications belonging to the whole experiment
@param[in] id_data The identifications with m/z and RT
@param[in] load_proteins If this flag is set to false, the protein identifications are not loaded
@param[in] load_empty_hits Many spectra will not return a hit. Report empty peptide identifications?
This class serves to read in a OMSSAXML file. The information can be
retrieved via the load function.
@exception FileNotFound
@exception ParseError
@ingroup FileIO
*/
void load(const String& filename,
ProteinIdentification& protein_identification,
PeptideIdentificationList& id_data,
bool load_proteins = true,
bool load_empty_hits = true);
/// sets the valid modifications
void setModificationDefinitionsSet(const ModificationDefinitionsSet& rhs);
protected:
// Docu in base class
void endElement(const XMLCh* const /*uri*/, const XMLCh* const /*local_name*/, const XMLCh* const qname) override;
// Docu in base class
void startElement(const XMLCh* const /*uri*/, const XMLCh* const /*local_name*/, const XMLCh* const qname, const xercesc::Attributes& attributes) override;
// Docu in base class
void characters(const XMLCh* const chars, const XMLSize_t /*length*/) override;
private:
OMSSAXMLFile(const OMSSAXMLFile& rhs);
OMSSAXMLFile& operator=(const OMSSAXMLFile& rhs);
/// reads the mapping file needed for modifications
void readMappingFile_();
/// the identifications (storing the peptide hits)
PeptideIdentificationList* peptide_identifications_;
ProteinHit actual_protein_hit_;
PeptideHit actual_peptide_hit_;
PeptideEvidence actual_peptide_evidence_;
std::vector<PeptideEvidence> actual_peptide_evidences_;
PeptideIdentification actual_peptide_id_;
ProteinIdentification actual_protein_id_;
String tag_;
/// site of the actual modification (simple position in the peptide)
UInt actual_mod_site_;
/// type of the modification
String actual_mod_type_;
/// modifications of the peptide defined by site and type
std::vector<std::pair<UInt, String> > modifications_;
/// should protein hits be read from the file?
bool load_proteins_;
/// should empty peptide identifications be loaded or skipped?
bool load_empty_hits_;
/// modifications mapping file from OMSSA mod num to UniMod accession
std::map<UInt, std::vector<const ResidueModification*> > mods_map_;
/// modification mapping reverse, from the modification to the mod_num
std::map<String, UInt> mods_to_num_;
/// modification definitions set of the search, needed to annotate fixed modifications
ModificationDefinitionsSet mod_def_set_;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/ParamCWLFile.h | .h | 1,733 | 50 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Authors: Simon Gene Gottlieb $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/FORMAT/ParamCTDFile.h>
namespace OpenMS
{
/**
@brief Exports .cwl files.
If Names include ':' it will be replaced with "__";
*/
class OPENMS_DLLAPI ParamCWLFile
{
public:
/**
\brief If set to true, all parameters will be listed without nesting when writing the CWL File.
The names will be expanded to include the nesting hierarchy.
*/
bool flatHierarchy{};
/**
@brief Write CWL file
@param[out] filename The name of the file the param data structure should be stored in.
@param[in] param The param data structure that should be stored.
@param[out] tool_info Additional information about the Tool for which the param data should be stored.
@exception std::ios::failure is thrown if the file could not be created
*/
void store(const std::string& filename, const Param& param, const ToolInfo& tool_info) const;
/**
@brief Write CWL to output stream.
@param[out] os_ptr The stream to which the param data should be written.
@param[out] param The param data structure that should be writte to stream.
@param[out] tool_info Additional information about the Tool for which the param data should be written.
*/
void writeCWLToStream(std::ostream* os_ptr, const Param& param, const ToolInfo& tool_info) const;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/Bzip2InputStream.h | .h | 2,470 | 95 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <xercesc/util/BinInputStream.hpp>
#include <xercesc/util/PlatformUtils.hpp>
#include <OpenMS/FORMAT/Bzip2Ifstream.h>
namespace OpenMS
{
class String;
/**
* @brief Implements the BinInputStream class of the xerces-c library in order to read bzip2 compressed XML files.
*
*/
class OPENMS_DLLAPI Bzip2InputStream :
public xercesc::BinInputStream
{
public:
///Constructor
explicit Bzip2InputStream(const String& file_name);
explicit Bzip2InputStream(const char* const file_name);
///Destructor
~Bzip2InputStream() override;
///returns true if file is open
bool getIsOpen() const;
/**
* @brief returns the current position in the file
*
* @note Implementation of the xerces-c input stream interface
*/
XMLFilePos curPos() const override;
/**
* @brief writes bytes into buffer from file
*
* @note Implementation of the xerces-c input stream interface
*
* @param[out] to_fill is the buffer which is written to
* @param[in] max_to_read is the size of the buffer
*
* @return returns the number of bytes which were actually read
*
*/
XMLSize_t readBytes(XMLByte* const to_fill, const XMLSize_t max_to_read) override;
/**
* @brief returns 0
*
* @note Implementation of the xerces-c input stream interface
*
* If no content type is provided for the data, 0 is returned (as is the
* case here, see xerces docs).
*
*/
const XMLCh* getContentType() const override;
private:
///pointer to an compression stream
Bzip2Ifstream* bzip2_;
///current index of the actual file
XMLSize_t file_current_index_;
//not implemented
Bzip2InputStream();
Bzip2InputStream(const Bzip2InputStream& stream);
Bzip2InputStream& operator=(const Bzip2InputStream& stream);
};
inline XMLFilePos Bzip2InputStream::curPos() const
{
return file_current_index_;
}
inline bool Bzip2InputStream::getIsOpen() const
{
return bzip2_->isOpen();
}
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/PercolatorInfile.h | .h | 4,291 | 90 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/METADATA/PeptideIdentification.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
#include <OpenMS/FORMAT/TextFile.h>
#include <vector>
namespace OpenMS
{
/**
@brief Class for storing Percolator tab-delimited input files.
*/
class OPENMS_DLLAPI PercolatorInfile
{
public:
static void store(const String& pin_file,
const PeptideIdentificationList& peptide_ids,
const StringList& feature_set,
const std::string& enz,
int min_charge,
int max_charge);
/**
* @brief Loads peptide identifications from a Percolator input file.
*
* This function reads a Percolator input file (`pin_file`) and returns a vector of `PeptideIdentification` objects.
* It extracts relevantinformation such as peptide sequences, scores, charges, annotations, and protein accessions, applying
* specified thresholds and handling decoy targets as needed.
* Note: If a filename column is encountered the set of @p filenames is filled in the order of appearance and PeptideIdentifications annotated with the id_merge_index meta value to link them to the filename (similar to a merged idXML file).
*
* @param[in] pin_file he path to the Percolator input file with a `.pin` extension.
*
* @param[in] higher_score_better A boolean flag indicating whether higher scores are considered better (`true`) or lower scores are better (`false`).
*
* @param[in] score_name The name of the primary score to be used for ranking peptide hits.
*
* @param[out] extra_scores A list of additional score names that should be extracted and stored in each `PeptideHit`.
*
* @param[out] filenames Will be populated with the unique raw file names extracted from the input data.
*
* @param[in] decoy_prefix The prefix used to identify decoy protein accessions. Proteins with accessions starting with this prefix are marked as decoys. Otherwise, it assumes that the pin file already contains the correctly annotated decoy status.
* @param[in] threshold A double value representing the threshold for the `spectrum_q` value. Only spectra with `spectrum_q` below this threshold are processed.
Implemented to allow prefiltering of Sage results.
* @param[in] SageAnnotation A boolean value used to determine if the pin file is coming from Sage or not
* @return A `std::vector` of `PeptideIdentification` objects containing the peptide identifications.
* @throws `Exception::ParseError` if any line in the input file does not have the expected number of columns.
* TODO: implement something similar to PepXMLFile().setPreferredFixedModifications(getModifications_(fixed_modifications_names));
*/
static PeptideIdentificationList load(const String& pin_file,
bool higher_score_better,
const String& score_name,
const StringList& extra_scores,
StringList& filenames,
String decoy_prefix = "",
double threshold = 0.01,
bool SageAnnotation = false);
// uses spectrum_reference, if empty uses spectrum_id, if also empty fall back to using index
static String getScanIdentifier(const PeptideIdentification& pid, size_t index);
protected:
//id <tab> label <tab> scannr <tab> calcmass <tab> expmass <tab> feature1 <tab> ... <tab> featureN <tab> peptide <tab> proteinId1 <tab> .. <tab> proteinIdM
static TextFile preparePin_(
const PeptideIdentificationList& peptide_ids,
const StringList& feature_set,
const std::string& enz,
int min_charge,
int max_charge);
static bool isEnz_(const char& n, const char& c, const std::string& enz);
static Size countEnzymatic_(const String& peptide, const std::string& enz);
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/MzTabBase.h | .h | 7,592 | 387 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/CONCEPT/Exception.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <map>
#include <vector>
#include <list>
#include <algorithm>
namespace OpenMS
{
/**
@brief Base functionality to for MzTab data models
@ingroup FileIO
*/
/// MzTab supports null, NaN, Inf for cells with Integer or Double values. MzTabCellType explicitly defines the state of the cell for these types.
enum MzTabCellStateType
{
MZTAB_CELLSTATE_DEFAULT,
MZTAB_CELLSTATE_NULL,
MZTAB_CELLSTATE_NAN,
MZTAB_CELLSTATE_INF,
SIZE_OF_MZTAB_CELLTYPE
};
class OPENMS_DLLAPI MzTabDouble
{
public:
MzTabDouble();
explicit MzTabDouble(const double v);
void set(const double& value);
double get() const;
String toCellString() const;
void fromCellString(const String& s);
bool isNull() const;
void setNull(bool b);
bool isNaN() const;
void setNaN();
bool isInf() const;
void setInf();
~MzTabDouble() = default;
bool operator<(const MzTabDouble& rhs) const;
bool operator==(const MzTabDouble& rhs) const;
protected:
double value_;
MzTabCellStateType state_;
};
class OPENMS_DLLAPI MzTabDoubleList
{
public:
MzTabDoubleList() = default;
bool isNull() const;
void setNull(bool b);
String toCellString() const;
void fromCellString(const String& s);
std::vector<MzTabDouble> get() const;
void set(const std::vector<MzTabDouble>& entries);
~MzTabDoubleList() = default;
protected:
std::vector<MzTabDouble> entries_;
};
class OPENMS_DLLAPI MzTabInteger
{
public:
MzTabInteger();
explicit MzTabInteger(const int v);
void set(const Int& value);
Int get() const;
String toCellString() const;
void fromCellString(const String& s);
bool isNull() const;
void setNull(bool b);
bool isNaN() const;
void setNaN();
bool isInf() const;
void setInf();
~MzTabInteger() = default;
protected:
Int value_;
MzTabCellStateType state_;
};
class OPENMS_DLLAPI MzTabIntegerList
{
public:
MzTabIntegerList() = default;
bool isNull() const;
void setNull(bool b);
String toCellString() const;
void fromCellString(const String& s);
std::vector<MzTabInteger> get() const;
void set(const std::vector<MzTabInteger>& entries);
~MzTabIntegerList() = default;
protected:
std::vector<MzTabInteger> entries_;
};
class OPENMS_DLLAPI MzTabBoolean
{
public:
MzTabBoolean();
bool isNull() const;
void setNull(bool b);
explicit MzTabBoolean(bool v);
void set(const bool& value);
Int get() const;
String toCellString() const;
void fromCellString(const String& s);
~MzTabBoolean() = default;
protected:
int value_;
};
class OPENMS_DLLAPI MzTabString
{
public:
MzTabString();
explicit MzTabString(const String& s);
bool isNull() const;
void setNull(bool b);
void set(const String& value);
String get() const;
String toCellString() const;
void fromCellString(const String& s);
~MzTabString() = default;
protected:
String value_;
};
typedef std::pair<String, MzTabString> MzTabOptionalColumnEntry; //< column name (not null able), value (null able)
class OPENMS_DLLAPI MzTabParameter
{
public:
MzTabParameter();
bool isNull() const;
void setNull(bool b);
void setCVLabel(const String& CV_label);
void setAccession(const String& accession);
void setName(const String& name);
void setValue(const String& value);
String getCVLabel() const;
String getAccession() const;
String getName() const;
String getValue() const;
String toCellString() const;
void fromCellString(const String& s);
~MzTabParameter() = default;
protected:
String CV_label_;
String accession_;
String name_;
String value_;
};
class OPENMS_DLLAPI MzTabParameterList
{
public:
MzTabParameterList() = default;
bool isNull() const;
void setNull(bool b);
String toCellString() const;
void fromCellString(const String& s);
std::vector<MzTabParameter> get() const;
void set(const std::vector<MzTabParameter>& parameters);
~MzTabParameterList() = default;
protected:
std::vector<MzTabParameter> parameters_;
};
class OPENMS_DLLAPI MzTabStringList
{
public:
MzTabStringList();
bool isNull() const;
void setNull(bool b);
/// needed for e.g. ambiguity_members and GO accessions as these use ',' as separator while the others use '|'
void setSeparator(char sep);
String toCellString() const;
void fromCellString(const String& s);
std::vector<MzTabString> get() const;
void set(const std::vector<MzTabString>& entries);
~MzTabStringList() = default;
protected:
std::vector<MzTabString> entries_;
char sep_;
};
class OPENMS_DLLAPI MzTabSpectraRef
{
public:
MzTabSpectraRef();
bool isNull() const;
void setNull(bool b);
void setMSFile(Size index);
void setSpecRef(const String& spec_ref);
String getSpecRef() const;
Size getMSFile() const;
void setSpecRefFile(const String& spec_ref);
String toCellString() const;
void fromCellString(const String& s);
~MzTabSpectraRef() = default;
protected:
Size ms_run_; //< number is specified in the meta data section.
String spec_ref_;
};
// MTD
struct OPENMS_DLLAPI MzTabSoftwareMetaData
{
MzTabParameter software;
std::map<Size, MzTabString> setting;
};
struct OPENMS_DLLAPI MzTabSampleMetaData
{
MzTabString description;
std::map<Size, MzTabParameter> species;
std::map<Size, MzTabParameter> tissue;
std::map<Size, MzTabParameter> cell_type;
std::map<Size, MzTabParameter> disease;
std::map<Size, MzTabParameter> custom;
};
struct OPENMS_DLLAPI MzTabCVMetaData
{
MzTabString label;
MzTabString full_name;
MzTabString version;
MzTabString url;
};
struct OPENMS_DLLAPI MzTabInstrumentMetaData
{
MzTabParameter name;
MzTabParameter source;
std::map<Size, MzTabParameter> analyzer;
MzTabParameter detector;
};
struct OPENMS_DLLAPI MzTabContactMetaData
{
MzTabString name;
MzTabString affiliation;
MzTabString email;
};
class OPENMS_DLLAPI MzTabBase
{
public:
MzTabBase() = default;
virtual ~MzTabBase() = default;
protected:
/// Helper function for "get...OptionalColumnNames" functions
template <typename SectionRows>
std::vector<String> getOptionalColumnNames_(const SectionRows& rows) const
{
// vector is used to preserve the column order
std::vector<String> names;
for (typename SectionRows::const_iterator it = rows.begin(); it != rows.end(); ++it)
{
for (auto it_opt = it->opt_.cbegin(); it_opt != it->opt_.cend(); ++it_opt)
{
if (std::find(names.begin(), names.end(), it_opt->first) == names.end())
{
names.push_back(it_opt->first);
}
}
}
return names;
}
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/MascotXMLFile.h | .h | 3,097 | 87 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CHEMISTRY/AASequence.h>
#include <OpenMS/FORMAT/XMLFile.h>
#include <OpenMS/FORMAT/HANDLERS/MascotXMLHandler.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/METADATA/PeptideIdentification.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
namespace OpenMS
{
class ProteinIdentification;
/**
@brief Used to load Mascot XML files
This class is used to load documents that implement
the schema of Mascot XML files.
@ingroup FileIO
*/
class OPENMS_DLLAPI MascotXMLFile :
public Internal::XMLFile
{
public:
/// Constructor
MascotXMLFile();
/**
@brief Loads data from a Mascot XML file
@param[in] filename the file to be loaded
@param[in] protein_identification protein identifications belonging to the whole experiment
@param[in] id_data the identifications with m/z and RT
@param[in] lookup helper object for looking up spectrum meta data
@exception Exception::FileNotFound is thrown if the file does not exists.
@exception Exception::ParseError is thrown if the file does not suit to the standard.
*/
void load(const String& filename,
ProteinIdentification& protein_identification,
PeptideIdentificationList& id_data,
const SpectrumMetaDataLookup& lookup);
/**
@brief Loads data from a Mascot XML file
@param[in] filename the file to be loaded
@param[in] protein_identification protein identifications belonging to the whole experiment
@param[in] id_data the identifications with m/z and RT
@param[in,out] peptides a map of modified peptides identified by the String title
@param[in] lookup helper object for looking up spectrum meta data
@exception Exception::FileNotFound is thrown if the file does not exists.
@exception Exception::ParseError is thrown if the file does not suit to the standard.
*/
void load(const String& filename,
ProteinIdentification& protein_identification,
PeptideIdentificationList& id_data,
std::map<String, std::vector<AASequence> >& peptides,
const SpectrumMetaDataLookup& lookup);
/**
@brief Initializes a helper object for looking up spectrum meta data (RT, m/z)
@param[in] lookup Helper object to initialize
@param[in] experiment Experiment containing the spectra
@param[in] scan_regex Optional regular expression for extracting information from references to spectra
*/
static void initializeLookup(SpectrumMetaDataLookup& lookup, const PeakMap& experiment, const String& scan_regex = "");
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/SqliteConnector.h | .h | 11,822 | 351 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/CONCEPT/Exception.h>
#include <type_traits> // for is_same
// forward declarations
struct sqlite3;
struct sqlite3_stmt;
namespace OpenMS
{
/**
@brief File adapter for Sqlite files
This class contains certain helper functions to deal with Sqlite files.
@ingroup FileIO
*/
class OPENMS_DLLAPI SqliteConnector
{
public:
/// how an sqlite db should be opened
enum class SqlOpenMode
{
READONLY, ///< the DB must exist and is read-only
READWRITE, ///< the DB is readable and writable, but must exist when opening it
READWRITE_OR_CREATE ///< the DB readable and writable and is created new if not present already
};
/// Default constructor
SqliteConnector() = delete;
/// Constructor which opens a connection to @p filename
/// @throws Exception::SqlOperationFailed if the file does not exist/cannot be created (depending on @p mode)
explicit SqliteConnector(const String& filename, const SqlOpenMode mode = SqlOpenMode::READWRITE_OR_CREATE);
/// Destructor
~SqliteConnector();
/**
@brief Returns the raw pointer to the database
@note The pointer is tied to the lifetime of the SqliteConnector object,
do not use it after the object has gone out of scope!
@returns SQLite database ptr
*/
sqlite3* getDB()
{
return db_;
}
/**
@brief Checks whether the given table exists
@p tablename The name of the table to be checked
@returns Whether the table exists or not
*/
bool tableExists(const String& tablename)
{
return tableExists(db_, tablename);
}
/// Counts the number of entries in SQL table @p table_name
/// @throws Exception::SqlOperationFailed if table is unknown
Size countTableRows(const String& table_name);
/**
@brief Checks whether the given table contains a certain column
@p tablename The name of the table (needs to exist)
@p colname The name of the column to be checked
@returns Whether the column exists or not
*/
bool columnExists(const String& tablename, const String& colname)
{
return columnExists(db_, tablename, colname);
}
/**
@brief Executes a given SQL statement (insert statement)
This is useful for writing a single row of data
@p statement The SQL statement
@exception Exception::IllegalArgument is thrown if the SQL command fails.
*/
void executeStatement(const String& statement)
{
executeStatement(db_, statement);
}
/**
@brief Executes raw data SQL statements (insert statements)
This is useful for a case where raw data should be inserted into sqlite
databases, and the raw data needs to be passed separately as it cannot be
part of a true SQL statement
INSERT INTO TBL (ID, DATA) VALUES (100, ?1), (101, ?2), (102, ?3)"
See also https://www.sqlite.org/c3ref/bind_blob.html
@p statement The SQL statement
@p data The data to bind
@exception Exception::IllegalArgument is thrown if the SQL command fails.
*/
void executeBindStatement(const String& prepare_statement, const std::vector<String>& data)
{
executeBindStatement(db_, prepare_statement, data);
}
/**
@brief Prepares a SQL statement
This is useful for handling errors in a consistent manner.
@p db The sqlite database (needs to be open)
@p statement The SQL statement
@p data The data to bind
@exception Exception::IllegalArgument is thrown if the SQL command fails.
*/
void prepareStatement(sqlite3_stmt** stmt, const String& prepare_statement)
{
prepareStatement(db_, stmt, prepare_statement);
}
/**
@brief Checks whether the given table exists
@p db The sqlite database (needs to be open)
@p tablename The name of the table to be checked
@returns Whether the table exists or not
*/
static bool tableExists(sqlite3* db, const String& tablename);
/**
@brief Checks whether the given table contains a certain column
@p db The sqlite database (needs to be open)
@p tablename The name of the table (needs to exist)
@p colname The name of the column to be checked
@returns Whether the column exists or not
*/
static bool columnExists(sqlite3* db, const String& tablename, const String& colname);
/**
@brief Executes a given SQL statement (insert statement)
This is useful for writing a single row of data. It wraps sqlite3_exec with proper error handling.
@p db The sqlite database (needs to be open)
@p statement The SQL statement
@exception Exception::IllegalArgument is thrown if the SQL command fails.
*/
static void executeStatement(sqlite3* db, const std::stringstream& statement);
/**
@brief Executes a given SQL statement (insert statement)
This is useful for writing a single row of data. It wraps sqlite3_exec with proper error handling.
@p db The sqlite database (needs to be open)
@p statement The SQL statement
@exception Exception::IllegalArgument is thrown if the SQL command fails.
*/
static void executeStatement(sqlite3* db, const String& statement);
/**
@brief Converts an SQL statement into a prepared statement
This routine converts SQL text into a prepared statement object and
returns a pointer to that object. This interface requires a database
connection created by a prior call to sqlite3_open() and a text string
containing the SQL statement to be prepared. This API does not actually
evaluate the SQL statement. It merely prepares the SQL statement for
evaluation.
This is useful for handling errors in a consistent manner. Internally
calls sqlite3_prepare_v2.
@p db The sqlite database (needs to be open)
@p stmt The prepared statement (output)
@p prepare_statement The SQL statement to prepare (input)
@exception Exception::IllegalArgument is thrown if the SQL command fails.
*/
static void prepareStatement(sqlite3* db, sqlite3_stmt** stmt, const String& prepare_statement);
/**
@brief Executes raw data SQL statements (insert statements)
This is useful for a case where raw data should be inserted into sqlite
databases, and the raw data needs to be passed separately as it cannot be
part of a true SQL statement
INSERT INTO TBL (ID, DATA) VALUES (100, ?1), (101, ?2), (102, ?3)"
See also https://www.sqlite.org/c3ref/bind_blob.html
@p db The sqlite database (needs to be open)
@p statement The SQL statement
@p data The data to bind
@exception Exception::IllegalArgument is thrown if the SQL command fails.
*/
static void executeBindStatement(sqlite3* db, const String& prepare_statement, const std::vector<String>& data);
protected:
/**
@brief Opens a new SQLite database
@param[in] filename Filename of the database
@param[in] mode See SqlOpenMode
@note Call this only once!
*/
void openDatabase_(const String& filename, const SqlOpenMode mode);
protected:
sqlite3* db_ = nullptr;
};
namespace Internal
{
namespace SqliteHelper
{
/// Sql only stores signed 64bit ints, so we remove the highest bit, because some/most
/// of our sql-insert routines first convert to string, which might yield an uint64 which cannot
/// be represented as int64, and sqlite would attempt to store it as double(!), which will loose precision
template <typename T>
UInt64 clearSignBit(T /*value*/)
{
static_assert(std::is_same<T, std::false_type>::value, "Wrong input type to clearSignBit(). Please pass unsigned 64bit ints!");
return 0;
};
/// only allow UInt64 specialization
template <>
inline UInt64 clearSignBit(UInt64 value) {
return value & ~(1ULL << 63);
}
enum class SqlState
{
SQL_ROW,
SQL_DONE,
SQL_ERROR ///< includes SQLITE_BUSY, SQLITE_ERROR, SQLITE_MISUSE
};
/**
@brief retrieves the next row from a prepared statement
If you receive 'SqlState::SQL_DONE', do NOT query nextRow() again,
because you might enter an infinite loop!
To avoid oversights, you can pass the old return value into the function again
and get an Exception which will tell you that there is buggy code!
@param[in] stmt Sqlite statement object
@param[in] current Return value of the previous call to this function.
@return one of SqlState::SQL_ROW or SqlState::SQL_DONE
@throws Exception::SqlOperationFailed if state would be SqlState::ERROR
*/
SqlState nextRow(sqlite3_stmt* stmt, SqlState current = SqlState::SQL_ROW);
/**
@brief Extracts a specific value from an SQL column
@p dst Destination (where to store the value)
@p stmt Sqlite statement object
@p pos Column position
For example, to extract a specific integer from column 5 of an SQL statement, one can use:
sqlite3_stmt* stmt;
sqlite3* db;
SqliteConnector::prepareStatement(db, &stmt, select_sql);
sqlite3_step(stmt);
double target;
while (sqlite3_column_type(stmt, 0) != SQLITE_NULL)
{
extractValue<double>(&target, stmt, 5);
sqlite3_step( stmt );
}
sqlite3_finalize(stmt);
*/
template <typename ValueType>
bool extractValue(ValueType* /* dst */, sqlite3_stmt* /* stmt */, int /* pos */)
{
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Not implemented");
}
template <> bool extractValue<double>(double* dst, sqlite3_stmt* stmt, int pos); //explicit specialization
template <> bool extractValue<int>(int* dst, sqlite3_stmt* stmt, int pos); //explicit specialization
template <> bool extractValue<Int64>(Int64* dst, sqlite3_stmt* stmt, int pos); //explicit specialization
template <> bool extractValue<String>(String* dst, sqlite3_stmt* stmt, int pos); //explicit specialization
template <> bool extractValue<std::string>(std::string* dst, sqlite3_stmt* stmt, int pos); //explicit specialization
/// Special case where an integer should be stored in a String field
bool extractValueIntStr(String* dst, sqlite3_stmt* stmt, int pos);
/** @defgroup sqlThrowingGetters Functions for getting values from sql-select statements
All these function throw Exception::SqlOperationFailed if the given position is of the wrong type.
@{
*/
double extractDouble(sqlite3_stmt* stmt, int pos);
float extractFloat(sqlite3_stmt* stmt, int pos); ///< convenience function; note: in SQL there is no float, just double. So this might be narrowing.
int extractInt(sqlite3_stmt* stmt, int pos);
Int64 extractInt64(sqlite3_stmt* stmt, int pos);
String extractString(sqlite3_stmt* stmt, int pos);
char extractChar(sqlite3_stmt* stmt, int pos);
bool extractBool(sqlite3_stmt* stmt, int pos);
/** @} */ // end of sqlThrowingGetters
}
}
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/MzIdentMLFile.h | .h | 3,272 | 83 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Mathias Walzer $
// $Authors: Andreas Bertsch, Mathias Walzer $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/FORMAT/XMLFile.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/DATASTRUCTURES/StringListUtils.h>
#include <OpenMS/METADATA/ProteinIdentification.h>
#include <OpenMS/METADATA/PeptideIdentification.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
#include <vector>
namespace OpenMS
{
/**
@brief File adapter for MzIdentML files
This file adapter exposes the internal MzIdentML processing capabilities to the library. The file
adapter interface is kept the same as idXML file adapter for downward capability reasons.
For now, read-in will be performed with DOM write-out with STREAM
@note due to the limited capabilities of idXML/PeptideIdentification/ProteinIdentification not all
MzIdentML features can be supported. Development for these structures will be discontinued, a new
interface with appropriate structures will be provided.
@note If a critical error occurs due to the missing functionality, Exception::NotImplemented is thrown.
@note All PSM will be read into PeptideIdentification, even the passThreshold=false, threshold will be
read into ProteinIdentification (i.e. one id run), considered at writing also will only be the
threshold set in ProteinIdentification
@note All PSM will be read into PeptideIdentification, even the passThreshold=false
@ingroup FileIO
*/
class OPENMS_DLLAPI MzIdentMLFile :
public Internal::XMLFile,
public ProgressLogger
{
public:
///Default constructor
MzIdentMLFile();
///Destructor
~MzIdentMLFile() override;
/**
@brief Loads the identifications from a MzIdentML file.
@exception Exception::FileNotFound is thrown if the file could not be opened
@exception Exception::ParseError is thrown if an error occurs during parsing
*/
void load(const String& filename, std::vector<ProteinIdentification>& poid, PeptideIdentificationList& peid);
/**
@brief Stores the identifications in a MzIdentML file.
@exception Exception::UnableToCreateFile is thrown if the file could not be created
*/
void store(const String& filename, const std::vector<ProteinIdentification>& poid, const PeptideIdentificationList& peid) const;
/**
@brief Checks if a file is valid with respect to the mapping file and the controlled vocabulary.
@param[in] filename File name of the file to be checked.
@param[out] errors Errors during the validation are returned in this output parameter.
@param[out] warnings Warnings during the validation are returned in this output parameter.
@exception Exception::FileNotFound is thrown if the file could not be opened
*/
bool isSemanticallyValid(const String& filename, StringList& errors, StringList& warnings);
private:
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/ParamCTDFile.h | .h | 2,818 | 86 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <string>
#include <OpenMS/DATASTRUCTURES/Param.h>
namespace OpenMS
{
/**
@brief A struct to pass information about the tool as one parameter
*/
struct ToolInfo
{
std::string version_;
std::string name_;
std::string docurl_;
std::string category_;
std::string description_;
std::vector<std::string> citations_;
};
/**
@brief Serializes a Param class in paramCTD file format.
Note: only storing is currently possible
*/
class OPENMS_DLLAPI ParamCTDFile
{
public:
ParamCTDFile() = default; ///Constructor
~ParamCTDFile() = default; ///Destructor
/**
@brief Write CTD file
@param[out] filename The name of the file the param data structure should be stored in.
@param[in] param The param data structure that should be stored.
@param[out] tool_info Additional information about the Tool for which the param data should be stored.
@exception std::ios::failure is thrown if the file could not be created
*/
void store(const std::string& filename, const Param& param, const ToolInfo& tool_info) const;
/**
@brief Write CTD to output stream.
@param[out] os_ptr The stream to which the param data should be written.
@param[out] param The param data structure that should be writte to stream.
@param[out] tool_info Additional information about the Tool for which the param data should be written.
*/
void writeCTDToStream(std::ostream* os_ptr, const Param& param, const ToolInfo& tool_info) const;
private:
/**
@brief Escapes certain characters in a string that are not allowed in XML
Escaped characters are: & < > " '
@param[in] to_escape The string in which the characters should be escaped
@returns The escaped string
*/
static std::string escapeXML(const std::string& to_escape);
/**
@brief Replace all occurrences of a character in a string with a string
@param[in] replace_in The string in which the characters should be replaced.
@param[in] to_replace The character that should be replaced.
@param[in] replace_with The string the character should be replaced with.
*/
static void replace(std::string& replace_in, char to_replace, const std::string& replace_with);
const std::string schema_location_ = "/SCHEMAS/Param_1_8_0.xsd";
const std::string schema_version_ = "1.8.0";
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/TextFile.h | .h | 4,325 | 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/StringListUtils.h>
namespace OpenMS
{
/**
@brief This class provides some basic file handling methods for text files.
@ingroup FileIO
*/
class OPENMS_DLLAPI TextFile
{
public:
/** @name Type definitions
*/
//@{
/// Mutable iterator
typedef std::vector<String>::iterator Iterator;
/// Non-mutable iterator
typedef std::vector<String>::const_iterator ConstIterator;
/// Mutable reverse iterator
typedef std::vector<String>::reverse_iterator ReverseIterator;
/// Non-mutable reverse iterator
typedef std::vector<String>::const_reverse_iterator ConstReverseIterator;
//@}
///Default constructor
TextFile();
/// destructor
virtual ~TextFile();
/**
@brief Constructor with filename
@param[in] filename The input file name
@param[in] trim_lines Whether or not the lines are trimmed when reading them from file
@param[in] first_n If set, only @p first_n lines the lines from the beginning of the file are read
@param[in] skip_empty_lines Should empty lines be skipped? If used in conjunction with @p trim_lines, also lines with only whitespace will be skipped. Skipped lines do not count towards the total number of read lines.
@param[in] comment_symbol Lines prefixed with this string are skipped. Comment lines do not count towards the total number of read lines.
@exception Exception::FileNotFound is thrown if the file could not be opened.
*/
TextFile(const String& filename, bool trim_lines = false, Int first_n = -1, bool skip_empty_lines = false, const String& comment_symbol = "");
/**
@brief Loads data from a text file into the internal buffer.
Retrieve the data using begin() and end().
@param[in] filename The input file name
@param[in] trim_lines Whether or not the lines are trimmed when reading them from file
@param[in] first_n If set, only @p first_n lines the lines from the beginning of the file are read
@param[in] skip_empty_lines Should empty lines be skipped? If used in conjunction with @p trim_lines, also lines with only whitespace will be skipped. Skipped lines do not count towards the total number of read lines.
@param[in] comment_symbol Lines prefixed with this string are skipped. Comment lines do not count towards the total number of read lines.
@exception Exception::FileNotFound is thrown if the file could not be opened.
*/
void load(const String& filename, bool trim_lines = false, Int first_n = -1, bool skip_empty_lines = false, const String& comment_symbol = "");
/**
@brief Writes the data to a file
@param[in] filename The output file name
@note This function uses platform-dependent line breaks
@exception Exception::UnableToCreateFile is thrown if the file could not be created
*/
void store(const String& filename);
/// Operator for appending entries with less code
template <typename StringType>
TextFile& operator<<(const StringType& string)
{
buffer_.push_back(static_cast<String>(string));
return *this;
}
template <typename StringType>
void addLine(const StringType& line)
{
buffer_.push_back(static_cast<String>(line));
}
/**
@brief Platform-agnostic getline() which can deal with all line endings (\\r, \\r\\n, \\n)
Line endings will be removed from the resulting string.
*/
static std::istream& getLine(std::istream& is, std::string& t);
/**
@brief Gives access to the underlying text buffer.
*/
ConstIterator begin() const;
Iterator begin();
/**
@brief Gives access to the underlying text buffer.
*/
ConstIterator end() const;
Iterator end();
protected:
/// Internal buffer storing the lines before writing them to the file.
std::vector<String> buffer_;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/AbsoluteQuantitationMethodFile.h | .h | 2,751 | 82 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/ANALYSIS/QUANTITATION/AbsoluteQuantitationMethod.h>
#include <OpenMS/FORMAT/CsvFile.h>
#include <map>
namespace OpenMS
{
/**
@brief File adapter for AbsoluteQuantitationMethod files.
Loads and stores .csv or .tsv files describing an AbsoluteQuantitationMethod.
@ingroup FileIO
*/
class OPENMS_DLLAPI AbsoluteQuantitationMethodFile :
private CsvFile
{
public:
///Default constructor
AbsoluteQuantitationMethodFile() = default;
///Destructor
~AbsoluteQuantitationMethodFile() override = default;
/**
@brief Loads an AbsoluteQuantitationMethod file.
@exception Exception::FileNotFound is thrown if the file could not be opened
@exception Exception::ParseError is thrown if an error occurs during parsing
@param[in] filename The input file name.
@param[out] aqm_list Output variable where the AbsoluteQuantitationMethod data is loaded.
*/
void load(const String & filename, std::vector<AbsoluteQuantitationMethod> & aqm_list);
/**
@brief Stores an AbsoluteQuantitationMethod file.
@exception Exception::UnableToCreateFile is thrown if the file could not be created
@param[in] filename The output file name.
@param[in] aqm_list The AbsoluteQuantitationMethod data to write into the file.
*/
void store(const String & filename, const std::vector<AbsoluteQuantitationMethod> & aqm_list);
protected:
/**
@brief Parses a line into the members of AbsoluteQuantitationMethod.
@param[in] line A line of the .csv file.
@param[in] headers A map of header strings to column positions.
@param[out] aqm AbsoluteQuantitationMethod.
*/
void parseLine_(
const StringList & line,
const std::map<String, Size> & headers,
AbsoluteQuantitationMethod & aqm
) const;
/**
@brief Helper method which takes care of converting the given value to the desired type,
based on the header (here `key`) information.
@param[in] key The header name with which the correct conversion is chosen
@param[in] value The value to be converted
@param[in,out] params The object where the new value is saved
*/
void setCastValue_(const String& key, const String& value, Param& params) const;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/DTAFile.h | .h | 6,846 | 230 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/CONCEPT/Constants.h>
#include <OpenMS/METADATA/Precursor.h>
#include <OpenMS/SYSTEM/File.h>
#include <fstream>
#include <vector>
namespace OpenMS
{
/**
@brief File adapter for DTA files.
The first line contains the singly protonated peptide mass (MH+) and the
peptide charge state separated by a space. Subsequent lines contain space
separated pairs of fragment ion m/z and intensity values.
From precursor mass and charge state the mass-charge-ratio is calculated
and stored in the spectrum as precursor mass.
@ingroup FileIO
*/
class OPENMS_DLLAPI DTAFile
{
public:
/// Default constructor
DTAFile();
/// Destructor
virtual ~DTAFile();
/**
@brief Loads a DTA file to a spectrum.
The content of the file is stored in @p spectrum.
@p spectrum has to be a MSSpectrum or have the same interface.
@exception Exception::FileNotFound is thrown if the file could not be opened
@exception Exception::ParseError is thrown if an error occurs during parsing
*/
template <typename SpectrumType>
void load(const String & filename, SpectrumType & spectrum)
{
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);
}
}
// delete old spectrum
spectrum.clear(true);
// temporary variables
String line;
std::vector<String> strings(2);
typename SpectrumType::PeakType p;
char delimiter;
// line number counter
Size line_number = 1;
// read first line and store precursor m/z and charge
getline(is, line, '\n');
line.trim();
// test which delimiter is used in the line
if (line.has('\t'))
{
delimiter = '\t';
}
else
{
delimiter = ' ';
}
line.split(delimiter, strings);
if (strings.size() != 2)
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, std::string("Bad data line (" + String(line_number) + "): \"") + line + "\" (got " + String(strings.size()) + ", expected 2 entries)", filename);
}
Precursor precursor;
double mh_mass;
Int charge;
try
{
// by convention the first line holds: singly protonated peptide mass, charge state
mh_mass = strings[0].toDouble();
charge = strings[1].toInt();
}
catch (...)
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, std::string("Bad data line (" + String(line_number) + "): \"") + line + "\": not a float number.", filename);
}
if (charge != 0)
{
precursor.setMZ((mh_mass - Constants::PROTON_MASS_U) / charge + Constants::PROTON_MASS_U);
}
else
{
precursor.setMZ(mh_mass);
}
precursor.setCharge(charge);
spectrum.getPrecursors().push_back(precursor);
spectrum.setMSLevel(default_ms_level_);
while (getline(is, line, '\n'))
{
++line_number;
line.trim();
if (line.empty()) continue;
//test which delimiter is used in the line
if (line.has('\t'))
{
delimiter = '\t';
}
else
{
delimiter = ' ';
}
line.split(delimiter, strings);
if (strings.size() != 2)
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, std::string("Bad data line (" + String(line_number) + "): \"") + line + "\" (got " + String(strings.size()) + ", expected 2 entries)", filename);
}
try
{
//fill peak
p.setPosition((typename SpectrumType::PeakType::PositionType)strings[0].toDouble());
p.setIntensity((typename SpectrumType::PeakType::IntensityType)strings[1].toDouble());
}
catch (Exception::BaseException & /*e*/)
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, std::string("Bad data line (" + String(line_number) + "): \"") + line + "\": not a float number.", filename);
}
spectrum.push_back(p);
}
spectrum.setName(File::basename(filename));
is.close();
}
/**
@brief Stores a spectrum in a DTA file.
The content of @p spectrum is stored in a file.
@p spectrum has to be a MSSpectrum or have the same interface.
@exception Exception::UnableToCreateFile is thrown if the file could not be created
*/
template <typename SpectrumType>
void store(const String & filename, const SpectrumType & spectrum) const
{
std::ofstream os(filename.c_str());
if (!os)
{
throw Exception::UnableToCreateFile(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename);
}
os.precision(writtenDigits<double>(0.0));
// write precursor information
Precursor precursor;
if (spectrum.getPrecursors().size() > 0)
{
precursor = spectrum.getPrecursors()[0];
}
if (spectrum.getPrecursors().size() > 1)
{
std::cerr << "Warning: The spectrum written to the DTA file '" << filename << "' has more than one precursor. The first precursor is used!" << "\n";
}
// unknown charge
if (precursor.getCharge() == 0)
{
os << precursor.getMZ();
}
// known charge
else
{
os << ((precursor.getMZ() - 1.0) * precursor.getCharge() + 1.0);
}
// charge
os << " " << precursor.getCharge() << "\n";
// iterate over all peaks of the spectrum and
// write one line for each peak of the spectrum.
typename SpectrumType::ConstIterator it(spectrum.begin());
for (; it != spectrum.end(); ++it)
{
// write m/z and intensity
os << it->getPosition() << " " << it->getIntensity() << "\n";
}
// done
os.close();
}
protected:
/// Default MS level used when reading the file
UInt default_ms_level_;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/ToolDescriptionFile.h | .h | 1,603 | 56 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/FORMAT/XMLFile.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/DATASTRUCTURES/StringListUtils.h>
#include <OpenMS/DATASTRUCTURES/ToolDescription.h>
namespace OpenMS
{
/**
@brief File adapter for ToolDescriptor files
If a critical error occurs due to the missing functionality, Exception::NotImplemented is thrown.
@ingroup FileIO
*/
class OPENMS_DLLAPI ToolDescriptionFile :
public Internal::XMLFile,
public ProgressLogger
{
public:
///Default constructor
ToolDescriptionFile();
///Destructor
~ToolDescriptionFile() override;
/**
@brief Loads a map from a ToolDescriptor file.
@exception Exception::FileNotFound is thrown if the file could not be opened
@exception Exception::ParseError is thrown if an error occurs during parsing
*/
void load(const String & filename, std::vector<Internal::ToolDescription> & tds);
/**
@brief Stores a map in a ToolDescriptor file.
@exception Exception::UnableToCreateFile is thrown if the file could not be created
*/
void store(const String & filename, const std::vector<Internal::ToolDescription> & tds) const;
private:
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/AbsoluteQuantitationStandardsFile.h | .h | 2,378 | 64 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/config.h> // OPENMS_DLLAPI
#include <OpenMS/FORMAT/CsvFile.h>
#include <OpenMS/METADATA/AbsoluteQuantitationStandards.h>
namespace OpenMS
{
/**
@brief Load files containing runConcentration data.
*/
class OPENMS_DLLAPI AbsoluteQuantitationStandardsFile
{
public:
AbsoluteQuantitationStandardsFile() = default;
virtual ~AbsoluteQuantitationStandardsFile() = default;
/**
@brief Load runConcentration data from a file and save it in memory.
An example of the format expected:
> sample_name,component_name,IS_component_name,actual_concentration,IS_actual_concentration,concentration_units,dilution_factor
> 150516_CM1_Level1,23dpg.23dpg_1.Light,23dpg.23dpg_1.Heavy,0,1,uM,1
> 150516_CM1_Level1,2mcit.2mcit_1.Light,2mcit.2mcit_1.Heavy,0,1,uM,1
> 150516_CM1_Level1,2obut.2obut_1.Light,2obut.2obut_1.Heavy,0,1,uM,1
@param[in] filename The file path from which the method is reading the data
@param[out] run_concentrations Where the runConcentration data is going to be saved
*/
void load(
const String& filename,
std::vector<AbsoluteQuantitationStandards::runConcentration>& run_concentrations
) const;
protected:
/**
@brief Extract one runConcentration from a single line
Any missing information is going to be filled with default data:
- an empty string for String data
- the value 0.0 for concentration values
- the value 1.0 for dilution factor
The `headers` argument makes sure that the data is taken from the correct column/position in `line`.
@param[in] line A list of strings each containing a column's info
@param[in] headers A mapping from header name to position in the StringList given in input
*/
AbsoluteQuantitationStandards::runConcentration extractRunFromLine_(
const StringList& line,
const std::map<String, Size>& headers
) const;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/OMSSACSVFile.h | .h | 1,558 | 52 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/METADATA/ProteinIdentification.h>
#include <OpenMS/METADATA/PeptideIdentification.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
#include <vector>
namespace OpenMS
{
class String;
/**
@brief File adapter for OMSSACSV files.
The files contain the results of the OMSSA algorithm in a comma separated manner. This file adapter is able to
load the data from such a file into the structures of OpenMS
@ingroup FileIO
*/
class OPENMS_DLLAPI OMSSACSVFile
{
public:
/// Default constructor
OMSSACSVFile();
/// Destructor
virtual ~OMSSACSVFile();
/**
@brief Loads a OMSSA file
@param[in] filename the name of the file to read from
@param[in] protein_identification the protein ProteinIdentification data
@param[in] id_data the peptide ids of the file
@throw FileNotFound is thrown if the given file could not be found
@throw ParseError is thrown if the given file could not be parsed
*/
void load(const String & filename, ProteinIdentification & protein_identification, PeptideIdentificationList & id_data) const;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/PepNovoOutfile.h | .h | 3,032 | 83 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CONCEPT/Exception.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/METADATA/PeptideIdentification.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
#include <vector>
#include <map>
namespace OpenMS
{
class ProteinIdentification;
/**
@brief Representation of a PepNovo output file
This class serves to read in a PepNovo outfile. The information can be
retrieved via the load function.
@ingroup FileIO
*/
class OPENMS_DLLAPI PepNovoOutfile
{
public:
typedef std::map<Size, std::pair<double, double> > IndexPosMappingType;
/// Constructor
PepNovoOutfile();
/// copy constructor
PepNovoOutfile(const PepNovoOutfile & pepnovo_outfile);
/// destructor
virtual ~PepNovoOutfile();
/// assignment operator
PepNovoOutfile & operator=(const PepNovoOutfile & pepnovo_outfile);
/// equality operator
bool operator==(const PepNovoOutfile & pepnovo_outfile) const;
/**
@brief loads data from a PepNovo outfile
@param[in] result_filename the file to be loaded
@param[in] peptide_identifications the peptide identifications
@param[in] protein_identification the protein identification
@param[in] score_threshold cutoff threshold for the PepNovo score (PnvScr)
@param[out] id_rt_mz map the spectrum identifiers returned by PepNovo
to the rt and mz values of the spectrum (used to map the identifications back to the spectra). key= <PepNovo Id>, value= <pair<rt,mz> >.
For spectra not present in this map identifications cannot be mapped back.
@param[out] mod_id_map map the OpenMS id for modifications (FullId) to the ids returned by PepNovo key= <PepNovo_key>, value= <OpenMS FullId>
*/
void load(const std::string & result_filename, PeptideIdentificationList & peptide_identifications,
ProteinIdentification & protein_identification,
const double & score_threshold,
const IndexPosMappingType & id_rt_mz,
const std::map<String, String> & mod_id_map);
/** @brief get the search engine version and search parameters from a PepNovo output file
*
* search parameters (precursor tolerance, peak mass tolerance, allowed modifications)are stored in the protein_identification.
@param[in] pepnovo_output_without_parameters_filename
@param[in] protein_identification
*/
void getSearchEngineAndVersion(const String & pepnovo_output_without_parameters_filename, ProteinIdentification & protein_identification);
};
} //namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/KroenikFile.h | .h | 2,388 | 71 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CONCEPT/Exception.h>
#include <OpenMS/KERNEL/FeatureMap.h>
namespace OpenMS
{
class String;
/**
@brief File adapter for Kroenik (HardKloer sibling) files.
The first line is the header and contains the column names:<br>
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
Every subsequent line is a feature.
All properties in the file are converted to Feature properties, whereas "First Scan", "Last Scan", "Num of Scans" and "Modifications" are stored as
metavalues with the following names "FirstScan", "LastScan", "NumOfScans" and "AveragineModifications".
The width in m/z of the overall convex hull of each feature is set to 3 Th in lack of a value provided by the Kroenik file.
@note Kroenik files are Tab (\\t) separated files.
@ingroup FileIO
*/
class OPENMS_DLLAPI KroenikFile
{
public:
/// Default constructor
KroenikFile();
/// Destructor
virtual ~KroenikFile();
/**
@brief Loads a Kroenik file into a featureXML.
The content of the file is stored in @p features.
@exception Exception::FileNotFound is thrown if the file could not be opened
@exception Exception::ParseError is thrown if an error occurs during parsing
*/
void load(const String& filename, FeatureMap& feature_map);
/**
@brief Stores a featureXML as a Kroenik file.
NOT IMPLEMENTED
@exception Exception::UnableToCreateFile is thrown if the file could not be created
*/
template <typename SpectrumType>
void store(const String& filename, const SpectrumType& spectrum) const
{
std::cerr << "Store() for KroenikFile not implemented. Filename was: " << filename << ", spec of size " << spectrum.size() << "\n";
throw Exception::NotImplemented(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/CachedMzML.h | .h | 2,536 | 104 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/MSExperiment.h>
#include <fstream>
namespace OpenMS
{
/**
@brief An class that uses on-disk caching to read and write spectra and chromatograms
This class provides functions to read and write spectra and chromatograms
to disk using a time-efficient format. Reading the data items from disk can
be very fast and done in random order (once the in-memory index is built
for the file).
*/
class OPENMS_DLLAPI CachedmzML
{
public:
/** @name Constructors and Destructor
*/
//@{
/// Default constructor
CachedmzML();
CachedmzML(const String& filename);
/// Copy constructor
CachedmzML(const CachedmzML & rhs);
/// Default destructor
~CachedmzML();
//@}
MSSpectrum getSpectrum(Size id);
MSChromatogram getChromatogram(Size id);
size_t getNrSpectra() const;
size_t getNrChromatograms() const;
const MSExperiment& getMetaData() const
{
return meta_ms_experiment_;
}
/**
@brief Stores a map in a cached MzML file.
@p filename The data location (ends in .mzML)
@p map has to be an MSExperiment or have the same interface.
@exception Exception::UnableToCreateFile is thrown if the file could not be created
*/
static void store(const String& filename, const PeakMap& map);
/**
@brief Loads a map from a cached MzML file
@p filename The data location (ends in .mzML, expects an adjacent .mzML.cached file)
@p map A CachedmzML result object
@exception Exception::FileNotFound is thrown if the file could not be opened
@exception Exception::ParseError is thrown if an error occurs during parsing
*/
static void load(const String& filename, CachedmzML& map);
protected:
void load_(const String& filename);
/// Meta data
MSExperiment meta_ms_experiment_;
/// Internal filestream
std::ifstream ifs_;
/// Name of the mzML file
String filename_;
/// Name of the cached mzML file
String filename_cached_;
/// Indices
std::vector<std::streampos> spectra_index_;
std::vector<std::streampos> chrom_index_;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/IBSpectraFile.h | .h | 2,541 | 84 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Stephan Aiche $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/config.h>
#include <OpenMS/DATASTRUCTURES/StringListUtils.h>
// std::shared_ptr
#include <memory>
namespace OpenMS
{
// forward declaration
class ConsensusMap;
class String;
class IsobaricQuantitationMethod;
class AASequence;
/**
@brief Implements the export of consensusmaps into the IBSpectra format
used by isobar to load quantification results.
*/
class OPENMS_DLLAPI IBSpectraFile
{
public:
/**
@brief Constructor.
*/
IBSpectraFile();
/**
@brief Copy constructor.
*/
IBSpectraFile(const IBSpectraFile& other);
/**
@brief Assignment operator.
*/
IBSpectraFile& operator=(const IBSpectraFile& rhs);
/**
@brief Writes the contents of the ConsensusMap cm into the file named by filename.
@param[in] filename The name of the file where the contents of cm should be stored.
@param[in] cm The ConsensusMap that should be exported to filename.
@throws Exception::InvalidParameter if the ConsensusMap does not hold the result of an isobaric quantification experiment (e.g., itraq).
*/
void store(const String& filename, const ConsensusMap& cm);
private:
/**
@brief Guesses the type of isobaric quantitation performed on the experiment.
@throws Exception::InvalidParameter if the ConsensusMap does not hold the result of an isobaric quantification experiment (e.g., itraq).
*/
std::shared_ptr<IsobaricQuantitationMethod> guessExperimentType_(const ConsensusMap& cm);
/**
@brief Constructs the matching file header for the given quantitation method.
@param[in] quantMethod The used quantitation method.
@return The header of the IBSpectra file for the given quantitation method.
*/
StringList constructHeader_(const IsobaricQuantitationMethod& quantMethod);
/**
@brief Generates the modification string for the given AASequence.
@param[in] sequence The sequence for which the modification string should be generated.
@return The modification string for the given sequence.
*/
String getModifString_(const AASequence& sequence);
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/XTandemInfile.h | .h | 8,287 | 276 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/CHEMISTRY/ModificationDefinitionsSet.h>
#include <OpenMS/FORMAT/XMLFile.h>
namespace OpenMS
{
/**
@brief XTandem input file.
This class is able to load/write a X!Tandem configuration file.
These files store parameters within 'note' tags, e.g.,
@verbatim
<note type="input" label="spectrum, fragment monoisotopic mass error">0.4</note>
<note type="input" label="output, proteins">yes</note>
@endverbatim
@ingroup FileIO
*/
class OPENMS_DLLAPI XTandemInfile :
public Internal::XMLFile
{
public:
/// error unit, either Da or ppm
enum ErrorUnit
{
DALTONS = 0,
PPM
};
/// Mass type of the precursor, either monoisotopic or average
enum MassType
{
MONOISOTOPIC = 0,
AVERAGE
};
/// constructor
XTandemInfile();
/// constructor
~XTandemInfile() override;
/// setter for the fragment mass tolerance
void setFragmentMassTolerance(double tolerance);
/// returns the fragment mass tolerance
double getFragmentMassTolerance() const;
/// sets the precursor mass tolerance (plus only)
void setPrecursorMassTolerancePlus(double tol);
/// returns the precursor mass tolerance (plus only)
double getPrecursorMassTolerancePlus() const;
/// set the precursor mass tolerance (minus only)
void setPrecursorMassToleranceMinus(double tol);
/// returns the precursor mass tolerance (minus only)
double getPrecursorMassToleranceMinus() const;
/// sets the precursor mass type
void setPrecursorErrorType(MassType mono_isotopic);
/// returns the precursor mass type
MassType getPrecursorErrorType() const;
/// sets the fragment mass error unit (Da, ppm)
void setFragmentMassErrorUnit(ErrorUnit unit);
/// returns the fragment mass error unit (Da, ppm)
ErrorUnit getFragmentMassErrorUnit() const;
/// sets the precursor mass error unit (Da, ppm)
void setPrecursorMassErrorUnit(ErrorUnit unit);
/// returns the precursor mass error unit (Da, ppm)
ErrorUnit getPrecursorMassErrorUnit() const;
/// sets the number of threads used during the identifications
void setNumberOfThreads(UInt threads);
/// returns the number of threads
UInt getNumberOfThreads() const;
/// sets the modifications using a modification definitions set
void setModifications(const ModificationDefinitionsSet& mods);
/// returns the modifications set, using a modification definitions set
const ModificationDefinitionsSet& getModifications() const;
/// sets the output filename
void setOutputFilename(const String& output);
/// returns the output filename
const String& getOutputFilename() const;
/// sets the input filename
void setInputFilename(const String& input_file);
/// returns the input filename
const String& getInputFilename() const;
/// set the filename of the taxonomy file
void setTaxonomyFilename(const String& filename);
/// returns the filename of the taxonomy file
const String& getTaxonomyFilename() const;
/// sets the default parameters file
void setDefaultParametersFilename(const String& filename);
/// returns the default parameters file
const String& getDefaultParametersFilename() const;
/// sets the taxon used in the taxonomy file
void setTaxon(const String& taxon);
/// returns the taxon used in the taxonomy file
const String& getTaxon() const;
/// sets the max precursor charge
void setMaxPrecursorCharge(Int max_charge);
/// returns the max precursor charge
Int getMaxPrecursorCharge() const;
/// sets the number of missed cleavages allowed
void setNumberOfMissedCleavages(UInt missed_cleavages);
/// returns the number of missed cleavages allowed
UInt getNumberOfMissedCleavages() const;
/// sets the output result type ("all", "valid" or "stochastic")
void setOutputResults(const String& result);
/// returns the output result type ("all", "valid" or "stochastic")
String getOutputResults() const;
/// sets the max valid E-value allowed in the list
void setMaxValidEValue(double value);
/// returns the max valid E-value allowed in the list
double getMaxValidEValue() const;
/// set state of semi cleavage
void setSemiCleavage(const bool semi_cleavage);
/// set if misassignment of precursor to first and second 13C isotopic peak should also be considered
void setAllowIsotopeError(const bool allow_isotope_error);
/// get state of noise suppression
bool getNoiseSuppression() const;
/// set state of noise suppression
void setNoiseSuppression(const bool noise_suppression);
/// set the cleavage site with a X! Tandem conform regex
void setCleavageSite(const String& cleavage_site);
/// returns the cleavage site regex
const String& getCleavageSite() const;
/**
@brief Writes the X! Tandem input file to the given filename
If @p ignore_member_parameters is true, only a very limited number of
tags fed by member variables (i.e. in, out, database/taxonomy) is written.
@param[out] filename the name of the file which is written
@param[in] ignore_member_parameters Do not write tags for class members
@param[in] force_default_mods Force writing of mods covered by special parameters
@throw UnableToCreateFile is thrown if the given file could not be created
*/
void write(const String& filename, bool ignore_member_parameters = false,
bool force_default_mods = false);
protected:
XTandemInfile(const XTandemInfile& rhs);
XTandemInfile& operator=(const XTandemInfile& rhs);
void writeTo_(std::ostream& os, bool ignore_member_parameters);
void writeNote_(std::ostream& os, const String& label, const String& value);
void writeNote_(std::ostream& os, const String& label, const char* value);
void writeNote_(std::ostream& os, const String& label, bool value);
/**
@brief Converts the given set of Modifications into a format compatible to X!Tandem.
The set affected_origins can be used to avoid duplicate modifications, which are not supported in X! Tandem.
Currently, a warning message is printed.
Also, if a fixed mod is already given, a corresponding variable mods needs to have its delta mass reduced by the fixed modifications mass.
This is also done automatically here.
@param[in] mods The modifications to convert
@param[in] affected_origins Set of origins, which were used previously. Will be augmented with the current mods.
@return An X! Tandem compatible string representation.
*/
String convertModificationSet_(const std::set<ModificationDefinition>& mods, std::map<String, double>& affected_origins) const;
double fragment_mass_tolerance_;
double precursor_mass_tolerance_plus_;
double precursor_mass_tolerance_minus_;
ErrorUnit fragment_mass_error_unit_;
ErrorUnit precursor_mass_error_unit_;
MassType fragment_mass_type_;
MassType precursor_mass_type_;
UInt max_precursor_charge_;
double precursor_lower_mz_;
double fragment_lower_mz_;
UInt number_of_threads_;
UInt batch_size_;
ModificationDefinitionsSet modifications_;
String input_filename_;
String output_filename_;
String taxonomy_file_;
String taxon_;
String cleavage_site_;
/// semi cleavage
bool semi_cleavage_;
bool allow_isotope_error_;
// scoring
UInt number_of_missed_cleavages_;
String default_parameters_file_;
// output parameters
String output_results_;
double max_valid_evalue_;
// force writing of mods covered by special parameters?
bool force_default_mods_;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/QuantmsIO.h | .h | 4,944 | 114 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/METADATA/ProteinIdentification.h>
#include <OpenMS/METADATA/PeptideIdentification.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
#include <vector>
#include <set>
namespace OpenMS
{
/**
@brief File adapter for writing PSM (Peptide Spectrum Match) data to parquet files
This class converts OpenMS ProteinIdentification and PeptideIdentification
objects to parquet format following the quantms.io PSM specification.
The parquet output contains columns following the quantms.io PSM specification:
- sequence: unmodified peptide sequence
- peptidoform: peptide sequence with modifications
- modifications: peptide modifications (null for now)
- precursor_charge: precursor charge
- posterior_error_probability: PEP score from metavalues (nullable)
- is_decoy: decoy flag (0=target, 1=decoy) based on target_decoy metavalue
- calculated_mz: theoretical m/z from sequence
- observed_mz: experimental precursor m/z
- additional_scores: additional scores (null for now)
- protein_accessions: protein accessions (null for now)
- predicted_rt: predicted retention time (null for now)
- reference_file_name: reference file name
- cv_params: CV parameters (null for now)
- scan: scan identifier
- rt: retention time in seconds (nullable)
- ion_mobility: ion mobility value (nullable, null for now)
- number_peaks: number of peaks (nullable, null for now)
- mz_array: m/z values array (null for now)
- intensity_array: intensity values array (null for now)
- file_metadata: file-level metadata with quantmsio_version (1.0), creator (OpenMS), file_type (psm), creation_date (actual timestamp), uuid (generated), scan_format (scan), software_provider (OpenMS)
Only the first peptide hit per peptide identification is processed by default (no rank field).
When export_all_psms is enabled, all peptide hits are processed with a rank field.
PEP scores are automatically detected from metavalues using known PEP score names.
Optional meta value columns can be added for specific keys.
@ingroup FileIO
*/
class OPENMS_DLLAPI QuantmsIO :
public ProgressLogger
{
public:
/// Default constructor
QuantmsIO() = default;
/// Destructor
~QuantmsIO();
/**
@brief Store peptide and protein identifications in parquet format
@param[out] filename Output filename (should end with .parquet)
@param[in] protein_identifications Vector of protein identifications
@param[in] peptide_identifications Vector of peptide identifications
@throws Exception::UnableToCreateFile if file cannot be created
*/
void store(const String& filename,
const std::vector<ProteinIdentification>& protein_identifications,
const PeptideIdentificationList& peptide_identifications);
/**
@brief Store peptide and protein identifications in parquet format with all PSMs
@param[out] filename Output filename (should end with .parquet)
@param[in] protein_identifications Vector of protein identifications
@param[in] peptide_identifications Vector of peptide identifications
@param[in] export_all_psms If true, export all PSMs per spectrum with rank column
@throws Exception::UnableToCreateFile if file cannot be created
*/
void store(const String& filename,
const std::vector<ProteinIdentification>& protein_identifications,
const PeptideIdentificationList& peptide_identifications,
bool export_all_psms);
/**
@brief Store peptide and protein identifications in parquet format with enhanced options
@param[out] filename Output filename (should end with .parquet)
@param[in] protein_identifications Vector of protein identifications
@param[in] peptide_identifications Vector of peptide identifications
@param[in] export_all_psms If true, export all PSMs per spectrum with rank column. If false, export only first PSM
@param[in] meta_value_keys Set of meta value keys to export as additional columns
@throws Exception::UnableToCreateFile if file cannot be created
*/
void store(const String& filename,
const std::vector<ProteinIdentification>& protein_identifications,
const PeptideIdentificationList& peptide_identifications,
bool export_all_psms,
const std::set<String>& meta_value_keys);
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/MascotRemoteQuery.h | .h | 5,191 | 174 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <QtCore/QObject>
#include <QtCore/QString>
#include <QtCore/QTimer>
#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkReply>
namespace OpenMS
{
/**
@brief Class which handles the communication between OpenMS and the Mascot server
This class provides a communication interface which is able to query the Mascot
server and reports the identifications provided be the Mascot server
@htmlinclude OpenMS_MascotRemoteQuery.parameters
*/
class MascotRemoteQuery :
public QObject,
public DefaultParamHandler
{
Q_OBJECT
public:
/** @name Constructors and destructors
*/
//@{
/// default constructor
OPENMS_DLLAPI MascotRemoteQuery(QObject* parent = 0);
/// assignment operator
OPENMS_DLLAPI MascotRemoteQuery& operator=(const MascotRemoteQuery& rhs) = delete;
/// copy constructor
OPENMS_DLLAPI MascotRemoteQuery(const MascotRemoteQuery& rhs) = delete;
/// destructor
OPENMS_DLLAPI ~MascotRemoteQuery() override;
//@}
/// sets the query spectra, given in MGF file format
OPENMS_DLLAPI void setQuerySpectra(const String& exp);
/// returns the Mascot XML response which contains the identifications
OPENMS_DLLAPI const QByteArray& getMascotXMLResponse() const;
/// returns the Mascot XML response which contains the decoy identifications (note: setExportDecoys must be set to true, otherwise result will be empty)
OPENMS_DLLAPI const QByteArray& getMascotXMLDecoyResponse() const;
/// predicate which returns true if an error occurred during the query
OPENMS_DLLAPI bool hasError() const;
/// returns the error message, if hasError can be used to check whether an error has occurred
OPENMS_DLLAPI const String& getErrorMessage() const;
/// returns the search number
OPENMS_DLLAPI String getSearchIdentifier() const;
/// request export of decoy summary and decoys (note: internal decoy search must be enabled in the MGF file passed to mascot)
OPENMS_DLLAPI void setExportDecoys(const bool b);
protected:
OPENMS_DLLAPI void updateMembers_() override;
public slots:
OPENMS_DLLAPI void run();
private slots:
/// slot connected to QTimer (timeout_)
OPENMS_DLLAPI void timedOut() const;
/// slot connected to the QNetworkAccessManager::finished signal
OPENMS_DLLAPI void readResponse(QNetworkReply* reply);
/// slot connected to signal downloadProgress
OPENMS_DLLAPI void downloadProgress(qint64 bytes_read, qint64 bytes_total);
/// slot connected to signal uploadProgress
OPENMS_DLLAPI void uploadProgress(qint64 bytes_read, qint64 bytes_total);
/// slot connected to signal gotRedirect
OPENMS_DLLAPI void followRedirect(QNetworkReply * reply);
signals:
/// signal when class got a redirect
OPENMS_DLLAPI void gotRedirect(QNetworkReply * reply);
/// signal when class is done and results can be collected
OPENMS_DLLAPI void done();
private:
/// login to Mascot server
void login();
/// execute query (upload file)
void execQuery();
/// download result file
void getResults(const QString& results_path);
/// finish a run and emit "done"
OPENMS_DLLAPI void endRun_();
/**
@brief Remove host name information from an url, e.g., "http://www.google.de/search" -> "search"
@param[in] url The url that will be manipulated.
*/
void removeHostName_(QString& url);
/// helper function to build URL
QUrl buildUrl_(const std::string& path);
/// Write HTTP header to error stream (for debugging)
OPENMS_DLLAPI void logHeader_(const QNetworkRequest& header, const String& what);
/// Write HTTP header to error stream (for debugging)
OPENMS_DLLAPI void logHeader_(const QNetworkReply* header, const String& what);
OPENMS_DLLAPI String getSearchIdentifierFromFilePath(const String& path) const;
/// parse new response header
OPENMS_DLLAPI void readResponseHeader(const QNetworkReply* reply);
QNetworkAccessManager* manager_;
// Input / Output data
String query_spectra_;
QByteArray mascot_xml_;
QByteArray mascot_decoy_xml_;
// Internal data structures
QString cookie_;
String error_message_;
QTimer timeout_;
String search_identifier_;
/// Path on mascot server
String server_path_;
/// Hostname of the mascot server
String host_name_;
/// Login required
bool requires_login_;
/// Use SSL connection
bool use_ssl_;
/// boundary string that will be embedded into the HTTP requests
String boundary_;
/// Timeout after these many seconds
Int to_;
bool export_decoys_ = false;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/MzTab.h | .h | 38,926 | 883 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/FORMAT/SVOutStream.h>
#include <OpenMS/FORMAT/MzTabBase.h>
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/KERNEL/FeatureMap.h>
#include <OpenMS/KERNEL/ConsensusMap.h>
#include <OpenMS/CHEMISTRY/AASequence.h>
#include <OpenMS/METADATA/PeptideEvidence.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
#include <optional>
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wnon-virtual-dtor"
#endif
namespace OpenMS
{
/**
@brief Data model of MzTab files.
Please see the official MzTab specification at https://code.google.com/p/mztab/
@ingroup FileIO
*/
class OPENMS_DLLAPI MzTabModification
{
public:
MzTabModification();
bool isNull() const;
void setNull(bool b);
/// set (potentially ambiguous) position(s) with associated parameter (might be null if not set)
void setPositionsAndParameters(const std::vector<std::pair<Size, MzTabParameter> >& ppp);
std::vector<std::pair<Size, MzTabParameter> > getPositionsAndParameters() const;
void setModificationIdentifier(const MzTabString& mod_id);
MzTabString getModOrSubstIdentifier() const;
String toCellString() const;
void fromCellString(const String& s);
~MzTabModification() = default;
protected:
std::vector<std::pair<Size, MzTabParameter> > pos_param_pairs_;
MzTabString mod_identifier_;
};
class OPENMS_DLLAPI MzTabModificationList
{
public:
bool isNull() const;
void setNull(bool b);
String toCellString() const;
void fromCellString(const String& s);
std::vector<MzTabModification> get() const;
void set(const std::vector<MzTabModification>& entries);
~MzTabModificationList() = default;
protected:
std::vector<MzTabModification> entries_;
};
// MTD
struct OPENMS_DLLAPI MzTabModificationMetaData
{
MzTabParameter modification;
MzTabString site;
MzTabString position;
};
struct OPENMS_DLLAPI MzTabAssayMetaData
{
MzTabParameter quantification_reagent;
std::map<Size, MzTabModificationMetaData> quantification_mod;
MzTabString sample_ref;
std::vector<int> ms_run_ref; // adapted to address https://github.com/HUPO-PSI/mzTab/issues/26
};
struct OPENMS_DLLAPI MzTabMSRunMetaData
{
MzTabParameter format;
MzTabString location;
MzTabParameter id_format;
MzTabParameterList fragmentation_method;
};
struct OPENMS_DLLAPI MzTabStudyVariableMetaData
{
std::vector<int> assay_refs;
std::vector<int> sample_refs;
MzTabString description;
};
/// all meta data of a mzTab file. Please refer to specification for documentation.
class OPENMS_DLLAPI MzTabMetaData
{
public:
MzTabMetaData();
MzTabString mz_tab_version;
MzTabString mz_tab_mode;
MzTabString mz_tab_type;
MzTabString mz_tab_id;
MzTabString title;
MzTabString description;
std::map<Size, MzTabParameter> protein_search_engine_score;
std::map<Size, MzTabParameter> peptide_search_engine_score;
std::map<Size, MzTabParameter> psm_search_engine_score;
std::map<Size, MzTabParameter> smallmolecule_search_engine_score;
std::map<Size, MzTabParameter> nucleic_acid_search_engine_score;
std::map<Size, MzTabParameter> oligonucleotide_search_engine_score;
std::map<Size, MzTabParameter> osm_search_engine_score;
std::map<Size, MzTabParameterList> sample_processing;
std::map<Size, MzTabInstrumentMetaData> instrument;
std::map<Size, MzTabSoftwareMetaData> software;
MzTabParameterList false_discovery_rate;
std::map<Size, MzTabString> publication;
std::map<Size, MzTabContactMetaData> contact;
std::map<Size, MzTabString> uri;
std::map<Size, MzTabModificationMetaData> fixed_mod;
std::map<Size, MzTabModificationMetaData> variable_mod;
MzTabParameter quantification_method;
MzTabParameter protein_quantification_unit;
MzTabParameter peptide_quantification_unit;
MzTabParameter small_molecule_quantification_unit;
std::map<Size, MzTabMSRunMetaData> ms_run;
std::map<Size, MzTabParameter> custom;
std::map<Size, MzTabSampleMetaData> sample;
std::map<Size, MzTabAssayMetaData> assay;
std::map<Size, MzTabStudyVariableMetaData> study_variable;
std::map<Size, MzTabCVMetaData> cv;
std::vector<String> colunit_protein;
std::vector<String> colunit_peptide;
std::vector<String> colunit_psm;
std::vector<String> colunit_small_molecule;
};
/// PRT - Protein section (Table based)
struct OPENMS_DLLAPI MzTabProteinSectionRow
{
MzTabProteinSectionRow();
MzTabString accession; ///< The protein’s accession.
MzTabString description; ///< Human readable description (i.e. the name)
MzTabInteger taxid; ///< NEWT taxonomy for the species.
MzTabString species; ///< Human readable name of the species
MzTabString database; ///< Name of the protein database.
MzTabString database_version; ///< String Version of the protein database.
MzTabParameterList search_engine; ///< Search engine(s) identifying the protein.
std::map<Size, MzTabDouble> best_search_engine_score; ///< best_search_engine_score[1-n]
std::map<Size, std::map<Size, MzTabDouble> > search_engine_score_ms_run; ///< search_engine_score[index1]_ms_run[index2]
MzTabInteger reliability;
std::map<Size, MzTabInteger> num_psms_ms_run;
std::map<Size, MzTabInteger> num_peptides_distinct_ms_run;
std::map<Size, MzTabInteger> num_peptides_unique_ms_run;
MzTabStringList ambiguity_members; ///< Alternative protein identifications.
MzTabModificationList modifications; ///< Modifications identified in the protein.
MzTabString uri; ///< Location of the protein’s source entry.
MzTabStringList go_terms; ///< List of GO terms for the protein.
MzTabDouble coverage; ///< (0-1) Amount of protein sequence identified.
std::map<Size, MzTabDouble> protein_abundance_assay;
std::map<Size, MzTabDouble> protein_abundance_study_variable;
std::map<Size, MzTabDouble> protein_abundance_stdev_study_variable;
std::map<Size, MzTabDouble> protein_abundance_std_error_study_variable;
std::vector<MzTabOptionalColumnEntry> opt_; ///< Optional Columns must start with “opt_”
/// Comparison operator for sorting rows
struct RowCompare
{
bool operator()(const MzTabProteinSectionRow& row1,
const MzTabProteinSectionRow& row2) const
{
return row1.accession.get() < row2.accession.get();
}
};
};
/// PEP - Peptide section (Table based)
struct OPENMS_DLLAPI MzTabPeptideSectionRow
{
MzTabString sequence; ///< The peptide’s sequence.
MzTabString accession; ///< The protein’s accession.
MzTabBoolean unique; ///< 0=false, 1=true, null else: Peptide is unique for the protein.
MzTabString database; ///< Name of the sequence database.
MzTabString database_version; ///< Version (and optionally # of entries).
MzTabParameterList search_engine; ///< Search engine(s) that identified the peptide.
std::map<Size, MzTabDouble> best_search_engine_score; ///< Search engine(s) score(s) for the peptide.
std::map<Size, std::map<Size, MzTabDouble> > search_engine_score_ms_run;
MzTabInteger reliability; ///< (1-3) 0=null Identification reliability for the peptide.
MzTabModificationList modifications; ///< Modifications identified in the peptide.
MzTabDoubleList retention_time; ///< Time points in seconds. Semantics may vary.
MzTabDoubleList retention_time_window;
MzTabInteger charge; ///< Precursor ion’s charge.
MzTabDouble mass_to_charge; ///< Precursor ion’s m/z.
MzTabString uri; ///< Location of the PSMs source entry.
MzTabSpectraRef spectra_ref; ///< Spectra identifying the peptide.
std::map<Size, MzTabDouble> peptide_abundance_assay;
std::map<Size, MzTabDouble> peptide_abundance_study_variable;
std::map<Size, MzTabDouble> peptide_abundance_stdev_study_variable;
std::map<Size, MzTabDouble> peptide_abundance_std_error_study_variable;
std::vector<MzTabOptionalColumnEntry> opt_; ///< Optional columns must start with “opt_”.
/// Comparison operator for sorting rows
struct RowCompare
{
bool operator()(const MzTabPeptideSectionRow& row1,
const MzTabPeptideSectionRow& row2) const
{
return (std::make_pair(row1.sequence.get(), row1.accession.get()) <
std::make_pair(row2.sequence.get(), row2.accession.get()));
}
};
};
/// PSM - PSM section (Table based)
struct OPENMS_DLLAPI MzTabPSMSectionRow
{
MzTabString sequence; ///< The peptide’s sequence.
MzTabInteger PSM_ID; ///< A unique ID of a PSM line
MzTabString accession; ///< List of potential parent protein accessions as in the fasta DB.
MzTabBoolean unique; ///< 0=false, 1=true, null else: Peptide is unique for the protein.
MzTabString database; ///< Name of the sequence database.
MzTabString database_version; ///< Version (and optionally # of entries).
MzTabParameterList search_engine; ///< Search engine(s) that identified the peptide.
std::map<Size, MzTabDouble> search_engine_score; ///< Search engine(s) score(s) for the peptide.
MzTabInteger reliability; ///< (1-3) 0=null Identification reliability for the peptide.
MzTabModificationList modifications; ///< Modifications identified in the peptide.
MzTabDoubleList retention_time; ///< Time points in seconds. Semantics may vary.
MzTabInteger charge; ///< The charge of the experimental precursor ion.
MzTabDouble exp_mass_to_charge; ///< The observed m/z ratio of the experimental precursor ion (either directly from the raw data or corrected).
MzTabDouble calc_mass_to_charge; ///< The calculated m/z ratio of the experimental precursor ion.
MzTabString uri; ///< Location of the PSM’s source entry.
MzTabSpectraRef spectra_ref; ///< Spectrum for this PSM
MzTabString pre; ///< (List of) Amino acid in parent protein(s) before the start of the current PSM
MzTabString post; ///< (List of) Amino acid in parent protein(s) after the start of the current PSM
MzTabString start; ///< (List of) Start positions in parent protein(s)
MzTabString end; ///< (List of) Start positions in parent protein(s)
std::vector<MzTabOptionalColumnEntry> opt_; ///< Optional columns must start with “opt_”.
/**
@brief Gets peptide_evidences with data from internal structures adds their info to an MzTabPSMSectionRow (pre- or unfilled)
@param[in] peptide_evidences Vector of PeptideEvidence holding internal data.
*/
void addPepEvidenceToRows(const std::vector<PeptideEvidence>& peptide_evidences);
/// Comparison operator for sorting rows
struct RowCompare
{
bool operator()(const MzTabPSMSectionRow& row1,
const MzTabPSMSectionRow& row2) const
{
// @TODO: sort by "PSM_ID"? what's the point of that field?
return (std::make_tuple(row1.sequence.get(),
row1.spectra_ref.getMSFile(),
row1.spectra_ref.getSpecRef(),
row1.accession.get()) <
std::make_tuple(row2.sequence.get(),
row2.spectra_ref.getMSFile(),
row2.spectra_ref.getSpecRef(),
row2.accession.get()));
}
};
};
/// SML Small molecule section (table based)
struct OPENMS_DLLAPI MzTabSmallMoleculeSectionRow
{
MzTabStringList identifier; ///< The small molecule’s identifier.
MzTabString chemical_formula; ///< Chemical formula of the identified compound.
MzTabString smiles; ///< Molecular structure in SMILES format.
MzTabString inchi_key; ///< InChi Key of the identified compound.
MzTabString description; ///< Human readable description (i.e. the name)
MzTabDouble exp_mass_to_charge; ///< Precursor ion’s m/z.
MzTabDouble calc_mass_to_charge; ///< Precursor ion’s m/z.
MzTabInteger charge; ///< Precursor ion’s charge.
MzTabDoubleList retention_time; ///< Time points in seconds. Semantics may vary.
MzTabInteger taxid; ///< NEWT taxonomy for the species.
MzTabString species; ///< Human readable name of the species
MzTabString database; ///< Name of the used database.
MzTabString database_version; ///< String Version of the database (and optionally # of compounds).
MzTabInteger reliability; ///< (1-3) The identification reliability.
MzTabString uri; ///< The source entry’s location.
MzTabSpectraRef spectra_ref; ///< Spectra identifying the small molecule.
MzTabParameterList search_engine; ///< Search engine(s) identifying the small molecule.
std::map<Size, MzTabDouble> best_search_engine_score; ///< Search engine(s) identifications score(s).
std::map<Size, std::map<Size, MzTabDouble> > search_engine_score_ms_run;
MzTabString modifications; ///< Modifications identified on the small molecule.
std::map<Size, MzTabDouble> smallmolecule_abundance_assay;
std::map<Size, MzTabDouble> smallmolecule_abundance_study_variable;
std::map<Size, MzTabDouble> smallmolecule_abundance_stdev_study_variable;
std::map<Size, MzTabDouble> smallmolecule_abundance_std_error_study_variable;
std::vector<MzTabOptionalColumnEntry> opt_; ///< Optional columns must start with “opt_”.
};
/// NUC - Nucleic acid section (table-based)
struct OPENMS_DLLAPI MzTabNucleicAcidSectionRow
{
MzTabString accession; ///< The nucleic acid’s accession.
MzTabString description; ///< Human readable description (i.e. the name)
MzTabInteger taxid; ///< NEWT taxonomy for the species.
MzTabString species; ///< Human readable name of the species
MzTabString database; ///< Name of the sequence database.
MzTabString database_version; ///< Version of the sequence database.
MzTabParameterList search_engine; ///< Search engine(s) that identified the nucleic acid.
std::map<Size, MzTabDouble> best_search_engine_score; ///< Best search engine(s) score(s) (over all MS runs)
std::map<Size, std::map<Size, MzTabDouble> > search_engine_score_ms_run;
MzTabInteger reliability;
std::map<Size, MzTabInteger> num_osms_ms_run;
std::map<Size, MzTabInteger> num_oligos_distinct_ms_run;
std::map<Size, MzTabInteger> num_oligos_unique_ms_run;
MzTabStringList ambiguity_members; ///< Alternative nucleic acid identifications.
MzTabModificationList modifications; ///< Modifications identified in the nucleic acid.
MzTabString uri; ///< Location of the nucleic acid’s source entry.
// do GO terms make sense for nucleic acid sequences?
MzTabStringList go_terms; ///< List of GO terms for the nucleic acid.
MzTabDouble coverage; ///< (0-1) Fraction of nucleic acid sequence identified.
std::vector<MzTabOptionalColumnEntry> opt_; ///< Optional Columns must start with “opt_”
/// Comparison operator for sorting rows
struct RowCompare
{
bool operator()(const MzTabNucleicAcidSectionRow& row1,
const MzTabNucleicAcidSectionRow& row2) const
{
return row1.accession.get() < row2.accession.get();
}
};
};
/// OLI - Oligonucleotide section (table-based)
struct OPENMS_DLLAPI MzTabOligonucleotideSectionRow
{
MzTabString sequence; ///< The oligonucleotide’s sequence.
MzTabString accession; ///< The nucleic acid’s accession.
MzTabBoolean unique; ///< 0=false, 1=true, null else: Oligonucleotide maps uniquely to the nucleic acid sequence.
MzTabParameterList search_engine; ///< Search engine(s) that identified the match.
std::map<Size, MzTabDouble> best_search_engine_score; ///< Search engine(s) score(s) for the match.
std::map<Size, std::map<Size, MzTabDouble>> search_engine_score_ms_run; ///< Search engine(s) score(s) per individual MS run
MzTabInteger reliability; ///< (1-3) 0=null Identification reliability for the match.
MzTabModificationList modifications; ///< Modifications identified in the oligonucleotide.
MzTabDoubleList retention_time; ///< Time points in seconds. Semantics may vary.
MzTabDoubleList retention_time_window;
MzTabString uri; ///< Location of the oligonucleotide's source entry.
MzTabString pre;
MzTabString post;
MzTabInteger start;
MzTabInteger end;
std::vector<MzTabOptionalColumnEntry> opt_; ///< Optional columns must start with “opt_”.
/// Comparison operator for sorting rows
struct RowCompare
{
bool operator()(const MzTabOligonucleotideSectionRow& row1,
const MzTabOligonucleotideSectionRow& row2) const
{
return (std::make_tuple(row1.sequence.get(), row1.accession.get(),
row1.start.get(), row1.end.get()) <
std::make_tuple(row2.sequence.get(), row2.accession.get(),
row2.start.get(), row2.end.get()));
}
};
};
/// OSM - OSM (oligonucleotide-spectrum match) section (table-based)
struct OPENMS_DLLAPI MzTabOSMSectionRow
{
MzTabString sequence; ///< The oligonucleotide’s sequence.
MzTabParameterList search_engine; ///< Search engine(s) that identified the match.
std::map<Size, MzTabDouble> search_engine_score; ///< Search engine(s) score(s) for the match.
MzTabInteger reliability; ///< (1-3) 0=null Identification reliability for the match.
MzTabModificationList modifications; ///< Modifications identified in the oligonucleotide.
MzTabDoubleList retention_time; ///< Time points in seconds. Semantics may vary.
MzTabInteger charge; ///< The charge of the experimental precursor ion.
MzTabDouble exp_mass_to_charge; ///< The m/z ratio of the experimental precursor ion.
MzTabDouble calc_mass_to_charge; ///< The theoretical m/z ratio of the oligonucleotide.
MzTabString uri; ///< Location of the OSM’s source entry.
MzTabSpectraRef spectra_ref; ///< Reference to the spectrum underlying the match.
std::vector<MzTabOptionalColumnEntry> opt_; ///< Optional columns must start with “opt_”.
/// Comparison operator for sorting rows
struct RowCompare
{
bool operator()(const MzTabOSMSectionRow& row1,
const MzTabOSMSectionRow& row2) const
{
return (std::make_tuple(row1.sequence.get(),
row1.spectra_ref.getMSFile(),
row1.spectra_ref.getSpecRef()) <
std::make_tuple(row2.sequence.get(),
row2.spectra_ref.getMSFile(),
row2.spectra_ref.getSpecRef()));
}
};
};
typedef std::vector<MzTabProteinSectionRow> MzTabProteinSectionRows;
typedef std::vector<MzTabPeptideSectionRow> MzTabPeptideSectionRows;
typedef std::vector<MzTabPSMSectionRow> MzTabPSMSectionRows;
typedef std::vector<MzTabSmallMoleculeSectionRow> MzTabSmallMoleculeSectionRows;
typedef std::vector<MzTabNucleicAcidSectionRow> MzTabNucleicAcidSectionRows;
typedef std::vector<MzTabOligonucleotideSectionRow> MzTabOligonucleotideSectionRows;
typedef std::vector<MzTabOSMSectionRow> MzTabOSMSectionRows;
/**
@brief Data model of MzTab files.
Please see the official MzTab specification at https://code.google.com/p/mztab/
@ingroup FileIO
*/
class OPENMS_DLLAPI MzTab : public MzTabBase
{
public:
/// Default constructor
MzTab() = default;
~MzTab() = default;
const MzTabMetaData& getMetaData() const;
void setMetaData(const MzTabMetaData& md);
MzTabProteinSectionRows& getProteinSectionRows();
const MzTabProteinSectionRows& getProteinSectionRows() const;
void setProteinSectionRows(const MzTabProteinSectionRows& psd);
MzTabPeptideSectionRows& getPeptideSectionRows();
const MzTabPeptideSectionRows& getPeptideSectionRows() const;
void setPeptideSectionRows(const MzTabPeptideSectionRows& psd);
MzTabPSMSectionRows& getPSMSectionRows();
const MzTabPSMSectionRows& getPSMSectionRows() const;
/// Returns the number of PSMs in the PSM section (which is not necessarily the number of rows in the section, due to duplication of rows for each protein)
/// @note Relies on the PSM_ID to be set correctly for each PSM row
size_t getNumberOfPSMs() const;
void setPSMSectionRows(const MzTabPSMSectionRows& psd);
const MzTabSmallMoleculeSectionRows& getSmallMoleculeSectionRows() const;
void setSmallMoleculeSectionRows(const MzTabSmallMoleculeSectionRows& smsd);
const MzTabNucleicAcidSectionRows& getNucleicAcidSectionRows() const;
void setNucleicAcidSectionRows(const MzTabNucleicAcidSectionRows& nasd);
const MzTabOligonucleotideSectionRows& getOligonucleotideSectionRows() const;
void setOligonucleotideSectionRows(const MzTabOligonucleotideSectionRows& onsd);
const MzTabOSMSectionRows& getOSMSectionRows() const;
void setOSMSectionRows(const MzTabOSMSectionRows& osd);
void setCommentRows(const std::map<Size, String>& com);
void setEmptyRows(const std::vector<Size>& empty);
const std::vector<Size>& getEmptyRows() const;
const std::map<Size, String>& getCommentRows() const;
/// Extract opt_ (custom, optional column names)
std::vector<String> getProteinOptionalColumnNames() const;
/// Extract opt_ (custom, optional column names)
std::vector<String> getPeptideOptionalColumnNames() const;
/// Extract opt_ (custom, optional column names)
std::vector<String> getPSMOptionalColumnNames() const;
/// Extract opt_ (custom, optional column names)
std::vector<String> getSmallMoleculeOptionalColumnNames() const;
/// Extract opt_ (custom, optional column names)
std::vector<String> getNucleicAcidOptionalColumnNames() const;
/// Extract opt_ (custom, optional column names)
std::vector<String> getOligonucleotideOptionalColumnNames() const;
static void addMetaInfoToOptionalColumns(const std::set<String>& keys, std::vector<MzTabOptionalColumnEntry>& opt, const String& id, const MetaInfoInterface& meta);
/// Extract opt_ (custom, optional column names)
std::vector<String> getOSMOptionalColumnNames() const;
static std::map<Size, MzTabModificationMetaData> generateMzTabStringFromModifications(const std::vector<String>& mods);
static std::map<Size, MzTabModificationMetaData> generateMzTabStringFromVariableModifications(const std::vector<String>& mods);
static std::map<Size, MzTabModificationMetaData> generateMzTabStringFromFixedModifications(const std::vector<String>& mods);
static MzTab exportFeatureMapToMzTab(const FeatureMap& feature_map, const String& filename);
/**
* @brief Export peptide and protein identifications to mzTab
*
* Additionally this function fills two std::maps with mappings for external usage.
*
* @param[in] prot_ids Data structure containing protein identifications
* @param[in] peptide_ids Data structure containing peptide identifications
* @param[in] filename Input idXML file name
* @param[in] first_run_inference_only Is all protein inference information (groups and scores) stored in the first run?
* @param[in] export_empty_pep_ids Export spectra without PSMs as well?
* @param[in] export_all_psms Instead of just the best PSM per spectrum, should other PSMs be exported as well?
* @param[in] title The title for the metadata section
* @return mzTab object
*/
static MzTab exportIdentificationsToMzTab(
const std::vector<ProteinIdentification>& prot_ids,
const PeptideIdentificationList& peptide_ids,
const String& filename,
bool first_run_inference_only,
bool export_empty_pep_ids = false,
bool export_all_psms = false,
const String& title = "ID export from OpenMS");
/// Generate MzTab style list of PTMs from PeptideHit (PSM) object.
/// All passed fixed modifications are not reported (as suggested by the standard for the PRT and PEP section).
/// In contrast, all modifications are reported in the PSM section (see standard document for details).
/// If meta values for modification localization are found, this information is added.
static MzTabModificationList extractModificationList(const PeptideHit& pep_hit, const std::vector<String>& fixed_mods, const std::vector<String>& localization_mods);
/**
* @brief export linked peptide features aka consensus map
*
* @param[in] consensus_map data structure of the linked peptide features
* @param[in] filename input consensusXML file name
* @param[out] first_run_inference_only Is all protein inference information (groups and scores) stored in the first run?
* @param[in] export_unidentified_features Should not identified peptide features be exported?
* @param[in] export_unassigned_ids Should unassigned identifications be exported?
* @param[in] export_subfeatures The position of the consensus feature will always be exported. Should the individual subfeatures be exported as well?
* @param[in] export_empty_pep_ids Export spectra without PSMs as well?
* @param[in] export_all_psms Instead of just the best PSM per spectrum, should other PSMs be exported as well?
* @param[in] title The title for the metadata section
*
* @return mzTab object
*/
static MzTab exportConsensusMapToMzTab(
const ConsensusMap& consensus_map,
const String& filename,
const bool first_run_inference_only,
const bool export_unidentified_features,
const bool export_unassigned_ids,
const bool export_subfeatures,
const bool export_empty_pep_ids = false,
const bool export_all_psms = false,
const String& title = "ConsensusMap export from OpenMS");
class IDMzTabStream
{
public:
IDMzTabStream(
const std::vector<const ProteinIdentification*>& prot_ids,
const std::vector<const PeptideIdentification*>& peptide_ids,
const String& filename,
bool first_run_inference_only,
bool export_empty_pep_ids = false,
bool export_all_psms = false,
const String& title = "ID export from OpenMS");
const MzTabMetaData& getMetaData() const;
const std::vector<String>& getProteinOptionalColumnNames() const;
const std::vector<String>& getPeptideOptionalColumnNames() const;
const std::vector<String>& getPSMOptionalColumnNames() const;
bool nextPRTRow(MzTabProteinSectionRow& row);
bool nextPEPRow(MzTabPeptideSectionRow& row);
bool nextPSMRow(MzTabPSMSectionRow& row);
private:
std::set<String> protein_hit_user_value_keys_;
std::set<String> peptide_id_user_value_keys_;
std::set<String> peptide_hit_user_value_keys_;
// beautiful mapping structs
std::map<Size, std::set<Size>> ind2prot_;
std::map<Size, std::set<Size>> pg2prot_;
std::map<String, size_t> idrunid_2_idrunindex_;
std::map<Size, std::vector<std::pair<String, String>>> run_to_search_engines_;
std::map<Size, std::vector<std::vector<std::pair<String, String>>>> run_to_search_engines_settings_;
std::map<std::pair<size_t,size_t>,size_t> map_id_run_fileidx_2_msfileidx_;
std::map<std::pair< String, unsigned >, unsigned> path_label_to_assay_;
std::vector<const ProteinIdentification*> prot_ids_;
std::vector<const PeptideIdentification*> peptide_ids_;
StringList ms_runs_;
bool first_run_inference_;
String filename_;
StringList fixed_mods_;
/* currently unused
bool export_unidentified_features_;
bool export_subfeatures_; */
bool export_empty_pep_ids_;
bool export_all_psms_;
size_t quant_study_variables_ = 0;
// size_t n_study_variables_ = 0; //currently unused
size_t PRT_STATE_ = 0;
size_t prt_run_id_ = 0; // current (protein) identification run
size_t prt_hit_id_ = 0; // current protein in (protein) identification run
size_t prt_group_id_ = 0;
size_t prt_indistgroup_id_ = 0;
size_t pep_id_ = 0;
size_t psm_id_ = 0;
size_t current_psm_idx_ = 0;
MzTabString db_, db_version_;
std::vector<String> prt_optional_column_names_;
std::vector<String> pep_optional_column_names_;
std::vector<String> psm_optional_column_names_;
MzTabMetaData meta_data_;
};
class CMMzTabStream
{
public:
CMMzTabStream(
const ConsensusMap& consensus_map,
const String& filename,
const bool first_run_inference_only,
const bool export_unidentified_features,
const bool export_unassigned_ids,
const bool export_subfeatures,
const bool export_empty_pep_ids = false,
const bool export_all_psms = false,
const String& title = "ConsensusMap export from OpenMS");
const MzTabMetaData& getMetaData() const;
const std::vector<String>& getProteinOptionalColumnNames() const;
const std::vector<String>& getPeptideOptionalColumnNames() const;
const std::vector<String>& getPSMOptionalColumnNames() const;
bool nextPRTRow(MzTabProteinSectionRow& row);
bool nextPEPRow(MzTabPeptideSectionRow& row);
bool nextPSMRow(MzTabPSMSectionRow& row);
private:
const ConsensusMap& consensus_map_;
std::set<String> protein_hit_user_value_keys_;
std::set<String> consensus_feature_user_value_keys_;
std::set<String> consensus_feature_peptide_identification_user_value_keys_;
std::set<String> consensus_feature_peptide_hit_user_value_keys_;
// beautiful mapping structs
std::map<Size, std::set<Size>> ind2prot_;
std::map<Size, std::set<Size>> pg2prot_;
std::map<String, size_t> idrunid_2_idrunindex_;
std::map<Size, std::vector<std::pair<String, String>>> run_to_search_engines_;
std::map<Size, std::vector<std::vector<std::pair<String, String>>>> run_to_search_engines_settings_;
std::map<std::pair<size_t,size_t>,size_t> map_id_run_fileidx_2_msfileidx_;
std::map<std::pair< String, unsigned >, unsigned> path_label_to_assay_;
std::vector<const ProteinIdentification*> prot_ids_;
std::vector<const PeptideIdentification*> peptide_ids_;
StringList ms_runs_;
bool first_run_inference_;
String filename_;
StringList fixed_mods_;
bool export_unidentified_features_;
bool export_subfeatures_;
bool export_empty_pep_ids_;
bool export_all_psms_;
size_t quant_study_variables_ = 0;
size_t n_study_variables_ = 0;
size_t PRT_STATE_ = 0;
size_t prt_run_id_ = 0; // current (protein) identification run
size_t prt_hit_id_ = 0; // current protein in (protein) identification run
size_t prt_group_id_ = 0;
size_t prt_indistgroup_id_ = 0;
size_t pep_id_ = 0;
size_t pep_counter_ = 0;
size_t psm_id_ = 0;
size_t current_psm_idx_ = 0;
MzTabString db_, db_version_;
std::vector<String> prt_optional_column_names_;
std::vector<String> pep_optional_column_names_;
std::vector<String> psm_optional_column_names_;
MzTabMetaData meta_data_;
};
protected:
// extract basic mappings
static std::map<String, Size> mapIDRunIdentifier2IDRunIndex_(const std::vector<const ProteinIdentification*>& prot_ids);
static std::optional<MzTabPSMSectionRow> PSMSectionRowFromPeptideID_(
PeptideIdentification const& pid,
std::vector<ProteinIdentification const*> const& prot_id,
std::map<String, size_t>& idrun_2_run_index,
std::map<std::pair<size_t, size_t>, size_t>& map_run_fileidx_2_msfileidx,
std::map<Size, std::vector<std::pair<String, String>>>& run_to_search_engines,
Size const current_psm_idx,
Size const psm_id,
MzTabString const& db,
MzTabString const& db_version,
bool const export_empty_pep_ids,
bool const export_all_psms);
static MzTabPeptideSectionRow peptideSectionRowFromConsensusFeature_(
const ConsensusFeature& c,
const ConsensusMap& consensus_map,
const StringList& ms_runs,
const Size n_study_variables,
const std::set<String>& consensus_feature_user_value_keys,
const std::set<String>& peptide_identifications_user_value_keys,
const std::set<String>& peptide_hit_user_value_keys,
const std::map<String, size_t>& idrun_2_run_index,
const std::map<std::pair<size_t,size_t>,size_t>& map_run_fileidx_2_msfileidx,
const std::map< std::pair< String, unsigned >, unsigned>& path_label_to_assay,
const std::vector<String>& fixed_mods,
bool export_subfeatures);
static MzTabPeptideSectionRow peptideSectionRowFromFeature_(
const Feature& c,
const std::set<String>& feature_user_value_keys,
const std::set<String>& peptide_identifications_user_value_keys,
const std::set<String>& peptide_hit_user_value_keys,
const std::vector<String>& fixed_mods);
static MzTabProteinSectionRow proteinSectionRowFromProteinHit_(
const ProteinHit& hit,
const MzTabString& db,
const MzTabString& db_version,
const std::set<String>& protein_hit_user_value_keys);
static MzTabProteinSectionRow nextProteinSectionRowFromProteinGroup_(
const ProteinIdentification::ProteinGroup& group,
const MzTabString& db,
const MzTabString& db_version);
static MzTabProteinSectionRow nextProteinSectionRowFromIndistinguishableGroup_(
const std::vector<ProteinHit>& protein_hits,
const ProteinIdentification::ProteinGroup& group,
const size_t g,
const std::map<Size, std::set<Size>>& ind2prot,
const MzTabString& db,
const MzTabString& db_version);
static void addMSRunMetaData_(
const std::map<size_t, String>& msrunindex_2_msfilename,
MzTabMetaData& meta_data);
static void mapBetweenMSFileNameAndMSRunIndex_(
const std::vector<const ProteinIdentification*>& prot_ids,
bool skip_first,
std::map<String, size_t>& msfilename_2_msrunindex,
std::map<size_t, String>& msrunindex_2_msfilename);
static size_t getQuantStudyVariables_(const ProteinIdentification& pid);
static MzTabParameter getProteinScoreType_(const ProteinIdentification& prot_id);
// TODO: move to core classes?
static void getConsensusMapMetaValues_(const ConsensusMap& consensus_map,
std::set<String>& consensus_feature_user_value_keys,
std::set<String>& peptide_identification_user_value_keys,
std::set<String>& peptide_hit_user_value_keys);
static void getFeatureMapMetaValues_(const FeatureMap& feature_map,
std::set<String>& feature_user_value_keys,
std::set<String>& peptide_identification_user_value_keys,
std::set<String>& peptide_hit_user_value_keys);
static void getIdentificationMetaValues_(
const std::vector<const ProteinIdentification*>& prot_ids,
std::vector<const PeptideIdentification*>& peptide_ids_,
std::set<String>& protein_hit_user_value_keys,
std::set<String>& peptide_id_user_value_keys,
std::set<String>& peptide_hit_user_value_keys);
// determine spectrum reference identifier type (e.g., Thermo nativeID) from spectrum references
static MzTabParameter getMSRunSpectrumIdentifierType_(const std::vector<const PeptideIdentification*>& peptide_ids_);
static void mapBetweenRunAndSearchEngines_(
const std::vector<const ProteinIdentification*>& prot_ids,
const std::vector<const PeptideIdentification*>& pep_ids,
bool skip_first_run,
std::map<std::tuple<String, String, String>, std::set<Size>>& search_engine_to_runs,
std::map<Size, std::vector<std::pair<String, String>>>& run_to_search_engines,
std::map<Size, std::vector<std::vector<std::pair<String, String>>>>& run_to_search_engines_settings,
std::map<String, std::vector<std::pair<String, String>>>& search_engine_to_settings);
static std::map<Size, std::set<Size>> mapGroupsToProteins_(
const std::vector<ProteinIdentification::ProteinGroup>& groups,
const std::vector<ProteinHit>& proteins);
static void addSearchMetaData_(
const std::vector<const ProteinIdentification*>& prot_ids,
const std::map<std::tuple<String, String, String>, std::set<Size>>& search_engine_to_runs,
const std::map<String, std::vector<std::pair<String,String>>>& search_engine_to_settings,
MzTabMetaData& meta_data,
bool first_run_inference_only);
static void mapIDRunFileIndex2MSFileIndex_(
const std::vector<const ProteinIdentification*>& prot_ids,
const std::map<String, size_t>& msfilename_2_msrunindex,
bool skip_first_run,
std::map<std::pair<size_t, size_t>, size_t>& map_run_fileidx_2_msfileidx);
static void getSearchModifications_(
const std::vector<const ProteinIdentification*>& prot_ids,
StringList& var_mods,
StringList& fixed_mods);
// create MzTab compatible modification identifier from ResidueModification
// If the Modification has a unimod identifier it will be prefixed as UNIMOD
// otherwise as CHEMMOD (see MzTab specification for details)
static MzTabString getModificationIdentifier_(const ResidueModification& r);
static void checkSequenceUniqueness_(const PeptideIdentificationList& curr_pep_ids);
MzTabMetaData meta_data_;
MzTabProteinSectionRows protein_data_;
MzTabPeptideSectionRows peptide_data_;
MzTabPSMSectionRows psm_data_;
MzTabSmallMoleculeSectionRows small_molecule_data_;
MzTabNucleicAcidSectionRows nucleic_acid_data_;
MzTabOligonucleotideSectionRows oligonucleotide_data_;
MzTabOSMSectionRows osm_data_; ///</ oligonucleotide-spectrum matches
std::vector<Size> empty_rows_; ///< index of empty rows
std::map<Size, String> comment_rows_; ///< comments
};
} // namespace OpenMS
#ifdef __clang__
#pragma clang diagnostic pop
#endif
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/XMassFile.h | .h | 8,616 | 234 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/FORMAT/HANDLERS/AcqusHandler.h>
#include <OpenMS/FORMAT/HANDLERS/FidHandler.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/SYSTEM/File.h>
namespace OpenMS
{
/**
@brief File adapter for 'XMass Analysis (fid)' files.
XMass Analysis files is native format for Bruker spectrometer Flex Series.<br />
Each spectrum are saved in one directory. Each directory contains several files.
We use 2 files for import in OpenMS :<br />
<b>acqus</b> : contains meta data about calibration (conversion for time to mz ratio),
instrument specification and acquisition method.<br />
<b>fid</b> : contains intensity array. Intensity for each point are coded in 4 bytes integer.
@note MZ ratio are calculated with formula based on article :<br />
<i>A database application for pre-processing, storage and comparison of mass spectra
derived from patients and controls</i><br />
<b>Mark K Titulaer, Ivar Siccama, Lennard J Dekker, Angelique LCT van Rijswijk,
Ron MA Heeren, Peter A Sillevis Smitt, and Theo M Luider</b><br />
BMC Bioinformatics. 2006; 7: 403<br />
http://www.pubmedcentral.nih.gov/picrender.fcgi?artid=1594579&blobtype=pdf<br />
@ingroup FileIO
*/
class OPENMS_DLLAPI XMassFile :
public ProgressLogger
{
public:
/// Default constructor
XMassFile();
/// Destructor
~XMassFile() override;
/**
@brief Loads a spectrum from a XMass file.
@param[in] filename Name of the XMass file which should be loaded.
@param[out] spectrum Spectrum in which the data loaded from the file should be stored.
@exception Exception::FileNotFound is thrown if the file could not be read
*/
void load(const String & filename, MSSpectrum & spectrum)
{
Internal::AcqusHandler acqus(filename.prefix(filename.length() - 3) + String("acqus"));
Internal::FidHandler fid(filename);
if (!fid)
{
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);
}
}
// Delete old spectrum
spectrum.clear(true);
//temporary variables
Peak1D p;
while (spectrum.size() < acqus.getSize())
{
//fill peak
p.setPosition((Peak1D::PositionType)acqus.getPosition(fid.getIndex()));
p.setIntensity((Peak1D::IntensityType)fid.getIntensity());
spectrum.push_back(p);
}
fid.close();
// import metadata
spectrum.setRT(0.0);
spectrum.setMSLevel(1);
spectrum.setName("Xmass analysis file " + acqus.getParam("$ID_raw"));
spectrum.setType(SpectrumSettings::SpectrumType::PROFILE);
spectrum.setNativeID("spectrum=xsd:" + acqus.getParam("$ID_raw").remove('<').remove('>'));
spectrum.setComment("no comment");
InstrumentSettings instrument_settings;
instrument_settings.setScanMode(InstrumentSettings::ScanMode::MASSSPECTRUM);
instrument_settings.setZoomScan(false);
if (acqus.getParam(".IONIZATION MODE") == "LD+")
{
instrument_settings.setPolarity(IonSource::Polarity::POSITIVE);
}
else if (acqus.getParam(".IONIZATION MODE") == "LD-")
{
instrument_settings.setPolarity(IonSource::Polarity::NEGATIVE);
}
else
{
instrument_settings.setPolarity(IonSource::Polarity::POLNULL);
}
spectrum.setInstrumentSettings(instrument_settings);
AcquisitionInfo acquisition_info;
acquisition_info.setMethodOfCombination("Sum of " + acqus.getParam("$NoSHOTS") + " raw spectrum");
spectrum.setAcquisitionInfo(acquisition_info);
SourceFile source_file;
source_file.setNameOfFile("fid");
source_file.setPathToFile(filename.prefix(filename.length() - 3));
source_file.setFileSize(4.0 * acqus.getSize() / 1024 / 1024); // 4 bytes / point
source_file.setFileType("Xmass analysis file (fid)");
spectrum.setSourceFile(source_file);
DataProcessing data_processing;
Software software;
software.setName("FlexControl");
String fc_ver = acqus.getParam("$FCVer"); // FlexControlVersion
if (fc_ver.hasPrefix("<flexControl "))
{
fc_ver = fc_ver.suffix(' ');
}
if (fc_ver.hasSuffix(">"))
{
fc_ver = fc_ver.prefix('>');
}
software.setVersion(fc_ver);
software.setMetaValue("Acquisition method", DataValue(acqus.getParam("$ACQMETH").remove('<').remove('>')));
data_processing.setSoftware(software);
std::set<DataProcessing::ProcessingAction> actions;
actions.insert(DataProcessing::SMOOTHING);
actions.insert(DataProcessing::BASELINE_REDUCTION);
actions.insert(DataProcessing::CALIBRATION);
data_processing.setProcessingActions(actions);
data_processing.setCompletionTime(DateTime::now());
std::vector< std::shared_ptr< DataProcessing> > data_processing_vector;
data_processing_vector.push_back( std::shared_ptr< DataProcessing>(new DataProcessing(data_processing)) );
spectrum.setDataProcessing(data_processing_vector);
}
/**
@brief Import settings from a XMass file.
@param[in] filename File from which the experimental settings should be loaded.
@param[out] exp MSExperiment where the experimental settings will be stored.
@exception Exception::FileNotFound is thrown if the file could not be opened.
*/
void importExperimentalSettings(const String & filename, PeakMap & exp)
{
Internal::AcqusHandler acqus(filename.prefix(filename.length() - 3) + String("acqus"));
ExperimentalSettings & experimental_settings = exp.getExperimentalSettings();
Instrument & instrument = experimental_settings.getInstrument();
instrument.setName(acqus.getParam("SPECTROMETER/DATASYSTEM"));
instrument.setVendor(acqus.getParam("ORIGIN"));
instrument.setModel(acqus.getParam("$InstrID").remove('<').remove('>'));
std::vector<IonSource> & ionSourceList = instrument.getIonSources();
ionSourceList.clear();
ionSourceList.resize(1);
if (acqus.getParam(".INLET") == "DIRECT")
{
ionSourceList[0].setInletType(IonSource::InletType::DIRECT);
}
else
{
ionSourceList[0].setInletType(IonSource::InletType::INLETNULL);
ionSourceList[0].setIonizationMethod(IonSource::IonizationMethod::MALDI);
}
if (acqus.getParam(".IONIZATION MODE") == "LD+")
{
ionSourceList[0].setPolarity(IonSource::Polarity::POSITIVE);
}
else if (acqus.getParam(".IONIZATION MODE") == "LD-")
{
ionSourceList[0].setPolarity(IonSource::Polarity::NEGATIVE);
}
else
{
ionSourceList[0].setPolarity(IonSource::Polarity::POLNULL);
}
ionSourceList[0].setMetaValue("MALDI target reference", DataValue(acqus.getParam("$TgIDS").remove('<').remove('>')));
ionSourceList[0].setOrder(0);
std::vector<MassAnalyzer> & massAnalyzerList = instrument.getMassAnalyzers();
massAnalyzerList.clear();
massAnalyzerList.resize(1);
if (acqus.getParam(".SPECTROMETER TYPE") == "TOF")
{
massAnalyzerList[0].setType(MassAnalyzer::AnalyzerType::TOF);
}
else
{
massAnalyzerList[0].setType(MassAnalyzer::AnalyzerType::ANALYZERNULL);
}
DateTime date;
date.set(acqus.getParam("$AQ_DATE").remove('<').remove('>'));
experimental_settings.setDateTime(date);
}
/**
@brief Stores a spectrum in a XMass file (not available)
@exception Exception::FileNotWritable is thrown
*/
void store(const String & /*filename*/, const MSSpectrum & /*spectrum*/)
{
throw Exception::NotImplemented(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/UnimodXMLFile.h | .h | 1,405 | 55 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/FORMAT/XMLFile.h>
namespace OpenMS
{
class ResidueModification;
/**
@brief Used to load XML files from unimod.org files
@ingroup FileIO
*/
class OPENMS_DLLAPI UnimodXMLFile :
public Internal::XMLFile
{
public:
/// Default constructor
UnimodXMLFile();
/// Destructor
~UnimodXMLFile() override;
/**
@brief loads data from unimod.xml file
@param[in] filename the filename were the unimod xml file should be read from
@param[in] modifications the modifications which are read from the file
@throw FileNotFound is thrown if the file could not be found
@throw ParseError is thrown if the given file could not be parsed
@ingroup FileIO
*/
void load(const String & filename, std::vector<ResidueModification *> & modifications);
private:
///Not implemented
UnimodXMLFile(const UnimodXMLFile & rhs);
///Not implemented
UnimodXMLFile & operator=(const UnimodXMLFile & rhs);
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/FLASHDeconvSpectrumFile.h | .h | 5,901 | 116 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/ANALYSIS/TOPDOWN/DeconvolvedSpectrum.h>
#include <OpenMS/ANALYSIS/TOPDOWN/FLASHHelperClasses.h>
#include <OpenMS/config.h>
#include <iomanip>
namespace OpenMS
{
/**
@brief FLASHDeconv Spectrum level output *.tsv, *.msalign (for TopPIC) file formats
@ingroup FileIO
**/
class OPENMS_DLLAPI FLASHDeconvSpectrumFile
{
public:
/**
@brief write the header in the tsv output file (spectrum level)
@param[out] os output stream to the output file
@param[in] ms_level ms level of the spectrum
@param[out] detail if set true, detailed information of the mass (e.g., peak list for the mass) is written
@param[out] report_decoy if set true, decoy and qvalue information will be written.
*/
static void writeDeconvolvedMassesHeader(std::ostream& os,
uint ms_level,
bool detail,
bool report_decoy);
/**
@brief write the deconvolved masses in the output file (spectrum level)
@param[in] dspec deconvolved spectrum to write
@param[out] fs file stream to the output file
@param[out] file_name the output file name that the deconvolved masses will be written.
@param[in] avg averagine information to calculate monoisotopic and average mass difference within this function. In PeakGroup (peaks of DeconvolvedSpectrum) only monoisotopic mass is recorded. To write both monoisotopic and average masses, their mass difference should be calculated using this averagine information.
@param[in] decoy_avg averagine for noise decoy
@param[in] tol mass tolerance
@param[out] write_detail if this is set, more detailed information on each mass will be written in the output file.
@param[out] record_decoy if set true, decoy and qvalue information will be written.
@param[out] noise_decoy_weight noise decoy weight. Determines how often the noise decoy masses will be written
Default MS1 headers are:
FileName, ScanNum, TargetDecoyType, RetentionTime, MassCountInSpec, AverageMass, MonoisotopicMass,
SumIntensity, MinCharge, MaxCharge,
PeakCount, IsotopeCosine, ChargeScore, MassSNR, ChargeSNR, RepresentativeCharge, RepresentativeMzStart, RepresentativeMzEnd, setQscore, PerChargeIntensity, PerIsotopeIntensity
Default MS2 headers include MS1 headers plus:
PrecursorScanNum, PrecursorMz, PrecursorIntensity, PrecursorCharge, PrecursorSNR, PrecursorMonoisotopicMass, PrecursorQscore
Detailed MS1 and MS2 headers include all corresponding headers above plus:
PeakMZs, PeakIntensities, PeakCharges, PeakMasses, PeakIsotopeIndices, PeakPPMErrors
*/
static void writeDeconvolvedMasses(const DeconvolvedSpectrum& dspec,
std::ostream& os,
const String& file_name,
const FLASHHelperClasses::PrecalculatedAveragine& avg,
const FLASHHelperClasses::PrecalculatedAveragine& decoy_avg,
double tol,
bool write_detail,
bool record_decoy, double noise_decoy_weight);
/**
*
* @param[in] map
* @param[in] deconvolved_spectra
* @param[in] deconvolved_mzML_file
* @param[in] annotated_mzML_file
* @param[in] mzml_charge
* @param[in] tols
*/
static void writeMzML(const MSExperiment& map,
std::vector<DeconvolvedSpectrum>& deconvolved_spectra,
const String& deconvolved_mzML_file,
const String& annotated_mzML_file,
int mzml_charge, DoubleList tols);
/**
* write isobaric quantification results
* @param[out] os output stream
* @param[in] deconvolved_spectra deconvolved spectra to write
*/
static void writeIsobaricQuantification(std::ostream& os, std::vector<DeconvolvedSpectrum>& deconvolved_spectra);
/// write topFD header
static void writeTopFDHeader(std::ostream& os, const Param& param);
/**
@brief write the deconvolved masses TopFD output (*.msalign)
@param[in] dspec deconvolved spectrum to write
@param[out] os output stream to the output file
@param[in] filename mzml file name
@param[in] qval_threshold qvalue threshold to filter out high qvalue precursors.
@param[in] min_ms_level min ms level of the dataset
@param[in] randomize_precursor_mass if set, a random number between -100 to 100 is added to precursor mass
@param[in] randomize_fragment_mass if set, a random number between -100 to 100 is added to fragment mass
*/
static void writeTopFD(const DeconvolvedSpectrum& dspec, std::ostream& os, const String& filename,
double qval_threshold = 1.0,
uint min_ms_level = 1,
bool randomize_precursor_mass = false,
bool randomize_fragment_mass = false);
private:
/// number of minimum peak count in topFD msalign file
static const int topFD_min_peak_count_ = 3;
/// number of maximum peak count in topFD msalign file
static const int topFD_max_peak_count_ = 500;
};
}// namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/ExperimentalDesignFile.h | .h | 2,053 | 56 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Timo Sachsenberg, Lukas Zimmermann $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/ListUtils.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <map>
#include <set>
namespace OpenMS
{
class ExperimentalDesign;
class TextFile;
/**
@brief Load an experimental design from a TSV file. (see ExperimentalDesign for details on the supported format)
@ingroup Format
*/
class OPENMS_DLLAPI ExperimentalDesignFile
{
public:
/// Loads an experimental design from a tabular separated file
static ExperimentalDesign load(const String& tsv_file, bool require_spectra_files);
/// Loads an experimental design from an already loaded or generated, tabular file
static ExperimentalDesign load(const TextFile& text_file, const bool require_spectra_file, String filename);
private:
static bool isOneTableFile_(const TextFile& text_file);
static ExperimentalDesign parseOneTableFile_(const TextFile& text_file, const String& tsv_file, bool require_spectra_file);
static ExperimentalDesign parseTwoTableFile_(const TextFile& text_file, const String& tsv_file, bool require_spectra_file);
/// Reads header line of File and Sample section, checks for the existence of required headers
/// and maps the column name to its position
static void parseHeader_(
const StringList &header,
const String &filename,
std::map <String, Size> &column_map,
const std::set <String> &required,
const std::set <String> &optional,
bool allow_other_header);
/// Throws @class ParseError with @p filename and @p message if @p test is false.
static void parseErrorIf_(const bool test, const String &filename, const String &message);
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/MascotGenericFile.h | .h | 14,103 | 375 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/METADATA/SpectrumSettings.h>
#include <OpenMS/SYSTEM/File.h>
#include <OpenMS/CONCEPT/Constants.h>
#include <vector>
#include <fstream>
#ifdef _OPENMP
#include <omp.h>
#endif
namespace OpenMS
{
/**
@brief Read/write Mascot generic files (MGF).
For details of the format, see http://www.matrixscience.com/help/data_file_help.html#GEN.
@htmlinclude OpenMS_MascotGenericFile.parameters
@ingroup FileIO
*/
class OPENMS_DLLAPI MascotGenericFile :
public ProgressLogger,
public DefaultParamHandler
{
public:
/// constructor
MascotGenericFile();
/// destructor
~MascotGenericFile() override;
/// docu in base class
void updateMembers_() override;
/// stores the experiment data in a MascotGenericFile that can be used as input for MASCOT shell execution (optionally a compact format is used: no zero-intensity peaks, limited number of decimal places)
void store(const String& filename, const PeakMap& experiment,
bool compact = false);
/// store the experiment data in a MascotGenericFile; the output is written to the given stream, the filename will be noted in the file (optionally a compact format is used: no zero-intensity peaks, limited number of decimal places)
void store(std::ostream& os, const String& filename,
const PeakMap& experiment, bool compact = false);
/**
@brief loads a Mascot Generic File into a PeakMap
@param[in] filename file name which the map should be read from
@param[out] exp the map which is filled with the data from the given file
@throw FileNotFound is thrown if the given file could not be found
*/
template <typename MapType>
void load(const String& filename, MapType& exp)
{
if (!File::exists(filename))
{
throw Exception::FileNotFound(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename);
}
exp.reset();
std::ifstream is(filename.c_str());
// get size of file
is.seekg(0, std::ios::end);
startProgress(0, is.tellg(), "loading MGF");
is.seekg(0, std::ios::beg);
UInt spectrum_number(0);
Size line_number(0); // carry line number for error messages within getNextSpectrum()
typename MapType::SpectrumType spectrum;
spectrum.setMSLevel(2);
spectrum.getPrecursors().resize(1);
spectrum.setType(SpectrumSettings::SpectrumType::CENTROID); // MGF is always centroided, by definition
while (getNextSpectrum_(is, spectrum, line_number, spectrum_number))
{
exp.addSpectrum(spectrum);
setProgress(is.tellg());
++spectrum_number;
} // next spectrum
exp.updateRanges();
endProgress();
}
/**
@brief enclosing Strings of the peak list body for HTTP submission
Can be used to embed custom content into HTTP submission (when writing only the MGF header in HTTP format and then
adding the peaks (in whatever format, e.g. mzXML) enclosed in this body.
The @p filename can later be found in the Mascot response.
*/
std::pair<String, String> getHTTPPeakListEnclosure(const String& filename) const;
/// writes a spectrum in MGF format to an ostream
void writeSpectrum(std::ostream& os, const PeakSpectrum& spec, const String& filename, const String& native_id_type_accession);
protected:
/// use a compact format for storing (no zero-intensity peaks, limited number of decimal places)?
bool store_compact_;
/// mapping of modifications with specificity groups, that have to be treated specially (e.g. "Deamidated (NQ)")
std::map<String, String> mod_group_map_;
/// writes a parameter header
void writeParameterHeader_(const String& name, std::ostream& os);
/// write a list of (fixed or variable) modifications
void writeModifications_(const std::vector<String>& mods, std::ostream& os,
bool variable_mods = false);
/// writes the full header
void writeHeader_(std::ostream& os);
/// writes the MSExperiment
void writeMSExperiment_(std::ostream& os, const String& filename, const PeakMap& experiment);
/// reads a spectrum block, the section between 'BEGIN IONS' and 'END IONS' of a MGF file
template <typename SpectrumType>
bool getNextSpectrum_(std::ifstream& is, SpectrumType& spectrum, Size& line_number, const Size& spectrum_number)
{
spectrum.resize(0);
spectrum.setNativeID(String("index=") + (spectrum_number));
if (spectrum.metaValueExists("TITLE"))
{
spectrum.removeMetaValue("TITLE");
}
typename SpectrumType::PeakType p;
String line;
// seek to next peak list block
while (getline(is, line, '\n'))
{
++line_number;
line.trim(); // remove whitespaces, line-endings etc
// found peak list block?
if (line == "BEGIN IONS")
{
while (getline(is, line, '\n'))
{
++line_number;
line.trim(); // remove whitespaces, line-endings etc
if (line.empty()) continue;
if (isdigit(line[0])) // actual data .. this comes first, since its the most common case
{
std::vector<String> split;
do
{
if (line.empty())
{
continue;
}
line.simplify(); // merge double spaces (explicitly allowed by MGF), to prevent empty split() chunks and subsequent parse error
line.substitute('\t', ' '); // also accept Tab (strictly, only space(s) are allowed)
if (line.split(' ', split, false))
{
try
{
p.setPosition(split[0].toDouble());
p.setIntensity(split[1].toDouble());
}
catch (Exception::ConversionError& /*e*/)
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "The content '" + line + "' at line #" + String(line_number) + " could not be converted to a number! Expected two (m/z int) or three (m/z int charge) numbers separated by whitespace (space or tab).", "");
}
spectrum.push_back(p);
}
else
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "The content '" + line + "' at line #" + String(line_number) + " does not contain m/z and intensity values separated by whitespace (space or tab)!", "");
}
}
while (getline(is, line, '\n') && ++line_number && line.trim() != "END IONS"); // line.trim() is important here!
if (line == "END IONS")
{
return true; // found end of spectrum
}
else
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, R"(Reached end of file. Found "BEGIN IONS" but not the corresponding "END IONS"!)", "");
}
}
else if (line.hasPrefix("PEPMASS")) // parse precursor position
{
String tmp = line.substr(8); // copy since we might need the original line for error reporting later
tmp.substitute('\t', ' ');
std::vector<String> split;
tmp.split(' ', split);
if (split.size() == 1)
{
spectrum.getPrecursors()[0].setMZ(split[0].trim().toDouble());
}
else if (split.size() == 2)
{
spectrum.getPrecursors()[0].setMZ(split[0].trim().toDouble());
spectrum.getPrecursors()[0].setIntensity(split[1].trim().toDouble());
}
else
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Cannot parse PEPMASS in '" + line + "' at line #" + String(line_number) + " (expected 1 or 2 entries, but " + String(split.size()) + " were present)!", "");
}
}
else if (line.hasPrefix("CHARGE"))
{
String tmp = line.substr(7);
tmp.remove('+');
spectrum.getPrecursors()[0].setCharge(tmp.toInt());
}
else if (line.hasPrefix("RTINSECONDS"))
{
String tmp = line.substr(12);
spectrum.setRT(tmp.toDouble());
}
else if (line.hasPrefix("TITLE"))
{
// test if we have a line like "TITLE= Cmpd 1, +MSn(595.3), 10.9 min"
if (line.hasSubstring("min"))
{
try
{
std::vector<String> split;
line.split(',', split);
if (!split.empty())
{
for (Size i = 0; i != split.size(); ++i)
{
if (split[i].hasSubstring("min"))
{
std::vector<String> split2;
split[i].trim().split(' ', split2);
if (!split2.empty())
{
spectrum.setRT(split2[0].trim().toDouble() * 60.0);
}
}
}
}
}
catch (Exception::BaseException& /*e*/)
{
// just do nothing and write the whole title to spec
std::vector<String> split;
if (line.split('=', split))
{
if (!split[1].empty()) spectrum.setMetaValue("TITLE", split[1]);
}
}
}
else // just write the title as metainfo to the spectrum and add native ID to make the titles unique
{
Size firstEqual = line.find('=', 4);
if (firstEqual != std::string::npos)
{
if (String(spectrum.getMetaValue("TITLE")).hasSubstring(spectrum.getNativeID()))
{
spectrum.setMetaValue("TITLE", line.substr(firstEqual + 1));
}
else
{
spectrum.setMetaValue("TITLE", line.substr(firstEqual + 1) + "_" + spectrum.getNativeID());
}
}
}
}
else if (line.hasPrefix("NAME"))
{
String tmp = line.substr(5);
spectrum.setMetaValue(Constants::UserParam::MSM_METABOLITE_NAME, tmp);
}
else if (line.hasPrefix("COMPOUND_NAME"))
{
String tmp = line.substr(14);
spectrum.setMetaValue(Constants::UserParam::MSM_METABOLITE_NAME, tmp);
}
else if (line.hasPrefix("INCHI="))
{
String tmp = line.substr(6);
spectrum.setMetaValue(Constants::UserParam::MSM_INCHI_STRING, tmp);
}
else if (line.hasPrefix("SMILES"))
{
String tmp = line.substr(7);
spectrum.setMetaValue(Constants::UserParam::MSM_SMILES_STRING, tmp);
}
else if (line.hasPrefix("IONMODE"))
{
String tmp = line.substr(8);
spectrum.setMetaValue("IONMODE", tmp);
}
else if (line.hasPrefix("MSLEVEL"))
{
String tmp = line.substr(8);
try
{
int ms_level = std::stoi(tmp);
spectrum.setMSLevel(ms_level);
}
catch (const std::invalid_argument& /*e*/)
{
// Default to MS2 if parsing fails
spectrum.setMSLevel(2);
spectrum.setMetaValue("MSLEVEL", "2");
}
catch (const std::out_of_range& /*e*/)
{
spectrum.setMSLevel(2);
}
}
else if (line.hasPrefix("SOURCE_INSTRUMENT"))
{
String tmp = line.substr(18);
spectrum.setMetaValue("SOURCE_INSTRUMENT", tmp);
}
else if (line.hasPrefix("ORGANISM"))
{
String tmp = line.substr(9);
spectrum.setMetaValue("ORGANISM", tmp);
}
else if (line.hasPrefix("PI"))
{
String tmp = line.substr(3);
spectrum.setMetaValue("PI", tmp);
}
else if (line.hasPrefix("DATACOLLECTOR"))
{
String tmp = line.substr(14);
spectrum.setMetaValue("DATACOLLECTOR", tmp);
}
else if (line.hasPrefix("LIBRARYQUALITY"))
{
String tmp = line.substr(15);
spectrum.setMetaValue("LIBRARYQUALITY", tmp);
}
else if (line.hasPrefix("SPECTRUMID"))
{
String tmp = line.substr(11);
spectrum.setMetaValue("GNPS_Spectrum_ID", tmp);
}
else if (line.hasPrefix("SCANS="))
{
String tmp = line.substr(6);
spectrum.setMetaValue("Scan_ID", tmp);
}
}
}
}
return false; // found end of file
}
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/OMSFileStore.h | .h | 12,857 | 301 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hendrik Weisser $
// $Authors: Hendrik Weisser, Chris Bielow $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/KERNEL/ConsensusMap.h>
#include <OpenMS/KERNEL/FeatureMap.h>
#include <OpenMS/METADATA/ID/IdentificationData.h>
namespace SQLite
{
class Database;
class Exception;
class Statement;
}
namespace OpenMS
{
namespace Internal
{
/*!
@brief Raise a more informative database error
Add context to an SQL error encountered by Qt and throw it as a FailedAPICall exception.
@param[in] error The error that occurred
@param[in] line Line in the code where error occurred
@param[in] function Name of the function where error occurred
@param[in] context Context for the error
@param[in] query Text of the query that was executed (optional)
@throw Exception::FailedAPICall Throw this exception
*/
void raiseDBError_(const String& error, int line, const char* function, const String& context, const String& query = "");
/*!
@brief Execute and reset an SQL query
@return Whether the number of modifications made by the query matches the expected number
*/
bool execAndReset(SQLite::Statement& query, int expected_modifications);
/// If execAndReset() returns false, call raiseDBError_()
void execWithExceptionAndReset(SQLite::Statement& query, int expected_modifications, int line, const char* function, const char* context);
/*!
@brief Helper class for storing .oms files (SQLite format)
This class encapsulates the SQLite database in a .oms file and allows to write data to it.
*/
class OMSFileStore: public ProgressLogger
{
public:
///< Type used for database keys
using Key = int64_t; //std::decltype(((SQLite::Database*)nullptr)->getLastInsertRowid());
/*!
@brief Constructor
Deletes the output file if it exists, then creates an SQLite database in its place.
Opens the database and configures it for fast writing.
@param[out] filename Path to the .oms output file (SQLite database)
@param[in] log_type Type of logging to use
@throw Exception::FailedAPICall Database cannot be opened
*/
OMSFileStore(const String& filename, LogType log_type);
/*!
@brief Destructor
Closes the connection to the database file.
*/
~OMSFileStore();
/// Write data from an IdentificationData object to database
void store(const IdentificationData& id_data);
/// Write data from a FeatureMap object to database
void store(const FeatureMap& features);
/// Write data from a ConsensusMap object to database
void store(const ConsensusMap& consensus);
private:
/*!
@brief Helper function to create a database table
@param[in] name Name of the new table
@param[in] definition Table definition in SQL
@param[in] may_exist If true, the table may already exist (otherwise this is an error)
*/
void createTable_(const String& name, const String& definition, bool may_exist = false);
/// Create a database table for the data types used in DataValue
void createTableDataValue_DataType_();
/// Create a database table (and prepare a query) for storing CV terms
void createTableCVTerm_();
/// Create a database table (and prepare a query) for storing meta values
void createTableMetaInfo_(const String& parent_table,
const String& key_column = "id");
/// Store version information and current date/time in the database
void storeVersionAndDate_();
/// Store a CV term in the database
Key storeCVTerm_(const CVTerm& cv_term);
/// Store meta values (associated with one object) in the database
void storeMetaInfo_(const MetaInfoInterface& info, const String& parent_table,
Key parent_id);
/// Store meta values (for all objects in a container) in the database
template<class MetaInfoInterfaceContainer, class DBKeyTable>
void storeMetaInfos_(const MetaInfoInterfaceContainer& container,
const String& parent_table, const DBKeyTable& db_keys)
{
bool table_created = false;
for (const auto& element : container)
{
if (!element.isMetaEmpty())
{
if (!table_created)
{
createTableMetaInfo_(parent_table);
table_created = true;
}
storeMetaInfo_(element, parent_table, db_keys.at(&element));
}
}
}
/// @name Helper functions for storing identification data
///@{
/// Store score type information from IdentificationData in the database
void storeScoreTypes_(const IdentificationData& id_data);
/// Store input file information from IdentificationData in the database
void storeInputFiles_(const IdentificationData& id_data);
/// Store information on data processing software from IdentificationData in the database
void storeProcessingSoftwares_(const IdentificationData& id_data);
/// Store sequence database search parameters from IdentificationData in the database
void storeDBSearchParams_(const IdentificationData& id_data);
/// Store information on data processing steps from IdentificationData in the database
void storeProcessingSteps_(const IdentificationData& id_data);
/// Store information on observations (e.g. spectra) from IdentificationData in the database
void storeObservations_(const IdentificationData& id_data);
/// Store information on parent sequences (e.g. proteins) from IdentificationData in the database
void storeParentSequences_(const IdentificationData& id_data);
/// Store information on parent group sets (e.g. protein groups) from IdentificationData in the database
void storeParentGroupSets_(const IdentificationData& id_data);
/// Store information on identified compounds from IdentificationData in the database
void storeIdentifiedCompounds_(const IdentificationData& id_data);
/// Store information on identified sequences (peptides or oligonucleotides) from IdentificationData in the database
void storeIdentifiedSequences_(const IdentificationData& id_data);
/// Store information on adducts from IdentificationData in the database
void storeAdducts_(const IdentificationData& id_data);
/// Store information on observation matches (e.g. PSMs) from IdentificationData in the database
void storeObservationMatches_(const IdentificationData& id_data);
/// Create a database table for molecule types (proteins, compounds, RNA)
void createTableMoleculeType_();
/// Create a database table for storing processing metadata
void createTableAppliedProcessingStep_(const String& parent_table);
/// Store processing metadata for a particular class (stored in @p parent_table) in the database
void storeAppliedProcessingStep_(
const IdentificationData::AppliedProcessingStep& step, Size step_order,
const String& parent_table, Key parent_id);
/// Create a database table for storing identified molecules (peptides, compounds, oligonucleotides)
void createTableIdentifiedMolecule_();
/// Return the database key used for an identified molecule (peptide, compound or oligonucleotide)
Key getDatabaseKey_(const IdentificationData::IdentifiedMolecule& molecule_var);
/// Create a database table for storing parent matches (e.g. proteins for a peptide)
void createTableParentMatches_();
/// Store information on parent matches in the database
void storeParentMatches_(
const IdentificationData::ParentMatches& matches, Key molecule_id);
/// Store metadata on scores/processing steps (for all objects in a container) in the database
template<class ScoredProcessingResultContainer, class DBKeyTable>
void storeScoredProcessingResults_(const ScoredProcessingResultContainer& container,
const String& parent_table, const DBKeyTable& db_keys)
{
bool table_created = false;
for (const auto& element : container)
{
if (!element.steps_and_scores.empty())
{
if (!table_created)
{
createTableAppliedProcessingStep_(parent_table);
table_created = true;
}
Size counter = 0;
for (const IdentificationData::AppliedProcessingStep& step : element.steps_and_scores)
{
storeAppliedProcessingStep_(step, ++counter, parent_table, db_keys.at(&element));
}
}
}
storeMetaInfos_(container, parent_table, db_keys);
}
///@}
/// @name Helper functions for storing (consensus) feature data
///@{
/// Create a table for storing feature information
void createTableBaseFeature_(bool with_metainfo, bool with_idmatches);
/// Store information on a feature in the database
void storeBaseFeature_(const BaseFeature& feature, int feature_id, int parent_id);
/// Store information on features from a feature map in the database
void storeFeatures_(const FeatureMap& features);
/// Store a feature (incl. its subordinate features) in the database
void storeFeatureAndSubordinates_(
const Feature& feature, int& feature_id, int parent_id);
/// check whether a predicate is true for any feature (or subordinate thereof) in a container
template <class FeatureContainer, class Predicate>
bool anyFeaturePredicate_(const FeatureContainer& features, const Predicate& pred)
{
if (features.empty()) return false;
for (const Feature& feature : features)
{
if (pred(feature)) return true;
if (anyFeaturePredicate_(feature.getSubordinates(), pred)) return true;
}
return false;
}
/// Store feature/consensus map meta data in the database
template <class MapType>
void storeMapMetaData_(const MapType& features, const String& experiment_type = "");
/// Store information on data processing from a feature/consensus map in the database
void storeDataProcessing_(const std::vector<DataProcessing>& data_processing);
/// Store information on consensus features from a consensus map in the database
void storeConsensusFeatures_(const ConsensusMap& consensus);
/// Store information on column headers from a consensus map in the database
void storeConsensusColumnHeaders_(const ConsensusMap& consensus);
///@}
/// The database connection (read/write)
std::unique_ptr<SQLite::Database> db_;
/// Prepared queries for inserting data into different tables
std::map<std::string, std::unique_ptr<SQLite::Statement>> prepared_queries_;
// mapping between loaded data and database keys:
// @NOTE: in principle we could use `unordered_map` here for efficiency,
// but that gives compiler errors when pointers or iterators (`...Ref`)
// are used as keys (because they aren't hashable?)
std::map<const IdentificationData::ScoreType*, Key> score_type_keys_;
std::map<const IdentificationData::InputFile*, Key> input_file_keys_;
std::map<const IdentificationData::ProcessingSoftware*, Key> processing_software_keys_;
std::map<const IdentificationData::ProcessingStep*, Key> processing_step_keys_;
std::map<const IdentificationData::DBSearchParam*, Key> search_param_keys_;
std::map<const IdentificationData::Observation*, Key> observation_keys_;
std::map<const IdentificationData::ParentSequence*, Key> parent_sequence_keys_;
std::map<const IdentificationData::ParentGroupSet*, Key> parent_grouping_keys_;
std::map<const IdentificationData::IdentifiedCompound*, Key> identified_compound_keys_;
std::map<const IdentificationData::IdentifiedPeptide*, Key> identified_peptide_keys_;
std::map<const IdentificationData::IdentifiedOligo*, Key> identified_oligo_keys_;
std::map<const AdductInfo*, Key> adduct_keys_;
std::map<const IdentificationData::ObservationMatch*, Key> observation_match_keys_;
// for feature/consensus maps:
std::map<const DataProcessing*, Key> feat_processing_keys_;
};
}
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/MzTabFile.h | .h | 10,308 | 210 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/FORMAT/MzTab.h>
#include <OpenMS/METADATA/PeptideHit.h>
#include <OpenMS/METADATA/PeptideIdentification.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
#include <OpenMS/METADATA/ProteinIdentification.h>
#include <OpenMS/DATASTRUCTURES/ListUtils.h>
#include <vector>
namespace OpenMS
{
class String;
class SVOutStream;
/**
@brief File adapter for MzTab files
@ingroup FileIO
*/
class OPENMS_DLLAPI MzTabFile
{
public:
///Default constructor
MzTabFile();
///Destructor
~MzTabFile();
typedef std::map<std::pair<String, String>, std::vector<PeptideHit> > MapAccPepType;
// store MzTab file
void store(const String& filename, const MzTab& mz_tab) const;
// stream IDs to file
void store(
const String& filename,
const std::vector<ProteinIdentification>& protein_identifications,
const PeptideIdentificationList& peptide_identifications,
bool first_run_inference_only,
bool export_empty_pep_ids = false,
bool export_all_psms = false,
const String& title = "ID export from OpenMS");
// stream ConsensusMap to file
void 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 = false,
const bool export_all_psms = false) const;
// Set store behaviour of optional "reliability" and "uri" columns (default=no)
void storeProteinReliabilityColumn(bool store);
void storePeptideReliabilityColumn(bool store);
void storePSMReliabilityColumn(bool store);
void storeSmallMoleculeReliabilityColumn(bool store);
void storeProteinUriColumn(bool store);
void storePeptideUriColumn(bool store);
void storePSMUriColumn(bool store);
void storeSmallMoleculeUriColumn(bool store);
void storeProteinGoTerms(bool store);
// load MzTab file
void load(const String& filename, MzTab& mz_tab);
protected:
bool store_protein_reliability_;
bool store_peptide_reliability_;
bool store_psm_reliability_;
bool store_smallmolecule_reliability_;
bool store_protein_uri_;
bool store_peptide_uri_;
bool store_psm_uri_;
bool store_smallmolecule_uri_;
bool store_protein_goterms_;
bool store_nucleic_acid_reliability_;
bool store_oligonucleotide_reliability_;
bool store_osm_reliability_;
bool store_nucleic_acid_uri_;
bool store_oligonucleotide_uri_;
bool store_osm_uri_;
bool store_nucleic_acid_goterms_;
void generateMzTabMetaDataSection_(const MzTabMetaData& map, StringList& sl) const;
/// Needs a reference row to get the collected optional columns from the MetaValues
/// TODO refactor this behaviour by e.g. storing it in the MzTab object
String 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;
String generateMzTabSectionRow_(const MzTabProteinSectionRow& row, const std::vector<String>& optional_columns, const MzTabMetaData& meta, size_t& n_columns) const;
String generateMzTabPeptideHeader_(Size search_ms_runs, Size n_best_search_engine_scores, Size n_search_engine_score, Size assays, Size study_variables, const std::vector<String>& optional_columns, size_t& n_columns) const;
String generateMzTabSectionRow_(const MzTabPeptideSectionRow& row, const std::vector<String>& optional_columns, const MzTabMetaData& meta, size_t& n_columns) const;
String generateMzTabPSMHeader_(Size n_search_engine_scores, const std::vector<String>& optional_columns, size_t& n_columns) const;
String generateMzTabSectionRow_(const MzTabPSMSectionRow& row, const std::vector<String>& optional_columns, const MzTabMetaData& meta, size_t& n_columns) const;
String generateMzTabSmallMoleculeHeader_(Size search_ms_runs, Size n_best_search_engine_scores, Size n_search_engine_score, Size assays, Size study_variables, const std::vector<String>& optional_columns, size_t& n_columns) const;
String generateMzTabSectionRow_(const MzTabSmallMoleculeSectionRow& row, const std::vector<String>& optional_columns, const MzTabMetaData& meta, size_t& n_columns) const;
String 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;
String generateMzTabSectionRow_(const MzTabNucleicAcidSectionRow& row, const std::vector<String>& optional_columns, const MzTabMetaData& meta, size_t& n_columns) const;
String generateMzTabOligonucleotideHeader_(Size search_ms_runs, Size n_best_search_engine_scores, Size n_search_engine_score, const std::vector<String>& optional_columns, size_t& n_columns) const;
String generateMzTabSectionRow_(const MzTabOligonucleotideSectionRow& row, const std::vector<String>& optional_columns, const MzTabMetaData& meta, size_t& n_columns) const;
String generateMzTabOSMHeader_(Size n_search_engine_scores, const std::vector<String>& optional_columns, size_t& n_columns) const;
String generateMzTabSectionRow_(const MzTabOSMSectionRow& row, const std::vector<String>& optional_columns, const MzTabMetaData& meta, size_t& n_columns) const;
/// Generate an mzTab section comprising multiple rows of the same type and perform sanity check
template <typename SectionRow> void generateMzTabSection_(const std::vector<SectionRow>& rows, const std::vector<String>& optional_columns, const MzTabMetaData& meta, StringList& output, size_t n_header_columns) const
{
output.reserve(output.size() + rows.size() + 1);
for (const auto& row : rows)
{
size_t n_section_columns = 0;
output.push_back(generateMzTabSectionRow_(row, optional_columns, meta, n_section_columns));
if (n_header_columns != n_section_columns) throw Exception::Postcondition(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Header and content differs in columns. Please report this bug to the OpenMS developers.");
}
}
// auxiliary functions
/// Helper function for "generateMzTabSectionRow_" functions
static void addOptionalColumnsToSectionRow_(const std::vector<String>& column_names, const std::vector<MzTabOptionalColumnEntry>& column_entries, StringList& output);
// extract two integers from string (e.g. search_engine_score[1]_ms_run[2] -> 1,2)
static std::pair<int, int> extractIndexPairsFromBrackets_(const String& s);
static void sortPSM_(PeptideIdentificationList::iterator begin, PeptideIdentificationList::iterator end);
static void keepFirstPSM_(PeptideIdentificationList::iterator begin, PeptideIdentificationList::iterator end);
/// Extract protein and peptide identifications for each run. maps are assumed empty.
static void partitionIntoRuns_(const PeptideIdentificationList& pep_ids,
const std::vector<ProteinIdentification>& pro_ids,
std::map<String, PeptideIdentificationList >& map_run_to_pepids,
std::map<String, std::vector<ProteinIdentification> >& map_run_to_proids
);
/// create links from protein to peptides
static void createProteinToPeptideLinks_(const std::map<String, PeptideIdentificationList >& map_run_to_pepids, MapAccPepType& map_run_accession_to_pephits);
/// Extracts, if possible a unique protein accession for a peptide hit in mzTab format. Otherwise NA is returned
static String extractProteinAccession_(const PeptideHit& peptide_hit);
/// Extracts, modifications and positions of a peptide hit in mzTab format
static String extractPeptideModifications_(const PeptideHit& peptide_hit);
/// Map search engine identifier to CV, param etc.
static String mapSearchEngineToCvParam_(const String& openms_search_engine_name);
static String mapSearchEngineScoreToCvParam_(const String& openms_search_engine_name, double score, String score_type);
static String extractNumPeptides_(const String& common_identifier, const String& protein_accession,
const MapAccPepType& map_run_accession_to_peptides);
// mzTab definition of distinct
static String extractNumPeptidesDistinct_(String common_identifier, String protein_accession,
const MapAccPepType& map_run_accession_to_peptides);
// same as distinct but additional constraint of uniqueness (=maps to exactly one Protein)
static String extractNumPeptidesUnambiguous_(String common_identifier, String protein_accession,
const MapAccPepType& map_run_accession_to_peptides);
static std::map<String, Size> extractNumberOfSubSamples_(const std::map<String, std::vector<ProteinIdentification> >& map_run_to_proids);
static void writePeptideHeader_(SVOutStream& output, std::map<String, Size> n_sub_samples);
static void writeProteinHeader_(SVOutStream& output, std::map<String, Size> n_sub_samples);
static void writeProteinData_(SVOutStream& output,
const ProteinIdentification& prot_id,
Size run_count,
String input_filename,
bool has_coverage,
const MapAccPepType& map_run_accession_to_peptides,
const std::map<String, Size>& map_run_to_num_sub
);
private:
friend class MzTabMFile;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/FileHandler.h | .h | 20,402 | 392 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/config.h>
#include <OpenMS/ANALYSIS/MAPMATCHING/TransformationDescription.h>
#include <OpenMS/FORMAT/FileTypes.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/FORMAT/OPTIONS/PeakFileOptions.h>
#include <OpenMS/FORMAT/OPTIONS/FeatureFileOptions.h>
#include <OpenMS/METADATA/ProteinIdentification.h>
#include <OpenMS/METADATA/PeptideIdentification.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
#include <OpenMS/KERNEL/ConsensusMap.h>
namespace OpenMS
{
class PeakFileOptions;
class MSSpectrum;
class MSExperiment;
class FeatureMap;
class ConsensusMap;
class TargetedExperiment;
/**
@brief Facilitates file handling by file type recognition.
This class provides file type recognition from the file name and
from the file content.
It also offer a common interface to load MSExperiment data
and allows querying for supported file types.
@see FileTypes
@ingroup FileIO
*/
class OPENMS_DLLAPI FileHandler
{
public:
/**
@brief Tries to determine the file type (by name or content)
First tries to determine the type from the file name.
If this fails, the type is determined from the file content.
@param[in] filename the name of the file to check
@return A FileTypes::Type corresponding to the extension, or FileTypes::UNKNOWN if not determinable
@exception Exception::FileNotFound is thrown if the file is not present
*/
static FileTypes::Type getType(const String& filename);
/**
@brief Try to get the file type from the filename
@param[in] filename the name of the file to check
@return A FileTypes::Type corresponding to the extension, or FileTypes::UNKNOWN if not determinable
@exception Exception::FileNotFound is thrown if the file is not present
*/
static FileTypes::Type getTypeByFileName(const String& filename);
/**
@brief Check if @p filename has the extension @p type
If the extension is not known (e.g. '.tmp') this is also allowed.
However, if the extension is another one (neither @p type nor unknown), false is returned.
@param[in] filename The filename to check
@param[in] type The expected file type
*/
static bool hasValidExtension(const String& filename, const FileTypes::Type type);
/**
@brief If filename contains an extension, it will be removed (including the '.'). Special extensions, known to OpenMS, e.g. '.mzML.gz' will be recognized as well.
E.g. 'experiment.featureXML' becomes 'experiment' and 'c:\\files\\data.mzML.gz' becomes 'c:\\files\\data'
If the extension is unknown, the everything in the basename of the file after the last '.' is removed. E.g. 'future.newEnding' becomes 'future'
If the filename does not contain '.', but the path (if any) does, nothing is removed, e.g. '/my.dotted.dir/filename' is returned unchanged.
@param[in] filename the name to strip
@return the stripped filename
*/
static String stripExtension(const String& filename);
/**
@brief Tries to find and remove a known file extension, and append the new one.
Internally calls 'stripExtension()' and adds the new suffix to the result.
E.g. 'experiment.featureXML'+ FileTypes::TRANSFORMATIONXML becomes 'experiment.trafoXML' and 'c:\\files\\data.mzML.gz' + FileTypes::FEATUREXML becomes 'c:\\files\\data.featureXML'
If the existing extension is unknown, the everything after the last '.' is removed, e.g. 'exp.tmp' + FileTypes::IDXML becomes 'exp.idXML'
@param[in] filename the original @p filename
@param[in] new_type the @p FileTypes::Types to use to set the new extension
@return the updated string
*/
static String swapExtension(const String& filename, const FileTypes::Type new_type);
/**
@brief Useful function for TOPP tools which have an 'out_type' parameter and want to know what
output format to write.
This function makes sure that the type derived from @p output_filename and @p requested_type are consistent, i.e.
are either identical or one of them is UNKNOWN. Upon conflict, an error message is printed and the UNKNOWN type is returned.
@param[in] output_filename A full filename (with none, absolute or relative paths) whose type is
determined using FileHandler::getTypeByFileName() internally
@param[in] requested_type A type as string, usually obtained from '-out_type', e.g. "FASTA" (case insensitive).
The string can be empty (yields UNKNOWN for this type)
@return A consistent file type or UNKNOWN upon conflict
*/
static FileTypes::Type getConsistentOutputfileType(const String& output_filename, const String& requested_type);
/**
@brief Determines the file type of a file by parsing the first few lines
@param[in] filename The file to check
@exception Exception::FileNotFound is thrown if the file is not present
*/
static FileTypes::Type getTypeByContent(const String& filename);
/// @brief Returns if the file type is supported in this build of the library
static bool isSupported(FileTypes::Type type);
/// @brief Mutable access to the options for loading/storing
PeakFileOptions& getOptions();
/// @brief Non-mutable access to the options for loading/storing
const PeakFileOptions& getOptions() const;
/// @brief Mutable access to the feature file options for loading/storing
FeatureFileOptions& getFeatOptions();
/// @brief Non-mutable access to the feature file options for loading/storing
const FeatureFileOptions& getFeatOptions() const;
/// @brief set options for loading/storing
void setOptions(const PeakFileOptions&);
/// @brief set feature file options for loading/storing
void setFeatOptions(const FeatureFileOptions&);
/**
@brief Loads a file into an MSExperiment
@param[out] filename The file name of the file to load.
@param[in] exp The experiment to load the data into.
@param[in] allowed_types A vector of supported filetypes. If the vector is empty, load from any type that we have a handler for. Otherwise @p getType() is called internally to check the type
@param[in] log Progress logging mode
@param[in] rewrite_source_file Set's the SourceFile name and path to the current file. Note that this looses the link to the primary MS run the file originated from.
@param[out] compute_hash If source files are rewritten, this flag triggers a recomputation of hash values. A SHA1 string gets stored in the checksum member of SourceFile.
@exception Exception::FileNotFound is thrown if the file could not be opened
@exception Exception::ParseError is thrown if an error occurs during parsing
*/
void loadExperiment(const String& filename, PeakMap& exp, const std::vector<FileTypes::Type> allowed_types = std::vector<FileTypes::Type>(),
ProgressLogger::LogType log = ProgressLogger::NONE, const bool rewrite_source_file = false,
const bool compute_hash = false);
/**
@brief Stores an MSExperiment to a file
The file type to store the data in is determined by the file name. Supported formats for storing are mzML, mzXML, mzData and DTA2D. If the file format cannot be determined from the file name, the mzML format is used.
@param[in] filename The name of the file to store the data in.
@param[out] exp The experiment to store.
@param[in] allowed_types A vector of supported filetypes. If empty we try to guess based on the filename. If that fails we throw UnableToCreateFile. If there is only one allowed type, check whether it agrees with the filename, and throw UnableToCreateFile if they disagree.
@param[in] log Progress logging mode
@exception Exception::UnableToCreateFile is thrown if the file could not be written
*/
void storeExperiment(const String& filename, const PeakMap& exp, const std::vector<FileTypes::Type> allowed_types = {}, ProgressLogger::LogType log = ProgressLogger::NONE);
/**
@brief Loads a single MSSpectrum from a file
@param[in] filename The file name of the file to load.
@param[out] spec The spectrum to load the data into.
@param[in] allowed_types A vector of supported filetypes. If the vector is empty, load from any type that we have a handler for. Otherwise @p getType() is called internally to check the type
@exception Exception::FileNotFound is thrown if the file could not be opened
@exception Exception::ParseError is thrown if an error occurs during parsing
*/
void loadSpectrum(const String& filename, MSSpectrum& spec, const std::vector<FileTypes::Type> allowed_types = {});
/**
@brief Stores a single MSSpectrum to a file
@param[in] filename The file name of the file to store.
@param[in] spec The spectrum to store the data from.
@param[in] allowed_types A vector of supported filetypes. If the vector is empty, load from any type that we have a handler for. Otherwise @p getType() is called internally to check the type
@exception Exception::UnableToCreateFile is thrown if the file could not be written
*/
void storeSpectrum(const String& filename, MSSpectrum& spec, const std::vector<FileTypes::Type> allowed_types = {});
/**
@brief Loads a file into a FeatureMap
@param[in] filename the file name of the file to load.
@param[out] map The FeatureMap to load the data into.
@param[in] allowed_types A vector of supported filetypes. If the vector is empty, load from any type that we have a handler for. Otherwise @p getType() is called internally to check the type
@param[in] log Progress logging mode
@exception Exception::FileNotFound is thrown if the file could not be opened
@exception Exception::ParseError is thrown if an error occurs during parsing
*/
void loadFeatures(const String& filename, FeatureMap& map, const std::vector<FileTypes::Type> allowed_types = {}, ProgressLogger::LogType log = ProgressLogger::NONE);
/**
@brief Store a FeatureMap
@param[in] filename the file name of the file to write.
@param[out] map The FeatureMap to store.
@param[in] allowed_types A vector of supported filetypes. If empty we try to guess based on the filename. If that fails we throw UnableToCreateFile. If there is only one allowed type, check whether it agrees with the filename, and throw UnableToCreateFile if they disagree.
@param[in] log Progress logging mode
@exception Exception::UnableToCreateFile is thrown if the file could not be written
*/
void storeFeatures(const String& filename, const FeatureMap& map, const std::vector<FileTypes::Type> allowed_types = {}, ProgressLogger::LogType log = ProgressLogger::NONE);
/**
@brief Loads a file into a ConsensusMap
@param[in] filename the file name of the file to load.
@param[in] map The ConsensusMap to load the data into.
@param[in] allowed_types A vector of supported filetypes. If the vector is empty, load from any type that we have a handler for. Otherwise @p getType() is called internally to check the type
@param[in] log Progress logging mode
@exception Exception::FileNotFound is thrown if the file could not be opened
@exception Exception::ParseError is thrown if an error occurs during parsing
*/
void loadConsensusFeatures(const String& filename, ConsensusMap& map, const std::vector<FileTypes::Type> allowed_types = {}, ProgressLogger::LogType log = ProgressLogger::NONE);
/**
@brief Store a ConsensusFeatureMap
@param[in] filename the file name of the file to write.
@param[out] map The ConsensusMap to store.
@param[in] allowed_types A vector of supported filetypes. If empty we try to guess based on the filename. If that fails we throw UnableToCreateFile. If there is only one allowed type, check whether it agrees with the filename, and throw UnableToCreateFile if they disagree.
@param[in] log Progress logging mode
@exception Exception::UnableToCreateFile is thrown if the file could not be written
*/
void storeConsensusFeatures(const String& filename, const ConsensusMap& map, const std::vector<FileTypes::Type> allowed_types = {}, ProgressLogger::LogType log = ProgressLogger::NONE);
/**
@brief Loads an identification file into a proteinIdentifications and peptideIdentifications
@param[in] filename the file name of the file to load.
@param[in] additional_proteins The proteinIdentification vector to load the data into.
@param[in] additional_peptides The peptideIdentification vector to load the data into.
@param[in] allowed_types A vector of supported filetypes. If the vector is empty, load from any type that we have a handler for. Otherwise @p getType() is called internally to check the type
@param[in] log Progress logging mode
@exception Exception::FileNotFound is thrown if the file could not be opened
@exception Exception::ParseError is thrown if an error occurs during parsing
*/
void loadIdentifications(const String& filename, std::vector<ProteinIdentification>& additional_proteins, PeptideIdentificationList& additional_peptides, const std::vector<FileTypes::Type> allowed_types = {}, ProgressLogger::LogType log = ProgressLogger::NONE);
/**
@brief Stores proteins and peptides into an Identification File
@param[in] filename the file name of the file to write to.
@param[in] additional_proteins The proteinIdentification vector to load the data from.
@param[in] additional_peptides The peptideIdentification vector to load the data from.
@param[in] allowed_types A vector of supported filetypes. If empty we try to guess based on the filename. If that fails we throw UnableToCreateFile. If there is only one allowed type, check whether it agrees with the filename, and throw UnableToCreateFile if they disagree.
@param[in] log Progress logging mode
@exception Exception::UnableToCreateFile is thrown if the file could not be written
*/
void storeIdentifications(const String& filename, const std::vector<ProteinIdentification>& additional_proteins, const PeptideIdentificationList& additional_peptides, const std::vector<FileTypes::Type> allowed_types = {}, ProgressLogger::LogType log = ProgressLogger::NONE);
/**
@brief Load transitions of a spectral library
@param[in] filename the file name of the file to read.
@param[out] library The TargetedExperiment to load.
@param[in] allowed_types A vector of supported filetypes. If the vector is empty, load from any type that we have a handler for. Otherwise @p getType() is called internally to check the type
@param[in] log Progress logging mode
@exception Exception::FileNotFound is thrown if the file could not be opened
@exception Exception::ParseError is thrown if an error occurs during parsing
*/
void loadTransitions(const String& filename, TargetedExperiment& library, const std::vector<FileTypes::Type> allowed_types = {}, ProgressLogger::LogType log = ProgressLogger::NONE);
/**
@brief Store transitions of a spectral library
@param[out] filename the file name of the file to write.
@param[out] library The TargetedExperiment to store.
@param[in] allowed_types A vector of supported filetypes. If empty we try to guess based on the filename. If that fails we throw UnableToCreateFile. If there is only one allowed type, check whether it agrees with the filename, and throw UnableToCreateFile if they disagree.
@param[in] log Progress logging mode
@exception Exception::UnableToCreateFile is thrown if the file could not be written
*/
void storeTransitions(const String& filename, const TargetedExperiment& library, const std::vector<FileTypes::Type> allowed_types = {}, ProgressLogger::LogType log = ProgressLogger::NONE);
/**
@brief Loads a file into Transformations
@param[in] filename the file name of the file to load.
@param[out] map The Transformations to load the data into.
@param[in] fit_model Call fitModel() on the @p map before returning?
@param[in] allowed_types A vector of supported filetypes. If the vector is empty, load from any type that we have a handler for. Otherwise @p getType() is called internally to check the type
@exception Exception::FileNotFound is thrown if the file could not be opened
@exception Exception::ParseError is thrown if an error occurs during parsing
*/
void loadTransformations(const String& filename, TransformationDescription& map, bool fit_model=true, const std::vector<FileTypes::Type> allowed_types = {});
/**
@brief Store Transformations
@param[out] filename the file name of the file to write.
@param[in] map The Transformations to store.
@param[in] allowed_types A vector of supported filetypes. If empty we try to guess based on the filename. If that fails we throw UnableToCreateFile. If there is only one allowed type, check whether it agrees with the filename, and throw UnableToCreateFile if they disagree.
@exception Exception::UnableToCreateFile is thrown if the file could not be written
*/
void storeTransformations(const String& filename, const TransformationDescription& map, const std::vector<FileTypes::Type> allowed_types = {});
/**
@brief Store QC info
@brief Stores QC data in mzQC file with JSON format
@param[in] input_file mzML input file name
@param[in] filename mzQC output file name
@param[in] exp MSExperiment to extract QC data from, prior sortSpectra() and updateRanges() required
@param[in] feature_map FeatureMap from feature file (featureXML)
@param[in] prot_ids protein identifications from ID file (idXML)
@param[in] pep_ids protein identifications from ID file (idXML)
@param[out] consensus_map an optional consensus map to store.
@param[in] contact_name name of the person creating the mzQC file
@param[in] contact_address contact address (mail/e-mail or phone) of the person creating the mzQC file
@param[in] description description and comments about the mzQC file contents
@param[in] label unique and informative label for the run
@param[in] remove_duplicate_features whether to remove duplicate features only for QCML for now
@param[in] allowed_types A vector of supported filetypes. If empty we try to guess based on the filename. If that fails we throw UnableToCreateFile. If there is only one allowed type, check whether it agrees with the filename, and throw UnableToCreateFile if they disagree.
@exception Exception::UnableToCreateFile is thrown if the file could not be written
*/
void storeQC(const String& input_file,
const String& filename,
const MSExperiment& exp,
const FeatureMap& feature_map,
std::vector<ProteinIdentification>& prot_ids,
PeptideIdentificationList& pep_ids,
const ConsensusMap& consensus_map = ConsensusMap(),
const String& contact_name = "",
const String& contact_address = "",
const String& description = "",
const String& label = "label",
const bool remove_duplicate_features = false,
const std::vector<FileTypes::Type> allowed_types = {});
/**
@brief Computes a SHA-1 hash value for the content of the given file.
@return The SHA-1 hash of the given file.
*/
static String computeFileHash(const String& filename);
private:
PeakFileOptions options_;
FeatureFileOptions f_options_;
};
} //namespace
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/XMLFile.h | .h | 3,592 | 107 | // 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 $
// --------------------------------------------------------------------------
#pragma once
// OpenMS includes
#include <OpenMS/CONCEPT/Types.h>
#include <OpenMS/DATASTRUCTURES/String.h>
namespace OpenMS
{
namespace Internal
{
class XMLHandler;
///Base class for loading/storing XML files that have a handler derived from XMLHandler.
class OPENMS_DLLAPI XMLFile
{
public:
///Default constructor
XMLFile();
/// Constructor that sets the schema location
XMLFile(const String& schema_location, const String& version);
///Destructor
virtual ~XMLFile();
/**
@brief Checks if a file validates against the XML schema
Error messages are printed to the error stream, unless redirected with the attribute @p os .
@param[in] filename The name of the file to validate.
@param[in,out] os The ostream where error messages should be send.
@exception Exception::FileNotFound is thrown if the file cannot be found
@exception Exception::NotImplemented is thrown if there is no schema available for the file type
*/
bool isValid(const String& filename, std::ostream& os);
///return the version of the schema
const String& getVersion() const;
protected:
/**
@brief Parses the XML file given by @p filename using the handler given by @p handler.
@param[in] filename The XML file to parse
@param[in] handler The XML handler to use for parsing
@exception Exception::FileNotFound is thrown if the file is not found
@exception Exception::ParseError is thrown if an error occurred during the parsing
*/
void parse_(const String& filename, XMLHandler* handler);
/**
@brief Parses the in-memory buffer given by @p buffer using the handler given by @p handler.
@param[in] buffer The buffer to parse
@param[in] handler The XML handler to use for parsing
@note Currently the buffer needs to be plain text, gzip buffer is not supported.
@exception Exception::ParseError is thrown if an error occurred during the parsing
*/
void parseBuffer_(const std::string & buffer, XMLHandler * handler);
/**
@brief Stores the contents of the XML handler given by @p handler in the file given by @p filename.
@param[in] filename The output filename
@param[in] handler The XML handler containing the content to write
@exception Exception::UnableToCreateFile is thrown if the file cannot be created
*/
void save_(const String& filename, XMLHandler* handler) const;
/// XML schema file location
String schema_location_;
/// Version string
String schema_version_;
/// Encoding string that replaces the encoding (system dependent or specified in the XML). Disabled if empty. Used as a workaround for XTandem output xml.
String enforced_encoding_;
void enforceEncoding_(const String& encoding);
};
/**
@brief Encodes tabs '\\t' in the string as &\#x9; and returns the encoded string.
@param[in] to_encode The String to encode.
@return The encoded string.
*/
String OPENMS_DLLAPI encodeTab(const String& to_encode);
} // namespace Internal
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/FASTAFile.h | .h | 7,166 | 184 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow, Nora Wild $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CONCEPT/Exception.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <fstream>
#include <utility>
#include <vector>
namespace OpenMS
{
/**
@brief This class serves for reading in and writing FASTA files
If the protein/gene sequence contains unusual symbols (such as translation end (*)),
they will be kept!
You can use aggregate methods load() and store() to read/write a
set of protein sequences at the cost of memory.
Or use single read/write of protein sequences using readStart(), readNext()
and writeStart(), writeNext(), writeEnd() for more memory efficiency.
Reading from one and writing to another FASTA file can be handled by
one single FASTAFile instance.
*/
class OPENMS_DLLAPI FASTAFile : public ProgressLogger
{
public:
/**
@brief FASTA entry type (identifier, description and sequence)
The first String corresponds to the identifier that is
written after the > in the FASTA file. The part after the
first whitespace is stored in description and the text
from the next line until the next > (exclusive) is stored
in sequence.
*/
struct FASTAEntry
{
String identifier;
String description;
String sequence;
FASTAEntry() = default;
FASTAEntry(const String& id, const String& desc, const String& seq) :
identifier(id),
description(desc),
sequence(seq)
{
}
FASTAEntry(const FASTAEntry& rhs) = default;
FASTAEntry(FASTAEntry&& rhs) noexcept
:
identifier(::std::move(rhs.identifier)),
description(::std::move(rhs.description)),
sequence(::std::move(rhs.sequence))
{
}
FASTAEntry& operator=(const FASTAEntry& rhs) = default;
bool operator==(const FASTAEntry& rhs) const
{
return identifier == rhs.identifier
&& description == rhs.description
&& sequence == rhs.sequence;
}
bool headerMatches(const FASTAEntry& rhs) const
{
return identifier == rhs.identifier &&
description == rhs.description;
}
bool sequenceMatches(const FASTAEntry& rhs) const
{
return sequence == rhs.sequence;
}
};
/// Default constructor
FASTAFile() = default;
/// Destructor
~FASTAFile() override = default;
/**
@brief Prepares a FASTA file given by @p filename for streamed reading using readNext().
@exception Exception::FileNotFound is thrown if the file does not exists.
@exception Exception::ParseError is thrown if the file does not suit to the standard.
*/
void readStart(const String& filename);
/// same as readStart(), but does internal progress logging whenever readNextWithProgress() is called
void readStartWithProgress(const String& filename, const String& progress_label);
/**
@brief Reads the next FASTA entry from file.
If you want to read all entries in one go, use load().
@return true if entry was read; false if EOF was reached
@exception Exception::FileNotFound is thrown if the file does not exists.
@exception Exception::ParseError is thrown if the file does not suit to the standard.
*/
bool readNext(FASTAEntry& protein);
/// same as readNext(), but does internal progress logging; use readStartWithProgress() to enable this
/// Calls progressEnd() when EOF is reached (i.e. when returning false)
bool readNextWithProgress(FASTAEntry& protein);
/// current stream position when reading a file
std::streampos position();
/// is stream at EOF?
bool atEnd();
/// seek stream to @p pos
bool setPosition(const std::streampos& pos);
/**
@brief Prepares a FASTA file given by 'filename' for streamed writing using writeNext().
@exception Exception::UnableToCreateFile is thrown if the process is not able to write to the file (disk full?).
*/
void writeStart(const String& filename);
/**
@brief Stores the data given by @p protein. Call writeStart() once before calling writeNext().
Call writeEnd() when done to close the file!
@exception Exception::UnableToCreateFile is thrown if the process is not able to write the file.
*/
void writeNext(const FASTAEntry& protein);
/**
@brief Closes the file (flush). Called implicitly when FASTAFile object goes out of scope.
*/
void writeEnd();
/**
@brief loads a FASTA file given by 'filename' and stores the information in 'data'
This uses more RAM than readStart() and readNext().
@exception Exception::FileNotFound is thrown if the file does not exists.
@exception Exception::ParseError is thrown if the file does not suit to the standard.
*/
void load(const String& filename, std::vector<FASTAEntry>& data) const;
/**
@brief stores the data given by 'data' at the file 'filename'
This uses more RAM than writeStart() and writeNext().
@exception Exception::UnableToCreateFile is thrown if the process is not able to write the file.
*/
void store(const String& filename, const std::vector<FASTAEntry>& data) const;
protected:
/**
@brief Reads a protein entry from the current file position and returns the ID and sequence
@return Return true if the protein entry was read and saved successfully, false otherwise
*/
bool readEntry_(std::string& id, std::string& description, std::string& seq);
std::fstream infile_; ///< filestream for reading; init using FastaFile::readStart()
std::ofstream outfile_; ///< filestream for writing; init using FastaFile::writeStart()
Size entries_read_{0}; ///< some internal book-keeping during reading
std::streampos fileSize_{}; ///< total number of characters of filestream
std::string seq_; ///< sequence of currently read protein
std::string id_; ///< identifier of currently read protein
std::string description_; ///< description of currently read protein
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/PepXMLFile.h | .h | 11,719 | 323 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CHEMISTRY/AASequence.h>
#include <OpenMS/CHEMISTRY/Element.h>
#include <OpenMS/CHEMISTRY/ResidueDB.h>
#include <OpenMS/FORMAT/HANDLERS/XMLHandler.h>
#include <OpenMS/FORMAT/XMLFile.h>
#include <OpenMS/METADATA/PeptideIdentification.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
#include <OpenMS/METADATA/ProteinIdentification.h>
#include <OpenMS/METADATA/SpectrumMetaDataLookup.h>
#include <vector>
#include <map>
#include <set>
namespace OpenMS
{
/**
@brief Used to load and store PepXML files
This class is used to load and store documents that implement the schema of PepXML files.
A documented schema for this format comes with the TPP and can also be
found at https://github.com/OpenMS/OpenMS/tree/develop/share/OpenMS/SCHEMAS
@ingroup FileIO
*/
class OPENMS_DLLAPI PepXMLFile :
protected Internal::XMLHandler,
public Internal::XMLFile
{
public:
/// Constructor
PepXMLFile();
/// Destructor
~PepXMLFile() override;
/**
@brief Loads peptide sequences with modifications out of a PepXML file
@param[in] filename PepXML file to load
@param[out] proteins Protein identification output
@param[out] peptides Peptide identification output
@param[out] experiment_name Experiment file name, which is used to extract the corresponding search results from the PepXML file.
@param[in] lookup Helper for looking up retention times (PepXML may contain only scan numbers).
@exception Exception::FileNotFound is thrown if the file could not be opened
@exception Exception::ParseError is thrown if an error occurs during parsing
*/
void load(const String& filename,
std::vector<ProteinIdentification>& proteins,
PeptideIdentificationList& peptides,
const String& experiment_name,
const SpectrumMetaDataLookup& lookup);
/**
@brief @a load function with empty defaults for some parameters (see above)
@exception Exception::FileNotFound is thrown if the file could not be opened
@exception Exception::ParseError is thrown if an error occurs during parsing
*/
void load(const String& filename,
std::vector<ProteinIdentification>& proteins,
PeptideIdentificationList& peptides,
const String& experiment_name = "");
/**
@brief Stores idXML as PepXML file
@exception Exception::UnableToCreateFile is thrown if the file could not be opened for writing
*/
void store(const String& filename, std::vector<ProteinIdentification>& protein_ids,
PeptideIdentificationList& peptide_ids, const String& mz_file = "",
const String& mz_name = "", bool peptideprophet_analyzed = false, double rt_tolerance = 0.01);
/**
@brief Whether we should keep the native spectrum name of the pepXML
@note This will lead to a "pepxml_spectrum_name" meta value being added
to each PeptideIdentification containing the original name of the
spectrum in TPP format.
*/
void keepNativeSpectrumName(bool keep)
{
keep_native_name_ = keep;
}
/// sets the preferred fixed modifications
void setPreferredFixedModifications(const std::vector<const ResidueModification*>& mods);
/// sets the preferred variable modifications
void setPreferredVariableModifications(const std::vector<const ResidueModification*>& mods);
/// sets if during load, unknown scores should be parsed
void setParseUnknownScores(bool parse_unknown_scores);
protected:
/// Docu in base class
void endElement(const XMLCh* const /*uri*/, const XMLCh* const /*local_name*/, const XMLCh* const qname) override;
/// Docu in base class
void startElement(const XMLCh* const /*uri*/, const XMLCh* const /*local_name*/, const XMLCh* const qname, const xercesc::Attributes& attributes) override;
private:
/// Fill @p scan_map_
void makeScanMap_();
/// Read RT, m/z, charge information from attributes of "spectrum_query"
void readRTMZCharge_(const xercesc::Attributes& attributes);
struct AminoAcidModification
{
private:
String aminoacid_;
double massdiff_;
double mass_;
bool is_variable_;
String description_;
String terminus_;
bool is_protein_terminus_; // "true" if protein terminus, "false" if peptide terminus
ResidueModification::TermSpecificity term_spec_;
std::vector<String> errors_;
const ResidueModification* registered_mod_;
const ResidueModification* lookupModInPreferredMods_(const std::vector<const ResidueModification*>& preferred_fixed_mods,
const String& aminoacid,
double massdiff,
const String& description,
const ResidueModification::TermSpecificity term_spec,
double tolerance);
public:
AminoAcidModification() = delete;
/// Creates an AminoAcidModification object from the pepXML attributes in
/// EITHER aminoacid_modification elements
/// OR terminal_modification elements
/// since we use them ambiguously
AminoAcidModification(
const String& aminoacid, const String& massdiff, const String& mass,
String variable, const String& description, String terminus, const String& protein_terminus,
const std::vector<const ResidueModification*>& preferred_fixed_mods,
const std::vector<const ResidueModification*>& preferred_var_mods,
double tolerance);
AminoAcidModification(const AminoAcidModification& rhs) = default;
virtual ~AminoAcidModification() = default;
AminoAcidModification& operator=(const AminoAcidModification& rhs) = default;
String toUnimodLikeString() const;
const String& getDescription() const;
bool isVariable() const;
const ResidueModification* getRegisteredMod() const;
double getMassDiff() const;
double getMass() const;
const String& getTerminus() const;
const String& getAminoAcid() const;
const std::vector<String>& getErrors() const;
};
/// Pointer to the list of identified proteins
std::vector<ProteinIdentification>* proteins_;
/// Pointer to the list of identified peptides
PeptideIdentificationList* peptides_;
/// Pointer to wrapper for looking up spectrum meta data
const SpectrumMetaDataLookup* lookup_;
/// Name of the associated experiment (filename of the data file, extension will be removed)
String exp_name_;
/// Set name of search engine
String search_engine_;
/// Several optional attributes of spectrum_query
String native_spectrum_name_;
String experiment_label_;
String swath_assay_;
String status_;
/// Get RT and m/z for peptide ID from precursor scan (should only matter for RT)?
bool use_precursor_data_{};
/// Mapping between scan number in the pepXML file and index in the corresponding MSExperiment
std::map<Size, Size> scan_map_;
/// Hydrogen data (for mass types)
Element hydrogen_;
/// Are we currently in an "analysis_summary" element (should be skipped)?
bool analysis_summary_;
/// Whether we should keep the native spectrum name of the pepXML
bool keep_native_name_;
/// Are we currently in an "search_score_summary" element (should be skipped)?
bool search_score_summary_;
/// Are we currently in an "search_summary" element (should be skipped)?
bool search_summary_{};
/// Do current entries belong to the experiment of interest (for pepXML files that bundle results from different experiments)?
bool wrong_experiment_{};
/// Have we seen the experiment of interest at all?
bool seen_experiment_{};
/// Have we checked the "base_name" attribute in the "msms_run_summary" element?
bool checked_base_name_{};
/// Does the file have decoys (e.g. from Comet's internal decoy search)
bool has_decoys_{};
/// Also parse unknown scores as metavalues?
bool parse_unknown_scores_{};
/// In case it has decoys, what is the prefix?
String decoy_prefix_;
/// current base name
String current_base_name_;
/// References to currently active ProteinIdentifications
std::vector<std::vector<ProteinIdentification>::iterator> current_proteins_;
/// Search parameters of the current identification run
ProteinIdentification::SearchParameters params_;
/// Enzyme name associated with the current identification run
String enzyme_;
String enzyme_cuttingsite_;
/// PeptideIdentification instance currently being processed
PeptideIdentification current_peptide_;
/// Analysis result instance currently being processed
PeptideHit::PepXMLAnalysisResult current_analysis_result_;
/// PeptideHit instance currently being processed
PeptideHit peptide_hit_;
/// Sequence of the current peptide hit
String current_sequence_;
/// RT and m/z of current PeptideIdentification (=spectrum)
double rt_{}, mz_{};
/// 1-based scan nr. of current PeptideIdentification (=spectrum). Scannr is usually from the start_scan attribute
Size scannr_{};
/// Precursor ion charge
Int charge_{};
/// ID of current search result
UInt search_id_{};
/// Identifier linking PeptideIdentifications and ProteinIdentifications
String prot_id_;
/// Date the pepXML file was generated
DateTime date_;
/// Mass of a hydrogen atom (monoisotopic/average depending on case)
double hydrogen_mass_{};
/// The modifications of the current peptide hit (position is 1-based)
std::vector<std::pair<const ResidueModification*, Size> > current_modifications_;
/// Fixed aminoacid modifications as parsed from the header
std::vector<AminoAcidModification> fixed_modifications_;
/// Variable aminoacid modifications as parsed from the header
std::vector<AminoAcidModification> variable_modifications_;
/// Fixed modifications that should be preferred when parsing the header
/// (e.g. when pepXML was produced through an adapter)
std::vector<const ResidueModification*> preferred_fixed_modifications_;
/// Variable modifications that should be preferred when parsing the header
/// (e.g. when pepXML was produced through an adapter)
std::vector<const ResidueModification*> preferred_variable_modifications_;
//@}
static const double mod_tol_;
static const double xtandem_artificial_mod_tol_;
/// looks up modification by @p modification_mass and aminoacid of current_sequence_[ @p modification_position ]
/// and adds it to the current_modifications_
bool lookupAddFromHeader_(double modification_mass,
Size modification_position,
std::vector<AminoAcidModification> const& header_mods);
//static std::vector<int> getIsotopeErrorsFromIntSetting_(int intSetting);
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/ParamJSONFile.h | .h | 3,053 | 89 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Authors: Simon Gene Gottlieb $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/FORMAT/ParamCTDFile.h>
namespace OpenMS
{
/**
@brief Load from JSON (in a Common Workflow Language (CWL) compatible way) into the Param class.
The JSON file must contain one top level mapping of param value names to actual values.
These values can be one of the following types:
- null
- boolean
- int
- long
- float
- double
- string
- a CWL style file path ({ "class": "File", "path": "./myFolder/myFile.txt" })
- an array of these
param value names match the command line option without the leading '-'. Optionally the ':'
can be replaced with a double underscore "__".
@code
{
"in": {
"class": "File",
"path": "./myFolder/myFile.txt"
},
"out_prefix": "test_cwl_",
"algorithm:threshold": 5,
"algorithm:score_type": "ID"
}
@endcode
Same file with "__" instead of ':' as the section separator.
@code
{
"in": {
"class": "File",
"path": "./myFolder/myFile.txt"
},
"out_prefix": "test_cwl_",
"algorithm__threshold": 5,
"algorithm__score_type": "ID"
}
@endcode
*/
class OPENMS_DLLAPI ParamJSONFile
{
public:
/**
\brief If set to true, all parameters will be listed on when writing the JSON file.
The names will be expanded to include the nesting hierarchy.
*/
bool flatHierarchy{};
/**
@brief Read JSON file that is formatted in CWL conforming style.
@param[out] filename The file from where to read the Param object.
@param[out] param A param object with pre-filled defaults, which are updated by the values in the JSON file
@return returns true if file was successfully loaded; false if an unknown (non-default) parameter name was encountered in the JSON file
@exception Exception::FileNotFound is thrown if the file could not be found
@exception Exception::ParseError is thrown if an error occurs during parsing
*/
static bool load(const std::string& filename, Param& param);
/**
@brief Write Json file with set values
@param[in] filename The name of the file the param data structure should be stored in.
@param[in,out] param The param data structure that should be stored.
@param[in] tool_info unused, required for compatiblity with ParamCWLFile
@exception std::ios::failure is thrown if the file could not be created
*/
void store(const std::string& filename, const Param& param, const ToolInfo& tool_info) const;
void writeToStream(std::ostream* os_ptr, const Param& param) const;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/OMSFile.h | .h | 2,707 | 87 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/METADATA/ID/IdentificationData.h>
namespace OpenMS
{
class FeatureMap;
class ConsensusMap;
/**
@brief This class supports reading and writing of OMS files.
OMS files are SQLite databases consisting of several tables.
*/
class OPENMS_DLLAPI OMSFile: public ProgressLogger
{
public:
/// Constructor (with option to set log type)
explicit OMSFile(LogType log_type = LogType::NONE):
log_type_(log_type)
{
setLogType(log_type);
}
/** @brief Write out an IdentificationData object to SQL-based OMS file
*
* @param[in] filename The output file
* @param[in] id_data The IdentificationData object
*/
void store(const String& filename, const IdentificationData& id_data);
/** @brief Write out a feature map to SQL-based OMS file
*
* @param[in] filename The output file
* @param[in] features The feature map
*/
void store(const String& filename, const FeatureMap& features);
/** @brief Write out a consensus map to SQL-based OMS file
*
* @param[in] filename The output file
* @param[in] consensus The consensus map
*/
void store(const String& filename, const ConsensusMap& consensus);
/** @brief Read in an OMS file and construct an IdentificationData object
*
* @param[out] filename The input file
* @param[in] id_data The IdentificationData object
*/
void load(const String& filename, IdentificationData& id_data);
/** @brief Read in an OMS file and construct a feature map
*
* @param[out] filename The input file
* @param[in] features The feature map
*/
void load(const String& filename, FeatureMap& features);
/** @brief Read in an OMS file and construct a consensus map
*
* @param[out] filename The input file
* @param[in] consensus The consensus map
*/
void load(const String& filename, ConsensusMap& consensus);
/** @brief Read in an OMS file and write out the contents in JSON format
*
* @param[in] filename_in The input file (OMS)
* @param[out] filename_out The output file (JSON)
*/
void exportToJSON(const String& filename_in, const String& filename_out);
protected:
LogType log_type_;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/MSPGenericFile.h | .h | 4,187 | 135 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/config.h> // OPENMS_DLLAPI
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/KERNEL/MSExperiment.h>
namespace OpenMS
{
/**
@brief Load MSP text file and save it into an `MSExperiment`
This class is specialized for metabolites data.
The required fields are: Name, Num Peaks, and the peaks data
Points (meaning x and y info) may be separated by a space or a colon.
Peaks may be separated by a space or a semicolon.
An example of the expected format:
> Name: foo
> Num Peaks: 11
> 35 310; 36 1230; 37 27; 38 303; 47 5240;
> 66 203; 67 68; 68 77; 82 63; 83 240;
> 136 350;
Another supported format:
> Name: bar
> Num Peaks: 11
> 35:310 36:1230 37:27 38:303 47:5240
> 66:203 67:68 68:77 82:63 83:240
> 136:350
*/
class OPENMS_DLLAPI MSPGenericFile :
public DefaultParamHandler
{
public:
/// Default constructor
MSPGenericFile();
/// Constructor with filename and output library
MSPGenericFile(const String& filename, MSExperiment& library);
/// Destructor
~MSPGenericFile() override = default;
/// Get the class' default parameters
void getDefaultParameters(Param& params);
/// To test private and protected methods
friend class MSPGenericFile_friend;
/**
@brief Load the file's data and metadata, and save it into an `MSExperiment`.
@param[in] filename Path to the MSP input file
@param[out] library The variable into which the extracted information will be saved
@throw FileNotFound If the file could not be found
*/
void load(const String& filename, MSExperiment& library);
/**
@brief Save data and metadata into a file.
@param[in] filename Path to the MSP input file
@param[out] library The variable from which extracted information will be saved
@throw FileNotWritable If the file is not writable
*/
void store(const String& filename, const MSExperiment& library) const;
private:
/// Overrides `DefaultParamHandler`'s method
void updateMembers_() override;
/**
Validate and add a spectrum to a spectral library
The spectrum is added to the library if all following criteria are met:
- Name field is present and not empty
- The number of peaks parsed matches the value of Num Peaks
- A spectrum of the same name has not already been added
@throw MissingInformation If the spectrum doesn't have a name or Num Peaks info is missing
@throw ParseError If Num Peaks' value doesn't match with the number of raw peaks parsed
@param[in,out] spectrum The spectrum to be added
@param[out] library The spectrum is added into this `MSExperiment` library
*/
void addSpectrumToLibrary(
MSSpectrum& spectrum,
MSExperiment& library
);
/// To keep track of which spectra have already been loaded and avoid duplicates
std::set<String> loaded_spectra_names_;
/*
The synonyms of a spectrum are collected into this variable and,
when `addSpectrumtoLibrary()` is called, the elements are concatenated
and the result is saved as a "Synon" metaValue.
The synonyms are separated by `synonyms_separator_`.
*/
std::vector<String> synonyms_;
/// The separator to be used in "Synon" metaValue
String synonyms_separator_;
};
class MSPGenericFile_friend
{
public:
MSPGenericFile_friend() = default;
~MSPGenericFile_friend() = default;
void addSpectrumToLibrary(
MSSpectrum& spectrum,
MSExperiment& library
)
{
return msp_.addSpectrumToLibrary(spectrum, library);
}
MSPGenericFile msp_;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/Bzip2Ifstream.h | .h | 2,936 | 98 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/config.h>
#include <bzlib.h>
#include <istream>
namespace OpenMS
{
/**
@brief Decompresses files which are compressed in the bzip2 format (*.bz2)
*/
class OPENMS_DLLAPI Bzip2Ifstream
{
public:
///Default Constructor
Bzip2Ifstream();
/// Detailed constructor with filename
explicit Bzip2Ifstream(const char * filename);
///Destructor
virtual ~Bzip2Ifstream();
/**
* @brief Reads n bytes from the bzip2 compressed file into buffer s
*
* @param[out] s Buffer to be filled with the output
* @param[in] n The size of the buffer s
* @return The number of actually read bytes. If it is less than n, the end of the file was reached and the stream is closed
*
* @note This returns a raw byte stream that is *not* null-terminated. Be careful here.
* @note The length of the buffer needs to at least n
* @note Closes the stream if the end of file is reached. Check isOpen before reading from the file again
*
* @exception Exception::ConversionError is thrown if decompression fails
* @exception Exception::IllegalArgument is thrown if no file for decompression is given. This can happen even happen if a file was already open but read until the end.
*/
size_t read(char * s, size_t n);
/**
* @brief indicates whether the read function can be used safely
*
* @return true if end of file was reached. Otherwise false.
*/
bool streamEnd() const;
/**
* @brief returns whether a file is open.
*/
bool isOpen() const;
/**
* @brief opens a file for reading (decompression)
* @note any previous open files will be closed first!
*/
void open(const char * filename);
/**
* @brief closes current file.
*/
void close();
protected:
/// pointer to a FILE object. Necessary for opening the file
FILE * file_;
/// a pointer to a BZFILE object. Necessary for decompression
BZFILE * bzip2file_;
///counts the last read buffer
size_t n_buffer_;
///saves the last returned error by the read function
int bzerror_;
///true if end of file is reached
bool stream_at_end_;
//not implemented
Bzip2Ifstream(const Bzip2Ifstream & bzip2);
Bzip2Ifstream & operator=(const Bzip2Ifstream & bzip2);
};
//return bzip2file???!!!!????
inline bool Bzip2Ifstream::isOpen() const
{
return file_ != nullptr;
}
inline bool Bzip2Ifstream::streamEnd() const
{
return stream_at_end_;
}
} //namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/OSWFile.h | .h | 5,718 | 140 | // 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, Chris Bielow $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CONCEPT/Exception.h>
#include <OpenMS/DATASTRUCTURES/OSWData.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/FORMAT/SqliteConnector.h>
#include <OpenMS/KERNEL/StandardTypes.h>
#include <array>
#include <map>
namespace OpenMS
{
/**
@brief This class serves for reading in and writing OpenSWATH OSW files.
See OpenSwathOSWWriter for more functionality.
The reader and writer returns data in a format suitable for PercolatorAdapter.
OSW files have a flexible data structure. They contain all peptide query
parameters of TraML/PQP files with the detected and quantified features of
OpenSwathWorkflow (feature, feature_ms1, feature_ms2 & feature_transition).
The OSWFile reader extracts the feature information from the OSW file for
each level (MS1, MS2 & transition) separately and generates Percolator input
files. For each of the three Percolator reports, OSWFile writer adds a table
(score_ms1, score_ms2, score_transition) with the respective confidence metrics.
These tables can be mapped to the corresponding feature tables, are very similar
to PyProphet results and can thus be used interchangeably.
*/
class OPENMS_DLLAPI OSWFile
{
public:
/// query all proteins, not just one with a particular ID
static constexpr Size ALL_PROTEINS = -1;
/// opens an OSW file for reading.
/// @throws Exception::FileNotReadable if @p filename does not exist
OSWFile(const String& filename);
OSWFile(const OSWFile& rhs) = default;
OSWFile& operator=(const OSWFile& rhs) = default;
/// read data from an SQLLite OSW file into @p swath_result
/// Depending on the number of proteins, this could take a while.
/// @note If you just want the proteins and transitions without peptides and features, use readMinimal().
void read(OSWData& swath_result);
/// Reads in transitions and a list of protein names/IDs
/// but no peptide/feature/transition mapping data (which could be very expensive).
/// Use in conjunction with on-demand readProtein() to fully populate proteins with peptide/feature data as needed.
/// @note If you read in all proteins afterwards in one go anyway, using the read() method will be faster (by about 30%)
void readMinimal(OSWData& swath_result);
/**
@brief populates a protein at index @p index within @p swath_results 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.
@param[in] swath_result OSWData obtained from the readMinimal() method
@param[out] index Index into swath_result.getProteins()[index]. Make sure the index is within the vector's size.
@throws Exception::InvalidValue if the protein at @p index does not have any peptides present in the OSW file
*/
void readProtein(OSWData& swath_result, const Size index);
/// for Percolator data read/write operations
enum class OSWLevel
{
MS1,
MS2,
TRANSITION,
SIZE_OF_OSWLEVEL
};
static const std::array<std::string, (Size)OSWLevel::SIZE_OF_OSWLEVEL> names_of_oswlevel;
struct PercolatorFeature
{
PercolatorFeature(double score, double qvalue, double pep)
: score(score), qvalue(qvalue), posterior_error_prob(pep)
{}
PercolatorFeature(const PercolatorFeature& rhs) = default;
double score;
double qvalue;
double posterior_error_prob;
};
/**
@brief Reads an OSW SQLite file and returns the data on MS1-, MS2- or transition-level
as ostream (e.g. stringstream or ofstream).
*/
static void readToPIN(const std::string& filename, const OSWFile::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);
/**
@brief Updates an OpenSWATH OSW SQLite file with the MS1-, MS2- or transition-level results of Percolator.
*/
static void writeFromPercolator(const std::string& osw_filename, const OSWFile::OSWLevel osw_level, const std::map< std::string, PercolatorFeature >& features);
/// extract the RUN::ID from the sqMass file
/// @throws Exception::SqlOperationFailed more than on run exists
UInt64 getRunID() const;
protected:
/** populate transitions of @p swath_result
Clears swath_result entirely (incl. proteins) before adding transitions.
*/
void readTransitions_(OSWData& swath_result);
/**
@brief fill one (@p prot_id) or all proteins into @p swath_result
@param[out] swath_result Output data. Proteins are cleared before if ALL_PROTEINS is used.
@param[in] prot_index Using ALL_PROTEINS queries all proteins (could take some time)
*/
void getFullProteins_(OSWData& swath_result, Size prot_index = ALL_PROTEINS);
/// set source file and sqMass run-ID
void readMeta_(OSWData& data);
private:
String filename_; ///< sql file to open/write to
SqliteConnector conn_; ///< SQL connection. Stays open as long as this object lives
bool has_SCOREMS2_; ///< database contains pyProphet's score_MS2 table with qvalues
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/InspectOutfile.h | .h | 7,105 | 158 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CONCEPT/Exception.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/METADATA/PeptideIdentification.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
#include <OpenMS/FORMAT/FileHandler.h>
#include <OpenMS/FORMAT/FileTypes.h>
namespace OpenMS
{
/**
@brief Representation of an Inspect outfile
This class serves to read in an Inspect outfile and write an idXML file
@todo Handle Modifications (Andreas)
@ingroup FileIO
*/
class OPENMS_DLLAPI InspectOutfile
{
public:
/// default constructor
InspectOutfile();
/// copy constructor
InspectOutfile(const InspectOutfile & inspect_outfile);
/// destructor
virtual ~InspectOutfile();
/// assignment operator
InspectOutfile & operator=(const InspectOutfile & inspect_outfile);
/// equality operator
bool operator==(const InspectOutfile & inspect_outfile) const;
/** load the results of an Inspect search
@param[out] result_filename Input parameter which is the file name of the input file
@param[out] peptide_identifications Output parameter which holds the peptide identifications from the given file
@param[out] protein_identification Output parameter which holds the protein identifications from the given file
@param[in] p_value_threshold
@param[in] database_filename
@throw FileNotFound is thrown if the given file could not be found
@throw ParseError is thrown if the given file could not be parsed
@throw FileEmpty is thrown if the given file is empty
*/
std::vector<Size> load(const String & result_filename, PeptideIdentificationList & peptide_identifications, ProteinIdentification & protein_identification, const double p_value_threshold, const String & database_filename = "");
/** loads only results which exceeds a given P-value threshold
@param[in] result_filename The filename of the results file
@param[in] p_value_threshold Only identifications exceeding this threshold are read
@throw FileNotFound is thrown is the file is not found
@throw FileEmpty is thrown if the given file is empty
*/
std::vector<Size> getWantedRecords(const String & result_filename, double p_value_threshold);
/** generates a trie database from another one, using the wanted records only
@throw Exception::FileNotFound
@throw Exception::ParseError
@throw Exception::UnableToCreateFile
*/
void compressTrieDB(const String & database_filename, const String & index_filename, std::vector<Size> & wanted_records, const String & snd_database_filename, const String & snd_index_filename, bool append = false);
/** generates a trie database from a given one (the type of database is determined by getLabels)
@throw Exception::FileNotFound
@throw Exception::UnableToCreateFile
*/
void generateTrieDB(const String & source_database_filename, const String & database_filename, const String & index_filename, bool append = false, const String& species = "");
/// retrieve the accession type and accession number from a protein description line
/// (e.g. from FASTA line: >gi|5524211|gb|AAD44166.1| cytochrome b [Elephas maximus maximus], get ac:AAD44166.1 ac type: GenBank)
void getACAndACType(String line, String & accession, String & accession_type);
/** retrieve the precursor retention time and mz value
@throw Exception::ParseError
*/
void getPrecursorRTandMZ(const std::vector<std::pair<String, std::vector<std::pair<Size, Size> > > > & files_and_peptide_identification_with_scan_number, PeptideIdentificationList & ids);
/** retrieve the labels of a given database (at the moment FASTA and Swissprot)
@throw Exception::FileNotFound
@throw Exception::ParseError
*/
void getLabels(const String & source_database_filename, String & ac_label, String & sequence_start_label, String & sequence_end_label, String & comment_label, String & species_label);
/** retrieve sequences from a trie database
@throw Exception::FileNotFound
*/
std::vector<Size> getSequences(const String & database_filename, const std::map<Size, Size> & wanted_records, std::vector<String> & sequences);
/**
get the experiment from a file
@throw Exception::ParseError is thrown if the file could not be parsed or the filetype could not be determined
*/
void getExperiment(PeakMap & exp, String & type, const String & in_filename)
{
type.clear();
exp.reset();
//input file type
FileHandler fh;
FileTypes::Type in_type = fh.getTypeByContent(in_filename);
if (in_type == FileTypes::UNKNOWN)
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Could not determine type of the file. Aborting!", in_filename);
}
type = FileTypes::typeToName(in_type);
fh.loadExperiment(in_filename, exp, {in_type});
}
/**
@brief get the search engine and its version from the output of the InsPecT executable without parameters
returns true on success, false otherwise
*/
bool getSearchEngineAndVersion(const String & cmd_output, ProteinIdentification & protein_identification);
/** @brief read the header of an inspect output file and retrieve various information
@throw Exception::ParseError
*/
void readOutHeader(const String & filename, const String & header_line, Int & spectrum_file_column, Int & scan_column, Int & peptide_column, Int & protein_column, Int & charge_column, Int & MQ_score_column, Int & p_value_column, Int & record_number_column, Int & DB_file_pos_column, Int & spec_file_pos_column, Size & number_of_columns);
protected:
/// a record in the index file that belongs to a trie database consists of three parts
/// 1) the protein's position in the original database
/// 2) the protein's position in the trie database
/// 3) the name of the protein (the line with the accession identifier)
static const Size db_pos_length_; ///< length of 1)
static const Size trie_db_pos_length_; ///< length of 2)
static const Size protein_name_length_; ///< length of 3)
static const Size record_length_; ///< length of the whole record
static const char trie_delimiter_; ///< the sequences in the trie database are delimited by this character
static const String score_type_; ///< type of score
};
} //namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/SequestInfile.h | .h | 14,701 | 272 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/String.h>
#include <map>
namespace OpenMS
{
/**
@brief Sequest input file adapter.
Creates a sequest.params file for Sequest search from a peak list.
@ingroup FileIO
*/
class OPENMS_DLLAPI SequestInfile
{
public:
/// default constructor
SequestInfile();
/// copy constructor
SequestInfile(const SequestInfile & sequest_infile);
/// destructor
virtual ~SequestInfile();
/// assignment operator
SequestInfile & operator=(const SequestInfile & sequest_infile);
/// equality operator
bool operator==(const SequestInfile & sequest_infile) const;
/** stores the experiment data in a Sequest input file that can be used as input for Sequest shell execution
@param[out] filename the name of the file in which the infile is stored into
@throw Exception::UnableToCreateFile is thrown if the file could not be created
*/
void store(const String & filename);
/// returns the enzyme list as a string
const String getEnzymeInfoAsString() const;
/// returns the used database
const String & getDatabase() const;
/// sets the used database
void setDatabase(const String & database);
/// returns whether neutral losses are considered for the a-, b- and y-ions
const String & getNeutralLossesForIons() const;
/// sets whether neutral losses are considered for the a-, b- and y-ions
void setNeutralLossesForIons(const String & neutral_losses_for_ions);
/// returns the weights for the a-, b-, c-, d-, v-, w-, x-, y- and z-ion series
const String & getIonSeriesWeights() const;
/// sets the weights for the a-, b-, c-, d-, v-, w-, x-, y- and z-ion series
void setIonSeriesWeights(const String & ion_series_weights);
/// returns the partial sequences (space delimited) that have to occur in the theoretical spectra
const String & getPartialSequence() const;
/// sets the partial sequences (space delimited) that have to occur in the theoretical spectra
void setPartialSequence(const String & partial_sequence);
/// returns the sequences (space delimited) that have to occur, or be absent (preceded by a tilde) in the header of a protein to be considered
const String & getSequenceHeaderFilter() const;
/// sets the sequences (space delimited) that have to occur, or be absent (preceded by a tilde) in the header of a protein to be considered
void setSequenceHeaderFilter(const String & sequence_header_filter);
/// returns the protein mass filter (either min and max mass, or mass and tolerance value in percent)
const String & getProteinMassFilter() const;
/// sets the protein mass filter (either min and max mass, or mass and tolerance value in percent)
void setProteinMassFilter(const String & protein_mass_filter);
/// returns the peak mass tolerance
float getPeakMassTolerance() const;
/// sets the peak mass tolerance
void setPeakMassTolerance(float peak_mass_tolerance);
/// returns the precursor mass tolerance
float getPrecursorMassTolerance() const;
/// sets the precursor mass tolerance
void setPrecursorMassTolerance(float precursor_mass_tolerance);
/// returns the match peak tolerance
float getMatchPeakTolerance() const;
/// sets the match peak tolerance
void setMatchPeakTolerance(float match_peak_tolerance);
/// returns the the cutoff of the ratio matching theoretical peaks/theoretical peaks
float getIonCutoffPercentage() const;
/// sets the ion cutoff of the ratio matching theoretical peaks/theoretical peaks
void setIonCutoffPercentage(float ion_cutoff_percentage);
/// returns the peptide mass unit
Size getPeptideMassUnit() const;
/// sets the peptide mass unit
void setPeptideMassUnit(Size peptide_mass_unit);
/// return the number of peptides to be displayed
Size getOutputLines() const;
/// sets the number of peptides to be displayed
void setOutputLines(Size output_lines);
/// returns the enzyme used for cleavage (by means of the number from a list of enzymes)
Size getEnzymeNumber() const;
/// returns the enzyme used for cleavage
String getEnzymeName() const;
/// sets the enzyme used for cleavage (by means of the number from a list of enzymes)
Size setEnzyme(const String& enzyme_name);
/// returns the maximum number of amino acids containing the same modification in a peptide
Size getMaxAAPerModPerPeptide() const;
/// sets the maximum number of amino acids containing the same modification in a peptide
void setMaxAAPerModPerPeptide(Size max_aa_per_mod_per_peptide);
/// returns the maximum number of modifications that are allowed in a peptide
Size getMaxModsPerPeptide() const;
/// set the maximum number of modifications that are allowed in a peptide
void setMaxModsPerPeptide(Size max_mods_per_peptide);
/// returns the nucleotide reading frame
Size getNucleotideReadingFrame() const;
/// sets the nucleotide reading frame:
/// 0 The FASTA file contains amino acid codes. No translation is needed. This is the best and fastest case.
/// 1 The DNA sequence is scanned left to right (forward direction). The amino acid code starts with the first DNA code.
/// 2 The DNA sequence is scanned left to right (forward direction). The amino acid code starts with the second DNA code.
/// 3 The DNA sequence is scanned left to right (forward direction). The amino acid code starts with the third DNA code.
/// 4 The DNA sequence is scanned right to left (backward direction for the complementary strand). The amino acid code starts with the first DNA code.
/// 5 The DNA sequence is scanned right to left (backward direction for the complementary strand). The amino acid code starts with the second DNA code.
/// 6 The DNA sequence is scanned right to left (backward direction for the complementary strand). The amino acid code starts with the third DNA code.
/// 7 Use each of the DNA translations of the codes 1, 2, 3.
/// 8 Use each of the DNA translations of the codes 4, 5, 6.
/// 9 Use each of the DNA translations of the codes 1, 2, 3, 4, 5, 6.
void setNucleotideReadingFrame(Size nucleotide_reading_frame);
/// returns the maximum number of internal cleavage sites
Size getMaxInternalCleavageSites() const;
/// sets the maximum number of internal cleavage sites
void setMaxInternalCleavageSites(Size max_internal_cleavage_sites);
/// returns the number of top abundant peaks to match with theoretical ones
Size getMatchPeakCount() const;
/// sets the number of top abundant peaks to with theoretical ones
void setMatchPeakCount(Size match_peak_count);
/// returns the number of top abundant peaks that are allowed not to match with a theoretical peak
Size getMatchPeakAllowedError() const;
/// sets the number of top abundant peaks that are allowed not to match with a theoretical peak
void setMatchPeakAllowedError(Size match_peak_allowed_error);
/// returns whether fragment ions shall be displayed
bool getShowFragmentIons() const;
/// sets whether fragment ions shall be displayed
void setShowFragmentIons(bool show_fragments);
/// returns whether all proteins containing a found peptide should be displayed
bool getPrintDuplicateReferences() const;
/// sets whether all proteins containing a found peptide should be displayed
void setPrintDuplicateReferences(bool print_duplicate_references);
/// return whether peaks near (15 amu) the precursor peak are removed
bool getRemovePrecursorNearPeaks() const;
/// sets whether peaks near (15 amu) the precursor peak are removed
void setRemovePrecursorNearPeaks(bool remove_precursor_near_peaks);
/// return the mass type of the parent (0 - monoisotopic, 1 - average mass)
bool getMassTypeParent() const;
/// sets the mass type of the parent (0 - monoisotopic, 1 - average mass)
void setMassTypeParent(bool mass_type_parent);
/// return the mass type of the fragments (0 - monoisotopic, 1 - average mass)
bool getMassTypeFragment() const;
/// sets the mass type of the fragments (0 - monoisotopic, 1 - average mass)
void setMassTypeFragment(bool mass_type_fragment);
/// returns whether normalized xcorr values are displayed
bool getNormalizeXcorr() const;
/// sets whether normalized xcorr values are displayed
void setNormalizeXcorr(bool normalize_xcorr);
/// returns whether residues are in upper case
bool getResiduesInUpperCase() const;
/// sets whether residues are in upper case
void setResiduesInUpperCase(bool residues_in_upper_case);
/// adds an enzyme to the list and sets is as used
/// the vector consists of four strings:
/// name, cut direction: 0 (N to C) / 1, cuts after (list of aa), doesn't cut before (list of aa)
void addEnzymeInfo(std::vector<String> & enzyme_info);
/// return the modifications (the modification names map to the affected residues, the mass change and the type)
const std::map<String, std::vector<String> > & getModifications() const;
/** retrieves the name, mass change, affected residues, type and position for all modifications from a string
@param[in] modification_line
@param[in] modifications_filename
@param[in] monoisotopic
@throw Exception::FileNotFound is thrown if the given file is not found
@throw Exception::FileNotReadable is thrown if the given file could not be read
@throw Exception::ParseError is thrown if the given file could not be parsed
*/
void handlePTMs(const String & modification_line, const String & modifications_filename, const bool monoisotopic);
protected:
/// returns the enzyme list
const std::map<String, std::vector<String> > & getEnzymeInfo_() const;
/// returns some standard enzymes (used to initialize the enzyme list)
void setStandardEnzymeInfo_();
std::map<String, std::vector<String> > enzyme_info_; ///< an endline-delimited list of enzymes; each with cutting direction 0 (N to C) /1; cuts after (list of aa); doesn't cut before (list of aa); the attributes are tab-delimited
String database_; ///< database used
String snd_database_; ///< second database used
String neutral_losses_for_ions_; ///< whether neutral losses are considered for the a-; b- and y-ions (e.g. 011 for b- and y-ions)
String ion_series_weights_; ///< weights for the a-; b-; c-; d-; v-; w-; x-; y- and z-ion series; space delimited
String partial_sequence_; ///< space-delimited list of sequence parts that have to occur in the theoretical spectra
String sequence_header_filter_; ///< space-delimited list of sequences that have to occur or be absent (preceded by a tilde) in a protein header; to be considered
String protein_mass_filter_;
float precursor_mass_tolerance_; ///< tolerance for matching a theoretical to an experimental peptide
float peak_mass_tolerance_; ///< tolerance for matching a theoretical to an experimental peak
float match_peak_tolerance_; ///< minimum distance between two experimental peaks
float ion_cutoff_percentage_; ///< cutoff of the ratio matching theoretical peaks/theoretical peaks
Size peptide_mass_unit_; ///< peptide mass unit (0 = amu; 1 = mmu; 2 = ppm)
Size output_lines_; ///< number of peptides to be displayed
Size enzyme_number_; ///< number of the enzyme used for cleavage
Size max_AA_per_mod_per_peptide_; ///< maximum number of amino acids containing the same modification in a peptide
Size max_mods_per_peptide_; ///< maximum number of modifications per peptide
Size nucleotide_reading_frame_; ///< nucleotide reading frame:
/// 0 The FASTA file contains amino acid codes. No translation is needed. This is the best and fastest case.
/// 1 The DNA sequence is scanned left to right (forward direction). The amino acid code starts with the first DNA code.
/// 2 The DNA sequence is scanned left to right (forward direction). The amino acid code starts with the second DNA code.
/// 3 The DNA sequence is scanned left to right (forward direction). The amino acid code starts with the third DNA code.
/// 4 The DNA sequence is scanned right to left (backward direction for the complementary strand). The amino acid code starts with the first DNA code.
/// 5 The DNA sequence is scanned right to left (backward direction for the complementary strand). The amino acid code starts with the second DNA code.
/// 6 The DNA sequence is scanned right to left (backward direction for the complementary strand). The amino acid code starts with the third DNA code.
/// 7 Use each of the DNA translations of the codes 1; 2; 3.
/// 8 Use each of the DNA translations of the codes 4; 5; 6.
/// 9 Use each of the DNA translations of the codes 1; 2; 3; 4; 5; 6.
Size max_internal_cleavage_sites_; ///< maximum number of internal cleavage sites
Size match_peak_count_; ///< number of the top abundant peaks to match with theoretical one
Size match_peak_allowed_error_; ///< number of peaks that may lack this test
bool show_fragment_ions_; ///< whether to display fragment ions
bool print_duplicate_references_; ///< whether all proteins containing a found peptide should be displayed
bool remove_precursor_near_peaks_; ///< whether peaks near (15 amu) the precursor peak are removed
bool mass_type_parent_; ///< mass type of the parent peak (0 - monoisotopic; 1 - average)
bool mass_type_fragment_; ///< mass type of fragment peaks (0 - monoisotopic; 1 - average)
bool normalize_xcorr_; ///< whether to display normalized xcorr values
bool residues_in_upper_case_; ///< whether residues are in upper case
std::map<String, std::vector<String> > PTMname_residues_mass_type_; ///< the modification names map to the affected residues, the mass change and the type
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/IndexedMzMLFileLoader.h | .h | 2,384 | 84 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/FORMAT/OPTIONS/PeakFileOptions.h>
namespace OpenMS
{
class OnDiscMSExperiment;
typedef OpenMS::OnDiscMSExperiment OnDiscPeakMap;
/**
@brief A class to load an indexedmzML file.
Providing the same interface as the other classes such as MzMLFile,
MzXMLFile etc. to load and store a file. Reading a file from disk will load
the file into a OnDiscMSExperiment while the class can write to disk both,
a MSExperiment and a OnDiscMSExperiment.
*/
class OPENMS_DLLAPI IndexedMzMLFileLoader
{
public:
/// Constructor
IndexedMzMLFileLoader();
/// Destructor
~IndexedMzMLFileLoader();
/// Mutable access to the options for loading/storing
PeakFileOptions& getOptions();
/// Non-mutable access to the options for loading/storing
const PeakFileOptions& getOptions() const;
/// set options for loading/storing
void setOptions(const PeakFileOptions &);
/**
@brief Load a file
Tries to parse the file, success needs to be checked with the return value.
@param[out] filename Filename determines where the file is located
@param[out] exp Object which will contain the data after the call
@return Indicates whether parsing was successful (if it is false, the file most likely was not an mzML or not indexed).
*/
bool load(const String& filename, OnDiscPeakMap& exp);
/**
@brief Store a file from an on-disc data-structure
@param[out] filename Filename determines where the file will be stored
@param[out] exp MS data to be stored
*/
void store(const String& filename, OnDiscPeakMap& exp);
/**
@brief Store a file from an in-memory data-structure
@param[in] filename Filename determines where the file will be stored
@param[out] exp MS data to be stored
*/
void store(const String& filename, PeakMap& exp);
private:
/// Options for storing
PeakFileOptions options_;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/DTA2DFile.h | .h | 10,162 | 325 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/FORMAT/OPTIONS/PeakFileOptions.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/CONCEPT/PrecisionWrapper.h>
#include <OpenMS/SYSTEM/File.h>
#include <fstream>
#include <iostream>
namespace OpenMS
{
/**
@brief DTA2D File adapter.
File adapter for files with three tab/space-separated columns.
The default format is: retention time (seconds) , m/z , intensity.
If the first line starts with '#', a different order is defined by the
the order of the keywords 'MIN' (retention time in minutes) or 'SEC' (retention time in seconds), 'MZ', and 'INT'.
Example: '\#MZ MIN INT'
Keywords can be lower/upper or mixed case, e.g. 'Int' or 'mz'.
The peaks of one retention time have to be in subsequent lines.
@ingroup FileIO
*/
class OPENMS_DLLAPI DTA2DFile :
public ProgressLogger
{
private:
PeakFileOptions options_;
public:
/** @name Constructors and Destructor */
//@{
/// Default constructor
DTA2DFile();
/// Destructor
~DTA2DFile() override;
//@}
/// Mutable access to the options for loading/storing
PeakFileOptions& getOptions();
/// Non-mutable access to the options for loading/storing
const PeakFileOptions& getOptions() const;
/**
@brief Loads a map from a DTA2D file.
@param[out] filename The file from which the map should be loaded.
@param[in] map has to be a MSExperiment or have the same interface.
@exception Exception::FileNotFound is thrown if the file could not be opened
@exception Exception::ParseError is thrown if an error occurs during parsing
*/
template <typename MapType>
void load(const String& filename, MapType& map)
{
startProgress(0, 0, "loading DTA2D file");
//try to open file
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);
}
}
map.reset();
//set DocumentIdentifier
map.setLoadedFileType(filename);
map.setLoadedFilePath(filename);
// temporary variables to store the data in
std::vector<String> strings(3);
typename MapType::SpectrumType spec;
spec.setRT(-1.0); //to make sure the first RT is different from the the initialized value
typename MapType::SpectrumType::PeakType p;
double rt(0.0);
char delimiter;
// default dimension of the data
Size rt_dim = 0;
Size mz_dim = 1;
Size int_dim = 2;
//RT unit (default is seconds)
bool time_in_minutes = false;
// string to store the current line in
String line;
// native ID (numbers from 0)
UInt native_id = 0;
// line number counter
Size line_number = 0;
while (getline(is, line, '\n'))
{
++line_number;
line.trim();
if (line.empty()) continue;
//test which delimiter is used in the line
if (line.has('\t'))
{
delimiter = '\t';
}
else
{
delimiter = ' ';
}
//is header line
if (line.hasPrefix("#"))
{
line = line.substr(1).trim().toUpper();
line.split(delimiter, strings);
// flags to check if dimension is set correctly
bool rt_set = false;
bool mz_set = false;
bool int_set = false;
//assign new order
for (Size i = 0; i < 3; ++i)
{
if (strings[i] == "RT" || strings[i] == "RETENTION_TIME" || strings[i] == "MASS-TO-CHARGE" || strings[i] == "IT" || strings[i] == "INTENSITY")
{
std::cerr << "Warning: This file contains the deprecated keyword '" << strings[i] << "'." << "\n";
std::cerr << " Please use only the new keywords SEC/MIN, MZ, INT." << "\n";
}
if ((strings[i] == "SEC" || strings[i] == "RT" || strings[i] == "RETENTION_TIME") && rt_set == false)
{
rt_dim = i;
rt_set = true;
}
else if ((strings[i] == "MIN") && rt_set == false)
{
rt_dim = i;
rt_set = true;
time_in_minutes = true;
}
else if ((strings[i] == "MZ" || strings[i] == "MASS-TO-CHARGE") && mz_set == false)
{
mz_dim = i;
mz_set = true;
}
else if ((strings[i] == "INT" || strings[i] == "IT" || strings[i] == "INTENSITY") && int_set == false)
{
int_dim = i;
int_set = true;
}
else
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Misformatted header line!", filename);
}
}
continue;
}
try
{
line.split(delimiter, strings);
if (strings.size() != 3)
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, std::string("Bad data line (" + String(line_number) + "): \"") + line + "\" (got " + String(strings.size()) + ", expected 3 entries)", filename);
}
p.setIntensity(strings[int_dim].toFloat());
p.setMZ(strings[mz_dim].toDouble());
rt = (strings[rt_dim].toDouble()) * (time_in_minutes ? 60.0 : 1.0);
}
// conversion to double or something else could have gone wrong
catch (Exception::BaseException& /*e*/)
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, std::string("Bad data line (" + String(line_number) + "): \"") + line + "\"", filename);
}
// Retention time changed -> new Spectrum
if (fabs(rt - spec.getRT()) > 0.0001)
{
if (spec.size() != 0
&&
(!options_.hasRTRange() || options_.getRTRange().encloses(DPosition<1>(spec.getRT())))) // RT restriction fulfilled
{
map.addSpectrum(spec);
}
setProgress(0);
spec.clear(true);
spec.setRT(rt);
spec.setNativeID(String("index=") + native_id);
++native_id;
}
//Skip peaks with invalid m/z or intensity value
if (
(!options_.hasMZRange() || options_.getMZRange().encloses(DPosition<1>(p.getMZ())))
&&
(!options_.hasIntensityRange() || options_.getIntensityRange().encloses(DPosition<1>(p.getIntensity())))
)
{
spec.push_back(p);
}
}
// add last Spectrum
if (
spec.size() != 0
&&
(!options_.hasRTRange() || options_.getRTRange().encloses(DPosition<1>(spec.getRT()))) // RT restriction fulfilled
)
{
map.addSpectrum(spec);
}
is.close();
map.updateRanges();
endProgress();
}
/**
@brief Stores a map in a DTA2D file.
@param[out] filename The name of the file where the map should be stored.
@param[in] map has to be a MSExperiment or have the same interface.
@exception Exception::UnableToCreateFile is thrown if the file could not be created
*/
template <typename MapType>
void store(const String& filename, const MapType& map) const
{
startProgress(0, map.size(), "storing DTA2D file");
std::ofstream os(filename.c_str());
if (!os)
{
throw Exception::UnableToCreateFile(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename);
}
// write header
os << "#SEC\tMZ\tINT\n";
// Iterate over all peaks of each spectrum and
// write one line for each peak of the spectrum.
UInt count = 0;
for (typename MapType::const_iterator spec = map.begin(); spec != map.end(); ++spec)
{
setProgress(count++);
for (typename MapType::SpectrumType::ConstIterator it = spec->begin(); it != spec->end(); ++it)
{
// Write rt, m/z and intensity.
os << precisionWrapper(spec->getRT()) << "\t" << precisionWrapper(it->getPos()) << "\t" << precisionWrapper(it->getIntensity()) << "\n";
}
}
os.close();
endProgress();
}
/**
@brief Stores the TIC of a map in a DTA2D file.
@param[in] filename The name of the file where the map should be stored.
@param[in] map has to be a MSExperiment or have the same interface.
@exception Exception::UnableToCreateFile is thrown if the file could not be created
*/
template <typename MapType>
void storeTIC(const String& filename, const MapType& map) const
{
startProgress(0, map.size(), "storing DTA2D file");
std::ofstream os(filename.c_str());
if (!os)
{
throw Exception::UnableToCreateFile(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename);
}
// write header (Always MZ=0 for chromatograms in DTA2D.)
os << "#SEC\tMZ\tINT\n";
typename MapType::ChromatogramType TIC = map.calculateTIC();
for (typename MapType::ChromatogramType::ConstIterator it = TIC.begin(); it != TIC.end(); ++it)
{
// write rt, (mz=0) and intensity.
os << precisionWrapper(it->getRT()) << "\t0\t" << precisionWrapper(it->getIntensity()) << "\n";
}
os.close();
endProgress();
}
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/MSNumpressCoder.h | .h | 8,761 | 239 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CONCEPT/Exception.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <algorithm>
#include <string>
#include <vector>
namespace OpenMS
{
const double BinaryDataEncoder_default_numpressErrorTolerance = .0001; // 1/100th of one percent
/**
@brief Class to encode and decode data encoded with MSNumpress
MSNumpress supports three encoding schemata:
- Linear (MS:1002312, MS-Numpress linear prediction compression)
- Pic (MS:1002313, MS-Numpress positive integer compression)
- Slof (MS:1002314, MS-Numpress short logged float compression)
Note that the linear compression scheme only makes sense for monotonically
increasing data (such as retention time and m/z) that is often equally
spaced. Pic compression only makes sense for positive integers as all data
will be rounded to the nearest integer. Slof makes sense for all other data
(such as non-integer intensity values).
For more information on the compression schemata, see
Teleman J et al, "Numerical compression schemes for proteomics mass spectrometry data."
Mol Cell Proteomics. 2014 Jun;13(6):1537-42. doi: 10.1074/mcp.O114.037879.
*/
class OPENMS_DLLAPI MSNumpressCoder
{
public:
/// Names of compression schemes
enum NumpressCompression {
NONE, ///< No compression is applied
LINEAR, ///< Linear (MS:1002312, MS-Numpress linear prediction compression)
PIC, ///< Pic (MS:1002313, MS-Numpress positive integer compression)
SLOF, ///< Slof (MS:1002314, MS-Numpress short logged float compression)
SIZE_OF_NUMPRESSCOMPRESSION
};
static const std::string NamesOfNumpressCompression[SIZE_OF_NUMPRESSCOMPRESSION];
/**
@brief Configuration class for MSNumpress
Contains configuration options for ms numpress
*/
struct OPENMS_DLLAPI NumpressConfig
{
/**
@brief fixed point for numpress algorithms
Determines the accuracy of the encoding, is automatically estimated
when estimate_fixed_point is set (only change this if you know what you
are doing).
*/
double numpressFixedPoint;
/**
@brief Check error tolerance after encoding
Check error tolerance after encoding to ensure that the maximum error
is abs(1.0-(encoded/decoded)) <= eps which is set here. In case it is
set to 0, checking the encoding error is disabled. Note that this will
slow down encoding substantially as all data needs to be encoded first
and then decoded again.
*/
double numpressErrorTolerance;
/**
@brief Which compression schema to use
This is of type NumpressCompression (see there)
*/
NumpressCompression np_compression;
/**
@brief Whether to estimate the fixed point used for encoding (highly recommended)
The fixed point determines the accuracy of the encoding and is
automatically estimated when estimate_fixed_point is set to true.
@note: only change this if you know what you are doing
*/
bool estimate_fixed_point;
/**
@brief Desired mass accuracy for *linear* encoding
This setting has no effect if set to -1, for example use 0.0001 for 0.2
ppm accuracy @ 500 m/z. Does not affect other encoding schemes (pic or
slof).
*/
double linear_fp_mass_acc;
NumpressConfig () :
numpressFixedPoint(0.0),
numpressErrorTolerance(BinaryDataEncoder_default_numpressErrorTolerance),
np_compression(NONE),
estimate_fixed_point(true),
linear_fp_mass_acc(-1)
{
}
/**
@brief Set compression using a string mapping to enum NumpressCompression.
@param[in] compression A string from NamesOfNumpressCompression[]. Valid strings are "none", "linear", "pic" and "slof".
@throws Exception::InvalidParameter if compression is unknown.
*/
void setCompression(const std::string& compression);
};
/// default constructor
MSNumpressCoder() {}
/// Destructor
virtual ~MSNumpressCoder() {}
/**
* @brief Encodes a vector of floating point numbers into a Base64 string using numpress
*
* This code is obtained from the proteowizard implementation
* ./pwiz/pwiz/data/msdata/BinaryDataEncoder.cpp (adapted by Hannes Roest).
*
* This function will first apply the numpress encoding to the data, then
* encode the result in base64 (with optional zlib compression before
* base64 encoding).
*
* @note In case of error, result string is empty
*
* @param[in] in The vector of floating point numbers to be encoded
* @param[out] result The resulting string
* @param[in] zlib_compression Whether to apply zlib compression after numpress compression
* @param[in] config The numpress configuration defining the compression strategy
*
*/
void encodeNP(const std::vector<double> & in,
String & result,
bool zlib_compression,
const NumpressConfig & config);
/// encodeNP from a float (convert first to double)
void encodeNP(const std::vector<float> & in,
String & result,
bool zlib_compression,
const NumpressConfig & config);
/**
* @brief Decodes a Base64 string to a vector of floating point numbers using numpress
*
* This code is obtained from the proteowizard implementation
* ./pwiz/pwiz/data/msdata/BinaryDataEncoder.cpp (adapted by Hannes Roest).
*
* This function will first decode the input base64 string (with optional
* zlib decompression after decoding) and then apply numpress decoding to
* the data.
*
* @param[in] in The base64 encoded string
* @param[out] out The resulting vector of doubles
* @param[in] zlib_compression Whether to apply zlib de-compression before numpress de-compression
* @param[in] config The numpress configuration defining the compression strategy
*
* @throw throws Exception::ConversionError if the string cannot be converted
*
*/
void decodeNP(const String & in,
std::vector<double> & out,
bool zlib_compression,
const NumpressConfig & config);
/**
* @brief Encode the data vector "in" to a raw byte array
*
* @note In case of error, "result" is given back unmodified
* @note The result is not a string but a raw byte array and may contain zero bytes
*
* This performs the raw numpress encoding on a set of data and does no
* Base64 encoding on the result. Therefore the result string is likely
* *unsafe* to handle and is a raw byte array.
*
* Please use the safe versions above unless you need access to the raw
* byte arrays.
*
* @param[in] in The vector of floating point numbers to be encoded
* @param[out] result The resulting string
* @param[in] config The numpress configuration defining the compression strategy
*
*/
void encodeNPRaw(const std::vector<double> & in,
String & result,
const NumpressConfig & config);
/**
* @brief Decode the raw byte array "in" to the result vector "out"
*
* @note The string in should *only* contain the data and _no_ extra
* null terminating byte.
*
* This performs the raw numpress decoding on a raw byte array (not Base64
* encoded). Therefore the input string is likely *unsafe* to handle and is
* basically a byte container.
*
* Please use the safe versions above unless you only have the raw byte
* arrays.
*
* @param[in] in The base64 encoded string
* @param[out] out The resulting vector of doubles
* @param[in] config The numpress configuration defining the compression strategy
*
* @throw throws Exception::ConversionError if the string cannot be converted
*
*/
void decodeNPRaw(const std::string & in,
std::vector<double> & out,
const NumpressConfig & config);
private:
void decodeNPInternal_(const unsigned char* in, size_t in_size, std::vector<double>& out, const NumpressConfig & config);
};
} //namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/ControlledVocabulary.h | .h | 8,980 | 250 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/ListUtils.h> // StringList
#include <OpenMS/DATASTRUCTURES/StringListUtils.h>
#include <OpenMS/CONCEPT/Exception.h>
#include <set>
#include <map>
namespace OpenMS
{
/**
@brief Representation of a controlled vocabulary.
This representation only contains the information used for parsing and validation.
All other lines are stored in the @em unparsed member of the CVTerm struct.
@ingroup Format
*/
class OPENMS_DLLAPI ControlledVocabulary
{
friend OPENMS_DLLAPI std::ostream& operator<<(std::ostream& os, const ControlledVocabulary& cv);
public:
/// ensure same hash on all platforms (for reproducibility)-
struct FNV1aHasher
{
size_t operator()(const String& key) const noexcept
{
size_t hash = 14695981039346656037ull;
for (auto c : key)
{
hash ^= static_cast<unsigned char>(c);
hash *= 1099511628211ull;
}
return hash;
}
};
/// Representation of a CV term
struct OPENMS_DLLAPI CVTerm
{
/// define xsd types allowed in cv term to specify their value-type
enum class XRefType
{
XSD_STRING = 0, // xsd:string A string
XSD_INTEGER, // xsd:integer Any integer
XSD_DECIMAL, // xsd:decimal Any real number
XSD_NEGATIVE_INTEGER, // xsd:negativeInteger Any negative integer
XSD_POSITIVE_INTEGER, // xsd:positiveInteger Any integer > 0
XSD_NON_NEGATIVE_INTEGER, // xsd:nonNegativeInteger Any integer >= 0
XSD_NON_POSITIVE_INTEGER, // xsd:nonPositiveInteger Any integer < 0
XSD_BOOLEAN, // xsd:boolean True or false
XSD_DATE, // xsd:date An XML-Schema date
XSD_ANYURI, // xsd:anyURI uniform resource identifier
NONE
};
static String getXRefTypeName(XRefType type);
//static bool isSearchEngineSpecificScore();
static bool isHigherBetterScore(ControlledVocabulary::CVTerm term); ///if it is a score type, lookup has_order
String name; ///< Text name
String id; ///< Identifier
std::set<String> parents; ///< The parent IDs
std::set<String> children; ///< The child IDs
bool obsolete; ///< Flag that indicates of the term is obsolete
String description; ///< Term description
StringList synonyms; ///< List of synonyms
StringList unparsed; ///< Unparsed lines from the definition file
XRefType xref_type; ///< xref value-type for the CV-term
StringList xref_binary; ///< xref binary-data-type for the CV-term (list of all allowed data value types for the current binary data array)
std::set<String> units; ///< unit accession ids, defined by relationship has units
///Default constructor
CVTerm();
CVTerm(const CVTerm& rhs);
CVTerm& operator=(const CVTerm& rhs);
/// get mzidentml formatted string. i.e. a cvparam xml element, ref should be the name of the ControlledVocabulary (i.e. cv.name()) containing the CVTerm (e.g. PSI-MS for the psi-ms.obo - gets loaded in all cases like that??), value can be empty if not available
String toXMLString(const String& ref, const String& value = String("")) const;
/// get mzidentml formatted string. i.e. a cvparam xml element, ref should be the name of the ControlledVocabulary (i.e. cv.name()) containing the CVTerm (e.g. PSI-MS for the psi-ms.obo - gets loaded in all cases like that??), value can be empty if not available
String toXMLString(const String& ref, const DataValue& value) const;
};
/// Constructor
ControlledVocabulary();
///Destructor
virtual ~ControlledVocabulary();
/// Returns the CV name (set in the load method)
const String& name() const;
/// Returns the CV label (set in the load method)
const String& label() const;
/// Returns the CV version (set in the load method)
const String& version() const;
/// Returns the CV url (set in the load method)
const String& url() const;
/**
@brief Loads the CV from an OBO file
@param[in] name The CV name
@param[in] filename The OBO file path
@exception Exception::FileNotFound is thrown if the file could not be opened
@exception Exception::ParseError is thrown if an error occurs during parsing
*/
void loadFromOBO(const String& name, const String& filename);
/// Returns true if the term is in the CV. Returns false otherwise.
bool exists(const String& id) const;
/// Returns true if a term with the given name is in the CV. Returns false otherwise.
bool hasTermWithName(const String& name) const;
/**
@brief Returns a term specified by ID
@exception Exception::InvalidValue is thrown if the term is not present
*/
const CVTerm& getTerm(const String& id) const;
/**
@brief Returns a term specified by name
@exception Exception::InvalidValue is thrown if the term is not present
*/
const CVTerm& getTermByName(const String& name, const String& desc = "") const;
/// returns all the terms stored in the CV
const std::map<String, CVTerm>& getTerms() const;
/**
@brief Writes all child terms recursively into terms
If parent has child this method writes them recursively into the term object
@param[out] terms Output set of child term IDs
@param[in] parent_id The parent term ID
@exception Exception::InvalidValue is thrown if the term is not present
*/
void getAllChildTerms(std::set<String>& terms, const String& parent_id) const;
/**
@brief Iterates over all children (incl. subchildren etc) of parent recursively, i.e. the whole subtree.
@param[in] parent_id Id of parent (to be passed to getTerm(), to obtain its children).
@param[in] lbd Function that gets the child-Ids passed. Must return bool.
Used for comparisons and / or to set captured variables.
If the lambda returns true, the iteration is exited prematurely.
E.g. if you have found your search, you don't need to continue searching.
Otherwise, if you want to go through the whole tree (e.g. to fill a vector)
you can just return false always to not quit early.
*/
template <class LAMBDA>
bool iterateAllChildren(const String& parent_id, LAMBDA lbd) const
{
for (const auto& child_id : getTerm(parent_id).children)
{
if (lbd(child_id) || iterateAllChildren(child_id, lbd))
return true;
}
return false;
}
/**
@brief Searches the existing terms for the given @p name
@param[in] name The term name to search for
@return const Pointer to found term. When term is not found, returns nullptr
*/
const ControlledVocabulary::CVTerm* checkAndGetTermByName(const OpenMS::String& name) const;
/**
@brief Returns if @p child is a child of @p parent
@param[in] child_id The child term ID
@param[in] parent_id The parent term ID
@exception Exception::InvalidValue is thrown if one of the terms is not present
*/
bool isChildOf(const String& child_id, const String& parent_id) const;
/**
@brief Returns a CV for parsing/storing PSI-MS related data, e.g. mzML, or handle accessions/ids in datastructures
The CV will be initialized on first access. Repeated access is therefor cheap.
It consists of the following CVs:<br>
<ul>
<li>PSI-MS (psi-ms.obo)</li>
<li>PATO (quality.obo)</li>
<li>UO (unit.obo)</li>
<li>BTO (CV/brenda.obo)</li>
<li>GO (goslim_goa.obo)</li>
</ul>
*/
static const ControlledVocabulary& getPSIMSCV();
protected:
/**
@brief checks if a name corresponds to an id
If the term is not known, 'true' is returned!
*/
bool checkName_(const String& id, const String& name, bool ignore_case = true) const;
/// Map from ID to CVTerm
// note: unordered_map would be faster (5% for loading mzML), but order differs across platforms
std::map<String, CVTerm> terms_;
/// Map from name to id
std::map<String, String> namesToIds_;
/// Name set in the load method
String name_;
/// CV label
String label_;
/// CV version
String version_;
/// CV URL
String url_;
};
///Print the contents to a stream.
OPENMS_DLLAPI std::ostream& operator<<(std::ostream& os, const ControlledVocabulary& cv);
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/TransformationXMLFile.h | .h | 2,363 | 78 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/ANALYSIS/MAPMATCHING/TransformationDescription.h>
#include <OpenMS/FORMAT/HANDLERS/XMLHandler.h>
#include <OpenMS/FORMAT/XMLFile.h>
#include <vector>
namespace OpenMS
{
/**
@brief Used to load and store TransformationXML files
This class is used to load and store documents that implement the schema of
TransformationXML files.
A documented schema for this format can be found at https://github.com/OpenMS/OpenMS/tree/develop/share/OpenMS/SCHEMAS
@ingroup FileIO
*/
class OPENMS_DLLAPI TransformationXMLFile :
protected Internal::XMLHandler,
public Internal::XMLFile
{
public:
/// Constructor
TransformationXMLFile();
/**
@brief Loads the transformation from an TransformationXML file
The information is read in and the information is stored in the
corresponding variables
@exception Exception::FileNotFound is thrown if the file could not be opened
@exception Exception::ParseError is thrown if an error occurs during parsing
*/
void load(const String& filename, TransformationDescription& transformation, bool fit_model=true);
/**
@brief Stores the data in an TransformationXML file
The data is read in and stored in the file named 'filename'.
@exception Exception::UnableToCreateFile is thrown if the file could not be created
@exception Exception::IllegalArgument is thrown if unsupported parameter types have been set
*/
void store(const String& filename, const TransformationDescription& transformation);
protected:
// Docu in base class
void startElement(const XMLCh* const /*uri*/, const XMLCh* const /*local_name*/, const XMLCh* const qname, const xercesc::Attributes& attributes) override;
/// @name Members for use during loading data
//@{
/// Param to fill in during parse
Param params_;
/// Data vector
TransformationDescription::DataPoints data_;
/// Model type
String model_type_;
//@}
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/CVMappingFile.h | .h | 2,609 | 88 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/FORMAT/XMLFile.h>
#include <OpenMS/FORMAT/HANDLERS/XMLHandler.h>
#include <OpenMS/DATASTRUCTURES/CVMappings.h>
#include <OpenMS/DATASTRUCTURES/CVMappingRule.h>
#include <vector>
namespace OpenMS
{
class String;
/**
@brief Used to load CvMapping files
This file contains the mapping of CV terms to the schema, which
is used by PSI standard formats to semantically validate files.
A documented schema for this format can be found at https://github.com/OpenMS/OpenMS/tree/develop/share/OpenMS/SCHEMAS
@ingroup FileIO
*/
class OPENMS_DLLAPI CVMappingFile :
protected Internal::XMLHandler,
public Internal::XMLFile
{
public:
/// Default constructor
CVMappingFile();
/// Destructor
~CVMappingFile() override;
/**
@brief loads CvMappings from the given file
@exception Exception::FileNotFound is thrown if the file could not be opened
@exception Exception::ParseError is thrown if an error occurs during parsing
@param[in] filename The filename to read from
@param[out] cv_mappings The CVMappings instance in which the rules, cvs and other content from the file should be stored
@param[in] strip_namespaces if enable, namespace definitions of the paths are eliminated, e.g. 'pf:cvParam' -> 'cvParam'
*/
void load(const String& filename, CVMappings& cv_mappings, bool strip_namespaces = false);
protected:
// Docu in base class
void startElement(const XMLCh* const /*uri*/, const XMLCh* const /*local_name*/, const XMLCh* const qname, const xercesc::Attributes& attributes) override;
// Docu in base class
void endElement(const XMLCh* const /*uri*/, const XMLCh* const /*local_name*/, const XMLCh* const qname) override;
// Docu in base class
void characters(const XMLCh* const chars, const XMLSize_t /*length*/) override;
private:
///Not implemented
CVMappingFile(const CVMappingFile& rhs);
///Not implemented
CVMappingFile& operator=(const CVMappingFile& rhs);
String tag_;
bool strip_namespaces_;
CVMappingRule actual_rule_;
std::vector<CVMappingRule> rules_;
std::vector<CVReference> cv_references_;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/Base64.h | .h | 20,985 | 649 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#ifndef OPENMS_IS_BIG_ENDIAN
#if defined OPENMS_BIG_ENDIAN
#define OPENMS_IS_BIG_ENDIAN true
#else
#define OPENMS_IS_BIG_ENDIAN false
#endif
#endif
#include <OpenMS/CONCEPT/Types.h>
#include <OpenMS/CONCEPT/Exception.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/FORMAT/ZlibCompression.h>
#include <algorithm>
#include <array>
#include <cmath>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>
#ifdef OPENMS_COMPILER_MSVC
#pragma comment(linker, "/export:compress")
#endif
namespace OpenMS
{
/**
@brief Class to encode and decode Base64
Base64 supports two precisions: 32 bit (float) and 64 bit (double).
*/
class OPENMS_DLLAPI Base64
{
public:
/// default constructor
Base64() = default;
/// Byte order type
enum ByteOrder
{
BYTEORDER_BIGENDIAN, ///< Big endian type
BYTEORDER_LITTLEENDIAN ///< Little endian type
};
/**
@brief Encodes a vector of floating point numbers to a Base64 string
You can specify the byte order of the output and if it is zlib-compressed.
@note @p in will be empty after this method
*/
template <typename FromType>
static void encode(std::vector<FromType> & in, ByteOrder to_byte_order, String & out, bool zlib_compression = false);
/**
@brief Decodes a Base64 string to a vector of floating point numbers
You have to specify the byte order of the input and if it is zlib-compressed.
*/
template <typename ToType>
static void decode(const String & in, ByteOrder from_byte_order, std::vector<ToType> & out, bool zlib_compression = false);
/**
@brief Encodes a vector of integer point numbers to a Base64 string
You can specify the byte order of the output and if it is zlib-compressed.
@note @p in will be empty after this method
*/
template <typename FromType>
static void encodeIntegers(std::vector<FromType> & in, ByteOrder to_byte_order, String & out, bool zlib_compression = false);
/**
@brief Decodes a Base64 string to a vector of integer numbers
You have to specify the byte order of the input and if it is zlib-compressed.
*/
template <typename ToType>
static void decodeIntegers(const String & in, ByteOrder from_byte_order, std::vector<ToType> & out, bool zlib_compression = false);
/**
@brief Encodes a vector of strings to a Base64 string
You can specify zlib-compression.
@param[in] in A vector of data to be encoded (String)
@param[out] out A String containing the Base64 encoded data
@param[in] zlib_compression Whether the data should be compressed with zlib before encoding in Base64
@param[in] append_null_byte Whether a null-byte should be appended after each of the Strings contained in the in vector
@note Unless append_null_byte is false, will add a null byte ("\0") at the end of each input
*/
static void encodeStrings(const std::vector<String> & in, String & out, bool zlib_compression = false, bool append_null_byte = true);
/**
@brief Decodes a Base64 string to a vector of (null-terminated) strings
You have to specify whether the Base64 string is zlib-compressed.
@param[in] in A String containing the Base64 encoded data
@param[out] out A vector containing the decoded data (split at null "\0") bytes
@param[in] zlib_compression Whether the data should be decompressed with zlib after decoding in Base64
*/
static void decodeStrings(const String & in, std::vector<String> & out, bool zlib_compression = false);
/**
@brief Decodes a Base64 string
@param[in] in A String containing the Base64 encoded data
@param[out] out A String containing the decoded data
@param[in] zlib_compression Should the data be decompressed with zlib after decoding in Base64?
*/
static void decodeSingleString(const String& in, String& out, bool zlib_compression);
private:
///Internal class needed for type-punning
union Reinterpreter64_
{
double f;
UInt64 i;
};
///Internal class needed for type-punning
union Reinterpreter32_
{
float f;
UInt32 i;
};
static const char encoder_[];
static const char decoder_[];
/// Decodes a Base64 string to a vector of floating point numbers
template <typename ToType>
static void decodeUncompressed_(const String & in, ByteOrder from_byte_order, std::vector<ToType> & out);
///Decodes a compressed Base64 string to a vector of floating point numbers
template <typename ToType>
static void decodeCompressed_(const String & in, ByteOrder from_byte_order, std::vector<ToType> & out);
/// Decodes a Base64 string to a vector of integer numbers
template <typename ToType>
static void decodeIntegersUncompressed_(const String & in, ByteOrder from_byte_order, std::vector<ToType> & out);
///Decodes a compressed Base64 string to a vector of integer numbers
template <typename ToType>
static void decodeIntegersCompressed_(const String & in, ByteOrder from_byte_order, std::vector<ToType> & out);
static void stringSimdEncoder_(std::string& in, std::string& out);
static void stringSimdDecoder_(const std::string& in, std::string& out);
};
// Possible optimization: add simd registerwise endianizer (this will only be beneficial for ARM, since mzML + x64 CPU does not need to convert since both use LITTLE_ENDIAN).
// mzXML(!), which is outdated uses BIG_ENDIAN, i.e. "network", in its base64 encoding, so there x64 will benefit, but not ARM.
// However: the code below gets optimized to the bswap instruction by most compilers, which is very fast (1 cycle latency + 1 ops)
// and it is doubtful that SSE4's _mm_shuffle_epi8 will do better, see https://dev.to/wunk/fast-array-reversal-with-simd-j3p
/// Endianizes a 32 bit type from big endian to little endian and vice versa
inline UInt32 endianize32(const UInt32& n)
{
return ((n & 0x000000ff) << 24) |
((n & 0x0000ff00) << 8) |
((n & 0x00ff0000) >> 8) |
((n & 0xff000000) >> 24);
}
/// Endianizes a 64 bit type from big endian to little endian and vice versa
inline UInt64 endianize64(const UInt64& n)
{
return ((n >> 56) & 0x00000000000000FF) |
((n >> 40) & 0x000000000000FF00) |
((n >> 24) & 0x0000000000FF0000) |
((n >> 8) & 0x00000000FF000000) |
((n << 8) & 0x000000FF00000000) |
((n << 24) & 0x0000FF0000000000) |
((n << 40) & 0x00FF000000000000) |
((n << 56) & 0xFF00000000000000);
}
template <typename FromType>
void Base64::encode(std::vector<FromType> & in, ByteOrder to_byte_order, String & out, bool zlib_compression)
{
out.clear();
if (in.empty())
{
return;
}
// initialize
const Size element_size = sizeof(FromType);
const Size input_bytes = element_size * in.size();
// change endianness if necessary
if ((OPENMS_IS_BIG_ENDIAN && to_byte_order == Base64::BYTEORDER_LITTLEENDIAN) || (!OPENMS_IS_BIG_ENDIAN && to_byte_order == Base64::BYTEORDER_BIGENDIAN))
{
if (element_size == 4)
{
for (Size i = 0; i < in.size(); ++i)
{
Reinterpreter32_ tmp;
tmp.f = in[i];
tmp.i = endianize32(tmp.i);
in[i] = tmp.f;
}
}
else
{
for (Size i = 0; i < in.size(); ++i)
{
Reinterpreter64_ tmp;
tmp.f = static_cast<double>(in[i]);
tmp.i = endianize64(tmp.i);
in[i] = tmp.f;
}
}
/////////////////////////endianize registerwise
}
// encode with compression
if (zlib_compression)
{
String compressed;
ZlibCompression::compressData((void*)in.data(), input_bytes, compressed);
stringSimdEncoder_(compressed, out);
}
else // encode without compression
{
String str((char*)in.data(), input_bytes);
stringSimdEncoder_(str, out);
}
}
template <typename ToType> ////////////////////////////////////////////nothing to change here, magic happenes elsewhere
void Base64::decode(const String & in, ByteOrder from_byte_order, std::vector<ToType> & out, bool zlib_compression)
{
if (zlib_compression)
{
decodeCompressed_(in, from_byte_order, out);
}
else
{
decodeUncompressed_(in, from_byte_order, out);
}
}
template <int type_size>
inline void invertEndianess(void* byte_buffer, const size_t element_count);
template<>
inline void invertEndianess<4>(void* byte_buffer, const size_t element_count)
{
UInt32* p = reinterpret_cast<UInt32*>(byte_buffer);
std::transform(p, p + element_count, p, endianize32);
}
template<>
inline void invertEndianess<8>(void* byte_buffer, const size_t element_count)
{
UInt64* p = reinterpret_cast<UInt64*>(byte_buffer);
std::transform(p, p + element_count, p, endianize64);
}
template <typename ToType>
void Base64::decodeCompressed_(const String& in, ByteOrder from_byte_order, std::vector<ToType>& out)
{
out.clear();
if (in.empty())
{
return;
}
String decompressed;
Base64::decodeSingleString(in, decompressed, true);
void* byte_buffer = reinterpret_cast<void*>(&decompressed[0]);
Size buffer_size = decompressed.size();
const ToType * float_buffer = reinterpret_cast<const ToType *>(byte_buffer);
constexpr Size element_size = sizeof(ToType);
if (buffer_size % element_size != 0)
{
throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Bad BufferCount?");
}
Size float_count = buffer_size / element_size;
// change endianness if necessary
if ((OPENMS_IS_BIG_ENDIAN && from_byte_order == Base64::BYTEORDER_LITTLEENDIAN) || (!OPENMS_IS_BIG_ENDIAN && from_byte_order == Base64::BYTEORDER_BIGENDIAN))
{
invertEndianess<element_size>(byte_buffer, float_count);
}
// copy values
out.assign(float_buffer, float_buffer + float_count);
}
template <typename ToType>
void Base64::decodeUncompressed_(const String& in, ByteOrder from_byte_order , std::vector<ToType>& out)
{
out.clear();
// The length of a base64 string is always a multiple of 4 (always 3
// bytes are encoded as 4 characters)
if (in.size() < 4)
{
return;
}
if (in.size() % 4 != 0)
{
throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Malformed base64 input, length is not a multiple of 4.");
}
Size src_size = in.size();
// last one or two '=' are skipped if contained
int padding = 0;
if (in[src_size - 1] == '=') padding++;
if (in[src_size - 2] == '=') padding++;
src_size -= padding;
constexpr Size element_size = sizeof(ToType);
String s;
stringSimdDecoder_(in,s);
// change endianness if necessary (mzML is always LITTLE_ENDIAN; x64 is LITTLE_ENDIAN)
if ((OPENMS_IS_BIG_ENDIAN && from_byte_order == Base64::BYTEORDER_LITTLEENDIAN) || (!OPENMS_IS_BIG_ENDIAN && from_byte_order == Base64::BYTEORDER_BIGENDIAN))
{
invertEndianess<element_size>((void*)s.data(), s.size() / element_size);
}
const char* cptr = s.data();
const ToType * fptr = reinterpret_cast<const ToType*>(cptr);
out.assign(fptr,fptr + s.size()/element_size);
}
template <typename FromType>
void Base64::encodeIntegers(std::vector<FromType> & in, ByteOrder to_byte_order, String & out, bool zlib_compression)
{
out.clear();
if (in.empty())
return;
// initialize
const Size element_size = sizeof(FromType);
const Size input_bytes = element_size * in.size();
// change endianness if necessary
if ((OPENMS_IS_BIG_ENDIAN && to_byte_order == Base64::BYTEORDER_LITTLEENDIAN) || (!OPENMS_IS_BIG_ENDIAN && to_byte_order == Base64::BYTEORDER_BIGENDIAN))
{
if (element_size == 4)
{
for (Size i = 0; i < in.size(); ++i)
{
UInt32 tmp = in[i];
tmp = endianize32(tmp);
in[i] = tmp;
}
}
else
{
for (Size i = 0; i < in.size(); ++i)
{
UInt64 tmp = in[i];
tmp = endianize64(tmp);
in[i] = tmp;
}
}
}
// encode with compression (use Qt because of zlib support)
if (zlib_compression)
{
String compressed;
ZlibCompression::compressData((void*)in.data(), input_bytes, compressed);
stringSimdEncoder_(compressed, out);
}
else // encode without compression
{
String str((char*)in.data(), input_bytes);
stringSimdEncoder_(str, out);
}
}
template <typename ToType>
void Base64::decodeIntegers(const String & in, ByteOrder from_byte_order, std::vector<ToType> & out, bool zlib_compression)
{
if (zlib_compression)
{
decodeIntegersCompressed_(in, from_byte_order, out);
}
else
{
decodeIntegersUncompressed_(in, from_byte_order, out);
}
}
template <typename ToType>
void Base64::decodeIntegersCompressed_(const String & in, ByteOrder from_byte_order, std::vector<ToType> & out)
{
out.clear();
if (in.empty())
return;
constexpr Size element_size = sizeof(ToType);
String decompressed;
Base64::decodeSingleString(in, decompressed, true);
if (decompressed.empty())
{
throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Decompression error?");
}
void* byte_buffer = reinterpret_cast<void*>(&decompressed[0]);
Size buffer_size = decompressed.size();
// change endianness if necessary
if ((OPENMS_IS_BIG_ENDIAN && from_byte_order == Base64::BYTEORDER_LITTLEENDIAN) || (!OPENMS_IS_BIG_ENDIAN && from_byte_order == Base64::BYTEORDER_BIGENDIAN))
{
if constexpr(element_size == 4)
{
const Int32 * float_buffer = reinterpret_cast<const Int32 *>(byte_buffer);
if (buffer_size % element_size != 0)
throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Bad BufferCount?");
Size float_count = buffer_size / element_size;
UInt32 * p = reinterpret_cast<UInt32 *>(byte_buffer);
std::transform(p, p + float_count, p, endianize32);
out.resize(float_count);
// do NOT use assign here, as it will give a lot of type conversion warnings on VS compiler
for (Size i = 0; i < float_count; ++i)
{
out[i] = (ToType) * float_buffer;
++float_buffer;
}
}
else
{
const Int64 * float_buffer = reinterpret_cast<const Int64 *>(byte_buffer);
if (buffer_size % element_size != 0)
throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Bad BufferCount?");
Size float_count = buffer_size / element_size;
UInt64 * p = reinterpret_cast<UInt64 *>(byte_buffer);
std::transform(p, p + float_count, p, endianize64);
out.resize(float_count);
// do NOT use assign here, as it will give a lot of type conversion warnings on VS compiler
for (Size i = 0; i < float_count; ++i)
{
out[i] = (ToType) * float_buffer;
++float_buffer;
}
}
}
else
{
if constexpr(element_size == 4)
{
const Int * float_buffer = reinterpret_cast<const Int *>(byte_buffer);
if (buffer_size % element_size != 0)
throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Bad BufferCount while decoding?");
Size float_count = buffer_size / element_size;
out.resize(float_count);
// do NOT use assign here, as it will give a lot of type conversion warnings on VS compiler
for (Size i = 0; i < float_count; ++i)
{
out[i] = (ToType) * float_buffer;
++float_buffer;
}
}
else
{
const Int64 * float_buffer = reinterpret_cast<const Int64 *>(byte_buffer);
if (buffer_size % element_size != 0)
throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Bad BufferCount while decoding?");
Size float_count = buffer_size / element_size;
out.resize(float_count);
// do NOT use assign here, as it will give a lot of type conversion warnings on VS compiler
for (Size i = 0; i < float_count; ++i)
{
out[i] = (ToType) * float_buffer;
++float_buffer;
}
}
}
}
template <typename ToType>
void Base64::decodeIntegersUncompressed_(const String & in, ByteOrder from_byte_order, std::vector<ToType> & out)
{
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;
}
Size src_size = in.size();
// last one or two '=' are skipped if contained
int padding = 0;
if (in[src_size - 1] == '=') padding++;
if (in[src_size - 2] == '=') padding++;
src_size -= padding;
UInt a;
UInt b;
UInt offset = 0;
int inc = 1;
UInt written = 0;
const Size element_size = sizeof(ToType);
// enough for either float or double
char element[8] = "\x00\x00\x00\x00\x00\x00\x00";
if ((OPENMS_IS_BIG_ENDIAN && from_byte_order == Base64::BYTEORDER_LITTLEENDIAN) || (!OPENMS_IS_BIG_ENDIAN && from_byte_order == Base64::BYTEORDER_BIGENDIAN))
{
offset = (element_size - 1); // other endian
inc = -1;
}
else
{
offset = 0;
inc = 1;
}
// reserve enough space in the output vector
out.reserve((UInt)(std::ceil((4.0 * src_size) / 3.0) + 6.0));
// sort all read bytes correctly into a char[4] (double) or
// char[8] (float) and push_back when necessary.
for (Size i = 0; i < src_size; i += 4)
{
// decode 4 Base64-Chars to 3 Byte
// -------------------------------
// decode the first two chars
a = decoder_[(int)in[i] - 43] - 62;
b = decoder_[(int)in[i + 1] - 43] - 62;
if (i + 1 >= src_size)
{
b = 0;
}
// write first byte (6 bits from a and 2 highest bits from b)
element[offset] = (unsigned char) ((a << 2) | (b >> 4));
written++;
offset = (offset + inc) % element_size;
if (written % element_size == 0)
{
ToType float_value;
if (element_size == 4)
{
Int32 * value = reinterpret_cast<Int32 *>(&element[0]);
float_value = (ToType) * value;
}
else
{
Int64 * value = reinterpret_cast<Int64 *>(&element[0]);
float_value = (ToType) * value;
}
out.push_back(float_value);
strcpy(element, "");
}
// decode the third char
a = decoder_[(int)in[i + 2] - 43] - 62;
if (i + 2 >= src_size)
{
a = 0;
}
// write second byte (4 lowest bits from b and 4 highest bits from a)
element[offset] = (unsigned char) (((b & 15) << 4) | (a >> 2));
written++;
offset = (offset + inc) % element_size;
if (written % element_size == 0)
{
ToType float_value;
if (element_size == 4)
{
Int32 * value = reinterpret_cast<Int32 *>(&element[0]);
float_value = (ToType) * value;
}
else
{
Int64 * value = reinterpret_cast<Int64 *>(&element[0]);
float_value = (ToType) * value;
}
out.push_back(float_value);
strcpy(element, "");
}
// decode the fourth char
b = decoder_[(int)in[i + 3] - 43] - 62;
if (i + 3 >= src_size)
{
b = 0;
}
// write third byte (2 lowest bits from a and 6 bits from b)
element[offset] = (unsigned char) (((a & 3) << 6) | b);
written++;
offset = (offset + inc) % element_size;
if (written % element_size == 0)
{
ToType float_value;
if (element_size == 4)
{
Int32 * value = reinterpret_cast<Int32 *>(&element[0]);
float_value = (ToType) * value;
}
else
{
Int64 * value = reinterpret_cast<Int64 *>(&element[0]);
float_value = (ToType) * value;
}
out.push_back(float_value);
strcpy(element, "");
}
}
}
} //namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/CompressedInputSource.h | .h | 1,569 | 47 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/String.h>
#include <xercesc/sax/InputSource.hpp>
namespace OpenMS
{
/**
@brief This class is based on xercesc::LocalFileInputSource
*/
class OPENMS_DLLAPI CompressedInputSource :
public xercesc::InputSource
{
public:
///Constructor
CompressedInputSource(const String & file_path, const String & header, xercesc::MemoryManager * const manager = xercesc::XMLPlatformUtils::fgMemoryManager);
///Constructor
CompressedInputSource(const XMLCh * const file_path, const String & header, xercesc::MemoryManager * const manager = xercesc::XMLPlatformUtils::fgMemoryManager);
///Constructor
~CompressedInputSource() override;
/**
@brief Depending on the header in the Constructor a Bzip2InputStream or a GzipInputStream object is returned
@note InputSource interface implementation
*/
xercesc::BinInputStream * makeStream() const override;
private:
String head_;
/// private CTor - not implemented
CompressedInputSource();
CompressedInputSource(const CompressedInputSource & source);
CompressedInputSource & operator=(const CompressedInputSource & source);
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/PTMXMLFile.h | .h | 1,638 | 56 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/FORMAT/XMLFile.h>
#include <map>
#include <vector>
namespace OpenMS
{
/**
@brief Used to load and store PTMXML files
This class is used to load and store documents that implement
the schema of PTMXML files.
@ingroup FileIO
*/
class OPENMS_DLLAPI PTMXMLFile :
public Internal::XMLFile
{
public:
/// Constructor
PTMXMLFile();
/**
@brief Loads the information of a PTMXML file
@param[in] filename The name of the file
@param[out] ptm_informations the PTM information from the file are stored herein
@throw FileNotFound is thrown if the given file could not be found
@throw ParseError is thrown if the given file could not be parsed
The information is read in and stored in the corresponding variables
*/
void load(const String & filename, std::map<String, std::pair<String, String> > & ptm_informations);
/**
@brief Stores the data in an PTMXML file
@throw UnableToCreateFile is thrown if the given filename could not be created
The data is read in and stored in the file 'filename'.
*/
void store(const String& filename, std::map<String, std::pair<String, String> > & ptm_informations) const;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/GzipIfstream.h | .h | 3,855 | 128 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/config.h>
#include <zlib.h>
namespace OpenMS
{
/**
@brief Decompresses files which are compressed in the gzip format (*.gzip)
*/
class OPENMS_DLLAPI GzipIfstream
{
public:
///Default Constructor
GzipIfstream();
/// Detailed constructor with filename
explicit GzipIfstream(const char * filename);
///Destructor
virtual ~GzipIfstream();
/**
* @brief Reads n bytes from the bzip2 compressed file into buffer s
*
* @param[out] s Buffer to be filled with the output
* @param[in] n The size of the buffer s
* @return The number of actually read bytes. If it is less than n, the end of the file was reached and the stream is closed
*
* @note This returns a raw byte stream that is *not* null-terminated. Be careful here.
* @note The length of the buffer needs to at least n
* @note Closes the stream if the end of file is reached. Check isOpen before reading from the file again
*
* @exception Exception::ConversionError is thrown if decompression fails
* @exception Exception::IllegalArgument is thrown if no file for decompression is given. This can happen even happen if a file was already open but read until the end.
*/
size_t read(char * s, size_t n);
/**
* @brief indicates whether the read function can be used safely
*
* @return true if end of file was reached. Otherwise false.
*/
bool streamEnd() const;
/**
* @brief returns whether a file is open.
*/
bool isOpen() const;
/**
* @brief opens a file for reading (decompression)
*
* @note any previous open files will be closed first!
*/
void open(const char * filename);
/**
* @brief closes current file.
*/
void close();
/*
@brief updates crc32 check sum whether the buffer is corrupted
@note if this function is used it has to be called after every call of function read
@param[in] s the buffer which will be checked
@param[in] n the size of the buffer
*
//void updateCRC32(const char* s,const size_t n);
*
@brief checks if data is corrupted after crc32 was computed
@note it can only be used if updateCRC32 was called after every call of function read
@return true if the buffer and hence the file is corrupted; no decompression is possible
*
//bool isCorrupted();
//unsigned long Crc32_ComputeBuf( unsigned long inCrc32, const void *buf,
// size_t bufLen );*/
protected:
///a gzFile object(void*) . Necessary for decompression
gzFile gzfile_;
///counts the last read duffer
int n_buffer_;
///saves the last returned error by the read function
int gzerror_;
///true if end of file is reached
bool stream_at_end_;
//needed if one wants to know whether file is okay
//unsigned long original_crc;
//needed if one wants to know whether file is okay
//unsigned long crc;
///not implemented
GzipIfstream(const GzipIfstream & bzip2);
GzipIfstream & operator=(const GzipIfstream & bzip2);
};
inline bool GzipIfstream::isOpen() const
{
return gzfile_ != nullptr;
}
inline bool GzipIfstream::streamEnd() const
{
return stream_at_end_;
}
/* inline bool GzipIfstream::isCorrupted()
{
std::cout<<"CRC"<<crc<<std::endl;
return (crc != original_crc);
}*/
} //namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/SequestOutfile.h | .h | 5,107 | 114 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CONCEPT/Exception.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/METADATA/PeptideIdentification.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
#include <map>
#include <vector>
#include <cmath>
namespace OpenMS
{
class ProteinIdentification;
class DateTime;
/**
@brief Representation of a Sequest output file
This class serves to read in a Sequest outfile. The information can be
retrieved via the load function.
@todo Handle Modifications (Andreas)
@todo Complete rewrite of the parser (and those of InsPecT and PepNovo), the code is bullshit... (Andreas)
@ingroup FileIO
*/
class OPENMS_DLLAPI SequestOutfile
{
public:
/// Constructor
SequestOutfile();
/// copy constructor
SequestOutfile(const SequestOutfile & sequest_outfile);
/// destructor
virtual ~SequestOutfile();
/// assignment operator
SequestOutfile & operator=(const SequestOutfile & sequest_outfile);
/// equality operator
bool operator==(const SequestOutfile & sequest_outfile) const;
/**
@brief loads data from a Sequest outfile
@param[in] result_filename the file to be loaded
@param[in] peptide_identifications the identifications
@param[in] protein_identification the protein identifications
@param[in] p_value_threshold the significance level (for the peptide hit scores)
@param[in] pvalues a list with the pvalues of the peptides (pvalues computed with peptide prophet)
@param[in] database the database used for the search
@param[in] ignore_proteins_per_peptide this is a hack to deal with files that use a suffix like "+1" in column "Reference", but do not actually list extra protein references in subsequent lines
@throw Exception::FileNotFound is thrown if the given result file could not be found
@throw Exception::ParseError is thrown if the given result file could not be parsed
@throw Exception::IllegalArgument
This class serves to read in a Sequest outfile. The information can be
retrieved via the load function.
*/
void load(const String & result_filename, PeptideIdentificationList & peptide_identifications, ProteinIdentification & protein_identification, const double p_value_threshold, std::vector<double> & pvalues, const String & database = "", const bool ignore_proteins_per_peptide = false);
// /// retrieve the p-values from the out files
// void getPValuesFromOutFiles(vector< pair < String, vector< double > > >& filenames_and_pvalues) throw (Exception::FileNotFound&, Exception::ParseError);
/// retrieve columns from a Sequest outfile line
bool getColumns(const String & line, std::vector<String> & substrings, Size number_of_columns, Size reference_column);
/** retrieve sequences from a FASTA database
@param[in] database_filename
@param[in] ac_position_map
@param[in] sequences
@param[in] found
@param[in] not_found
@throw Exception::FileNotFound is thrown if the database file could not be found
*/
void getSequences(const String & database_filename, const std::map<String, Size> & ac_position_map, std::vector<String> & sequences, std::vector<std::pair<String, Size> > & found, std::map<String, Size> & not_found);
/// retrieve the accession type and accession number from a protein description line
/// (e.g. from FASTA line: >gi|5524211|gb|AAD44166.1| cytochrome b [Elephas maximus maximus], get ac:AAD44166.1 ac type: GenBank)
void getACAndACType(String line, String & accession, String & accession_type);
/** read the header of an out file and retrieve various information
@throw Exception::FileNotFound is thrown if the results file could not be found
@throw Exception::ParseError is thrown if the results file could not be parsed
*/
void 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 & ions_column, Int & reference_column, Int & peptide_column, Int & score_column, Size & number_of_columns);
private:
static double const_weights_[];
static double xcorr_weights_[];
static double delta_cn_weights_[];
static double rank_sp_weights_[];
static double delta_mass_weights_[];
static Size max_pep_lens_[];
static Size num_frags_[];
};
} //namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/EDTAFile.h | .h | 3,238 | 109 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/CONCEPT/Exception.h>
#include <OpenMS/KERNEL/ConsensusMap.h>
#include <OpenMS/KERNEL/Feature.h>
#include <OpenMS/FORMAT/TextFile.h>
#include <fstream>
#include <vector>
namespace OpenMS
{
/**
@brief File adapter for Enhanced DTA files.
Input text file containing tab, space or comma separated columns.
The separator between columns is checked in the first line in this order.
It supports three variants of this format.
- Columns are: RT, MZ, Intensity
A header is optional.
- Columns are: RT, MZ, Intensity, Charge, <Meta-Data> columns{0,}
A header is mandatory.
Example:
@code
RT m/z Intensity charge mymeta1 mymeta2
321 405.233 24543534 2 lala lili
321 406.207 4343344 2 blubb blabb
@endcode
- Columns are: (RT, MZ, Intensity, Charge){1,}, <Meta-Data> columns{0,}
Header is mandatory.
First quadruplet is the consensus. All following quadruplets describe the sub-features.
This variant is discerned from variant #2 by the name of the fifth column, which is required to be RT1 (or rt1).
All other column names for sub-features are faithfully ignored.
Example:
@code
RT MZ INT CHARGE RT1 MZ1 INT1 CHARGE1 RT2 MZ2 INT2 CHARGE2
321 405 100 2 321 405 100 2 321 406 50 2
323 406 200 2 323 406 200 2 323 407 100 2 323 407 50 2
@endcode
@ingroup FileIO
*/
class OPENMS_DLLAPI EDTAFile
{
public:
/// Default constructor
EDTAFile();
/// Destructor
virtual ~EDTAFile();
private:
/**
* Check if column exists and convert String into double.
*/
double checkedToDouble_(const std::vector<String> & parts, Size index, double def = -1);
/**
* Check if column exists and convert String into Int.
*/
Int checkedToInt_(const std::vector<String> & parts, Size index, Int def = -1);
public:
/**
@brief Loads a EDTA file into a consensusXML.
The content of the file is stored in @p features.
@exception Exception::FileNotFound is thrown if the file could not be opened
@exception Exception::ParseError is thrown if an error occurs during parsing
*/
void load(const String & filename, ConsensusMap & consensus_map);
/**
@brief Stores a ConsensusMap as an enhanced DTA file.
NOT IMPLEMENTED
@exception Exception::UnableToCreateFile is thrown if the file could not be created
*/
void store(const String & filename, const ConsensusMap & map) const;
/**
@brief Stores a FeatureMap as an enhanced DTA file.
Creating columns: RT, m/z, intensity, charge
@exception Exception::UnableToCreateFile is thrown if the file could not be created
*/
void store(const String & filename, const FeatureMap & map) const;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/TraMLFile.h | .h | 2,682 | 80 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Andreas Bertsch$
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/FORMAT/XMLFile.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/DATASTRUCTURES/ListUtils.h>
namespace OpenMS
{
class Identification;
class TargetedExperiment;
/**
@brief File adapter for HUPO PSI TraML files
TraML files contain information about transitions used for targeted
proteomics and metabolomics experiments:
Deutsch et al. "TraML--a standard format for exchange of selected reaction monitoring transition lists."
Mol Cell Proteomics. 2012 Apr;11(4):R111.015040. doi: 10.1074/mcp.R111.015040.
In OpenMS, TraML files can be generated from TSV or CSV files using the
@ref OpenMS::TransitionTSVFile "TransitionTSVFile class" or the @ref
TOPP_TargetedFileConverter "TargetedFileConverter TOPP Tool". For more information on the TSV format required by the TOPP tool, see
see also the documentation of @ref
OpenMS::TransitionTSVFile "TransitionTSVFile".
@ingroup FileIO
*/
class OPENMS_DLLAPI TraMLFile :
public Internal::XMLFile,
public ProgressLogger
{
public:
///Default constructor
TraMLFile();
///Destructor
~TraMLFile() override;
/**
@brief Loads a map from a TraML file.
@exception Exception::FileNotFound is thrown if the file could not be opened
@exception Exception::ParseError is thrown if an error occurs during parsing
*/
void load(const String & filename, TargetedExperiment & id);
/**
@brief Stores a map in a TraML file.
@exception Exception::UnableToCreateFile is thrown if the file could not be created
*/
void store(const String & filename, const TargetedExperiment & id) const;
/**
@brief Checks if a file is valid with respect to the mapping file and the controlled vocabulary.
@param[in] filename File name of the file to be checked.
@param[out] errors Errors during the validation are returned in this output parameter.
@param[out] warnings Warnings during the validation are returned in this output parameter.
@exception Exception::FileNotFound is thrown if the file could not be opened
*/
bool isSemanticallyValid(const String & filename, StringList & errors, StringList & warnings);
private:
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/HDF5Connector.h | .h | 985 | 51 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/CONCEPT/Exception.h>
// forward declarations
namespace H5
{
struct H5File;
}
namespace OpenMS
{
/**
@brief File adapter for HDF5 files
This class contains certain helper functions to deal with HDF5 files.
@ingroup FileIO
*/
class OPENMS_DLLAPI HDF5Connector
{
public:
/// Constructor
HDF5Connector(const String& filename, bool createNewFile = false);
/// Destructor
~HDF5Connector();
void close();
protected:
H5::H5File* file_ = nullptr;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/MzMLFile.h | .h | 8,450 | 209 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/FORMAT/XMLFile.h>
#include <OpenMS/FORMAT/OPTIONS/PeakFileOptions.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/CONCEPT/Exception.h>
#include <OpenMS/DATASTRUCTURES/ListUtils.h> // StringList
#include <OpenMS/INTERFACES/IMSDataConsumer.h>
#include <map>
namespace OpenMS
{
/**
@brief File adapter for MzML files
This implementation does currently not support the whole functionality of MzML.
@ingroup FileIO
*/
class OPENMS_DLLAPI MzMLFile :
public Internal::XMLFile,
public ProgressLogger
{
public:
///Default constructor
MzMLFile();
///Destructor
~MzMLFile() override;
/// Mutable access to the options for loading/storing
PeakFileOptions& getOptions();
/// Non-mutable access to the options for loading/storing
const PeakFileOptions& getOptions() const;
/// set options for loading/storing
void setOptions(const PeakFileOptions&);
/**
@brief Loads a map from a MzML file. Spectra and chromatograms are sorted by default (this can be disabled using PeakFileOptions).
@param[in] filename The filename with the data
@param[out] map Is an MSExperiment
@exception Exception::FileNotFound is thrown if the file could not be opened
@exception Exception::ParseError is thrown if an error occurs during parsing
*/
void load(const String& filename, PeakMap& map);
/**
@brief Loads a map from a MzML file stored in a buffer (in memory).
@param[in] buffer The buffer with the data (i.e. string with content of an mzML file)
@param[out] map Is an MSExperiment
@exception Exception::ParseError is thrown if an error occurs during parsing
*/
void loadBuffer(const std::string& buffer, PeakMap& map);
/**
@brief Only count the number of spectra and chromatograms from a file
This method honors PeakOptions (if specified) for spectra, i.e. only spectra within the specified
RT range and MS levels are counted.
If PeakOptions have no filters set (the default), then spectra and chromatogram counts
are taken from the counts attribute of the spectrumList/chromatogramList tags (the
parsing skips all intermediate data and ends as soon as both counts are available).
*/
void loadSize(const String & filename, Size& scount, Size& ccount);
/**
@brief Stores a map in an MzML file.
@p map has to be an MSExperiment or have the same interface.
@exception Exception::UnableToCreateFile is thrown if the file could not be created
*/
void store(const String& filename, const PeakMap& map) const;
/**
@brief Stores a map in an output string.
@p output An empty string to store the result
@p map has to be an MSExperiment
*/
void storeBuffer(std::string & output, const PeakMap& map) const;
/**
@brief Transforms a map while loading using the supplied MSDataConsumer.
The result will not be stored directly but is available through the
events triggered by the parser and caught by the provided IMSDataConsumer
object.
This function should be used if processing and storage of the result can
be performed directly in the provided IMSDataConsumer object.
@note Transformation can be speed up by setting skip_full_count which
does not require a full first pass through the file to compute the
correct number of spectra and chromatograms in the input file.
@param[in] filename_in Filename of input mzML file to transform
@param[in] consumer Consumer class to operate on the input filename (implementing a transformation)
@param[in] skip_full_count Whether to skip computing the correct number of spectra and chromatograms in the input file
@param[in] skip_first_pass Skip first file parsing pass, which hands only meta-data (number of spectra/chroms and experimental settings) to the consumer
*/
void transform(const String& filename_in, Interfaces::IMSDataConsumer * consumer, bool skip_full_count = false, bool skip_first_pass = false);
/**
@brief Transforms a map while loading using the supplied MSDataConsumer
The result will be stored in the provided map.
This function should be used if a specific pre-processing should be
applied to the data before storing them in a map (e.g. if data-reduction
should be applied to the data before loading all data into memory).
@param[in] filename_in Filename of input mzML file to transform
@param[in] consumer Consumer class to operate on the input filename (implementing a transformation)
@param[in] map Map to store the resulting spectra and chromatograms
@param[in] skip_full_count Whether to skip computing the correct number of spectra and chromatograms in the input file
@param[in] skip_first_pass Skip first file parsing pass, which hands only meta-data (number of spectra/chroms and experimental settings) to the consumer
*/
void transform(const String& filename_in, Interfaces::IMSDataConsumer * consumer, PeakMap& map, bool skip_full_count = false, bool skip_first_pass = false);
/**
@brief Checks if a file validates against the XML schema.
@exception Exception::FileNotFound is thrown if the file cannot be found.
*/
bool isValid(const String& filename, std::ostream& os = std::cerr);
/**
@brief Checks if a file is valid with respect to the mapping file and the controlled vocabulary.
@param[in] filename File name of the file to be checked.
@param[out] errors Errors during the validation are returned in this output parameter.
@param[out] warnings Warnings during the validation are returned in this output parameter.
@exception Exception::FileNotFound is thrown if the file could not be opened
*/
bool isSemanticallyValid(const String& filename, StringList& errors, StringList& warnings);
/**
@brief Checks if a file is an indexed MzML file or not.
@param[in] filename File name of the file to be checked.
@exception Exception::FileNotFound is thrown if the file could not be opened
*/
bool hasIndex(const String& filename);
struct SpecInfo
{
Size count_centroided = 0;
Size count_profile = 0;
Size count_unknown = 0;
};
/**
@brief Check type of spectra based on their metadata (if available) or by inspecting the peaks itself.
By default, only the first @p first_n_spectra_only, which are NOT 'unknown' are checked to save time.
The current PeakFileOptions, e.g. which MS-level to read/skip, are honored, e.g. skipped spectra do not count
towards @p first_n_spectra_only.
You can use this function to estimate the spectrum type, but it should be done for each MS-level separately.
Otherwise you might get mixed (PROFILE+CENTROIDED) results.
@param[in] filename File name of the mzML file to be checked
@param[in] first_n_spectra_only Only inspect this many spectra (UNKNOWN spectra do not count) and then end parsing the file
@return Map of MS level to counts (centroided, profile, unknown)
@exception Exception::FileNotFound is thrown if the file could not be opened
*/
std::map<UInt, SpecInfo> getCentroidInfo(const String& filename, const Size first_n_spectra_only = 10);
protected:
/// Perform first pass through the file and retrieve the meta-data to initialize the consumer
void transformFirstPass_(const String& filename_in, Interfaces::IMSDataConsumer * consumer, bool skip_full_count);
/// Safe parse that catches exceptions and handles them accordingly
void safeParse_(const String & filename, Internal::XMLHandler * handler);
private:
/// Options for loading / storing
PeakFileOptions options_;
/// Location of indexed mzML schema
String indexed_schema_location_;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/XQuestResultXMLFile.h | .h | 6,036 | 129 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/FORMAT/XMLFile.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/METADATA/PeptideIdentification.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
#include <OpenMS/METADATA/ProteinIdentification.h>
#include <OpenMS/ANALYSIS/XLMS/OPXLDataStructs.h>
namespace OpenMS
{
/**
@brief Used to load and store xQuest result files
These files are used to store results derived from chemical cross-linking
coupled to MS experiments.
A documented schema for this format can be found at https://github.com/OpenMS/OpenMS/tree/develop/share/OpenMS/SCHEMAS
@ingroup FileIO
*/
class OPENMS_DLLAPI XQuestResultXMLFile :
public Internal::XMLFile,
public ProgressLogger
{
public:
XQuestResultXMLFile();
~XQuestResultXMLFile() override;
/**
@brief Load the content of the xquest.xml file into the provided data structures.
@param[in] filename Filename of the file which is to be loaded.
@param[in] pep_ids Where the spectra with identifications of the input file will be loaded to.
@param[in] prot_ids Where the protein identification of the input file will be loaded to.
*/
void load(const String & filename,
PeptideIdentificationList & pep_ids,
std::vector< ProteinIdentification > & prot_ids
);
/**
@brief Stores the identifications in a xQuest XML file.
@exception Exception::UnableToCreateFile is thrown if the file could not be created
*/
void store(const String& filename,
const std::vector<ProteinIdentification>& poid,
const PeptideIdentificationList& peid) const;
/**
* @brief Returns the total number of hits in the file
* @return total number of hits in the file
*/
int getNumberOfHits() const;
/**
* @brief Returns minimum score among the hits in the file.
* @return Minimum score among the hits in the file.
*/
double getMinScore() const;
/**
* @brief Returns maximum score among the hits in the file.
* @return Maximum score among the hits in the file.
*/
double getMaxScore() const;
/**
* @brief Writes spec.xml output containing matching peaks between heavy and light spectra after comparing and filtering
@param[out] out_file Path and filename for the output file
@param[in] base_name The base_name should be the name of the input spectra file without the file ending. Used as part of an identifier string for the spectra.
@param[in] preprocessed_pair_spectra The preprocessed spectra after comparing and filtering
@param[in] spectrum_pairs Indices of spectrum pairs in the input map
@param[out] all_top_csms CrossLinkSpectrumMatches, from which the IDs were generated. Only spectra with matches are written out.
@param[in] spectra The spectra, that were searched as a PeakMap. The indices in spectrum_pairs correspond to spectra in this map.
@param[in] test_mode Skip base64 encoding in test mode
*/
static void 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 = false);
/**
@brief Writes spec.xml output containing spectra for visualization. This version of the function is meant to be used for label-free linkers.
@param[out] out_file Path and filename for the output file
@param[in] base_name The base_name should be the name of the input spectra file without the file ending. Used as part of an identifier string for the spectra.
@param[out] all_top_csms CrossLinkSpectrumMatches, from which the IDs were generated. Only spectra with matches are written out.
@param[in] spectra The spectra, that were searched as a PeakMap.
@param[in] test_mode Skip base64 encoding in test mode
*/
static void 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 = false);
private:
/**
* @brief Transforms a PeakSpectrum into a base64 encoded string, which is the format used in spec.xml for xQuest.
* @param[in] spec The spectrum
* @param[in] header A header for the spectrum, build using the base_name parameter for writeXQuestXMLSpec and the index of the spectrum.
* @param[in] test_mode Skip base64 encoding in test mode
*/
static String getxQuestBase64EncodedSpectrum_(const PeakSpectrum& spec, const String& header, const bool& test_mode = false);
/**
* @brief A helper function, that takes one string containing one line and wraps it into several lines of a given width
* @param[in] input The string as one line
* @param[in] width The preferred line width
* @param[out] output String in which the output is written
*/
static void wrap_(const String& input, Size width, String& output);
int n_hits_; ///< Total number of hits within the result file
double min_score_; ///< Minimum score encountered in file
double max_score_; ///< Maximum score encountered in file
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/GzipInputStream.h | .h | 2,351 | 89 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/config.h>
#include <xercesc/util/BinInputStream.hpp>
namespace OpenMS
{
class GzipIfstream;
class String;
/**
* @brief Implements the BinInputStream class of the xerces-c library in order to read gzip compressed XML files.
*
*/
class OPENMS_DLLAPI GzipInputStream :
public xercesc::BinInputStream
{
public:
///Constructor
explicit GzipInputStream(const String& file_name);
explicit GzipInputStream(const char* const file_name);
///Destructor
~GzipInputStream() override;
///returns true if file is open
bool getIsOpen() const;
/**
* @brief returns the current position in the file
*
* @note Implementation of the xerces-c input stream interface
*/
XMLFilePos curPos() const override;
/**
* @brief writes bytes into buffer from file
*
* @note Implementation of the xerces-c input stream interface
*
* @param[out] to_fill is the buffer which is written to
* @param[in] max_to_read is the size of the buffer
*
* @return returns the number of bytes which were actually read
*
*/
XMLSize_t readBytes(XMLByte* const to_fill, const XMLSize_t max_to_read) override;
/**
* @brief returns 0
*
* @note Implementation of the xerces-c input stream interface
*
* If no content type is provided for the data, 0 is returned (as is the
* case here, see xerces docs).
*
*
*/
const XMLCh* getContentType() const override;
GzipInputStream() = delete;
GzipInputStream(const GzipInputStream& stream) = delete;
GzipInputStream& operator=(const GzipInputStream& stream) = delete;
private:
///pointer to an compression stream
GzipIfstream* gzip_ = nullptr;
///current index of the actual file
XMLSize_t file_current_index_;
};
inline XMLFilePos GzipInputStream::curPos() const
{
return file_current_index_;
}
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/PeakTypeEstimator.h | .h | 10,677 | 248 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/METADATA/SpectrumSettings.h>
#include <cmath>
#include <numeric>
namespace OpenMS
{
/**
@brief Estimates if the data of a spectrum is raw data or peak data
@ingroup Format
*/
class OPENMS_DLLAPI PeakTypeEstimator
{
public:
/**
@brief Estimates the peak type of the peaks in the iterator range based on intensity characteristics of up to five maxima
We estimate profile vs. centroided by looking at highest five peaks in the spectrum.
If at least two neighbouring sampling points to either side of a local maximum are found within 1 Th,
the peak is considered a profile peak. The intensities need to decline on both shoulders.
All sampling points successfully assigned as shoulder points are not considered for searching the next highest peak
(except local minima at the end of a shoulder, which can be used for shoulders from left and right).
If 5 peaks or 50% of total spectral intensity has been looked at, we compare the number of peaks hithero classified
as centroided (C) vs profile (P).
If P / (C+P) > 0.75, the spectrum is considered profile; centroided otherwise.
@note if there are less than 5 peaks in the iterator range SpectrumSettings::SpectrumType::UNKNOWN is returned
*/
template <typename PeakConstIterator>
static SpectrumSettings::SpectrumType estimateType(const PeakConstIterator& begin, const PeakConstIterator& end)
{
typedef typename PeakConstIterator::value_type PeakT;
// abort if there are less than 5 peak in the iterator range
if (end - begin < 5)
{
return SpectrumSettings::SpectrumType::UNKNOWN;
}
const int max_peaks = 5; // maximal number of peaks we are looking at
int profile_evidence = 0; // number of peaks found to be profile
int centroid_evidence = 0; // number of peaks found to be centroided
// copy data, since we need to modify
std::vector<PeakT> data(begin, end);
// total intensity of spectrum
double total_int = std::accumulate(begin, end, 0.0, [](double int_, const PeakT& p) { return int_ + p.getIntensity(); } );
double explained_int = 0;
// get the 5 highest peaks
for (int i = 0; i < max_peaks; ++i)
{
// stop if we explained +50% of all intensity
// (due to danger of interpreting noise - usually wrongly classified as centroided data)
if (explained_int > 0.5 * total_int) break;
double int_max = 0;
Size idx = std::numeric_limits<Size>::max();
// find highest peak position
for (Size i = 0; i < data.size(); ++i)
{
if (data[i].getIntensity() > int_max)
{
int_max = data[i].getIntensity();
idx = i;
}
}
// no more peaks
if (idx == std::numeric_limits<Size>::max()) break;
// check left and right peak shoulders and count number of sample points
typedef typename std::vector<PeakT>::iterator PeakIterator; // non-const version, since we need to modify the peaks
PeakIterator it_max = data.begin() + idx;
PeakIterator it = it_max;
double int_last = int_max;
while (it != data.begin()
&& it->getIntensity() <= int_last // at most 100% of last sample point
&& it->getIntensity() > 0
&& (it->getIntensity() / int_last) > 0.1 // at least 10% of last sample point
&& it->getMZ() + 1 > it_max->getMZ()) // at most 1 Th away
{
int_last = it->getIntensity();
explained_int += int_last;
it->setIntensity(0); // remove peak from future consideration
--it;
}
// if the current point is rising again, restore the intensity of the
// previous 'sink' point (because it could belong to a neighbour peak)
// e.g. imagine intensities: 1-2-3-2-1-2-4-2-1. We do not want to destroy the middle '1'
if (it->getIntensity() > int_last) (it+1)->setIntensity(int_last);
//std::cerr << " Peak candidate: " << it_max->getMZ() << " ...";
bool break_left = false;
if (it_max - it < 2+1) // 'it' does not fulfill the conditions, i.e. does not count
{ // fewer than two sampling points on left shoulder
//std::cerr << " break left " << it_max - it << " points\n";
break_left = true;
// do not end loop here.. we still need to clean up the right side
}
it_max->setIntensity(int_max); // restore center intensity
explained_int -= int_max;
it = it_max;
int_last = int_max;
while (it != data.end()
&& it->getIntensity() <= int_last // at most 100% of last sample point
&& it->getIntensity() > 0
&& (it->getIntensity() / int_last) > 0.1 // at least 10% of last sample point
&& it->getMZ() - 1 < it_max->getMZ()) // at most 1 Th away
{
int_last = it->getIntensity();
explained_int += int_last;
it->setIntensity(0); // remove peak from future consideration
++it;
}
// if the current point is rising again, restore the intensity of the
// previous 'sink' point (because it could belong to a neighbour peak)
// e.g. imagine intensities: 1-2-4-2-1-2-3-2-1. We do not want to destroy the middle '1'
// (note: the sequence is not identical to the one of the left shoulder)
if (it != data.end() && it->getIntensity() > int_last) (it-1)->setIntensity(int_last);
if (break_left || it - it_max < 2+1) // 'it' does not fulfill the conditions, i.e. does not count
{ // fewer than two sampling points on right shoulder
//std::cerr << " break right " << it - it_max << " points\n";
++centroid_evidence;
continue;
}
// peak has at least two sampling points on either side within 1 Th
++profile_evidence;
//std::cerr << " PROFILE " << it - it_max << " points right\n";
}
float evidence_ratio = profile_evidence / float(profile_evidence + centroid_evidence);
//std::cerr << "--> Evidence ratio: " << evidence_ratio;
if (evidence_ratio > 0.75) // 80% are profile
{
//std::cerr << " PROFILE\n";
return SpectrumSettings::SpectrumType::PROFILE;
}
else
{
//std::cerr << " CENTROID\n";
return SpectrumSettings::SpectrumType::CENTROID;
}
}
/**
Below code is left for reference, for things which do not work across instrument classes, resolutions and m/z ranges
(in case someone wants to try and improve it)
// this code does not work reliably, mainly on nearly-empty spectra.
// one could just use the median of minimal distances, but that requires a magical cutoff parameter, which is hard to find
// and will fail for extreme cases, e.g. very high m/z (where resolution is decreased and thus inter-peak spacing is large for profile data)
// Looking at quartiles of the distribution of inter-peak spacing also does not work reliable, due to variable sampling distances over the m/z range.
Profile distances are unimodal (with very few outliers),
aggregating around the sampling-interval of the instrument, e.g. 0.002 Th.
We restrict the search to the first 100 peaks, since sampling intervals can increase drastically over m/z, thus
distorting the unimodal model, e.g. for Orbitrap 0.0006@200 Th to 0.1@4000 Th.
Centroided distances are multimodal, aggregating at 1, 1/2, 1/3 etc and surprisingly often near 0 as well.
Comparing the distance between the first and third quantile of the distance distribution gives an indication
on the type of data. The Q1 vs. Q3 only differs by a few percent [(Q1-Q3)/Q1*100 ~ 4%] we are surely looking at profile data.
On the other hand, observing large differences (~ factor 10-100) indicates centroided data.
We set the threshold to factor of 5, i.e. if (Q3-Q1)/Q1 < 5, it's profile data.
template <typename PeakConstIterator>
static SpectrumSettings::SpectrumType estimateType(const PeakConstIterator& begin, const PeakConstIterator& end)
{
const int MAX_SAMPLED_DISTANCES = 100;
const double MAX_MZ_WINDOW = 300; // inspect only a small window, otherwise sampling distance between raw peaks will change too much
// abort if there are less than 5 peak in the iterator range
if (end - begin < 5)
{
return SpectrumSettings::SpectrumType::UNKNOWN;
}
int count(0);
std::vector<double> distances;
PeakConstIterator peak(begin);
while (peak->getIntensity() <= 0 && peak != end)
{ // 1st positive intensity
++peak;
}
if (peak == end)
{ // only zeros
return SpectrumSettings::SpectrumType::UNKNOWN;
}
double last_mz = peak->getMZ();
double last_dist = std::numeric_limits<double>::max();
for (++peak; peak != end
&& count < MAX_SAMPLED_DISTANCES
&& peak->getMZ() - begin->getMZ() < MAX_MZ_WINDOW
; ++peak)
{
if (peak->getIntensity() <= 0) continue;
double dist = peak->getMZ() - last_mz;
distances.push_back(std::min(last_dist, dist)); // min distances to either side
++count;
last_mz = peak->getMZ();
last_dist = dist;
}
if (count < 4) // at least 4 distances for non-zero(!) intensity peaks
{
if (peak != end) return estimateType(peak, end); // try further to the right
else return SpectrumSettings::SpectrumType::UNKNOWN;
}
double q1 = Math::quantile1st(distances.begin(), distances.end(), false);
double q3 = Math::quantile3rd(distances.begin(), distances.end(), true);
for (const auto& i : distances) std::cerr << i << ";";
std::cerr <<"\t";
if ((q3-q1) < q1*5) // q1 and q3 are roughly equal
{
return SpectrumSettings::SpectrumType::PROFILE;
}
else
{
return SpectrumSettings::SpectrumType::CENTROID;
}
}*/
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/GNPSMetaValueFile.h | .h | 624 | 21 | // 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/KERNEL/ConsensusMap.h>
#pragma once
namespace OpenMS
{
class OPENMS_DLLAPI GNPSMetaValueFile
{
public:
/// Generate a meta value table (tsv file) for GNPS FBMN with information on the input mzML files extracted from ConsensusMap.
static void store(const ConsensusMap& consensus_map, const String& output_file);
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/FeatureXMLFile.h | .h | 2,400 | 83 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/FORMAT/OPTIONS/FeatureFileOptions.h>
#include <OpenMS/FORMAT/XMLFile.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <iosfwd>
namespace OpenMS
{
class Feature;
class FeatureMap;
/**
@brief This class provides Input/Output functionality for feature maps
A documented schema for this format can be found at https://github.com/OpenMS/OpenMS/tree/develop/share/OpenMS/SCHEMAS
@todo Take care that unique ids are assigned properly by TOPP tools before
calling FeatureXMLFile::store(). There will be a message on OPENMS_LOG_INFO but
we will make no attempt to fix the problem in this class. (all developers)
@ingroup FileIO
*/
class OPENMS_DLLAPI FeatureXMLFile :
public Internal::XMLFile,
public ProgressLogger
{
public:
/** @name Constructors and Destructor */
//@{
///Default constructor
FeatureXMLFile();
///Destructor
~FeatureXMLFile() override;
//@}
/**
@brief loads the file with name @p filename into @p map and calls updateRanges().
@exception Exception::FileNotFound is thrown if the file could not be opened
@exception Exception::ParseError is thrown if an error occurs during parsing
*/
void load(const String& filename, FeatureMap& feature_map);
Size loadSize(const String& filename);
/**
@brief stores the map @p feature_map in file with name @p filename.
@exception Exception::UnableToCreateFile is thrown if the file could not be created
*/
void store(const String& filename, const FeatureMap& feature_map);
/// Mutable access to the options for loading/storing
FeatureFileOptions& getOptions();
/// Non-mutable access to the options for loading/storing
const FeatureFileOptions& getOptions() const;
/// setter for options for loading/storing
void setOptions(const FeatureFileOptions&);
protected:
/// Options that can be set
FeatureFileOptions options_;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/MzQCFile.h | .h | 2,059 | 56 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
#include <vector>
namespace OpenMS
{
class FeatureMap;
/**
@brief File adapter for mzQC files used to load and store mzQC files
This class collects the data for the mzQC File
@ingroup FileIO
*/
class OPENMS_DLLAPI MzQCFile
{
public:
// Default constructor
MzQCFile() = default;
/**
@brief Stores QC data in mzQC file with JSON format
@param[in] input_file mzML input file name
@param[out] output_file mzQC output file name
@param[in] exp MSExperiment to extract QC data from, prior sortSpectra() and updateRanges() required
@param[in] contact_name name of the person creating the mzQC file
@param[in] contact_address contact address (mail/e-mail or phone) of the person creating the mzQC file
@param[in] description description and comments about the mzQC file contents
@param[in] label unique and informative label for the run
@param[in] feature_map FeatureMap from feature file (featureXML)
@param[in] prot_ids protein identifications from ID file (idXML)
@param[in] pep_ids protein identifications from ID file (idXML)
*/
void store(const String& input_file,
const String& output_file,
const MSExperiment& exp,
const String& contact_name,
const String& contact_address,
const String& description,
const String& label,
const FeatureMap& feature_map,
std::vector<ProteinIdentification>& prot_ids,
PeptideIdentificationList& pep_ids) const;
};
} | Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/MzXMLFile.h | .h | 4,094 | 113 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/FORMAT/XMLFile.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/FORMAT/OPTIONS/PeakFileOptions.h>
#include <OpenMS/INTERFACES/IMSDataConsumer.h>
namespace OpenMS
{
class String;
/**
@brief File adapter for MzXML 3.1 files
@ingroup FileIO
*/
class OPENMS_DLLAPI MzXMLFile :
public Internal::XMLFile,
public ProgressLogger
{
typedef PeakMap MapType;
public:
///Default constructor
MzXMLFile();
///Destructor
~MzXMLFile() override;
/// Mutable access to the options for loading/storing
PeakFileOptions & getOptions();
/// Non-mutable access to the options for loading/storing
const PeakFileOptions & getOptions() const;
/// set options for loading/storing
void setOptions(const PeakFileOptions &);
/**
@brief Loads a map from a MzXML file.
@p map has to be a MSExperiment or have the same interface.
@exception Exception::FileNotFound is thrown if the file could not be opened
@exception Exception::ParseError is thrown if an error occurs during parsing
*/
void load(const String & filename, MapType & map);
/**
@brief Stores a map in a MzXML file.
@p map has to be a MSExperiment or have the same interface.
@exception Exception::UnableToCreateFile is thrown if the file could not be created
*/
void store(const String & filename, const MapType & map) const;
/**
@brief Transforms a map while loading using the supplied MSDataConsumer.
The result will not be stored directly but is available through the
events triggered by the parser and caught by the provided IMSDataConsumer
object.
This function should be used if processing and storage of the result can
be performed directly in the provided IMSDataConsumer object.
@note Transformation can be speed up by setting skip_full_count which
does not require a full first pass through the file to compute the
correct number of spectra and chromatograms in the input file.
@param[in] filename_in Filename of input mzML file to transform
@param[in] consumer Consumer class to operate on the input filename (implementing a transformation)
@param[in] skip_full_count Whether to skip computing the correct number of spectra and chromatograms in the input file
*/
void transform(const String& filename_in, Interfaces::IMSDataConsumer * consumer, bool skip_full_count = false);
/**
@brief Transforms a map while loading using the supplied MSDataConsumer
The result will be stored in the provided map.
This function should be used if a specific pre-processing should be
applied to the data before storing them in a map (e.g. if data-reduction
should be applied to the data before loading all data into memory).
@param[in] filename_in Filename of input mzXML file to transform
@param[in] consumer Consumer class to operate on the input filename (implementing a transformation)
@param[out] map Map to store the resulting spectra and chromatograms
@param[in] skip_full_count Whether to skip computing the correct number of spectra and chromatograms in the input file
*/
void transform(const String& filename_in, Interfaces::IMSDataConsumer * consumer, MapType& map, bool skip_full_count = false);
protected:
/// Perform first pass through the file and retrieve the meta-data to initialize the consumer
void transformFirstPass_(const String& filename_in, Interfaces::IMSDataConsumer * consumer, bool skip_full_count);
private:
PeakFileOptions options_;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/QcMLFile.h | .h | 9,354 | 207 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/FORMAT/HANDLERS/XMLHandler.h>
#include <OpenMS/FORMAT/XMLFile.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
#include <vector>
namespace OpenMS
{
class ConsensusMap;
class FeatureMap;
/**
@brief File adapter for QcML files used to load and store QcML files
This Class is supposed to internally collect the data for the qcML File
A documented schema for this format can be found at https://github.com/OpenMS/OpenMS/tree/develop/share/OpenMS/SCHEMAS
@ingroup FileIO
*/
class OPENMS_DLLAPI QcMLFile :
public Internal::XMLHandler,
public Internal::XMLFile,
public ProgressLogger
{
public:
/// Representation of a quality parameter
class OPENMS_DLLAPI QualityParameter
{
public:
String name; ///< Name
String id; ///< Identifier
String value; ///< Value
String cvRef; ///< cv reference
String cvAcc; ///< cv accession
String unitRef; ///< cv reference of the unit
String unitAcc; ///< cv accession of the unit
String flag; ///< cv accession of the unit
///Default constructor
QualityParameter();
QualityParameter(const QualityParameter& rhs);
QualityParameter& operator=(const QualityParameter& rhs);
bool operator==(const QualityParameter& rhs) const;
bool operator<(const QualityParameter& rhs) const;
bool operator>(const QualityParameter& rhs) const;
String toXMLString(UInt indentation_level) const;
};
/// Representation of an attachment
class OPENMS_DLLAPI Attachment
{
public:
String name; ///< Name
String id; ///< Name
String value; ///< Value
String cvRef; ///< cv reference
String cvAcc; ///< cv accession
String unitRef; ///< cv reference of the unit
String unitAcc; ///< cv accession of the unit
String binary; ///< binary content of the attachment
String qualityRef; ///< reference to qp to which attachment, if empty attached to run/set
std::vector<String> colTypes; ///< type of the cols if QP has a table of values
std::vector< std::vector<String> > tableRows; ///< cell values if QP has a table, type see colType
//~ TODO -schema- coltypes with full definition (uintRef, unitAcc)
///Default constructor
Attachment();
Attachment(const Attachment& rhs);
Attachment& operator=(const Attachment& rhs);
bool operator==(const Attachment& rhs) const;
bool operator<(const Attachment& rhs) const;
bool operator>(const Attachment& rhs) const;
String toXMLString(UInt indentation_level) const;
String toCSVString(const String& separator) const;
};
///Default constructor
QcMLFile();
///Destructor
~QcMLFile() override;
String map2csv(const std::map< String, std::map<String, String> >& cvs_table, const String& separator) const;
String exportIDstats(const String& filename) const;
/// Registers a run in the qcml file with the respective mappings
void registerRun(const String& id, const String& name);
/// Registers a set in the qcml file with the respective mappings
void registerSet(const String& id, const String& name, const std::set<String>& names);
/// Just adds a qualityparameter to run by the name r
void addRunQualityParameter(const String& r, const QualityParameter& qp);
/// Just adds a attachment to run by the name r
void addRunAttachment(const String& r, const Attachment& at);
/// Just adds a qualityparameter to set by the name r
void addSetQualityParameter(const String& r, const QualityParameter& qp);
/// Just adds a attachment to set by the name r
void addSetAttachment(const String& r, const Attachment& at);
/// Removes attachments referencing a id given in ids, from run/set r. All attachments if no attachment name is given with at.
void removeAttachment(const String& r, std::vector<String>& ids, const String& at = "");
/// Removes attachment with cv accession at from run/set r.
void removeAttachment(const String& r, const String& at);
/// Removes attachment with cv accession at from all runs/sets.
void removeAllAttachments(const String& at);
/// Just removes qualityparameter going by one of the ID attributes given in ids.
void removeQualityParameter(const String& r, std::vector<String>& ids);
/// merges the given QCFile into this one
void merge(const QcMLFile & addendum, const String& setname = "");
/// collects the values of given QPs (as CVid) of the given set
void/* std::vector<String>& */ collectSetParameter(const String& setname, const String& qp, std::vector<String>& ret);
/// Returns a String of a tab separated rows if found empty string else from run/set by the name filename of the qualityparameter by the name qpname
String exportAttachment(const String& filename, const String& qpname) const;
/// Returns a String value in quotation of a qualityparameter by the name qpname in run/set by the name filename
String exportQP(const String& filename, const String& qpname) const;
/// Returns a String of a tab separated qualityparameter by the name qpname in run/set by the name filename
String exportQPs(const String& filename, const StringList& qpnames) const;
/// Gives the ids of the registered runs in the vector ids.
void getRunIDs (std::vector<String>& ids) const;
/// Gives the names of the registered runs in the vector ids.
void getRunNames (std::vector<String>& ids) const;
/// Returns true if the given run id is present in this file, if checkname is true it also checks the names
bool existsRun(const String& filename, bool checkname = false) const;
/// Returns true if the given set id is present in this file, if checkname is true it also checks the names
bool existsSet(const String& filename, bool checkname = false) const;
/// Returns the ids of the parameter name given if found in given run empty else
void existsRunQualityParameter(const String& filename, const String& qpname, std::vector<String>& ids) const;
/// Returns the ids of the parameter name given if found in given set, empty else
void existsSetQualityParameter(const String& filename, const String& qpname, std::vector<String>& ids) const;
/// Calculation and collection of QC data
/**
@brief Collects QC data in qualityParameters and qualityAttachments
@param[in] prot_ids protein identifications from ID file
@param[in] pep_ids peptide identifications
@param[in] feature_map FeatureMap from feature file (featureXML)
@param[in] consensus_map ConsensusMap from consensus file (consensusXML)
@param[in] inputfile_raw mzML input file name
@param[in] remove_duplicate_features removes duplicates in a set of merged features
@param[in] exp MSExperiment to extract QC data from, prior sortSpectra() and updateRanges() required
*/
void collectQCData(std::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);
///Store the QCFile
/**
@brief Store the qcML file
@param[out] filename qcML output file name
*/
void store(const String& filename) const;
///Load a QCFile
void load(const String & filename);
//~ int siz; //debug
protected:
// Docu in base class
void endElement(const XMLCh * const /*uri*/, const XMLCh * const /*local_name*/, const XMLCh * const qname) override;
// Docu in base class
void startElement(const XMLCh * const /*uri*/, const XMLCh * const /*local_name*/, const XMLCh * const qname, const xercesc::Attributes & attributes) override;
// Docu in base class
void characters(const XMLCh * const chars, const XMLSize_t length) override;
std::map<String, std::vector< QualityParameter > > runQualityQPs_; //TODO run name attribute to schema of RunQuality
std::map<String, std::vector< Attachment > > runQualityAts_;
std::map<String, std::vector< QualityParameter > > setQualityQPs_;
std::map<String, std::vector< Attachment > > setQualityAts_;
std::map<String, std::set< String > > setQualityQPs_members_;
std::map<String, String > run_Name_ID_map_;
std::map<String, String > set_Name_ID_map_;
String tag_;
UInt progress_;
QualityParameter qp_;
Attachment at_;
std::vector<String> row_;
std::vector<String> header_;
String name_;
String run_id_;
std::set<String> names_;
std::vector<QualityParameter> qps_;
std::vector<Attachment> ats_;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/InspectInfile.h | .h | 7,409 | 162 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/String.h>
#include <map>
namespace OpenMS
{
/**
@brief Inspect input file adapter.
Creates a file that can be used for Inspect search from a peak list.
@ingroup FileIO
*/
class OPENMS_DLLAPI InspectInfile
{
public:
/// default constructor
InspectInfile();
/// copy constructor
InspectInfile(const InspectInfile& inspect_infile);
/// destructor
virtual ~InspectInfile();
/// assignment operator
InspectInfile& operator=(const InspectInfile& inspect_infile);
/// equality operator
bool operator==(const InspectInfile& inspect_infile) const;
/** stores the experiment data in an Inspect input file that can be used as input for Inspect shell execution
@param[in] filename set the given filename
@throw UnableToCreateFile is thrown if the file could not be created
*/
void store(const String& filename);
/** retrieves the name, mass change, affected residues, type and position for all modifications from a string
@param[in] modification_line
@param[in] modifications_filename
@param[in] monoisotopic if true, masses are considered to be monoisotopic
@throw FileNotReadable if the modifications_filename could not be read
@throw FileNotFound if modifications_filename could not be found
@throw ParseError if modifications_filename could not be parsed
*/
void handlePTMs(const String& modification_line, const String& modifications_filename, const bool monoisotopic);
/**
@brief Specifies a spectrum file to search.
You can specify the name of a directory to search every file in that directory (non-recursively). Supported spectra file formats are .mzXML, .mzData, .ms2, dta, and .pkl. Multiple spectra in one .dta file are not supported.
*/
const String& getSpectra() const;
void setSpectra(const String& spectra);
/**
@brief Specifies the name of a database (.trie file) to search.
The .trie file contains one or more protein sequences delimited by asterisks, with no whitespace or other data. Use PrepDB.py (see above) to prepare a .trie file. Most .trie files have a corresponding .index file giving the names of the proteins. You can specify at most one database.
*/
const String& getDb() const;
void setDb(const String& db);
/// Specifies the name of a enzyme. "Trypsin", "None", and "Chymotrypsin" are the available values.
const String& getEnzyme() const;
void setEnzyme(const String& enzyme);
/// Number of PTMs permitted in a single peptide.
Int getModificationsPerPeptide() const;
void setModificationsPerPeptide(Int modifications_per_peptide);
/**
@brief run Inspect in a blind mode
If true, use the MS-Alignment algorithm to perform a blind search (allowing arbitrary modification masses). Running a blind search with one mod per peptide is slower than the normal (tag-based) search; running time is approximately 1 second per spectra per megabyte of database. Running a blind search with two mods is significantly slower. We recommend performing "blind" searches against a small database, containing proteins output by an earlier search.
*/
UInt getBlind() const;
void setBlind(UInt blind);
/**
@brief the maximum modification size (in Da) to consider in a blind search
Defaults to 200. Larger values require more time to search.
*/
float getMaxPTMsize() const;
void setMaxPTMsize(float maxptmsize);
/**
@brief Specifies the parent mass tolerance, in Daltons.
A candidate's flanking mass can differ from the tag's flanking mass by no more than this amount.
*/
float getPrecursorMassTolerance() const;
void setPrecursorMassTolerance(float precursor_mass_tolerance);
/**
@brief How far b and y peaks can be shifted from their expected masses.
Default is 0.5. Higher values produce a more sensitive but much slower search.
*/
float getPeakMassTolerance() const;
void setPeakMassTolerance(float peak_mass_tolerance);
/// If set to true, attempt to guess the precursor charge and mass, and consider multiple charge states if feasible.
UInt getMulticharge() const;
void setMulticharge(UInt multicharge);
/// If set to QTOF, uses a QTOF-derived fragmentation model, and does not attempt to correct the parent mass.
const String& getInstrument() const;
void setInstrument(const String& instrument);
/// Number of tags to generate.
Int getTagCount() const;
void setTagCount(Int TagCount);
/// return the modifications (the modification names map to the affected residues, the mass change and the type)
const std::map<String, std::vector<String> >& getModifications() const;
private:
String spectra_; ///< Specifies a spectrum file to search.
String db_; ///< Specifies the name of a database (.trie file) to search. The .trie file contains one or more protein sequences delimited by asterisks, with no whitespace or other data.
String enzyme_; ///< Specifies the name of a enzyme. "Trypsin", "None", and "Chymotrypsin" are the available values.
Int modifications_per_peptide_; ///< allowed number of modifications per peptide
UInt blind_; ///< If true, use the MS-Alignment algorithm to perform a blind search (allowing arbitrary modification masses). Running a blind search with one mod per peptide is slower than the normal (tag-based) search; running time is approximately 1 second per spectra per megabyte of database. Running a blind search with two mods is significantly slower. We recommend performing "blind" searches against a small database, containing proteins output by an earlier search. (The "Summary.py" script can be used to generate a second-pass database from initial search results)
/// 0 - false, 1 - true, 2 - not set
float maxptmsize_; ///< For blind search, specifies the maximum modification size (in Da) to consider. Defaults to 200. Larger values require more time to search. <0 is not set
float precursor_mass_tolerance_; ///< Specifies the parent mass tolerance, in Daltons. A candidate's flanking mass can differ from the tag's flanking mass by no more than this amount. <0 is not set
float peak_mass_tolerance_; ///< How far b and y peaks can be shifted from their expected masses. Default is 0.5. Higher values produce a more sensitive but much slower search. <0 is not set
UInt multicharge_; ///< If set to true, attempt to guess the precursor charge and mass, and consider multiple charge states if feasible.
/// 0 - false, 1 - true, 2 - not set
String instrument_; ///< If set to QTOF, uses a QTOF-derived fragmentation model, and does not attempt to correct the parent mass.
Int tag_count_; ///< Number of tags to generate. <0 is not set
std::map<String, std::vector<String> > PTMname_residues_mass_type_; ///< the modification names map to the affected residues, the mass change and the type
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/SVOutStream.h | .h | 5,959 | 199 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/String.h>
#include <ostream>
#include <fstream> // std::ofstream
#include <sstream>
#include <boost/math/special_functions/fpclassify.hpp> // because isfinite not supported on Mac
namespace OpenMS
{
/// custom newline indicator
enum Newline {nl};
/**
@brief Stream class for writing to comma/tab/...-separated values files.
Automatically inserts separators between items and handles quoting of strings. Requires @p nl (preferred) or @p std::endl as the line delimiter - @p "\n" won't be accepted.
@ingroup Format
*/
class OPENMS_DLLAPI SVOutStream :
public std::ostream
{
public:
/**
@brief Constructor
@param[out] file_out Output filename; will be overwritten if exists
@param[in] sep Separator string (typically comma, semicolon, or tab)
@param[in] replacement If @p quoting is @p NONE, used to replace occurrences of @p sep within strings before writing them
@param[in] quoting Quoting method for strings (see @p String::quote)
*/
SVOutStream(const String& file_out,
const String& sep = "\t",
const String& replacement = "_",
String::QuotingMethod quoting = String::DOUBLE);
/**
@brief Constructor
@param[out] out Output stream to write to (open file or @p cout)
@param[in] sep Separator string (typically comma, semicolon, or tab)
@param[in] replacement If @p quoting is @p NONE, used to replace occurrences of @p sep within strings before writing them
@param[in] quoting Quoting method for strings (see @p String::quote)
*/
SVOutStream(std::ostream& out,
const String& sep = "\t",
const String& replacement = "_",
String::QuotingMethod quoting = String::DOUBLE);
/**
@brief Destructor
Frees ofstream_* if filename c'tor was used.
*/
~SVOutStream() override;
/**
@brief Stream output operator for @p String
The argument is quoted before writing; it must not contain the newline character
*/
SVOutStream& operator<<(String str); // use call-by-value here
/**
@brief Stream output operator for @p std::string
The argument is quoted before writing; it must not contain the newline character
*/
SVOutStream& operator<<(const std::string& str);
/**
@brief Stream output operator for @p char*
The argument is quoted before writing; it must not contain the newline character
*/
SVOutStream& operator<<(const char* c_str);
/**
@brief Stream output operator for @p char
The argument is quoted before writing; it must not contain the newline character
*/
SVOutStream& operator<<(const char c);
/// Stream output operator for manipulators (used to catch @p std::endl)
SVOutStream& operator<<(std::ostream& (*fp)(std::ostream&));
/**
@brief Stream output operator for custom newline (@p nl) without flushing
Use "nl" instead of "endl" for improved performance
*/
SVOutStream& operator<<(enum Newline);
/// numeric types should be converted to String first to make use
/// of StringConversion
template<typename T>
typename std::enable_if<std::is_arithmetic<typename std::remove_reference<T>::type>::value, SVOutStream&>::type operator<<(const T& value)
{
if (!newline_) static_cast<std::ostream&>(*this) << sep_;
else newline_ = false;
static_cast<std::ostream&>(*this) << String(value);
return *this;
};
/// Generic stream output operator (for non-character-based types)
template<typename T>
typename std::enable_if<!std::is_arithmetic<typename std::remove_reference<T>::type>::value, SVOutStream&>::type operator<<(const T& value)
{
if (!newline_)
static_cast<std::ostream &>(*this) << sep_;
else
newline_ = false;
static_cast<std::ostream &>(*this) << value;
return *this;
};
/// Unformatted output (no quoting: useful for comments, but use only on a line of its own!)
SVOutStream& write(const String& str); // write unmodified string
/**
@brief Switch modification of strings (quoting/replacing of separators) on/off
@return previous modification state
*/
bool modifyStrings(bool modify);
/// Write a numeric value or "nan"/"inf"/"-inf", if applicable (would not be needed for Linux)
template <typename NumericT>
SVOutStream& writeValueOrNan(NumericT thing)
{
if ((boost::math::isfinite)(thing)) return operator<<(thing);
bool old = modifyStrings(false);
if ((boost::math::isnan)(thing))
{
operator<<(nan_);
}
else if (thing < 0)
{
operator<<("-" + inf_);
}
else
{
operator<<(inf_);
}
modifyStrings(old);
return *this;
}
protected:
/// internal file stream when C'tor is called with a filename
std::ofstream* ofs_;
/// Separator string
String sep_;
/// Replacement for separator
String replacement_;
/// String to use for NaN values
String nan_;
/// String to use for Inf values
String inf_;
/// String quoting method
String::QuotingMethod quoting_;
/// On/off switch for modification of strings
bool modify_strings_;
/// Are we at the beginning of a line? (Otherwise, insert separator before next item.)
bool newline_;
/// Stream for testing if a manipulator is "std::endl"
std::stringstream ss_;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/FileTypes.h | .h | 10,079 | 201 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/config.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <vector>
namespace OpenMS
{
/**
@brief Centralizes the file types recognized by FileHandler.
FileType separate from FileHandler to avoid circular inclusions by DocumentIdentifier, ExperimentalSettings
and FileHandler and respective fileclasses (e.g. DTA2DFile).
@ingroup FileIO
*/
struct OPENMS_DLLAPI FileTypes
{
///Actual file types enum.
enum Type
{
UNKNOWN, ///< Unknown file extension
DTA, ///< DTA file (.dta)
DTA2D, ///< DTA2D file (.dta2d)
MZDATA, ///< MzData file (.mzData)
MZXML, ///< MzXML file (.mzXML)
FEATUREXML, ///< %OpenMS feature file (.featureXML)
IDXML, ///< %OpenMS identification format (.idXML)
CONSENSUSXML, ///< %OpenMS consensus map format (.consensusXML)
MGF, ///< Mascot Generic Format (.mgf)
INI, ///< %OpenMS parameters file (.ini)
TOPPAS, ///< %OpenMS parameters file with workflow information (.toppas)
TRANSFORMATIONXML, ///< Transformation description file (.trafoXML)
MZML, ///< MzML file (.mzML)
CACHEDMZML, ///< CachedMzML file (.cachedmzML)
MS2, ///< MS2 file (.ms2)
PEPXML, ///< TPP pepXML file (.pepXML)
PROTXML, ///< TPP protXML file (.protXML)
MZIDENTML, ///< mzIdentML (HUPO PSI AnalysisXML followup format) (.mzid)
QCML, ///< qcML (will undergo standardisation maybe) (.qcml)
MZQC, ///< mzQC (HUPO PSI format) (.mzQC)
GELML, ///< GelML (HUPO PSI format) (.gelML)
TRAML, ///< TraML (HUPO PSI format) for transitions (.traML)
MSP, ///< NIST spectra library file format (.msp)
OMSSAXML, ///< OMSSA XML file format for peptide identifications (.xml)
MASCOTXML, ///< Mascot XML file format for peptide identifications (.xml)
PNG, ///< Portable Network Graphics (.png)
XMASS, ///< XMass Analysis file (fid)
TSV, ///< any TSV file, for example msInspect file or OpenSWATH transition file (see TransitionTSVFile)
MZTAB, ///< mzTab file (.mzTab)
PEPLIST, ///< specArray file (.peplist)
HARDKLOER, ///< hardkloer file (.hardkloer)
KROENIK, ///< kroenik file (.kroenik)
FASTA, ///< FASTA file (.fasta)
EDTA, ///< enhanced comma separated files (RT, m/z, Intensity, [meta])
CSV, ///< general comma separated files format (might also be tab or space separated!!!), data should be regular, i.e. matrix form
TXT, ///< any text format, which has only loose definition of what it actually contains -- thus it is usually hard to say where the file actually came from (e.g. PepNovo).
OBO, ///< Controlled Vocabulary format
HTML, ///< any HTML format
ANALYSISXML, ///< analysisXML format
XSD, ///< XSD schema format
PSQ, ///< NCBI binary blast db
MRM, ///< SpectraST MRM List
SQMASS, ///< SqLite format for mass and chromatograms, see SqMassFile
PQP, ///< OpenSWATH Peptide Query Parameter (PQP) SQLite DB, see TransitionPQPFile
MS, ///< SIRIUS file format (.ms)
OSW, ///< OpenSWATH OpenSWATH report (OSW) SQLite DB
PSMS, ///< Percolator tab-delimited output (PSM level)
PIN, ///< Percolator tab-delimited input (PSM level)
PARAMXML, ///< internal format for writing and reading parameters (also used as part of CTD)
SPLIB, ///< SpectraST binary spectral library file (sptxt is the equivalent text-based format, similar to the MSP format)
NOVOR, ///< Novor custom parameter file
XQUESTXML, ///< xQuest XML file format for protein-protein cross-link identifications (.xquest.xml)
SPECXML, ///< xQuest XML file format for matched spectra for spectra visualization in the xQuest results manager (.spec.xml)
JSON, ///< JavaScript Object Notation file (.json)
RAW, ///< Thermo Raw File (.raw)
OMS, ///< OpenMS database file
EXE, ///< Executable (.exe)
XML, ///< any XML format
BZ2, ///< any BZ2 compressed file
GZ, ///< any Gzipped file
PARQUET, ///< Apache Parquet file format (.parquet, .pqt)
SIZE_OF_TYPE ///< No file type. Simply stores the number of types
};
enum class FileProperties
{
READABLE, // SOMETHING in OpenMS can read this (it doesn't have to be in FileHandler though)
WRITEABLE, // SOMETHING in OpenMS can write this (it doesn't have to be in FileHandler though)
PROVIDES_SPECTRUM, // All of the PROVIDES_x properties correspond to which FileHandlers are implemented for a file type.
PROVIDES_EXPERIMENT, //
PROVIDES_FEATURES, //
PROVIDES_CONSENSUSFEATURES, //
PROVIDES_IDENTIFICATIONS, //
PROVIDES_TRANSITIONS, //
PROVIDES_QUANTIFICATIONS, //
PROVIDES_TRANSFORMATIONS, //
PROVIDES_QC, //
SIZE_OF_FILEPROPERTIES // Not a property, just the number of 'em
};
/// Returns the name/extension of the type.
static String typeToName(Type type);
/// Returns the human-readable explanation of the type.
/// This may or may not add information, e.g.
/// MZML becomes "mzML raw data file", but FEATUREXML becomes "OpenMS feature map"
static String typeToDescription(Type type);
/// Converts a file type name into a Type
/// @param[in] name A case-insensitive name (e.g. FASTA or Fasta, etc.)
static Type nameToType(const String& name);
/// Returns the mzML name (TODO: switch to accession since they are more stable!)
static String typeToMZML(Type type);
};
enum class FilterLayout
{
COMPACT, ///< make a single item, e.g. 'all readable files (*.mzML *.mzXML);;'
ONE_BY_ONE, ///< list all types individually, e.g. 'mzML files (*.mzML);;mzXML files (*.mzXML);;'
BOTH ///< combine COMPACT and ONE_BY_ONE
};
/**
@brief holds a vector of known file types, e.g. as a way to specify supported input formats
The vector can be exported in Qt's file dialog format.
*/
class OPENMS_DLLAPI FileTypeList
{
public:
FileTypeList(const std::vector<FileTypes::Type>& types);
/// check if @p type is contained in this array
bool contains(const FileTypes::Type& type) const;
const std::vector<FileTypes::Type>& getTypes() const
{
return type_list_;
}
/// converts the array into a Qt-compatible filter for selecting files in a user dialog.
/// e.g. "all readable files (*.mzML *.mzXML);;". See Filter enum.
/// @param[in] style Create a combined filter, or single filters, or both
/// @param[in] add_all_filter Add 'all files (*)' as a single filter at the end?
String toFileDialogFilter(const FilterLayout style, bool add_all_filter) const;
/**
@brief Convert a Qt filter back to a Type if possible.
E.g. from a full filter such as '"mzML files (*.mzML);;mzData files (*.mzData);;mzXML files (*.mzXML);;all files (*)"',
as created by toFileDialogFilter(), the selected @p filter could be "mzML files (*.mzML)", in which case the type is Type::MZML .
However, for the filter "all files (*)", Type::UNKNOWN will be returned.
If the type is UNKNOWN, then the fallback is returned (by default also UNKNOWN). This is useful if you want a default type to fall back to.
@param[in] filter The filter returned by 'QFileDialog::getSaveFileName' and others, i.e. an item from the result of 'toFileDialogFilter'.
@param[in] fallback If the filter is ambiguous, return this type instead
@return The type associated to the filter or the fallback
@throw Exception::ElementNotFound if the given @p filter is not a filter produced by toFileDialogFilter()
**/
FileTypes::Type fromFileDialogFilter(const String& filter, const FileTypes::Type fallback = FileTypes::Type::UNKNOWN) const;
/**
@brief Get a std::vector<FileTypes::Type> with all fileTypes that support a set of features.
@param[in] features A set of features that must be supported
@return A std::vector<FileTypes::Type> with the files that support features
**/
static std::vector<FileTypes::Type> typesWithProperties(const std::vector<FileTypes::FileProperties> features);
private:
/// hold filter items (for Qt dialogs) along with their OpenMS type
struct FilterElements_
{
std::vector<String> items;
std::vector<FileTypes::Type> types;
};
/// creates Qt filters and the corresponding elements from type_list_
/// @param[in] style Create a combined filter, or single filters, or both
/// @param[in] add_all_filter Add 'all files (*)' as a single filter at the end?
FilterElements_ asFilterElements_(const FilterLayout style, bool add_all_filter) const;
std::vector<FileTypes::Type> type_list_;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/SqMassFile.h | .h | 2,858 | 93 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/INTERFACES/IMSDataConsumer.h>
namespace OpenMS
{
/**
@brief An class that uses on-disk SQLite database to read and write spectra and chromatograms
This class provides functions to read and write spectra and chromatograms
to disk using a SQLite database and store them in sqMass format. This
allows users to access, select and filter spectra and chromatograms
on-demand even in a large collection of data.
Spectra and chromatograms with precursor information will additionally load/store the metavalue
'peptide_sequence' from the first precursor (if any).
*/
class OPENMS_DLLAPI SqMassFile
{
public:
/**
@brief Configuration class for SqMassFile
Contains configuration options for SQLite file
*/
struct OPENMS_DLLAPI SqMassConfig
{
bool write_full_meta{true}; ///< write full meta data
bool use_lossy_numpress{false}; ///< use lossy numpress compression
double linear_fp_mass_acc{-1}; ///< desired mass accuracy for numpress linear encoding (-1 no effect, use 0.0001 for 0.2 ppm accuracy @ 500 m/z)
};
typedef MSExperiment MapType;
/** @name Constructors and Destructor
*/
//@{
/// Default constructor
SqMassFile();
/// Default destructor
~SqMassFile();
//@}
/** @name Read / Write a complete mass spectrometric experiment
*/
//@{
void load(const String& filename, MapType& map) const;
/**
@brief Store an MSExperiment in sqMass format
If you want a specific RUN::ID in the sqMass file,
make sure to populate MSExperiment::setSqlRunID(UInt64 id) before.
*/
void store(const String& filename, const MapType& map) const;
void transform(const String& filename_in, Interfaces::IMSDataConsumer* consumer, bool skip_full_count = false, bool skip_first_pass = false) const;
void setConfig(const SqMassConfig& config)
{
config_ = config;
}
// maybe later ...
// static inline void readSpectrumFast(OpenSwath::BinaryDataArrayPtr data1,
// OpenSwath::BinaryDataArrayPtr data2, std::ifstream& ifs, int& ms_level,
// double& rt)
// static inline void readChromatogramFast(OpenSwath::BinaryDataArrayPtr data1,
// OpenSwath::BinaryDataArrayPtr data2, std::ifstream& ifs)
protected:
SqMassConfig config_;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/SwathFile.h | .h | 4,445 | 101 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/OPENSWATHALGO/DATAACCESS/SwathMap.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/DATASTRUCTURES/ListUtils.h>
#include <OpenMS/KERNEL/StandardTypes.h>
#include <vector>
#include <memory>
namespace OpenMS
{
class ExperimentalSettings;
namespace Interfaces
{
class IMSDataConsumer;
}
/**
* @brief File adapter for Swath files.
*
* This class can load SWATH files in different storage versions. The most
* convenient file is a single MzML file which contains one experiment.
* However, also the loading of a list of files is supported (loadSplit)
* where it is assumed that each individual file only contains scans from one
* precursor isolation window (one SWATH). Finally, experimental support for
* mzXML is available but needs to be selected with a specific compile flag
* (this is not for everyday use).
*
*/
class OPENMS_DLLAPI SwathFile :
public ProgressLogger
{
public:
/// Loads a Swath run from a list of split mzML files
std::vector<OpenSwath::SwathMap> loadSplit(StringList file_list,
const String& tmp,
std::shared_ptr<ExperimentalSettings>& exp_meta,
const String& readoptions = "normal");
/**
@brief Loads a Swath run from a single mzML file
Using the @p plugin_consumer, you can provide a custom consumer which will be chained
into the process of loading the data and making it available (depending on @p readoptions).
This is useful if you want to modify the data a priori or extract some other information using
MSDataTransformingConsumer (for example). Make sure it leaves the data intact, such that the
returned SwathMaps are actually useful.
@param[in] file Input filename
@param[in] tmp Temporary directory (for cached data)
@param[out] exp_meta Experimental metadata from mzML file
@param[in] readoptions How are spectra accessed after reading - tradeoff between memory usage and time (disk caching)
@param[in] plugin_consumer An intermediate custom consumer
@return Swath maps for MS2 and MS1 (unless readoptions == split, which returns no data)
*/
std::vector<OpenSwath::SwathMap> loadMzML(const String& file,
const String& tmp,
std::shared_ptr<ExperimentalSettings>& exp_meta,
const String& readoptions = "normal",
Interfaces::IMSDataConsumer* plugin_consumer = nullptr);
/// Loads a Swath run from a single mzXML file
std::vector<OpenSwath::SwathMap> loadMzXML(const String& file,
const String& tmp,
std::shared_ptr<ExperimentalSettings>& exp_meta,
const String& readoptions = "normal");
/// Loads a Swath run from a single sqMass file
std::vector<OpenSwath::SwathMap> loadSqMass(const String& file, std::shared_ptr<ExperimentalSettings>& /* exp_meta */);
protected:
/// Cache a file to disk
OpenSwath::SpectrumAccessPtr doCacheFile_(const String& in, const String& tmp, const String& tmp_fname,
const std::shared_ptr<PeakMap >& experiment_metadata);
/// Only read the meta data from a file and use it to populate exp_meta
std::shared_ptr< PeakMap > populateMetaData_(const String& file);
/// Counts the number of scans in a full Swath file (e.g. concatenated non-split file)
void countScansInSwath_(const std::vector<MSSpectrum>& exp,
std::vector<int>& swath_counter, int& nr_ms1_spectra,
std::vector<OpenSwath::SwathMap>& known_window_boundaries,
double TOLERANCE=1e-6);
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/MRMFeaturePickerFile.h | .h | 3,721 | 95 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/config.h> // OPENMS_DLLAPI
#include <OpenMS/ANALYSIS/OPENSWATH/MRMFeaturePicker.h>
#include <OpenMS/FORMAT/CsvFile.h>
#include <map>
namespace OpenMS
{
/**
@brief _MRMFeaturePickerFile_ loads components and components groups parameters
from a .csv file.
The structures defined in [MRMFeaturePicker](@ref MRMFeaturePicker) are used.
It is required that columns `component_name` and `component_group_name` are present.
Lines whose `component_name`'s or `component_group_name`'s value is an empty string, will be skipped.
The class supports the absence of information within other columns.
A reduced example of the expected format (fewer columns are shown here):
> component_name,component_group_name,TransitionGroupPicker:stop_after_feature,TransitionGroupPicker:PeakPickerChromatogram:sgolay_frame_length
> arg-L.arg-L_1.Heavy,arg-L,2,15
> arg-L.arg-L_1.Light,arg-L,2,17
> orn.orn_1.Heavy,orn,3,21
> orn.orn_1.Light,orn,3,13
*/
class OPENMS_DLLAPI MRMFeaturePickerFile :
public CsvFile
{
public:
/// Constructor
MRMFeaturePickerFile() = default;
/// Destructor
~MRMFeaturePickerFile() override = default;
/**
@brief Loads the file's data and saves it into vectors of `ComponentParams` and `ComponentGroupParams`.
The file is expected to contain at least two columns: `component_name` and `component_group_name`. Otherwise,
an exception is thrown.
If a component group (identified by its name) is found multiple times, only the first one is saved.
@param[in] filename Path to the .csv input file
@param[out] cp_list Component params are saved in this list
@param[out] cgp_list Component Group params are saved in this list
@throw Exception::MissingInformation If the required columns are not found.
@throw Exception::FileNotFound If input file is not found.
*/
void load(
const String& filename,
std::vector<MRMFeaturePicker::ComponentParams>& cp_list,
std::vector<MRMFeaturePicker::ComponentGroupParams>& cgp_list
);
protected:
/**
@brief Extracts the information from a `StringList` and saves it into the correct data structures.
@param[in] line The line parsed from the input file
@param[in] headers A mapping from a given header to its value's position
@param[out] cp The extracted component parameters
@param[out] cgp The extracted component group parameters
@return Returns `false` if `component_name` or `component_group_name` are empty strings. Otherwise, it returns `true`.
*/
bool extractParamsFromLine_(
const StringList& line,
const std::map<String, Size>& headers,
MRMFeaturePicker::ComponentParams& cp,
MRMFeaturePicker::ComponentGroupParams& cgp
) const;
/**
@brief Helper method which takes care of converting the given value to the desired type,
based on the header (here `key`) information.
@param[in] key The header name with which the correct conversion is chosen
@param[in] value The value to be converted
@param[in,out] params The object where the new value is saved
*/
void setCastValue_(const String& key, const String& value, Param& params) const;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/ZlibCompression.h | .h | 2,602 | 78 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CONCEPT/Types.h>
#include <OpenMS/OpenMSConfig.h>
#include <OpenMS/CONCEPT/Exception.h>
#include <string>
#include <vector>
namespace OpenMS
{
class String;
/**
* @brief Compresses and uncompresses data using zlib
*
* @note The 'strings' here are not really null-terminated but rather
* containers of data. If you want safe conversions, use QtByteArray.
*
*/
class OPENMS_DLLAPI ZlibCompression
{
public:
/**
* @brief Compresses data using zlib directly
*
* @param[in] raw_data Data to be compressed
* @param[out] compressed_data Compressed result data
*
*/
static void compressString(std::string& raw_data, std::string& compressed_data);
/**
* @brief Compresses data using zlib directly
*
* @param[in] raw_data Data to be compressed
* @param[in] in_length Length of @p raw_data in bytes
* @param[out] compressed_data Compressed result data
*
*/
static void compressData(const void* raw_data, const size_t in_length, std::string& compressed_data);
/**
* @brief Uncompresses data using zlib
If available, provide the size of the uncompressed data in @p output_size for a small performance gain.
@note Does not support gzip format decompression (only zlib format).
@param[in] compressed_data The zlib compressed data
@param[in] nr_bytes Number of bytes in @p compressed data
@param[out] out Uncompressed result data
@param[in] output_size [optional] If known (!=0), provide the size of the uncompressed data
@throws Exception::InvalidValue if output_size was specified (>0) and turns out to be smaller than actual size of uncompressed data.
@throws Exception::InternalToolError if zlib cannot decompress the data (e.g. due to data corruption or unsupported gzip format)
*
*/
static void uncompressData(const void* compressed_data, size_t nr_bytes, std::string& out, size_t output_size = 0);
/// Convencience function calling @p uncompressData
static void uncompressString(const String& in, std::string& out, size_t output_size = 0);
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/MRMFeatureQCFile.h | .h | 6,586 | 176 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/FORMAT/CsvFile.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/DATASTRUCTURES/StringListUtils.h>
#include <OpenMS/ANALYSIS/OPENSWATH/MRMFeatureQC.h>
namespace OpenMS
{
/**
@brief File adapter for MRMFeatureQC files.
Loads and stores .csv or .tsv files describing an MRMFeatureQC.
@ingroup FileIO
*/
class OPENMS_DLLAPI MRMFeatureQCFile :
private CsvFile,
public ProgressLogger
{
public:
/// Default constructor
MRMFeatureQCFile() = default;
/// Destructor
~MRMFeatureQCFile() override = default;
/**
@brief Loads an MRMFeatureQC file.
@exception Exception::FileNotFound is thrown if the file could not be opened
@exception Exception::ParseError is thrown if an error occurs during parsing
@param[in] filename The path to the input file
@param[in,out] mrmfqc The output class which will contain the criteria
@param[in] is_component_group true if the user intends to load ComponentGroupQCs data, false otherwise
*/
void load(const String& filename, MRMFeatureQC& mrmfqc, const bool is_component_group) const;
/*
@brief Stores an MRMFeatureQC file.
@exception Exception::UnableToCreateFile is thrown if the file could not be created
@param[in] filename The path to the input file
@param[in] mrmfqc The output class which will contain the criteria
@param[in] is_component_group true if the user intends to store ComponentGroupQCs data, false otherwise
*/
void store(const String& filename, const MRMFeatureQC& mrmfqc, const bool is_component_group);
protected:
/**
@brief Save values from a line to a `ComponentQCs`.
@note Lines missing the `component_name` value will be skipped.
@param[in] line A line containing the values from a row in the input file
@param[in] headers A mapping from headers names to position indices
@param[out] c_qcs The output will be saved in a new element of this vector
*/
void pushValuesFromLine_(
const StringList& line,
const std::map<String, Size>& headers,
std::vector<MRMFeatureQC::ComponentQCs>& c_qcs
) const;
/**
@brief Save values from a line to a `ComponentGroupQCs`.
@note Lines missing the `component_group_name` value will be skipped.
@param[in] line A line containing the values from a row in the input file
@param[in] headers A mapping from headers names to position indices
@param[out] cg_qcs The output will be saved in a new element of this vector
*/
void pushValuesFromLine_(
const StringList& line,
const std::map<String, Size>& headers,
std::vector<MRMFeatureQC::ComponentGroupQCs>& cg_qcs
) const;
/**
@brief Set one of the values in a pair
The method is given in input a map from Strings to pairs.
Assuming the key is present within the map, its mapped value will be updated
with the given `value`, in the correct `boundary` position.
If the key is not found, a new pair will be created and both its values set
(in this case, a default value of 0.0 is given to the other pair's element).
@param[in] key The metavalue name
@param[in] value The mapped pair
@param[in] boundary "l" for lower bound or "u" for upper bound
@param[out] meta_values_qc The map containing the metavalues and pairs
*/
void setPairValue_(
const String& key,
const String& value,
const String& boundary,
std::map<String, std::pair<double,double>>& meta_values_qc
) const;
/**
@brief Extracts a column's value from a line.
The method looks for the value found within `line[headers[header]]`.
If the information is present and its value is valid, it will be converted
to `Int` and returned.
Otherwise, `default_value` (provided by the user) is returned.
@param[in] headers The mapping from columns' name to positions' indices
@param[in] line A list of strings containing a single row's values
@param[in] header The desired value's column name
@param[in] default_value A default value to return in case the information is not found or invalid
@return The found information (if found and valid) converted to `Int`. Otherwise `default_value`.
*/
Int getCastValue_(
const std::map<String, Size>& headers,
const StringList& line,
const String& header,
const Int default_value
) const;
/**
@brief Extracts a column's value from a line.
The method looks for the value found within `line[headers[header]]`.
If the information is present and its value is valid, it will be converted
to `double` and returned.
Otherwise, `default_value` (provided by the user) is returned.
@param[in] headers The mapping from columns' name to positions' indices
@param[in] line A list of strings containing a single row's values
@param[in] header The desired value's column name
@param[in] default_value A default value to return in case the information is not found or invalid
@return The found information (if found and valid) converted to `double`. Otherwise `default_value`.
*/
double getCastValue_(
const std::map<String, Size>& headers,
const StringList& line,
const String& header,
const double default_value
) const;
/**
@brief Extracts a column's value from a line.
The method looks for the value found within `line[headers[header]]`.
If the information is present and its value is valid, it will be converted
to `String` and returned.
Otherwise, `default_value` (provided by the user) is returned.
@param[in] headers The mapping from columns' name to positions' indices
@param[in] line A list of strings containing a single row's values
@param[in] header The desired value's column name
@param[in] default_value A default value to return in case the information is not found or invalid
@return The found information (if found and valid) converted to `String`. Otherwise `default_value`.
*/
String getCastValue_(
const std::map<String, Size>& headers,
const StringList& line,
const String& header,
const String& default_value
) const;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/PercolatorOutfile.h | .h | 1,894 | 60 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/METADATA/PeptideIdentification.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
#include <OpenMS/METADATA/ProteinIdentification.h>
#include <OpenMS/METADATA/SpectrumMetaDataLookup.h>
#include <vector>
namespace OpenMS
{
/**
@brief Class for reading Percolator tab-delimited output files.
For PSM-level output, the file extension should be ".psms".
*/
class OPENMS_DLLAPI PercolatorOutfile
{
public:
/// Types of Percolator scores
enum class ScoreType { QVALUE, POSTERRPROB, SCORE, SIZE_OF_SCORETYPE };
/// Names of Percolator scores (to match ScoreType)
static const std::string score_type_names[static_cast<size_t>(ScoreType::SIZE_OF_SCORETYPE)];
/// Return a score type given its name
static ScoreType getScoreType(String score_type_name);
/// Constructor
PercolatorOutfile();
/// Loads a Percolator output file
void load(const String& filename, ProteinIdentification& proteins,
PeptideIdentificationList& peptides,
SpectrumMetaDataLookup& lookup,
ScoreType output_score = ScoreType::QVALUE);
private:
/// Converts the peptide string to an 'AASequence' instance
void getPeptideSequence_(String peptide, AASequence& seq) const;
/// Resolve cases where N-terminal modifications may be misassigned to the first residue (for X! Tandem results)
void resolveMisassignedNTermMods_(String& peptide) const;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/GNPSQuantificationFile.h | .h | 923 | 24 | // 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 $
#pragma once
#include <OpenMS/KERNEL/ConsensusMap.h>
namespace OpenMS
{
class OPENMS_DLLAPI GNPSQuantificationFile
{
public:
/// Write feature quantification table (txt file) from a consensusXML file. Required for GNPS FBMN.
/// The table contains map information on the featureXML files from which the consensusXML file was generated as well as
/// a row for every consensus feature with information on rt, mz, intensity, width and quality. The same information is
/// added for each original feature in the consensus feature.
static void store(const ConsensusMap& consensus_map, const String& output_file);
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/MzDataFile.h | .h | 2,642 | 88 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/FORMAT/XMLFile.h>
#include <OpenMS/FORMAT/OPTIONS/PeakFileOptions.h>
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/KERNEL/Peak1D.h>
#include <OpenMS/FORMAT/HANDLERS/MzDataHandler.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/METADATA/DocumentIdentifier.h>
namespace OpenMS
{
/**
@brief File adapter for MzData files
@ingroup FileIO
*/
class OPENMS_DLLAPI MzDataFile :
public Internal::XMLFile,
public ProgressLogger
{
typedef PeakMap MapType;
public:
///Default constructor
MzDataFile();
///Destructor
~MzDataFile() override;
/// Mutable access to the options for loading/storing
PeakFileOptions & getOptions();
/// Non-mutable access to the options for loading/storing
const PeakFileOptions & getOptions() const;
/// set options for loading/storing
void setOptions(const PeakFileOptions &);
/**
@brief Loads a map from a MzData file.
@p map has to be a MSExperiment or have the same interface.
@exception Exception::FileNotFound is thrown if the file could not be opened
@exception Exception::ParseError is thrown if an error occurs during parsing
*/
void load(const String & filename, MapType & map);
/**
@brief Stores a map in a MzData file.
@p map has to be a MSExperiment or have the same interface.
@exception Exception::UnableToCreateFile is thrown if the file could not be created
*/
void store(const String & filename, const MapType & map) const;
/**
@brief Checks if a file is valid with respect to the mapping file and the controlled vocabulary.
@param[in] filename File name of the file to be checked.
@param[out] errors Errors during the validation are returned in this output parameter.
@param[out] warnings Warnings during the validation are returned in this output parameter.
@exception Exception::FileNotFound is thrown if the file could not be opened
*/
bool isSemanticallyValid(const String & filename, StringList & errors, StringList & warnings);
private:
/// Options for loading / storing
PeakFileOptions options_;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/ProtXMLFile.h | .h | 4,266 | 119 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/METADATA/ProteinIdentification.h>
#include <OpenMS/METADATA/PeptideIdentification.h>
#include <OpenMS/FORMAT/HANDLERS/XMLHandler.h>
#include <OpenMS/FORMAT/XMLFile.h>
#include <vector>
namespace OpenMS
{
/**
@brief Used to load (storing not supported, yet) ProtXML files
This class is used to load (storing not supported, yet) documents that implement
the schema of ProtXML files.
A documented schema for this format comes with the TPP and can also be
found at https://github.com/OpenMS/OpenMS/tree/develop/share/OpenMS/SCHEMAS
OpenMS can only read parts of the protein_summary subtree to extract
protein-peptide associations. All other parts are silently ignored.
For protein groups, only the "group leader" (which is annotated with a
probability and coverage) receives these attributes. All indistinguishable
proteins of the same group only have an accession and score of -1.
@todo Document which metavalues of Protein/PeptideHit are filled when reading ProtXML (Chris)
@todo Writing of protXML is currently not supported
@ingroup FileIO
*/
class OPENMS_DLLAPI ProtXMLFile :
protected Internal::XMLHandler,
public Internal::XMLFile
{
public:
/// A protein group (set of indices into ProteinIdentification)
typedef ProteinIdentification::ProteinGroup ProteinGroup;
/// Constructor
ProtXMLFile();
/**
@brief Loads the identifications of an ProtXML file without identifier
The information is read in and the information is stored in the
corresponding variables
@exception Exception::FileNotFound is thrown if the file could not be opened
@exception Exception::ParseError is thrown if an error occurs during parsing
*/
void load(const String & filename, ProteinIdentification & protein_ids, PeptideIdentification & peptide_ids);
/**
@brief [not implemented yet!] Stores the data in an ProtXML file
[not implemented yet!]
The data is stored in the file 'filename'.
@exception Exception::UnableToCreateFile is thrown if the file could not be created
*/
void store(const String & filename, const ProteinIdentification & protein_ids, const PeptideIdentification & peptide_ids, const String & document_id = "");
protected:
/// reset members after reading/writing
void resetMembers_();
/// Docu in base class
void endElement(const XMLCh * const /*uri*/, const XMLCh * const /*local_name*/, const XMLCh * const qname) override;
/// Docu in base class
void startElement(const XMLCh * const /*uri*/, const XMLCh * const /*local_name*/, const XMLCh * const qname, const xercesc::Attributes & attributes) override;
/// Creates a new protein entry (if not already present) and appends it to the current group
void registerProtein_(const String & protein_name);
/**
@brief find modification name given a modified AA mass
Matches a mass of a modified AA to a mod in our modification db
For ambiguous mods, the first (arbitrary) is returned
If no mod is found an error is issued and the return string is empty
@note A duplicate of this function is also used in PepXMLFile
@param[in,out] mass Modified AA's mass
@param[in] origin AA one letter code
@param[in] modification_description [out] Name of the modification, e.g. 'Carboxymethyl (C)'
*/
void matchModification_(const double mass, const String & origin, String & modification_description);
/// @name members for loading data
//@{
/// Pointer to protein identification
ProteinIdentification * prot_id_;
/// Pointer to peptide identification
PeptideIdentification * pep_id_;
/// Temporary peptide hit
PeptideHit * pep_hit_;
/// protein group
ProteinGroup protein_group_;
//@}
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/ChromeleonFile.h | .h | 1,616 | 54 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/config.h> // OPENMS_DLLAPI
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/KERNEL/MSExperiment.h>
namespace OpenMS
{
/**
@brief Load Chromeleon HPLC text file and save it into a `MSExperiment`.
An example of the expected format:
> Raw Data:
> Time (min) Step (s) Value (mAU)
> 0.003333 0.200 -0.002496
> 0.006667 0.200 -0.017589
> ...
*/
class OPENMS_DLLAPI ChromeleonFile
{
public:
/// Constructor
ChromeleonFile() = default;
/// Destructor
virtual ~ChromeleonFile() = default;
/**
@brief Load the file's data and metadata, and save it into a `MSExperiment`.
@param[in] filename Path to the Chromeleon input file
@param[out] experiment The variable into which the extracted information will be saved
*/
void load(const String& filename, MSExperiment& experiment) const;
/**
@brief Remove commas from the string (used as thousands separators) and
parse its value
@param[in] number A string representing a floating-point number
@return The value converted to `double`
*/
double removeCommasAndParseDouble(String& number) const;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/FLASHDeconvFeatureFile.h | .h | 2,064 | 52 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/ANALYSIS/TOPDOWN/DeconvolvedSpectrum.h>
#include <OpenMS/ANALYSIS/TOPDOWN/FLASHHelperClasses.h>
#include <OpenMS/ANALYSIS/TOPDOWN/PeakGroup.h>
#include <OpenMS/config.h>
#include <iomanip>
#include <iostream>
namespace OpenMS
{
/**
@brief FLASHDeconv feature level output *.tsv, *.ms1ft (for Promex), *.feature (for TopPIC) file formats
@ingroup FileIO
**/
class OPENMS_DLLAPI FLASHDeconvFeatureFile
{
public:
/// write header line for regular file output
static void writeHeader(std::ostream& os, bool report_decoy = false);
/// write header line for topFD feature file
static void writeTopFDFeatureHeader(std::ostream& os, uint ms_level);
/// write the features in regular file output
static void writeFeatures(const std::vector<FLASHHelperClasses::MassFeature>& mass_features, const String& file_name, std::ostream& os, bool report_decoy = false);
/**
* @brief Find mass features and write features in TopFD format files.
* @param[in,out] deconvolved_spectra deconvolved spectra - feature indices are updated only for TopFD and TopPIC outputs
* @param[out] mass_features mass features to be written
* @param[in] scan_rt_map scan number to retention time map
* @param[in] file_name input spectrum file name
* @param[out] os output stream
* @param[in] ms_level ms level
*/
static void 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);
};
} // namespace OpenMS | Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/GNPSMGFFile.h | .h | 1,726 | 45 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Dorrestein Lab - University of California San Diego - https://dorresteinlab.ucsd.edu/$
// $Authors: Abinesh Sarvepalli and Louis Felix Nothias$
// $Contributors: Fabian Aicheler and Oliver Alka from Oliver Kohlbacher's group at Tubingen University$
#pragma once
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/KERNEL/BinnedSpectrum.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
namespace OpenMS
{
class OPENMS_DLLAPI GNPSMGFFile :
public DefaultParamHandler,
public ProgressLogger
{
public:
// default c'tor
GNPSMGFFile();
// see GNPSExport tool documentation
/**
* @brief Create file for GNPS molecular networking.
* @param[in] consensus_file_path path to consensusXML with spectrum references
* @param[in] mzml_file_paths path to mzML files referenced in consensusXML. Used to extract spectra as MGF.
* @param[in] out MGF file with MS2 peak data for molecular networking.
*/
void store(const String& consensus_file_path, const StringList& mzml_file_paths, const String& out) const;
private:
static constexpr double DEF_COSINE_SIMILARITY = 0.9;
static constexpr double DEF_MERGE_BIN_SIZE = static_cast<double>(BinnedSpectrum::DEFAULT_BIN_WIDTH_HIRES);
// static constexpr double DEF_PREC_MASS_TOL = 0.5;
// static constexpr bool DEF_PREC_MASS_TOL_ISPPM = false;
static constexpr int DEF_PEPT_CUTOFF = 5;
static constexpr int DEF_MSMAP_CACHE = 50;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/OMSFileLoad.h | .h | 9,130 | 206 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hendrik Weisser $
// $Authors: Hendrik Weisser, Chris Bielow $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/METADATA/ID/IdentificationData.h>
#include <OpenMS/FORMAT/OMSFileStore.h>
#include <QtCore/QJsonArray> // for JSON export
namespace SQLite
{
class Database;
} // namespace SQLite
namespace OpenMS
{
class FeatureMap;
class ConsensusMap;
namespace Internal
{
/*!
@brief Helper class for loading .oms files (SQLite format)
This class encapsulates the SQLite database stored in a .oms file and allows to load data from it.
*/
class OMSFileLoad: public ProgressLogger
{
public:
using Key = OMSFileStore::Key; ///< Type used for database keys
/*!
@brief Constructor
Opens the connection to the database file (in read-only mode).
@param[in] filename Path to the .oms input file (SQLite database)
@param[in] log_type Type of logging to use
@throw Exception::FailedAPICall Database cannot be opened
*/
OMSFileLoad(const String& filename, LogType log_type);
/*!
@brief Destructor
Closes the connection to the database file.
*/
~OMSFileLoad();
/// Load data from database and populate an IdentificationData object
void load(IdentificationData& id_data);
/// Load data from database and populate a FeatureMap object
void load(FeatureMap& features);
/// Load data from database and populate a ConsensusMap object
void load(ConsensusMap& consensus);
/// Export database contents in JSON format, write to stream
void exportToJSON(std::ostream& output);
private:
/// Does the @p query contain an empty SQL statement (signifying that it shouldn't be executed)?
static bool isEmpty_(const SQLite::Statement& query);
/// Generate a DataValue with information returned by an SQL query
static DataValue makeDataValue_(const SQLite::Statement& query);
// static CVTerm loadCVTerm_(int id);
/// Load information on score type from the database into IdentificationData
void loadScoreTypes_(IdentificationData& id_data);
/// Load information on input files from the database into IdentificationData
void loadInputFiles_(IdentificationData& id_data);
/// Load information on data processing software from the database into IdentificationData
void loadProcessingSoftwares_(IdentificationData& id_data);
/// Load information on sequence database search parameters from the database into IdentificationData
void loadDBSearchParams_(IdentificationData& id_data);
/// Load information on data processing steps from the database into IdentificationData
void loadProcessingSteps_(IdentificationData& id_data);
/// Load information on observations (e.g. spectra) from the database into IdentificationData
void loadObservations_(IdentificationData& id_data);
/// Load information on parent sequences (e.g. proteins) from the database into IdentificationData
void loadParentSequences_(IdentificationData& id_data);
/// Load information on parent group sets (e.g. protein groups) from the database into IdentificationData
void loadParentGroupSets_(IdentificationData& id_data);
/// Load information on identified compounds from the database into IdentificationData
void loadIdentifiedCompounds_(IdentificationData& id_data);
/// Load information on identified sequences (peptides or oligonucleotides) from the database into IdentificationData
void loadIdentifiedSequences_(IdentificationData& id_data);
/// Load information on adducts from the database into IdentificationData
void loadAdducts_(IdentificationData& id_data);
/// Load information on observation matches (e.g. PSMs) from the database into IdentificationData
void loadObservationMatches_(IdentificationData& id_data);
/// Helper function for loading meta data on feature/consensus maps from the database
template <class MapType> String loadMapMetaDataTemplate_(MapType& features);
/// Load feature map meta data from the database
void loadMapMetaData_(FeatureMap& features);
/// Load consensus map meta data from the database
void loadMapMetaData_(ConsensusMap& consensus);
/// Load information on data processing for feature/consensus maps from the database
void loadDataProcessing_(std::vector<DataProcessing>& data_processing);
/// Load information on features from the database into a feature map
void loadFeatures_(FeatureMap& features);
/// Generate a feature (incl. subordinate features) from data returned by SQL queries
Feature loadFeatureAndSubordinates_(SQLite::Statement& query_feat,
SQLite::Statement& query_meta,
SQLite::Statement& query_match,
SQLite::Statement& query_hull);
/// Load consensus map column headers from the database
void loadConsensusColumnHeaders_(ConsensusMap& consensus);
/// Load information on consensus features from the database into a consensus map
void loadConsensusFeatures_(ConsensusMap& consensus);
/// Generate a BaseFeature (parent class) from data returned by SQL queries
BaseFeature makeBaseFeature_(int id, SQLite::Statement& query_feat,
SQLite::Statement& query_meta,
SQLite::Statement& query_match);
/// Prepare SQL queries for loading (meta) data on BaseFeatures from the database
void prepareQueriesBaseFeature_(SQLite::Statement& query_meta,
SQLite::Statement& query_match);
/// Prepare SQL query for loading meta values associated with a particular class (stored in @p parent_table)
bool prepareQueryMetaInfo_(SQLite::Statement& query, const String& parent_table);
/// Store results from an SQL query on meta values in a MetaInfoInterface(-derived) object
void handleQueryMetaInfo_(SQLite::Statement& query, MetaInfoInterface& info,
Key parent_id);
/// Prepare SQL query for loading processing metadata associated with a particular class (stored in @p parent_table)
bool prepareQueryAppliedProcessingStep_(SQLite::Statement& query,
const String& parent_table);
/// Store results from an SQL query on processing metadata in a ScoredProcessingResult(-derived) object
void handleQueryAppliedProcessingStep_(
SQLite::Statement& query,
IdentificationDataInternal::ScoredProcessingResult& result,
Key parent_id);
/// Store results from an SQL query on parent matches
void handleQueryParentMatch_(
SQLite::Statement& query, IdentificationData::ParentMatches& parent_matches,
Key molecule_id);
/// Store results from an SQL query on peak annotations in an observation match
void handleQueryPeakAnnotation_(
SQLite::Statement& query, IdentificationData::ObservationMatch& match,
Key parent_id);
/// Export the contents of a database table to JSON
QJsonArray exportTableToJSON_(const QString& table, const QString& order_by);
/// The database connection (read)
std::unique_ptr<SQLite::Database> db_;
int version_number_; ///< schema version number
QString subquery_score_; ///< query for score types used in JSON export
// mappings between database keys and loaded data:
std::unordered_map<Key, IdentificationData::ScoreTypeRef> score_type_refs_;
std::unordered_map<Key, IdentificationData::InputFileRef> input_file_refs_;
std::unordered_map<Key, IdentificationData::ProcessingSoftwareRef> processing_software_refs_;
std::unordered_map<Key, IdentificationData::ProcessingStepRef> processing_step_refs_;
std::unordered_map<Key, IdentificationData::SearchParamRef> search_param_refs_;
std::unordered_map<Key, IdentificationData::ObservationRef> observation_refs_;
std::unordered_map<Key, IdentificationData::ParentSequenceRef> parent_sequence_refs_;
std::unordered_map<Key, IdentificationData::IdentifiedMolecule> identified_molecule_vars_;
std::unordered_map<Key, IdentificationData::ObservationMatchRef> observation_match_refs_;
std::unordered_map<Key, IdentificationData::AdductRef> adduct_refs_;
// mapping: table name -> ordering critera (for JSON export)
// @TODO: could use 'unordered_map' here, but would need to specify hash function for 'QString'
static std::map<QString, QString> export_order_by_;
};
}
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/ConsensusXMLFile.h | .h | 2,684 | 73 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/FORMAT/OPTIONS/PeakFileOptions.h>
#include <OpenMS/FORMAT/XMLFile.h>
#include <OpenMS/KERNEL/ConsensusMap.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
namespace OpenMS
{
class ConsensusMap;
/**
@brief This class provides Input functionality for ConsensusMaps and Output functionality for
alignments and quantitation.
This class can be used to load the content of a consensusXML file into a ConsensusMap
or to save the content of an ConsensusMap object into an XML file.
A documented schema for this format can be found at https://github.com/OpenMS/OpenMS/tree/develop/share/OpenMS/SCHEMAS
@todo Take care that unique ids are assigned properly by TOPP tools before calling ConsensusXMLFile::store(). There will be a message on OPENMS_LOG_INFO but we will make no attempt to fix the problem in this class. (all developers)
@ingroup FileIO
*/
class OPENMS_DLLAPI ConsensusXMLFile :
public Internal::XMLFile,
public ProgressLogger
{
public:
///Default constructor
ConsensusXMLFile();
///Destructor
~ConsensusXMLFile() override;
/**
@brief Loads a consensus map from file and calls updateRanges
@exception Exception::FileNotFound is thrown if the file could not be opened
@exception Exception::ParseError is thrown if an error occurs during parsing
@exception Exception::MissingInformation is thrown if source files are missing/duplicated or map-IDs are referencing non-existing maps
*/
void load(const String& filename, ConsensusMap& map);
/**
@brief Stores a consensus map to file
@exception Exception::UnableToCreateFile is thrown if the file name is not writable
@exception Exception::IllegalArgument is thrown if the consensus map is not valid
@exception Exception::MissingInformation is thrown if source files are missing/duplicated or map-IDs are referencing non-existing maps
*/
void store(const String& filename, const ConsensusMap& consensus_map);
/// Mutable access to the options for loading/storing
PeakFileOptions& getOptions();
/// Non-mutable access to the options for loading/storing
const PeakFileOptions& getOptions() const;
protected:
/// Options that can be set
PeakFileOptions options_;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/CsvFile.h | .h | 2,984 | 106 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/FORMAT/TextFile.h>
#include <OpenMS/DATASTRUCTURES/StringListUtils.h>
namespace OpenMS
{
/**
@brief This class handles csv files. Currently only loading is implemented. Does NOT support comment lines!
@note items are allowed to be enclosed by only one character e.g. "item" where " is enclosing character
@ingroup FileIO
*/
class OPENMS_DLLAPI CsvFile :
private TextFile
{
public:
///Default constructor
CsvFile();
/// destructor
~CsvFile() override;
/**
@brief Constructor with filename
@param[in] filename The input file name.
@param[in] is character which separates the items.
@param[in] ie Whether or not every item is enclosed.
@param[in] first_n Only the given number of lines are read, starting from the beginning of the file.
@exception Exception::FileNotFound is thrown if the file could not be opened.
*/
CsvFile(const String& filename, char is = ',', bool ie = false, Int first_n = -1);
/**
@brief Loads data from a text file.
@param[in] filename The input file name.
@param[in] is character which separates the items.
@param[in] ie Whether or not every item is enclosed.
@param[in] first_n Only the given number of lines are read, starting from the beginning of the file.
@exception Exception::FileNotFound is thrown if the file could not be opened.
*/
void load(const String& filename, char is = ',', bool ie = false, Int first_n = -1);
/**
@brief Stores the buffer's content into a file.
@param[in] filename The output filename.
*/
void store(const String& filename);
/**
@brief Add a row to the buffer.
@param[in] list StringList which will contain all items of the row to add
*/
void addRow(const StringList& list);
/**
@brief Clears the buffer
Clears TextFile::buffer_
*/
void clear();
/**
@brief writes all items from a row to list
@param[in] row the row which will be read
@param[out] list StringList which will contain all items of the row
@exception Exception::InvalidIterator is thrown if the row is not existing
@return returns false if the given row could not be separated into items
*/
bool getRow(Size row, StringList& list) const;
/**
@brief Returns the number of rows that were loaded from the file.
@return The number of loaded rows.
*/
std::vector<String>::size_type rowCount() const;
private:
char itemseperator_;
bool itemenclosed_;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/IndentedStream.h | .h | 4,286 | 110 | // 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/APPLICATIONS/ConsoleUtils.h>
#include <sstream>
namespace OpenMS
{
class Colorizer;
/**
@brief Class for writing data which spans multiple lines with an indentation for each line (all except the first).
Internally, ConsoleUtils is used to determine the width of the current console.
The stream that is written to can be any ostream (including stdout or stderr).
If a single item passed to IndentedStream::operator<< spans multiple indented lines (e.g. a large string),
at most @p max_lines will be retained (excess lines will be replaced by '...').
You can manually insert extra linebreaks by pushing '\n' into the stream (they can be part of a larger string).
The class supports coloring its output if the underlying @p stream is either std::cout or cerr by passing a Colorizer.
Upon destruction of IndentedStream, the underlying @p stream is flushed.
*/
class OPENMS_DLLAPI IndentedStream
{
public:
/**
@brief C'tor
@param[in,out] stream Underlying stream to write to (its lifetime must exceed the one of this IndentedStream)
@param[in] indentation Number of spaces in front of each new line written to @p stream
@param[in] max_lines Shorten excessive single items to at most this many number of lines (replacing excess with '...')
*/
IndentedStream(std::ostream& stream, const UInt indentation, const UInt max_lines);
/// D'tor flushes the stream
~IndentedStream();
/// Support normal usage of Colorizer (for coloring cout/cerr). The underlying stream will receive ANSI codes unless its a redirected(!) cout/cerr.
/// Warning: the ANSI codes are NOT considered to advance the cursor and will lead to broken formatting if
/// the underlying @p stream is NOT cout/cerr.
/// I.e. using an IndentedStream with an underlying stringstream in combination with a Colorizer will mess up the formatting.
IndentedStream& operator<<(Colorizer& colorizer);
/// Support calling our member functions within a stream
IndentedStream& operator<<(IndentedStream& self);
template<typename T>
IndentedStream& operator<<(const T& data)
{
// convert data to string
std::stringstream str_data;
str_data << data;
auto result = ConsoleUtils::breakStringList(str_data.str(), indentation_, max_lines_, current_column_pos_);
if (result.empty())
{
return *this;
}
if (result.size() == 1)
{ // no new linebreak. advance our position
current_column_pos_ += result.back().size();
}
else
{ // new line: this is our new position
current_column_pos_ = result.back().size();
}
// push result into stream
*stream_ << result[0];
for (size_t i = 1; i < result.size(); ++i)
{
*stream_ << '\n';
*stream_ << result[i];
}
return *this;
}
/// Function pointer to a function that takes an ostream, and returns it, e.g. std::endl
typedef std::ostream& (*StreamManipulator)(std::ostream&);
/// Overload for function pointers, e.g. std::endl
IndentedStream& operator<<(StreamManipulator manip);
/// Support new indentation, on the fly.
/// This will take effect when the next line break is encountered (either manual or automatic linebreak (at the right side of the console).
IndentedStream& indent(const UInt new_indent);
private:
std::ostream* stream_; ///< the underlying stream to print to
UInt indentation_; ///< number of spaces in prefix of each line
UInt max_lines_; ///< maximum number of lines a single item is split into before excess lines are replaced by '...'
UInt max_line_width_; ///< width of console/output
Size current_column_pos_ = 0; ///< length of last(=current) line
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/MzTabMFile.h | .h | 3,720 | 101 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/FORMAT/MzTabM.h>
namespace OpenMS
{
class String;
class SVOutStream;
/**
@brief File adapter for MzTab-M files
@ingroup FileIO
*/
class OPENMS_DLLAPI MzTabMFile
{
public:
/// Default Constructor
MzTabMFile();
/// Default Destructor
~MzTabMFile();
/// Store MzTabM file
void store(const String& filename, const MzTabM& mztab_m) const;
protected:
/**
@brief Generates the MzTabM MetaData Section
@param[in] map MzTabMMetaData
@param[out] sl Fill Stringlist with MztabM MetaData entries
*/
void generateMzTabMMetaDataSection_(const MzTabMMetaData& map, StringList& sl) const;
/**
@brief Generates the MzTabM Small Molecule Header
@param[in] meta MzTabMMetaData
@param[in] optional_columns Add optional columns
@param[out] n_columns Stores the number of columns in the header
@return StringList with SMH entries
*/
String generateMzTabMSmallMoleculeHeader_(const MzTabMMetaData& meta, const std::vector<String>& optional_columns, size_t& n_columns) const;
/**
@brief Generates the MzTabM Small Molecule Section
@param[in] row MzTabMSmallMoleculeSectionRow
@param[in] optional_columns Add optional columns
@param[out] n_columns Stores the number of columns per row
@return StringList with SML entries
*/
String generateMzTabMSmallMoleculeSectionRow_(const MzTabMSmallMoleculeSectionRow& row, const std::vector<String>& optional_columns, size_t& n_columns) const;
/**
@brief Generates the MzTabM Small Molecule Header
@param[in] meta MzTabMMetaData
@param[in] optional_columns Add optional columns
@param[out] n_columns Stores the number of columns in the header
@return StringList with SFH entries
*/
String generateMzTabMSmallMoleculeFeatureHeader_(const MzTabMMetaData& meta, const std::vector<String>& optional_columns, size_t& n_columns) const;
/**
@brief Generates the MzTabM Small Molecule Feature Section
@param[in] row MzTabMSmallMoleculeFeatureSectionRow
@param[in] optional_columns Add optional columns
@param[out] n_columns Stores the number of columns per row
@return StringList with SMF entries
*/
String generateMzTabMSmallMoleculeFeatureSectionRow_(const MzTabMSmallMoleculeFeatureSectionRow& row, const std::vector<String>& optional_columns, size_t& n_columns) const;
/**
@brief Generates the MzTabM Small Molecule Header
@param[in] meta MzTabMMetaData
@param[in] optional_columns Add optional columns
@param[out] n_columns Stores the number of columns in the header
@return StringList with SEH entries
*/
String generateMzTabMSmallMoleculeEvidenceHeader_(const MzTabMMetaData& meta, const std::vector<String>& optional_columns, size_t& n_columns) const;
/**
@brief Generates the MzTabM Small Molecule Evidence Section
@param[in] row MzTabMSmallMoleculeFeatureSectionRow
@param[in] optional_columns Add optional columns
@param[out] n_columns Stores the number of columns per row
@return StringList with SME entries
*/
String generateMzTabMSmallMoleculeEvidenceSectionRow_(const MzTabMSmallMoleculeEvidenceSectionRow& row, const std::vector<String>& optional_columns, size_t& n_columns) const;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/ParamXMLFile.h | .h | 1,955 | 63 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/FORMAT/XMLFile.h>
#include <OpenMS/DATASTRUCTURES/Param.h>
namespace OpenMS
{
/**
@brief The file pendant of the Param class used to load and store the param
datastructure as paramXML (i.e. INI files).
A documented schema for this format can be found at https://github.com/OpenMS/OpenMS/tree/develop/share/OpenMS/SCHEMAS
*/
class OPENMS_DLLAPI ParamXMLFile :
public Internal::XMLFile
{
public:
/// Constructor.
ParamXMLFile();
/**
@brief Write XML file.
@param[in] filename The filename where the param data structure should be stored.
@param[out] param The Param class that should be stored in the file.
@exception Exception::UnableToCreateFile is thrown if the file could not be created
*/
void store(const String& filename, const Param& param) const;
/**
@brief Write XML to output stream.
@param[out] os_ptr The stream where the param class should be written to.
@param[out] param The Param class that should be written to the stream.
*/
void writeXMLToStream(std::ostream* os_ptr, const Param& param) const;
/**
@brief Read XML file.
@param[out] filename The file from where to read the Param object.
@param[out] param The param object where the read data should be stored.
@exception Exception::FileNotFound is thrown if the file could not be found
@exception Exception::ParseError is thrown if an error occurs during parsing
*/
void load(const String& filename, Param& param);
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/MSPFile.h | .h | 2,774 | 91 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/METADATA/PeptideIdentification.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/METADATA/AnnotatedMSRun.h>
#include <vector>
namespace OpenMS
{
class AnnotatedMSRun;
/**
@brief File adapter for MSP files (NIST spectra library)
@htmlinclude OpenMS_MSPFile.parameters
@ingroup FileIO
*/
class OPENMS_DLLAPI MSPFile :
public DefaultParamHandler
{
public:
/** Constructors and destructors
*/
//@{
///Default constructor
MSPFile();
/// Copy constructor
MSPFile(const MSPFile & rhs);
///Destructor
~MSPFile() override;
//@}
/// assignment operator
MSPFile & operator=(const MSPFile & rhs);
/**
@brief Loads a map from a MSPFile file.
@param[in] exp PeakMap which contains the spectra after reading
@param[in] filename the filename of the experiment
@param[out] ids output parameter which contains the peptide identifications from the spectra annotations
@throw FileNotFound is thrown if the file could not be found
@throw ParseError is thrown if the given file could not be parsed
@throw ElementNotFound is thrown if a annotated modification cannot be found in ModificationsDB (PSI-MOD definitions)
*/
void load(const String & filename, PeptideIdentificationList & ids, PeakMap & exp);
/**
@brief Loads a map from a MSPFile file.
@param[in] filename the filename of the experiment
@param[in] annot_exp annotated experiment with spectra and ids
@throw FileNotFound is thrown if the file could not be found
@throw ParseError is thrown if the given file could not be parsed
@throw ElementNotFound is thrown if a annotated modification cannot be found in ModificationsDB (PSI-MOD definitions)
*/
void load(const String & filename, AnnotatedMSRun & annot_exp);
/**
@brief Stores a map in a MSPFile file.
@throw UnableToCreateFile is thrown if the given file could not be created
*/
void store(const String & filename, const AnnotatedMSRun & exp) const;
protected:
/// reads the header information and stores it as metainfo in the spectrum
void parseHeader_(const String & header, PeakSpectrum & spec);
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/PepNovoInfile.h | .h | 2,586 | 83 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/CHEMISTRY/ModificationDefinitionsSet.h>
#include <OpenMS/FORMAT/TextFile.h>
#include <map>
namespace OpenMS
{
/**
@brief PepNovo input file adapter.
Creates a PepNovo_PTMs.txt file for PepNovo search.
@ingroup FileIO
*/
class OPENMS_DLLAPI PepNovoInfile
{
public:
/// default constructor
PepNovoInfile();
/// copy constructor
PepNovoInfile(const PepNovoInfile & pepnovo_infile);
/// destructor
virtual ~PepNovoInfile();
/// assignment operator
PepNovoInfile & operator=(const PepNovoInfile & pepnovo_infile);
/// equality operator
bool operator==(const PepNovoInfile & pepnovo_infile) const;
/** stores the experiment data in a PepNovo input file that can be used as input for PepNovo shell execution
@param[out] filename the file which the input file is stored into
@throw Exception::UnableToCreateFile is thrown if the given file could not be created
*/
void store(const String & filename);
/** @brief generates the PepNovo Infile for given fixed and variable modifications *
*
* @param[in] fixed_mods StringList of fixed modifications unique identifiers
* @param[in] variable_mods StringList of variable modifications unique identifiers
*/
void setModifications(const StringList & fixed_mods, const StringList & variable_mods);
/** @brief return the modifications.
*
* the modification unique identifiers are mapped to the keys used
* in the PepNovo Infile (origin+rounded monoisotopic mass of modification ).
* (e.g. modification_key_map["K+16"]=="Oxidation (K)" )
*/
void getModifications(std::map<String, String> & modification_key_map) const;
private:
ModificationDefinitionsSet mods_;
std::map<String, String> mods_and_keys_;
TextFile ptm_file_;
/** retrieves the name of modification, and generates the corresponding line for the
PepNovo infile.
@param[in] modification the modification
@param[in] variable should be set to true if it variable
*/
String handlePTMs_(const String & modification, const bool variable);
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FORMAT/MsInspectFile.h | .h | 5,067 | 149 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/CONCEPT/Exception.h>
#include <OpenMS/KERNEL/Feature.h>
#include <OpenMS/FORMAT/TextFile.h>
#include <fstream>
#include <vector>
namespace OpenMS
{
/**
@brief File adapter for MsInspect files.
Lines with "#" are comments and are ignored.
The first non-comment line is the header and contains the column names:<br>
scan time mz accurateMZ mass intensity charge chargeStates kl background median peaks scanFirst scanLast scanCount totalIntensity sumSquaresDist description
Every subsequent line is a feature.
@ingroup FileIO
*/
class OPENMS_DLLAPI MsInspectFile
{
public:
/// Default constructor
MsInspectFile();
/// Destructor
virtual ~MsInspectFile();
/**
@brief Loads a MsInspect file into a featureXML.
The content of the file is stored in @p features.
@exception Exception::FileNotFound is thrown if the file could not be opened
@exception Exception::ParseError is thrown if an error occurs during parsing
*/
template <typename FeatureMapType>
void load(const String& filename, FeatureMapType& feature_map)
{
// load input
TextFile input(filename);
// reset map
FeatureMapType fmap;
feature_map = fmap;
bool first_line = true;
for (TextFile::ConstIterator it = input.begin(); it != input.end(); ++it)
{
String line = *it;
//ignore comment lines
if (line.empty() || line[0] == '#') continue;
//skip leader line
if (first_line)
{
first_line = false;
continue;
}
//split lines: scan\ttime\tmz\taccurateMZ\tmass\tintensity\tcharge\tchargeStates\tkl\tbackground\tmedian\tpeaks\tscanFirst\tscanLast\tscanCount\ttotalIntensity\tsumSquaresDist\tdescription
std::vector<String> parts;
line.split('\t', parts);
if (parts.size() < 18)
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "", String("Failed to convert line ") + String((it - input.begin()) + 1) + ". Not enough columns (expected 18 or more, got " + String(parts.size()) + ")");
}
//create feature
Feature f;
Size column_to_convert = 0;
try
{
column_to_convert = 1;
f.setRT(parts[1].toDouble());
column_to_convert = 2;
f.setMZ(parts[2].toDouble());
column_to_convert = 5;
f.setIntensity(parts[5].toDouble());
column_to_convert = 6;
f.setCharge(parts[6].toInt());
column_to_convert = 8;
f.setOverallQuality(parts[8].toDouble());
column_to_convert = 3;
f.setMetaValue("accurateMZ", parts[3]);
column_to_convert = 4;
f.setMetaValue("mass", parts[4].toDouble());
column_to_convert = 7;
f.setMetaValue("chargeStates", parts[7].toInt());
column_to_convert = 9;
f.setMetaValue("background", parts[9].toDouble());
column_to_convert = 10;
f.setMetaValue("median", parts[10].toDouble());
column_to_convert = 11;
f.setMetaValue("peaks", parts[11].toInt());
column_to_convert = 12;
f.setMetaValue("scanFirst", parts[12].toInt());
column_to_convert = 13;
f.setMetaValue("scanLast", parts[13].toInt());
column_to_convert = 14;
f.setMetaValue("scanCount", parts[14].toInt());
column_to_convert = 15;
f.setMetaValue("totalIntensity", parts[15].toDouble());
column_to_convert = 16;
f.setMetaValue("sumSquaresDist", parts[16].toDouble());
}
catch ( Exception::BaseException& )
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "", String("Failed to convert value in column ") + String(column_to_convert + 1) + " into a number (line '" + String((it - input.begin()) + 1) + ")");
}
f.setMetaValue("description", parts[17]);
feature_map.push_back(f);
}
}
/**
@brief Stores a featureXML as a MsInspect file.
NOT IMPLEMENTED
@exception Exception::UnableToCreateFile is thrown if the file could not be created
*/
template <typename SpectrumType>
void store(const String& filename, const SpectrumType& spectrum) const
{
std::cerr << "Store() for MsInspectFile not implemented. Filename was: " << filename << ", spec of size " << spectrum.size() << "\n";
throw Exception::NotImplemented(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
};
} // namespace OpenMS
| Unknown |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.