Gromacs  2023.2
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
Classes | Macros | Typedefs | Enumerations | Functions | Directories | Files
Low-Level Utilities (utility)
+ Collaboration diagram for Low-Level Utilities (utility):

Description

Provides low-level utilities for error handling and other tasks.

This module provides various low-level utilities for tasks such as error handling and string formatting, as well as helper classes and common custom containers to simplify implementation of other code. Contents of the module are discussed in more details under the different headings below. Some of the code in installed headers in the module is intended for use directly from code outside the GROMACS library, but a significant portion is exposed only because other public headers depend on it.

Since this module implements error handling, it should be at the lowest level: it should not depend on other modules. Any functionality needed by the error handling code should also be kept in this module.

Error handling

Exception classes used in the library are declared in the exceptions.h header file. Most GROMACS-specific exceptions derive from gmx::GromacsException.

This header also declares a GMX_THROW macro that should be used for throwing exceptions. GMX_THROW_WITH_ERRNO is also provided for reporting syscall errors, but its use should be mostly limited to within the library. This header also declares helper functions printFatalErrorMessage(), formatExceptionMessageToString(), and formatExceptionMessageToFile() for creating standard error messages. processExceptionAtExit() provides clean-up code before exiting the program after an exception. To help in cases where bottom-up conversion to C++ is appropriate, macro GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR is also provided to catch all exceptions at C++ to C boundary.

Header file gmxassert.h is also provided for assertions. It declares macros GMX_ASSERT and GMX_RELEASE_ASSERT that should be used for assertions.

Basic file handling and streams

The header textstream.h declares interfaces for simple text format streams. Headers filestream.h and stringstream.h provide implementations for these streams for reading/writing files and for writing to in-memory strings.

The header fileredirector.h provides interfaces for redirecting file input and/or output to alternative streams, for use in testing, as well as default implementations for these interfaces that just use the file system.

The header textwriter.h provides gmx::TextWriter for more formatting support when writing to a text stream. Similarly, textreader.h provides more formatting support when reading from a text stream.

The header path.h declares helpers for manipulating paths as strings and for managing directories and files. The fate of this header depends on what is decided in Issue #950.

Logging

The headers logger.h and loggerbuilder.h provide interfaces and classes for writing log files (or logging to other targets). See Logging for an overview.

Implementation helpers

The header basedefinitions.h contains common definitions and macros used throughout GROMACS. It includes gmx_bool for C code, some macros for compiler-specific attributes, and GMX_UNUSED_VALUE and GMX_IGNORE_RETURN_VALUE for handling warnings about unused values.

The header classhelpers.h declares GMX_DISALLOW_COPY_AND_ASSIGN, GMX_DISALLOW_COPY_MOVE_AND_ASSIGN, GMX_DISALLOW_ASSIGN, and GMX_DEFAULT_CONSTRUCTORS macros for class declarations.

The header flags.h implements a gmx::FlagsTemplate template for better type safety when using bit flag fields.

Other functionality

The header init.h declares gmx::init() and gmx::finalize() for initializing and deinitializing the GROMACS library.

The header arrayref.h implements a gmx::ArrayRef class for exposing a C array or part of a std::vector (basically, any continuous stretch of memory) throuh a std::vector-like interface.

The header stringutil.h declares various string utility routines.

The header strconvert.h declares string parsing routines.

The header gmxmpi.h abstracts away the mechanism of including either MPI or thread-MPI headers depending on compilation options. Similarly, gmxomp.h removes the need to use conditional compilation for code that needs to include omp.h for OpenMP functions.

The header message_string_collector.h declares a gmx::MessageStringCollector class for composing messages with context information.

The header sysinfo.h declares gmx_getpid() for getting the current process id.

The header programcontext.h declares a gmx::IProgramContext that is used to initialize and access information about the running program, such as the name and path of the executable. This information is used, e.g., by the error handling code in formatting standard error messages.

The header qsort_threadsafe.h provides a guaranteed threadsafe implementation for qsort().

Author
Teemu Murtola teemu.nosp@m..mur.nosp@m.tola@.nosp@m.gmai.nosp@m.l.com

Overloads for converting a value of a given type to a string.

Exceptions
std::bad_allocif out of memory.
static std::string gmx::toString (bool t)
 
static std::string gmx::toString (int t)
 
static std::string gmx::toString (int64_t t)
 
static std::string gmx::toString (float t)
 
static std::string gmx::toString (double t)
 
static std::string gmx::toString (std::string t)
 

Classes

class  gmx::Allocator< T, AllocationPolicy >
 Policy-based memory allocator. More...
 
class  gmx::Any
 Represents a dynamically typed value of an arbitrary type - deprecated. More...
 
class  gmx::BinaryInformationSettings
 Settings for printBinaryInformation(). More...
 
class  gmx::DataFileOptions
 Search parameters for DataFileFinder. More...
 
struct  gmx::DataFileInfo
 Information about a data file found by DataFileFinder::enumerateFiles(). More...
 
class  gmx::DataFileFinder
 Searches data files from a set of paths. More...
 
class  gmx::DirectoryEnumerator
 Lists files in a directory. More...
 
class  gmx::IFileInputRedirector
 Allows overriding file existence checks from code that supports it. More...
 
class  gmx::IFileOutputRedirector
 Allows capturing stdout and file output from code that supports it. More...
 
class  gmx::StandardInputStream
 Text input stream implementation for reading from stdin. More...
 
class  gmx::TextInputFile
 Text input stream implementation for reading from a file. More...
 
class  gmx::TextOutputFile
 Text output stream implementation for writing to a file. More...
 
class  gmx::FixedCapacityVector< typename, size_t >
 Vector that behaves likes std::vector but has fixed capacity. More...
 
class  gmx::KeyValueTreePath
 Identifies an entry in a key-value tree. More...
 
class  gmx::KeyValueTreeBuilder
 Root builder for creating trees that have an object at the root. More...
 
class  gmx::KeyValueTreeValueBuilder
 Builder for KeyValueTreeValue objects. More...
 
class  gmx::KeyValueTreeUniformArrayBuilder< T >
 Builder for KeyValueTreeArray objects where all elements are of type T. More...
 
class  gmx::KeyValueTreeObjectArrayBuilder
 Builder for KeyValueTreeArray objects where all elements are KeyValueTreeObject objects. More...
 
class  gmx::KeyValueTreeObjectBuilder
 Builder for KeyValueTreeObject objects. More...
 
class  gmx::IKeyValueTreeTransformRules
 Interface to declare rules for transforming key-value trees. More...
 
class  gmx::KeyValueTreeTransformRulesScoped
 Helper object returned from IKeyValueTreeTransformRules::scopedTransform(). More...
 
class  gmx::KeyValueTreeTransformRuleBuilder
 Provides methods to specify one transformation rule. More...
 
class  gmx::ILogTarget
 Target where log output can be written. More...
 
class  gmx::LogEntryWriter
 Helper class for creating log entries with GMX_LOG. More...
 
class  gmx::LogLevelHelper
 Represents a single logging level. More...
 
class  gmx::MDLogger
 Declares a logging interface. More...
 
class  gmx::LoggerBuilder
 Initializes loggers. More...
 
class  gmx::LoggerOwner
 Manages memory for a logger built with LoggerBuilder. More...
 
class  gmx::MessageStringCollector
 Helper class for collecting message strings, optionally with context. More...
 
class  gmx::MessageStringContext
 Convenience class for creating a message context. More...
 
class  gmx::StringCompare
 Compare object for std::string STL containers and algorithms that supports run-time decision on how to compare. More...
 
class  gmx::StringOutputStream
 Text output stream implementation for writing to an in-memory string. More...
 
class  gmx::TextReader
 Reads text from a TextInputStream. More...
 
class  gmx::TextInputStream
 Interface for reading text. More...
 
class  gmx::TextOutputStream
 Interface for writing text. More...
 
class  gmx::TextWriter
 Writes text into a TextOutputStream. More...
 
struct  gmx::no_delete< T >
 Deleter for std::shared_ptr that does nothing. More...
 
class  gmx::ArrayRef< typename >
 STL-like interface to a C array of T (or part of a std container of T). More...
 
class  gmx::ExceptionInfo< Tag, T >
 Stores additional context information for exceptions. More...
 
class  gmx::ExceptionInitializer
 Provides information for Gromacs exception constructors. More...
 
class  gmx::GromacsException
 Base class for all exception objects in Gromacs. More...
 
class  gmx::FileIOError
 Exception class for file I/O errors. More...
 
class  gmx::UserInputError
 Exception class for user input errors. More...
 
class  gmx::InvalidInputError
 Exception class for situations where user input cannot be parsed/understood. More...
 
class  gmx::InconsistentInputError
 Exception class for situations where user input is inconsistent. More...
 
class  gmx::ToleranceError
 Exception class when a specified tolerance cannot be achieved. More...
 
class  gmx::SimulationInstabilityError
 Exception class for simulation instabilities. More...
 
class  gmx::InternalError
 Exception class for internal errors. More...
 
class  gmx::APIError
 Exception class for incorrect use of an API. More...
 
class  gmx::RangeError
 Exception class for out-of-range values or indices. More...
 
class  gmx::NotImplementedError
 Exception class for use of an unimplemented feature. More...
 
class  gmx::ParallelConsistencyError
 Exception class for use when ensuring that MPI ranks to throw in a coordinated fashion. More...
 
class  gmx::ModularSimulatorError
 Exception class for modular simulator. More...
 
class  gmx::FlagsTemplate< FlagType >
 Template class for typesafe handling of combination of flags. More...
 
struct  gmx::InstallationPrefixInfo
 Provides information about installation prefix (see IProgramContext::installationPrefix()). More...
 
class  gmx::IProgramContext
 Provides context information about the program that is calling the library. More...
 
class  gmx::StringFormatter
 Function object that wraps a call to formatString() that expects a single conversion argument, for use with algorithms. More...
 
class  gmx::IdentityFormatter
 Function object to implement the same interface as StringFormatter to use with strings that should not be formatted further. More...
 
class  gmx::EqualCaseInsensitive
 Function object for comparisons with equalCaseInsensitive. More...
 
class  gmx::TextLineWrapperSettings
 Stores settings for line wrapping. More...
 
class  gmx::TextLineWrapper
 Wraps lines to a predefined length. More...
 

Macros

#define GMX_LOG(logger)
 Helper to log information using gmx::MDLogger. More...
 
#define gmx_used_in_debug
 Attribute to explicitly indicate that a parameter or locally scoped variable is used just in debug mode.
 
#define GMX_UNUSED_VALUE(value)   (void)value
 Macro to explicitly ignore an unused value. More...
 
#define GMX_IGNORE_RETURN_VALUE(call)   ::gmx::internal::ignoreValueHelper(call)
 Macro to explicitly ignore a return value of a call. More...
 
#define GMX_DISALLOW_COPY_AND_ASSIGN(ClassName)
 Macro to declare a class non-copyable and non-assignable. More...
 
#define GMX_DISALLOW_COPY_MOVE_AND_ASSIGN(ClassName)
 Macro to declare a class non-copyable, non-movable, non-copy-assignable and non-move-assignable. More...
 
#define GMX_DISALLOW_ASSIGN(ClassName)   ClassName& operator=(const ClassName&) = delete
 Macro to declare a class non-assignable. More...
 
#define GMX_DEFAULT_CONSTRUCTORS(ClassName)
 Macro to declare default constructors. More...
 
#define GMX_CURRENT_FUNCTION   "(unknown)"
 Expands to a string that provides the name of the current function.
 
#define GMX_THROW(e)   throw(e) << gmx::ExceptionInfoLocation(gmx::ThrowLocation(GMX_CURRENT_FUNCTION, __FILE__, __LINE__))
 Macro for throwing an exception. More...
 
#define GMX_THROW_WITH_ERRNO(e, syscall, err)
 Macro for throwing an exception based on errno. More...
 
#define GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR   catch (const std::exception& ex) { ::gmx::processExceptionAsFatalError(ex); }
 Macro for catching exceptions at C++ -> C boundary. More...
 
#define GMX_RELEASE_ASSERT(condition, msg)
 Macro for asserts that should also be present in the release version. More...
 
#define GMX_ASSERT(condition, msg)   GMX_RELEASE_ASSERT(condition, msg)
 Macro for debug asserts. More...
 
#define gmx_format(archetype, string_index, first_to_check)
 GCC like function format attribute. More...
 
#define gmx_fmtstr
 MSVC like function format attribute. More...
 

Typedefs

typedef ExceptionInfo< struct
ExceptionInfoErrno_, int > 
gmx::ExceptionInfoErrno
 Stores errno value that triggered the exception.
 
typedef ExceptionInfo< struct
ExceptionInfoApiFunc_, const
char * > 
gmx::ExceptionInfoApiFunction
 Stores the function name that returned the errno in ExceptionInfoErrno.
 
typedef ExceptionInfo< struct
ExceptionInfoLocation_,
ThrowLocation > 
gmx::ExceptionInfoLocation
 Stores the location where the exception was thrown.
 

Enumerations

enum  gmx::ErrorCode {
  gmx::eeOK, gmx::eeOutOfMemory, gmx::eeFileNotFound, gmx::eeFileIO,
  gmx::eeInvalidInput, gmx::eeInconsistentInput, gmx::eeTolerance, gmx::eeInstability,
  gmx::eeNotImplemented, gmx::eeInvalidValue, gmx::eeInvalidCall, gmx::eeInternalError,
  gmx::eeAPIError, gmx::eeRange, gmx::eeParallelConsistency, gmx::eeModularSimulator,
  gmx::eeUnknownError
}
 Possible error return codes from Gromacs functions. More...
 
enum  gmx::StringCompareType { gmx::StringCompareType::Exact, gmx::StringCompareType::CaseInsensitive, gmx::StringCompareType::CaseAndDashInsensitive }
 Specifies how strings should be compared in various contexts. More...
 

Functions

const char * gmx::getErrorCodeString (int errorcode)
 Returns a short string description of an error code. More...
 
std::string gmx::simpleValueToString (const Any &value)
 Converts a Any value to a string. More...
 
template<typename T , int N>
constexpr int asize (T(&)[N])
 Calculates the number of elements in a static array at compile time.
 
IFileInputRedirector & gmx::defaultFileInputRedirector ()
 Returns default implementation for IFileInputRedirector. More...
 
IFileOutputRedirector & gmx::defaultFileOutputRedirector ()
 Returns default implementation for IFileOutputRedirector. More...
 
int gmx_omp_get_max_threads ()
 Returns an integer equal to or greater than the number of threads that would be available if a parallel region without num_threads were defined at that point in the code. More...
 
int gmx_omp_get_num_procs ()
 Returns the number of processors available when the function is called. More...
 
int gmx_omp_get_thread_num ()
 Returns the thread number of the thread executing within its thread team. More...
 
void gmx_omp_set_num_threads (int num_threads)
 Sets the number of threads in subsequent parallel regions, unless overridden by a num_threads clause. More...
 
bool gmx_omp_check_thread_affinity (char **message)
 Check for externally set thread affinity to avoid conflicts with GROMACS internal setting. More...
 
IKeyValueTreeErrorHandler * gmx::defaultKeyValueTreeErrorHandler ()
 Returns a default IKeyValueTreeErrorHandler that throws on first exception.
 
void gmx::init (int *argc, char ***argv)
 Initializes the GROMACS library. More...
 
void gmx::finalize ()
 Deinitializes the GROMACS library. More...
 
void gmx::dumpKeyValueTree (TextWriter *writer, const KeyValueTreeObject &tree)
 Writes a human-readable representation of the tree with given writer. More...
 
void gmx::compareKeyValueTrees (TextWriter *writer, const KeyValueTreeObject &tree1, const KeyValueTreeObject &tree2, real ftol, real abstol)
 Compares two KeyValueTrees and prints any differences.
 
void gmx::serializeKeyValueTree (const KeyValueTreeObject &root, ISerializer *serializer)
 Serializes a KeyValueTreeObject with given serializer.
 
KeyValueTreeObject gmx::deserializeKeyValueTree (ISerializer *serializer)
 Deserializes a KeyValueTreeObject from a given serializer.
 
bool gmx::boolFromString (const char *str)
 Parses a boolean from a string. More...
 
int gmx::intFromString (const char *str)
 Parses an integer from a string. More...
 
int64_t gmx::int64FromString (const char *str)
 Parses a 64-bit integer from a string. More...
 
float gmx::floatFromString (const char *str)
 Parses a float value from a string. More...
 
double gmx::doubleFromString (const char *str)
 Parses a double value from a string. More...
 
template<typename T >
static T gmx::fromString (const char *str)
 Parses a value from a string to a given type. More...
 
template<typename T >
static T gmx::fromString (const std::string &str)
 Parses a value from a string to a given type. More...
 
template<typename T >
static T gmx::fromStdString (const std::string &str)
 Parses a value from a string to a given type. More...
 
template<>
bool gmx::fromString< bool > (const char *str)
 Implementation for boolean values.
 
template<>
int gmx::fromString< int > (const char *str)
 Implementation for integer values.
 
template<>
int64_t gmx::fromString< int64_t > (const char *str)
 Implementation for 64-bit integer values.
 
template<>
float gmx::fromString< float > (const char *str)
 Implementation for float values.
 
template<>
double gmx::fromString< double > (const char *str)
 Implementation for double values.
 
static const char * gmx::boolToString (bool value)
 Converts a boolean to a "true"/"false" string. More...
 
static std::string gmx::intToString (int t)
 Returns a string containing the value of t. More...
 
static std::string gmx::int64ToString (int64_t t)
 Returns a string containing the value of t. More...
 
static std::string gmx::doubleToString (double t)
 Returns a string containing the value of t. More...
 
int gmx_gethostname (char *buf, size_t len)
 Gets the hostname as given by gethostname(), if available. More...
 
int gmx_getpid ()
 Returns the process ID of the current process. More...
 
int gmx_getuid ()
 Returns the current user ID, or -1 if not available. More...
 
int gmx_getusername (char *buf, size_t len)
 Gets the current user name, if available. More...
 
std::string gmx_ctime_r (const time_t *clock)
 Portable version of ctime_r. More...
 
std::string gmx_format_current_time ()
 Gets the current time as a string. More...
 
int gmx_set_nice (int level)
 Wrapper for nice(). More...
 
template<typename T >
void gmx::swap (ArrayRef< T > &a, ArrayRef< T > &b)
 Simple swap method for ArrayRef objects. More...
 
template<typename T >
std::vector< T > gmx::copyOf (const ArrayRef< const T > &arrayRef)
 Return a vector that is a copy of an ArrayRef. More...
 
const char * gmx_version ()
 Version string, containing the version, date, and abbreviated hash. More...
 
const char * gmx_version_git_full_hash ()
 Full git hash of the latest commit. More...
 
const char * gmx_version_git_central_base_hash ()
 Full git hash of the latest commit in a central GROMACS repository. More...
 
void gmx_is_double_precision ()
 Defined if libgromacs has been compiled in double precision. More...
 
void gmx_is_single_precision ()
 Defined if libgromacs has been compiled in single/mixed precision. More...
 
template<class Exception , class Tag , class T >
std::enable_if_t
< std::is_base_of
< GromacsException, Exception >
::value, Exception > 
gmx::operator<< (Exception ex, const ExceptionInfo< Tag, T > &item)
 Associates extra information with an exception. More...
 
void gmx::printFatalErrorMessage (FILE *fp, const std::exception &ex)
 Formats a standard fatal error message for reporting an exception. More...
 
std::string gmx::formatExceptionMessageToString (const std::exception &ex)
 Formats an error message for reporting an exception. More...
 
void gmx::formatExceptionMessageToFile (FILE *fp, const std::exception &ex)
 Formats an error message for reporting an exception. More...
 
void gmx::formatExceptionMessageToWriter (TextWriter *writer, const std::exception &ex)
 Formats an error message for reporting an exception. More...
 
int gmx::processExceptionAtExit (const std::exception &ex)
 Handles an exception that is causing the program to terminate. More...
 
void gmx::processExceptionAsFatalError (const std::exception &ex)
 Helper function for terminating the program on an exception. More...
 
const DataFileFinder & gmx::getLibraryFileFinder ()
 Gets a finder for locating data files from share/top/. More...
 
const IProgramContext & gmx::getProgramContext ()
 Returns the global IProgramContext instance. More...
 
void gmx::setProgramContext (const IProgramContext *context)
 Sets the global IProgramContext instance. More...
 
static bool gmx::isNullOrEmpty (const char *str)
 Tests whether a string is null or empty. More...
 
static bool gmx::startsWith (const std::string &str, const std::string &prefix)
 Tests whether a string starts with another string. More...
 
static bool gmx::startsWith (const char *str, const char *prefix)
 Tests whether a string starts with another string. More...
 
bool gmx::endsWith (const char *str, const char *suffix)
 Tests whether a string ends with another string. More...
 
static bool gmx::endsWith (const std::string &str, const char *suffix)
 Tests whether a string ends with another string. More...
 
static bool gmx::contains (const std::string &str, const char *substr)
 Tests whether a string contains another as a substring. More...
 
static bool gmx::contains (const std::string &str, const std::string &substr)
 Tests whether a string contains another as a substring. More...
 
std::size_t gmx::countWords (const char *s)
 Returns number of space-separated words in zero-terminated char ptr. More...
 
std::size_t gmx::countWords (const std::string &str)
 Returns the number of space-separated words in a string object. More...
 
static bool gmx::endsWith (const std::string &str, const std::string &suffix)
 Tests whether a string ends with another string. More...
 
std::string gmx::stripSuffixIfPresent (const std::string &str, const char *suffix)
 Removes a suffix from a string. More...
 
std::string gmx::stripString (const std::string &str)
 Removes leading and trailing whitespace from a string. More...
 
std::string gmx::formatString (const char *fmt,...)
 Formats a string (snprintf() wrapper). More...
 
std::string gmx::formatStringV (const char *fmt, va_list ap)
 Formats a string (vsnprintf() wrapper). More...
 
template<typename InputIterator , typename FormatterType >
std::string gmx::formatAndJoin (InputIterator begin, InputIterator end, const char *separator, const FormatterType &formatter)
 Formats all the range as strings, and then joins them with a separator in between. More...
 
template<typename ContainerType , typename FormatterType >
std::string gmx::formatAndJoin (const ContainerType &container, const char *separator, const FormatterType &formatter)
 Formats all elements of the container as strings, and then joins them with a separator in between. More...
 
template<typename InputIterator >
std::string gmx::joinStrings (InputIterator begin, InputIterator end, const char *separator)
 Joins strings from a range with a separator in between. More...
 
template<typename ContainerType >
std::string gmx::joinStrings (const ContainerType &container, const char *separator)
 Joins strings from a container with a separator in between. More...
 
template<size_t count>
std::string gmx::joinStrings (const char *const (&array)[count], const char *separator)
 Joins strings from an array with a separator in between. More...
 
std::vector< std::string > gmx::splitString (const std::string &str)
 Splits a string to whitespace separated tokens. More...
 
std::vector< std::string > gmx::splitDelimitedString (const std::string &str, char delim)
 Splits a string to tokens separated by a given delimiter. More...
 
std::vector< std::string > gmx::splitAndTrimDelimitedString (const std::string &str, char delim)
 Splits str to tokens separated by delimiter delim. Removes leading and trailing whitespace from those strings with std::isspace. More...
 
std::string gmx::replaceAll (const std::string &input, const char *from, const char *to)
 Replace all occurrences of a string with another string. More...
 
std::string gmx::replaceAll (const std::string &input, const std::string &from, const std::string &to)
 Replace all occurrences of a string with another string. More...
 
std::string gmx::replaceAllWords (const std::string &input, const char *from, const char *to)
 Replace whole words with others. More...
 
std::string gmx::replaceAllWords (const std::string &input, const std::string &from, const std::string &to)
 Replace whole words with others. More...
 
bool gmx::equalCaseInsensitive (const std::string &source, const std::string &target)
 Return whether two strings are equal, ignoring case. More...
 
bool gmx::equalCaseInsensitive (const std::string &source, const std::string &target, size_t maxLengthOfComparison)
 Checks if at most maxLengthOfComparison characters of two strings match case insensitive. More...
 
std::string gmx::toUpperCase (const std::string &text)
 Makes the string uppercase. More...
 
std::string gmx::toLowerCase (const std::string &text)
 Makes the string lowercase. More...
 

Directories

directory utility
 Low-Level Utilities (utility)
 
directory tests
 Unit tests for Low-Level Utilities (utility).
 

Files

file  errorcodes.h
 Declares error codes and related functions for fatal error handling.
 
file  alignedallocator.h
 Declares allocation policy classes and allocators that are used to make library containers compatible with alignment requirements of particular hardware, e.g. memory operations for SIMD or accelerators.
 
file  allocator.h
 Declares gmx::Allocator template whose allocation functionality is configured both by type of object allocated and a policy class that configures the necessary matching malloc and free operation.
 
file  any.h
 Declares gmx::Any.
 
file  arraysize.h
 Provides asize() function for calculating the static size of an array at compile time.
 
file  basenetwork.h
 Utility functions for basic MPI and network functionality.
 
file  binaryinformation.h
 Helper functionality for information about the currently running binary.
 
file  bitmask.h
 Declares gmx_bitmask_t and associated functions.
 
file  compare.h
 Utilities for comparing data structures (for gmx check).
 
file  coolstuff.h
 Functionality for printing cool strings.
 
file  cstringutil.h
 Generic C string handling functions.
 
file  datafilefinder.h
 Declares gmx::DataFileFinder and related classes.
 
file  defaultinitializationallocator.h
 Declares an allocator that can use default initialization instead of values initialization. This is useful for improving performance of resize() in standard vectors for buffers in performance critical code.
 
file  directoryenumerator.h
 Declares gmx::DirectoryEnumerator.
 
file  fatalerror.h
 Declares fatal error handling and debugging routines for C code.
 
file  fileredirector.h
 Declares gmx::IFileOutputRedirector.
 
file  filestream.h
 Declares implementations for textstream.h interfaces for file input/output.
 
file  fixedcapacityvector.h
 Declares gmx::FixedCapacityVector.
 
file  gmxmpi.h
 Wraps mpi.h usage in Gromacs.
 
file  gmxomp.h
 Declares OpenMP wrappers to avoid conditional compilation.
 
file  ikeyvaluetreeerror.h
 Declares an error handling interface for key-value tree operations.
 
file  init.h
 Declares functions for initializing the GROMACS library.
 
file  inmemoryserializer.h
 Declares gmx::ISerializer implementation for in-memory serialization.
 
file  int64_to_int.h
 Low-level utility for converting 64 bit int to int (the size of which is hardware dependent), printing a warning if an overflow will occur.
 
file  iserializer.h
 Declares a generic serialization interface that supports both directions.
 
file  keyvaluetree.h
 Declares a data structure for JSON-like structured key-value mapping.
 
file  keyvaluetreebuilder.h
 Declares classes for building the data structures in keyvaluetree.h.
 
file  keyvaluetreemdpwriter.h
 Declares a function to write a flat key-value tree to look like old-style mdp output.
 
file  keyvaluetreeserializer.h
 Declares serialization routines for KeyValueTree objects.
 
file  keyvaluetreetransform.h
 Declares utilities for transforming key-value trees.
 
file  logger.h
 Declares functionality for logging.
 
file  loggerbuilder.h
 Declares functionality for initializing logging.
 
file  message_string_collector.h
 Declares gmx::MessageStringCollector.
 
file  niceheader.h
 Declares function for printing a nice header for text output files.
 
file  path.h
 Declares functions for OS-independent path handling.
 
file  physicalnodecommunicator.h
 Declares functionality for communicators across physical nodes.
 
file  snprintf.h
 Provide snprintf symbol on all OS (for internal Gromacs use)
 
file  strconvert.h
 Declares common utility functions for conversions to and from strings.
 
file  strdb.h
 Declares C functions for reading files with a list of strings.
 
file  stringcompare.h
 Declares utility functionst for string comparison.
 
file  stringstream.h
 Declares implementations for textstream.h interfaces for input/output to in-memory strings.
 
file  stringtoenumvalueconverter.h
 Defines helper function object for class enumerations.
 
file  sysinfo.h
 Declares functions that wrap platform-specific calls for obtaining information about the operating environment and the current process.
 
file  template_mp.h
 Declares utilities for template metaprogramming.
 
file  textreader.h
 Declares gmx::TextReader.
 
file  textstream.h
 Declares interfaces for simple input/output streams.
 
file  textwriter.h
 Declares gmx::TextWriter.
 
file  txtdump.h
 Declares helper functions for dumping basic data structures as text.
 
file  typetraits.h
 Declares type traits.
 
file  nodelete.h
 Declares no_delete deleter for std::shared_ptr.
 
file  alignedallocator_impl.h
 Tests for allocators that offer a minimum alignment.
 
file  utility.h
 Public API convenience header for low-level utilities.
 
file  arrayref.h
 Declares gmx::ArrayRef.
 
file  basedefinitions.h
 Basic types and macros used throughout GROMACS.
 
file  baseversion.h
 Declares functions to get basic version information.
 
file  classhelpers.h
 Declares common utility classes and macros.
 
file  current_function.h
 Declares GMX_CURRENT_FUNCTION for getting the current function name.
 
file  enumerationhelpers.h
 Defines helper types for class enumerations.
 
file  exceptions.h
 Declares common exception classes and macros for fatal error handling.
 
file  fileptr.h
 Declares guard pointer for RAII-style handling of cstdio FILE pointers.
 
file  flags.h
 Declares gmx::FlagsTemplate.
 
file  futil.h
 Low-level wrappers for OS-specific file handling with some GROMACS customizations.
 
file  gmxassert.h
 Defines assert macros customized for Gromacs.
 
file  listoflists.h
 Declares gmx::ListOfLists.
 
file  pleasecite.h
 Declares please_cite() for printing out literature references. Declares writeSourceDoi for printing of source code DOI.
 
file  programcontext.h
 Declares gmx::IProgramContext and related methods.
 
file  range.h
 Declares gmx::Range.
 
file  real.h
 Declares real and related constants.
 
file  smalloc.h
 C-style memory allocation routines for GROMACS.
 
file  stringutil.h
 Declares common string utility and formatting routines.
 
file  unique_cptr.h
 Declares gmx::unique_cptr and gmx::sfree_guard.
 

Macro Definition Documentation

#define GMX_ASSERT (   condition,
  msg 
)    GMX_RELEASE_ASSERT(condition, msg)

Macro for debug asserts.

If NDEBUG is defined, this macro expands to nothing. If it is not defined, it will work exactly like GMX_RELEASE_ASSERT.

See Also
GMX_RELEASE_ASSERT
#define GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR   catch (const std::exception& ex) { ::gmx::processExceptionAsFatalError(ex); }

Macro for catching exceptions at C++ -> C boundary.

This macro is intended for uniform handling of exceptions when C++ code is called from C code within Gromacs. Since most existing code is written using the assumption that fatal errors terminate the program, this macro implements this behavior for exceptions. It should only be used in cases where the error cannot be propagated upwards using return values or such.

Having this as a macro instead of having the same code in each place makes it easy to 1) find all such locations in the code, and 2) change the exact behavior if needed.

Usage:

#define GMX_DEFAULT_CONSTRUCTORS (   ClassName)

Macro to declare default constructors.

Intended for copyable interfaces or bases classes which require to create custom destructor (e.g. protected or virtual) but need the default constructors.

#define GMX_DISALLOW_ASSIGN (   ClassName)    ClassName& operator=(const ClassName&) = delete

Macro to declare a class non-assignable.

For consistency, should appear last in the class declaration.

#define GMX_DISALLOW_COPY_AND_ASSIGN (   ClassName)

Macro to declare a class non-copyable and non-assignable.

For consistency, should appear last in the class declaration.

#define GMX_DISALLOW_COPY_MOVE_AND_ASSIGN (   ClassName)

Macro to declare a class non-copyable, non-movable, non-copy-assignable and non-move-assignable.

For consistency, should appear last in the class declaration.

#define gmx_fmtstr

MSVC like function format attribute.

Does type checking for printf like format strings in MSVC style. Attribute has to be placed before format string.

#define gmx_format (   archetype,
  string_index,
  first_to_check 
)

GCC like function format attribute.

The format attribute specifies that a function takes printf, scanf, ... style arguments that should be type-checked against a format string. The attribute has to be placed after the function. This attribute is only valid for function declarations and not function definitions (GCC limitation). For member functions the implicit this pointer is included in the argument count.

#define GMX_IGNORE_RETURN_VALUE (   call)    ::gmx::internal::ignoreValueHelper(call)

Macro to explicitly ignore a return value of a call.

Mainly meant for ignoring values of functions declared with __attribute__((warn_unused_return)). Makes it easy to find those places if they need to be fixed, and document the intent in cases where the return value really can be ignored. It also makes it easy to adapt the approach so that they don't produce warnings. A cast to void doesn't remove the warning in gcc, while adding a dummy variable can cause warnings about an unused variable.

#define GMX_LOG (   logger)
Value:
if (::gmx::LogWriteHelper helper = ::gmx::LogWriteHelper(logger)) {} \
else \
Helper class for creating log entries with GMX_LOG.
Definition: logger.h:80

Helper to log information using gmx::MDLogger.

Parameters
loggerLogLevelHelper instance to use for logging.

Used as

GMX_LOG(logger.warning).appendText(...);

and ensures that the code to format the output is only executed when the output goes somewhere.

See LogEntryWriter for functions that can be used with the macro (such as the appendText() in the example).

#define GMX_RELEASE_ASSERT (   condition,
  msg 
)
Value:
((void)((condition) ? (void)0 : [&]() { \
::gmx::internal::assertHandler(#condition, msg, GMX_CURRENT_FUNCTION, __FILE__, __LINE__); \
}()))
#define GMX_CURRENT_FUNCTION
Expands to a string that provides the name of the current function.

Macro for asserts that should also be present in the release version.

Regardless of NDEBUG, this macro checks condition, and if it is not true, it calls the assert handler.

Although this macro currently calls abort() if the assertion fails, it should only be used in a context where it is safe to throw an exception to keep the option open.

#define GMX_THROW (   e)    throw(e) << gmx::ExceptionInfoLocation(gmx::ThrowLocation(GMX_CURRENT_FUNCTION, __FILE__, __LINE__))

Macro for throwing an exception.

Parameters
[in]eException object to throw.

Using this macro instead of throw directly makes it possible to uniformly attach information into the exception objects. e should evaluate to an instance of an object derived from GromacsException.

Basic usage:

if (value < 0)
{
GMX_THROW(InconsistentUserInput("Negative values not allowed for value"));
}
#define GMX_THROW_WITH_ERRNO (   e,
  syscall,
  err 
)
Value:
do \
{ \
int stored_errno_ = (err); \
GMX_THROW((e) << gmx::ExceptionInfoErrno(stored_errno_) \
} while (0)
#define GMX_THROW(e)
Macro for throwing an exception.
Definition: exceptions.h:607
Stores additional context information for exceptions.
Definition: exceptions.h:120

Macro for throwing an exception based on errno.

Parameters
[in]eException object to throw.
[in]syscallName of the syscall that returned the error.
[in]errerrno value returned by the syscall.

This macro provides a convenience interface for throwing an exception to report an error based on a errno value. In addition to adding the necessary information to the exception object, the macro also ensures that errno is evaluated before, e.g., the constructor of e may call other functions that could overwrite the errno value. e should evaluate to an instance of an object derived from GromacsException.

Typical usage (note that gmx::File wraps this particular case):

FILE *fp = fopen("filename.txt", "r");
if (fp == NULL)
{
GMX_THROW(FileIOError("Could not open file"), "fopen", errno);
}
#define GMX_UNUSED_VALUE (   value)    (void)value

Macro to explicitly ignore an unused value.

Todo:
Deprecated - use gmx_unused

Enumeration Type Documentation

Possible error return codes from Gromacs functions.

Enumerator
eeOK 

Zero for successful return.

eeOutOfMemory 

Not enough memory to complete operation.

eeFileNotFound 

Provided file could not be opened.

eeFileIO 

System I/O error.

eeInvalidInput 

Invalid user input (could not be understood).

eeInconsistentInput 

Invalid user input (conflicting or unsupported settings).

eeTolerance 

Requested tolerance cannot be achieved.

eeInstability 

Simulation instability detected.

eeNotImplemented 

Requested feature not yet implemented.

eeInvalidValue 

Input value violates API specification.

eeInvalidCall 

Invalid routine called or wrong calling sequence detected.

eeInternalError 

Internal consistency check failed.

eeAPIError 

API specification was violated.

eeRange 

Range consistency check failed.

eeParallelConsistency 

Parallel consistency check failed.

eeModularSimulator 

Error specific for modular simulator.

eeUnknownError 

Unknown error detected.

Specifies how strings should be compared in various contexts.

Enumerator
Exact 

Only exact matches are accepted.

CaseInsensitive 

Case-insensitive comparison.

CaseAndDashInsensitive 

Case-insensitive comparison that also ignores '-' and '_'.

Function Documentation

bool gmx::boolFromString ( const char *  str)

Parses a boolean from a string.

Exceptions
InvalidInputErrorif str is not recognized as a boolean value.
static const char* gmx::boolToString ( bool  value)
inlinestatic

Converts a boolean to a "true"/"false" string.

Does not throw.

static bool gmx::contains ( const std::string &  str,
const char *  substr 
)
inlinestatic

Tests whether a string contains another as a substring.

Parameters
[in]strString to process.
[in]substrSubstring to find.
Returns
true if str contains substr.

Does not throw.

static bool gmx::contains ( const std::string &  str,
const std::string &  substr 
)
inlinestatic

Tests whether a string contains another as a substring.

Parameters
[in]strString to process.
[in]substrSubstring to find.
Returns
true if str contains substr.

Does not throw.

template<typename T >
std::vector<T> gmx::copyOf ( const ArrayRef< const T > &  arrayRef)

Return a vector that is a copy of an ArrayRef.

This makes it convenient, clear, and performant (the compiler will either do RVO to elide the temporary, or invoke the move constructor taking the unnamed temporary) to write a declaration like

auto v = copyOf(arrayRef);

std::size_t gmx::countWords ( const char *  s)

Returns number of space-separated words in zero-terminated char ptr.

Parameters
sCharacter pointer to zero-terminated, which will not be changed.
Returns
number of words in string.
Note
This routine is mainly meant to support legacy code in GROMACS. For new source you should try hard to use C++ string objects instead.
std::size_t gmx::countWords ( const std::string &  str)

Returns the number of space-separated words in a string object.

Parameters
strReference to string object, which will not be changed.
Returns
number of words in string.
IFileInputRedirector & gmx::defaultFileInputRedirector ( )

Returns default implementation for IFileInputRedirector.

The returned implementation does not redirect anything, but just uses the file system normally.

Does not throw.

IFileOutputRedirector & gmx::defaultFileOutputRedirector ( )

Returns default implementation for IFileOutputRedirector.

The returned implementation does not redirect anything, but just opens the files at requested locations.

Does not throw.

double gmx::doubleFromString ( const char *  str)

Parses a double value from a string.

Exceptions
InvalidInputErrorif str is not a valid number.

Also checks for overflow.

static std::string gmx::doubleToString ( double  t)
inlinestatic

Returns a string containing the value of t.

Exceptions
std::bad_allocif out of memory.
void gmx::dumpKeyValueTree ( TextWriter *  writer,
const KeyValueTreeObject &  tree 
)

Writes a human-readable representation of the tree with given writer.

The output format is designed to be readable by humans; if some particular machine-readable format is needed, that should be implemented outside the generic key-value tree code.

bool gmx::endsWith ( const char *  str,
const char *  suffix 
)

Tests whether a string ends with another string.

Parameters
[in]strString to process.
[in]suffixSuffix to find.
Returns
true if str ends with suffix.

Returns true if suffix is NULL or empty. Does not throw.

static bool gmx::endsWith ( const std::string &  str,
const char *  suffix 
)
inlinestatic

Tests whether a string ends with another string.

Parameters
[in]strString to process.
[in]suffixSuffix to find.
Returns
true if str ends with suffix.

Returns true if suffix is NULL or empty. Does not throw.

static bool gmx::endsWith ( const std::string &  str,
const std::string &  suffix 
)
inlinestatic

Tests whether a string ends with another string.

Parameters
[in]strString to process.
[in]suffixSuffix to find.
Returns
true if str ends with suffix.

Returns true if suffix is NULL or empty. Does not throw.

bool gmx::equalCaseInsensitive ( const std::string &  source,
const std::string &  target 
)

Return whether two strings are equal, ignoring case.

Checks if two strings have the same length and if all characters in them match when compared case insensitive. Characters are converted by using std::tolower.

Parameters
[in]sourceSearch string to compare against target.
[in]targetString to be matched to source.
Returns
True if the strings match.
bool gmx::equalCaseInsensitive ( const std::string &  source,
const std::string &  target,
size_t  maxLengthOfComparison 
)

Checks if at most maxLengthOfComparison characters of two strings match case insensitive.

The function tests two strings source and target to see if at most maxLengthOfComparison characters match between the two. If fewer characters are present in source, only the maximum number of characters in source will be compared instead. In this case both source and target also need to have the same length, or the strings will compare as false, even if target matches source over the length of source.

If maxLengthOfComparison is 0, the function always returns true. Characters are converted by using std::tolower.

Parameters
[in]sourceSearch string to compare against target.
[in]targetString to be matched to source.
[in]maxLengthOfComparisonThe maximum string length to compare.
Returns
True if the strings match.
void gmx::finalize ( )

Deinitializes the GROMACS library.

Decrements the initialization counter, and calls MPI_Finalize() if GROMACS is compiled with MPI support and the counter has reached zero. In that case, it is not possible to reinitialize GROMACS after calling this function. Instead, call gmx::init() at a higher level, and note that calls to init can be nested safely.

float gmx::floatFromString ( const char *  str)

Parses a float value from a string.

Exceptions
InvalidInputErrorif str is not a valid number.

Also checks for overflow.

template<typename InputIterator , typename FormatterType >
std::string gmx::formatAndJoin ( InputIterator  begin,
InputIterator  end,
const char *  separator,
const FormatterType &  formatter 
)

Formats all the range as strings, and then joins them with a separator in between.

Parameters
[in]beginIterator the beginning of the range to join.
[in]endIterator the end of the range to join.
[in]separatorString to put in between the joined strings.
[in]formatterFunction object to format the objects in container as strings
Returns
All objects in the range from begin to end formatted as strings and concatenated with separator between each pair.
Exceptions
std::bad_allocif out of memory.
template<typename ContainerType , typename FormatterType >
std::string gmx::formatAndJoin ( const ContainerType &  container,
const char *  separator,
const FormatterType &  formatter 
)

Formats all elements of the container as strings, and then joins them with a separator in between.

Parameters
[in]containerObjects to join.
[in]separatorString to put in between the joined strings.
[in]formatterFunction object to format the objects in container as strings
Returns
All objects from container formatted as strings and concatenated with separator between each pair.
Exceptions
std::bad_allocif out of memory.
void gmx::formatExceptionMessageToFile ( FILE *  fp,
const std::exception &  ex 
)

Formats an error message for reporting an exception.

Parameters
fpFile to write the message to.
[in]exException to format.
Exceptions
std::bad_allocif out of memory.
std::string gmx::formatExceptionMessageToString ( const std::exception &  ex)

Formats an error message for reporting an exception.

Parameters
[in]exException to format.
Returns
Formatted string containing details of ex.
Exceptions
std::bad_allocif out of memory.
void gmx::formatExceptionMessageToWriter ( TextWriter *  writer,
const std::exception &  ex 
)

Formats an error message for reporting an exception.

Parameters
writerWriter to use for writing the message.
[in]exException to format.
Exceptions
std::bad_allocif out of memory.
std::string gmx::formatString ( const char *  fmt,
  ... 
)

Formats a string (snprintf() wrapper).

Exceptions
std::bad_allocif out of memory.

This function works like sprintf(), except that it returns an std::string instead of requiring a preallocated buffer. Arbitrary length output is supported.

std::string gmx::formatStringV ( const char *  fmt,
va_list  ap 
)

Formats a string (vsnprintf() wrapper).

Exceptions
std::bad_allocif out of memory.

This function works like vsprintf(), except that it returns an std::string instead of requiring a preallocated buffer. Arbitrary length output is supported.

template<typename T >
static T gmx::fromStdString ( const std::string &  str)
inlinestatic

Parses a value from a string to a given type.

Template Parameters
TType of value to parse.

T can only be one of the types that is explicity supported. The main use for this function is to write fromString<real>(value), but it can also be used for other types for consistency.

Provided for situations where overload resolution cannot easily resolve the desired std::string parameter.

template<typename T >
static T gmx::fromString ( const char *  str)
inlinestatic

Parses a value from a string to a given type.

Template Parameters
TType of value to parse.

T can only be one of the types that is explicity supported. The main use for this function is to write fromString<real>(value), but it can also be used for other types for consistency.

template<typename T >
static T gmx::fromString ( const std::string &  str)
inlinestatic

Parses a value from a string to a given type.

Template Parameters
TType of value to parse.

T can only be one of the types that is explicity supported. The main use for this function is to write fromString<real>(value), but it can also be used for other types for consistency.

const char * gmx::getErrorCodeString ( int  errorcode)

Returns a short string description of an error code.

Parameters
[in]errorcodeError code to retrieve the string for.
Returns
A constant string corresponding to errorcode.

If errorcode is not one of those defined for gmx::ErrorCode, the string corresponding to eeUnknownError is returned.

This function does not throw.

const DataFileFinder & gmx::getLibraryFileFinder ( )

Gets a finder for locating data files from share/top/.

Returns
Finder set with setLibraryFileFinder(), or a default finder.

If setLibraryFileFinder() has not been called (or a NULL finder has been set), a default finder is returned. The default finder searches data files from the directory identified by the global program context; it does not respect GMXLIB environment variable. Calling initForCommandLine() sets a finder that respects GMXLIB.

Does not throw.

See setLibraryFileFinder() for thread safety.

const IProgramContext & gmx::getProgramContext ( )

Returns the global IProgramContext instance.

Returns
The context set with setProgramContext().

If nothing has been set with setProgramContext(), returns a default implementation that returns "GROMACS" for the program and display names, and empty strings for other values. The default implementation never throws.

Does not throw.

See setProgramContext() for thread safety notes. You should not call this method in global deinitialization methods (e.g., destructors of global variables), since it is very difficult to clean up the state correctly in the presence of such calls. For example, initForCommandLine() assumes that such calls do not exist to be able to free the context before exiting.

See Also
IProgramContext
std::string gmx_ctime_r ( const time_t *  clock)

Portable version of ctime_r.

Exceptions
std::bad_allocwhen out of memory.
std::string gmx_format_current_time ( )

Gets the current time as a string.

Exceptions
std::bad_allocwhen out of memory.
int gmx_gethostname ( char *  buf,
size_t  len 
)

Gets the hostname as given by gethostname(), if available.

Parameters
[out]bufBuffer to receive the hostname.
[in]lenLength of buffer buf (must be >= 8).
Returns
0 on success, -1 on error.

If the value is not available, "unknown" is returned. name should have at least size len.

Does not throw.

int gmx_getpid ( )

Returns the process ID of the current process.

Does not throw.

int gmx_getuid ( )

Returns the current user ID, or -1 if not available.

Does not throw.

int gmx_getusername ( char *  buf,
size_t  len 
)

Gets the current user name, if available.

Parameters
[out]bufBuffer to receive the username.
[in]lenLength of buffer buf (must be >= 8).
Returns
0 on success, -1 on error.

Does not throw.

void gmx_is_double_precision ( )

Defined if libgromacs has been compiled in double precision.

Allows detecting the compiled precision of the library through checking the presence of the symbol, e.g., from autoconf or other types of build systems.

void gmx_is_single_precision ( )

Defined if libgromacs has been compiled in single/mixed precision.

Allows detecting the compiled precision of the library through checking the presence of the symbol, e.g., from autoconf or other types of build systems.

bool gmx_omp_check_thread_affinity ( char **  message)

Check for externally set thread affinity to avoid conflicts with GROMACS internal setting.

Parameters
[out]messageReceives the message to be shown to the user.
Returns
true if we can set thread affinity ourselves.

The KMP_AFFINITY environment variable is used by Intel, GOMP_CPU_AFFINITY by the GNU compilers (Intel also honors it well). If any of the variables is set, we should honor it and disable the internal pinning.

If this function returns false, the caller is responsible to disable the pinning, show the message from *message to the user, and free the memory allocated for *message. If the return value is true, *message is NULL.

int gmx_omp_get_max_threads ( )

Returns an integer equal to or greater than the number of threads that would be available if a parallel region without num_threads were defined at that point in the code.

Acts as a wrapper for omp_get_max_threads().

int gmx_omp_get_num_procs ( )

Returns the number of processors available when the function is called.

Acts as a wrapper around omp_get_num_procs().

int gmx_omp_get_thread_num ( )

Returns the thread number of the thread executing within its thread team.

Acts as a wrapper for omp_get_thread_num().

void gmx_omp_set_num_threads ( int  num_threads)

Sets the number of threads in subsequent parallel regions, unless overridden by a num_threads clause.

Acts as a wrapper for omp_set_num_threads().

int gmx_set_nice ( int  level)

Wrapper for nice().

Does not throw.

const char* gmx_version ( )

Version string, containing the version, date, and abbreviated hash.

This can be a plain version if git version info was disabled during the build. The returned string used to start with a literal word VERSION before GROMACS 2016, but no longer does.

const char* gmx_version_git_central_base_hash ( )

Full git hash of the latest commit in a central GROMACS repository.

If git version info was disabled during the build, returns an empty string. Also, if the latest commit was from a central repository, the return value is an empty string.

const char* gmx_version_git_full_hash ( )

Full git hash of the latest commit.

If git version info was disabled during the build, returns an empty string.

void gmx::init ( int *  argc,
char ***  argv 
)

Initializes the GROMACS library.

Parameters
[in]argcargc value passed to main().
[in]argvargv array passed to main().

argc and argv are the command line arguments passed to main(). They are allowed to be NULL if GROMACS is not compiled with MPI, MPI_Init() has already been called, or if the MPI library GROMACS is compiled against allows it.

Does not throw.

int64_t gmx::int64FromString ( const char *  str)

Parses a 64-bit integer from a string.

Exceptions
InvalidInputErrorif str is not a valid integer.

Also checks for overflow.

static std::string gmx::int64ToString ( int64_t  t)
inlinestatic

Returns a string containing the value of t.

Exceptions
std::bad_allocif out of memory.
int gmx::intFromString ( const char *  str)

Parses an integer from a string.

Exceptions
InvalidInputErrorif str is not a valid integer.

Also checks for overflow.

static std::string gmx::intToString ( int  t)
inlinestatic

Returns a string containing the value of t.

Exceptions
std::bad_allocif out of memory.
static bool gmx::isNullOrEmpty ( const char *  str)
inlinestatic

Tests whether a string is null or empty.

Does not throw.

template<typename InputIterator >
std::string gmx::joinStrings ( InputIterator  begin,
InputIterator  end,
const char *  separator 
)

Joins strings from a range with a separator in between.

Parameters
[in]beginIterator the beginning of the range to join.
[in]endIterator the end of the range to join.
[in]separatorString to put in between the joined strings.
Returns
All strings from (begin, end) concatenated with separator between each pair.
Exceptions
std::bad_allocif out of memory.
template<typename ContainerType >
std::string gmx::joinStrings ( const ContainerType &  container,
const char *  separator 
)

Joins strings from a container with a separator in between.

Parameters
[in]containerStrings to join.
[in]separatorString to put in between the joined strings.
Returns
All strings from container concatenated with separator between each pair.
Exceptions
std::bad_allocif out of memory.
template<size_t count>
std::string gmx::joinStrings ( const char *const (&)  array[count],
const char *  separator 
)

Joins strings from an array with a separator in between.

Parameters
[in]arrayArray of strings to join.
[in]separatorString to put in between the joined strings.
Template Parameters
countDeduced number of elements in array.
Returns
All strings from aray concatenated with separator between each pair.
Exceptions
std::bad_allocif out of memory.
template<class Exception , class Tag , class T >
std::enable_if_t<std::is_base_of<GromacsException, Exception>::value, Exception> gmx::operator<< ( Exception  ex,
const ExceptionInfo< Tag, T > &  item 
)
inline

Associates extra information with an exception.

Template Parameters
ExceptionException type (must be derived from GromacsException).
TagExceptionInfo tag.
TExceptionInfo value type.
Parameters
[in,out]exException to associate the information to.
[in]itemInformation to associate.
void gmx::printFatalErrorMessage ( FILE *  fp,
const std::exception &  ex 
)

Formats a standard fatal error message for reporting an exception.

Parameters
[in]fpFile to format the message to.
[in]exException to format.

Does not throw. If memory allocation fails or some other error occurs while formatting the error, tries to print a reasonable alternative message.

Normal usage in Gromacs command-line programs is like this:

int main(int argc, char *argv[])
{
gmx::init(&argc, &argv);
try
{
// The actual code for the program
return 0;
}
catch (const std::exception &ex)
{
}
}
void gmx::processExceptionAsFatalError ( const std::exception &  ex)

Helper function for terminating the program on an exception.

Parameters
[in]exException that is the cause for terminating the program.

Does not throw, and does not return.

int gmx::processExceptionAtExit ( const std::exception &  ex)

Handles an exception that is causing the program to terminate.

Parameters
[in]exException that is the cause for terminating the program.
Returns
Return code to return from main().

This method should be called as the last thing before terminating the program because of an exception. It exists to terminate the program as gracefully as possible in the case of MPI processing (but the current implementation always calls MPI_Abort()).

See printFatalErrorMessage() for example usage.

Does not throw.

std::string gmx::replaceAll ( const std::string &  input,
const char *  from,
const char *  to 
)

Replace all occurrences of a string with another string.

Parameters
[in]inputInput string.
[in]fromString to find.
[in]toString to use to replace from.
Returns
Copy of input with all occurrences of from replaced with to.
Exceptions
std::bad_allocif out of memory.

The replacement is greedy and not recursive: starting from the beginning of input, each match of from is replaced with to, and the search for the next match begins after the end of the previous match.

Complexity is O(N), where N is length of output.

See Also
replaceAllWords()
std::string gmx::replaceAll ( const std::string &  input,
const std::string &  from,
const std::string &  to 
)

Replace all occurrences of a string with another string.

Parameters
[in]inputInput string.
[in]fromString to find.
[in]toString to use to replace from.
Returns
Copy of input with all occurrences of from replaced with to.
Exceptions
std::bad_allocif out of memory.

The replacement is greedy and not recursive: starting from the beginning of input, each match of from is replaced with to, and the search for the next match begins after the end of the previous match.

Complexity is O(N), where N is length of output.

See Also
replaceAllWords()
std::string gmx::replaceAllWords ( const std::string &  input,
const char *  from,
const char *  to 
)

Replace whole words with others.

Parameters
[in]inputInput string.
[in]fromString to find.
[in]toString to use to replace from.
Returns
Copy of input with all from words replaced with to.
Exceptions
std::bad_allocif out of memory.

Works as replaceAll(), but a match is only considered if it is delimited by non-alphanumeric characters.

See Also
replaceAll()
std::string gmx::replaceAllWords ( const std::string &  input,
const std::string &  from,
const std::string &  to 
)

Replace whole words with others.

Parameters
[in]inputInput string.
[in]fromString to find.
[in]toString to use to replace from.
Returns
Copy of input with all from words replaced with to.
Exceptions
std::bad_allocif out of memory.

Works as replaceAll(), but a match is only considered if it is delimited by non-alphanumeric characters.

See Also
replaceAll()
void gmx::setProgramContext ( const IProgramContext *  context)

Sets the global IProgramContext instance.

Parameters
[in]contextProgram context to set (can be NULL to restore the default context).

The library does not take ownership of context. The provided object must remain valid until the global instance is changed by another call to setProgramContext().

This method is not thread-safe. It must be the first call to the library after gmx::init(), and multi-threaded access is only supported after the call completes. If GROMACS is getting called from multiple threads, or uses multiple threads simultaneously, changing the program context is not supported once it is set. If the context is cleared at the end of the program, the caller must ensure that all other threads have been terminated at this point. These constraints simplify the implementation significantly.

Does not throw.

See Also
IProgramContext
std::string gmx::simpleValueToString ( const Any &  value)

Converts a Any value to a string.

As the name suggests, only some types of "simple" values (such as int) are supported. Asserts for unsupported types.

std::vector< std::string > gmx::splitAndTrimDelimitedString ( const std::string &  str,
char  delim 
)

Splits str to tokens separated by delimiter delim. Removes leading and trailing whitespace from those strings with std::isspace.

Parameters
[in]strString to process.
[in]delimDelimiter to use for splitting.
Returns
str split into tokens at delimiter, with whitespace stripped.
Exceptions
std::bad_allocif out of memory.

Unlike splitString(), consecutive delimiters will generate empty tokens, as will leading or trailing delimiters. Empty input will return an empty vector. Input with only whitespace will return a vector of size 1, that contains an empty token.

std::vector< std::string > gmx::splitDelimitedString ( const std::string &  str,
char  delim 
)

Splits a string to tokens separated by a given delimiter.

Parameters
[in]strString to process.
[in]delimDelimiter to use for splitting.
Returns
str split into tokens at delimiter.
Exceptions
std::bad_allocif out of memory.

Unlike splitString(), consecutive delimiters will generate empty tokens, as will leading or trailing delimiters. Empty input will return an empty vector.

std::vector< std::string > gmx::splitString ( const std::string &  str)

Splits a string to whitespace separated tokens.

Parameters
[in]strString to process.
Returns
str split into tokens at each whitespace sequence.
Exceptions
std::bad_allocif out of memory.

This function works like split in Python, i.e., leading and trailing whitespace is ignored, and consecutive whitespaces are treated as a single separator.

static bool gmx::startsWith ( const std::string &  str,
const std::string &  prefix 
)
inlinestatic

Tests whether a string starts with another string.

Parameters
[in]strString to process.
[in]prefixPrefix to find.
Returns
true if str starts with prefix.

Returns true if prefix is empty. Does not throw.

static bool gmx::startsWith ( const char *  str,
const char *  prefix 
)
inlinestatic

Tests whether a string starts with another string.

Parameters
[in]strString to process.
[in]prefixPrefix to find.
Returns
true if str starts with prefix.

Returns true if prefix is empty. Does not throw.

std::string gmx::stripString ( const std::string &  str)

Removes leading and trailing whitespace from a string.

Parameters
[in]strString to process.
Returns
str with leading and trailing whitespaces removed.
Exceptions
std::bad_allocif out of memory.
std::string gmx::stripSuffixIfPresent ( const std::string &  str,
const char *  suffix 
)

Removes a suffix from a string.

Parameters
[in]strString to process.
[in]suffixSuffix to remove.
Returns
str with suffix removed, or str unmodified if it does not end with suffix.
Exceptions
std::bad_allocif out of memory.

Returns str if suffix is NULL or empty.

template<typename T >
void gmx::swap ( ArrayRef< T > &  a,
ArrayRef< T > &  b 
)

Simple swap method for ArrayRef objects.

See Also
ArrayRef::swap()
std::string gmx::toLowerCase ( const std::string &  text)

Makes the string lowercase.

Parameters
[in]textInput text.
Returns
text with all characters transformed to lowercase.
Exceptions
std::bad_allocif out of memory.
std::string gmx::toUpperCase ( const std::string &  text)

Makes the string uppercase.

Parameters
[in]textInput text.
Returns
text with all characters transformed to uppercase.
Exceptions
std::bad_allocif out of memory.