guts
Loading...
Searching...
No Matches
gutilities Namespace Reference

Functions

bool is_unset (std::string_view s)
 Determine whether a string should be treated as "unset".
 
void apply_uimanager_commands (const std::string &commands)
 Apply a single Geant4 UI command if a UI manager is available.
 
std::filesystem::path executable_path ()
 Get the absolute canonical path to the current executable.
 
std::filesystem::path gemc_root ()
 Infer the GEMC installation root directory from the executable location.
 
std::string success_or_fail (bool condition)
 Convert a boolean condition to a stable status string.
 
String normalization and tokenization
string removeLeadingAndTrailingSpacesFromString (const std::string &input)
 Removes leading and trailing spaces and tabs from a string.
 
std::string_view removeLeadingAndTrailingSpacesFromString (const std::string_view input)
 Removes leading and trailing whitespace from a string view (no allocation).
 
string removeAllSpacesFromString (const std::string &str)
 Removes all spaces from a string.
 
vector< std::string > getStringVectorFromString (const std::string &input)
 Splits a string into a vector of strings using whitespace as delimiters.
 
string replaceCharInStringWithChars (const std::string &input, const std::string &toReplace, const std::string &replacement)
 Replaces all occurrences of specified characters in a string with another string.
 
string replaceAllStringsWithString (const string &source, const string &from, const string &to)
 Replaces all occurrences of a substring with another string.
 
string fillDigits (const string &word, const string &c, int ndigits)
 Pads a string with a specified character until it reaches a desired length.
 
Path and filesystem helpers
string getFileFromPath (const std::string &path)
 Extracts the filename from a given file path.
 
string getDirFromPath (const std::string &path)
 Extracts the directory path from a given file path.
 
bool directoryExists (const std::string &path)
 Checks if a directory exists at the given path.
 
string searchForDirInLocations (const string &dirName, const vector< string > &possibleLocations)
 Searches for a directory within a list of possible locations.
 
bool hasExtension (const string &filename, const vector< string > &extensions)
 Checks if a filename has one of the specified extensions.
 
vector< string > getListOfFilesInDirectory (const string &dirName, const vector< string > &extensions)
 Retrieves a list of files with specific extensions from a directory.
 
std::optional< std::string > searchForFileInLocations (const std::vector< std::string > &locations, std::string_view filename)
 Search for a regular file across candidate locations.
 
Numeric parsing with optional units
double getG4Number (const string &v, bool warnIfNotUnit=false)
 Converts a string representation of a number with optional units to a double.
 
double getG4Number (double input, const string &unit)
 Converts a numeric value with a unit into a Geant4-number string and parses it.
 
vector< double > getG4NumbersFromStringVector (const vector< string > &vstring, bool warnIfNotUnit=false)
 Converts a vector of strings representing numbers with units to a vector of doubles.
 
vector< double > getG4NumbersFromString (const string &vstring, bool warnIfNotUnit=false)
 Converts a comma-separated string of numbers with units to a vector of doubles.
 
Text file parsing and substring extraction
string parseFileAndRemoveComments (const string &filename, const string &commentChars="#", int verbosity=0)
 Parses a file and removes all lines containing specified comment characters.
 
string retrieveStringBetweenChars (const string &input, const string &firstDelimiter, const string &secondDelimiter)
 Retrieves a substring between two specified delimiters in a string.
 
vector< string > getStringVectorFromStringWithDelimiter (const string &input, const string &x)
 Splits a string into a vector of substrings using a specified delimiter.
 

Miscellaneous helpers

enum  randomModel { uniform , gaussian , cosine , sphere }
 Enumeration of random models. More...
 
string convertToLowercase (const string &str)
 Converts a string to lowercase.
 
template<class KEY , class VALUE >
vector< KEY > getKeys (const map< KEY, VALUE > &map)
 Retrieves all keys from a map.
 
randomModel stringToRandomModel (const std::string &str)
 Converts a string to a corresponding randomModel enum value.
 
G4Colour makeG4Colour (std::string_view code, double opacity)
 Convert a hex colour string to G4Colour.
 
constexpr const char * to_string (randomModel m) noexcept
 Convert a randomModel enum value to a stable string token.
 

Enumeration Type Documentation

◆ randomModel

This enum is used to select a distribution/model in places where randomized sampling is configurable via human-readable strings.

Enumerator
uniform 

Uniform distribution.

gaussian 

Gaussian distribution.

cosine 

Cosine distribution.

sphere 

Sphere distribution.

Definition at line 398 of file gutilities.h.

Function Documentation

◆ apply_uimanager_commands()

void gutilities::apply_uimanager_commands ( const std::string & commands)

This wrapper obtains the current G4UImanager singleton and calls ApplyCommand. If no UI manager exists, the call is a no-op.

Parameters
commandsCommand string to apply.
Note
This intentionally does not validate the command string; validation is delegated to the UI manager.

Definition at line 594 of file gutilities.cc.

◆ convertToLowercase()

string gutilities::convertToLowercase ( const string & str)
Parameters
strThe string to convert.
Returns
The lowercase version of the input string.
Note
This uses the C locale's ::tolower behavior (byte-wise). It is intended for ASCII-ish tokens such as configuration keywords and unit identifiers.

Definition at line 503 of file gutilities.cc.

◆ directoryExists()

bool gutilities::directoryExists ( const std::string & path)
Parameters
pathThe path to check for a directory.
Returns
true if the directory exists, false otherwise.
Note
This probes the filesystem and may fail for permission reasons; failures are treated as "does not exist" in the current implementation.

Definition at line 458 of file gutilities.cc.

◆ executable_path()

std::filesystem::path gutilities::executable_path ( )
inline

Platform-specific behavior:

  • macOS: uses _NSGetExecutablePath
  • Linux: uses readlink on /proc/self/exe
  • Windows: uses GetModuleFileNameW

The returned path is canonicalized via std::filesystem::canonical.

Returns
Canonical executable path.
Exceptions
std::runtime_erroron platform API failures.
Note
This utility is used to infer installation layout relative to the executable.

Definition at line 487 of file gutilities.h.

◆ fillDigits()

string gutilities::fillDigits ( const string & word,
const string & c,
int ndigits )

This function prepends the first character of c to word until its length equals ndigits. If c is empty or ndigits is not larger than the current length, the original word is returned.

Parameters
wordThe original string to be padded.
cThe character string to use for padding (only c[0] is used).
ndigitsThe target length of the padded string.
Returns
A new string padded to the specified length.

Definition at line 157 of file gutilities.cc.

◆ gemc_root()

std::filesystem::path gutilities::gemc_root ( )
inline

Current behavior:

  • If the executable directory is named "bin" or "build", the root is assumed to be its parent.
  • The function then requires that "<root>/api" exists, otherwise it throws.

The environment variable fallback is intentionally commented out and not used.

Returns
Filesystem path to the inferred GEMC root.
Exceptions
std::runtime_errorif the layout check fails.
Note
This function encodes a layout expectation. If the installation structure changes, update the documented assumptions here and the corresponding implementation.

Definition at line 539 of file gutilities.h.

◆ getDirFromPath()

std::string gutilities::getDirFromPath ( const std::string & path)

This function extracts and returns the directory path from a given POSIX-style file path using '/' as separator. If the path contains no separators, "." is returned.

Parameters
pathThe input file path.
Returns
The directory path extracted from the path.
Note
This is a string-based helper. It does not query the filesystem and does not normalize paths.

Definition at line 85 of file gutilities.cc.

◆ getFileFromPath()

std::string gutilities::getFileFromPath ( const std::string & path)

This function extracts and returns the filename from a given POSIX-style file path using '/' as separator. If the path contains no separators, the original string is returned.

Parameters
pathThe input file path.
Returns
The filename extracted from the path.
Note
This is a string-based helper. It does not query the filesystem and does not normalize paths.

Definition at line 71 of file gutilities.cc.

◆ getG4Number() [1/2]

double gutilities::getG4Number ( const string & v,
bool warnIfNotUnit = false )

Accepted formats:

  • Pure number: "12.3"
  • Number with unit: "<number>*<unit>" (exactly one '*' separator)

Key behavior:

  • Leading/trailing whitespace is ignored.
  • A single decimal comma is normalized to a dot if no dot is present.
  • The numeric part is parsed in the "C" locale to avoid locale-dependent decimal separators.
  • Units are converted using a fixed table and limited SI-prefix handling.
  • On invalid formatting or numeric parsing errors, the function prints a fatal error and exits with EC__G4NUMBERERROR.
  • If the unit is unknown, a warning is printed and the numeric part is returned (legacy behavior).
Parameters
vThe input string containing the number and optional units, formatted as "<number>*<unit>".
warnIfNotUnitFlag indicating whether to issue a warning if the units are not present.
Returns
The numeric value converted to a double, taking into account the units if provided.
Warning
This function may terminate the process on formatting or numeric parse errors. It is intended for configuration/parameter parsing where such errors are considered fatal.

Definition at line 210 of file gutilities.cc.

◆ getG4Number() [2/2]

double gutilities::getG4Number ( double input,
const string & unit )

This is a convenience overload that constructs "<input>*<unit>" and then calls getG4Number().

Parameters
inputThe numeric value to convert.
unitThe unit associated with the numeric value.
Returns
The converted numeric value as a double.

Definition at line 349 of file gutilities.cc.

◆ getG4NumbersFromString()

vector< double > gutilities::getG4NumbersFromString ( const string & vstring,
bool warnIfNotUnit = false )

The string is split on commas using getStringVectorFromStringWithDelimiter(), and each token is parsed using getG4Number().

Parameters
vstringA comma-separated string of numbers with optional units.
warnIfNotUnitFlag indicating whether to issue a warning if the units are not present.
Returns
A vector of doubles representing the converted numeric values.

Definition at line 363 of file gutilities.cc.

◆ getG4NumbersFromStringVector()

vector< double > gutilities::getG4NumbersFromStringVector ( const vector< string > & vstring,
bool warnIfNotUnit = false )

Each element is parsed independently using getG4Number().

Parameters
vstringA vector of strings, each containing a number with optional units.
warnIfNotUnitFlag indicating whether to issue a warning if the units are not present.
Returns
A vector of doubles representing the converted numeric values.

Definition at line 354 of file gutilities.cc.

◆ getKeys()

template<class KEY , class VALUE >
vector< KEY > gutilities::getKeys ( const map< KEY, VALUE > & map)
Template Parameters
KEYThe type of keys in the map.
VALUEThe type of values in the map.
Parameters
mapThe map from which to extract keys.
Returns
A vector containing all the keys from the map.

Complexity: linear in the map size.

Definition at line 511 of file gutilities.cc.

◆ getListOfFilesInDirectory()

vector< string > gutilities::getListOfFilesInDirectory ( const string & dirName,
const vector< string > & extensions )

Only regular files are returned. Directory entries that are not regular files are ignored.

Parameters
dirNameThe name of the directory to search in.
extensionsA vector of file extensions to filter the files.
Returns
A vector of file names that have the specified extensions.
Note
Returned values are filenames (not absolute paths).

Definition at line 483 of file gutilities.cc.

◆ getStringVectorFromString()

std::vector< std::string > gutilities::getStringVectorFromString ( const std::string & input)

The input is tokenized on whitespace (as implemented by std::stringstream extraction). Each token is trimmed (defensively) and empty tokens are skipped.

Parameters
inputThe input string to split.
Returns
A vector of strings obtained by splitting the input string.

Definition at line 99 of file gutilities.cc.

◆ getStringVectorFromStringWithDelimiter()

vector< string > gutilities::getStringVectorFromStringWithDelimiter ( const string & input,
const string & x )

The delimiter used is x[0]. Tokens are trimmed and empty tokens are skipped.

Parameters
inputThe input string to split.
xThe delimiter string (only the first character is used).
Returns
A vector of strings containing the split substrings.
Warning
If x is empty, behavior is undefined (the implementation indexes x[0]).

Definition at line 402 of file gutilities.cc.

◆ hasExtension()

bool gutilities::hasExtension ( const string & filename,
const vector< string > & extensions )

The comparison is a suffix match against each provided extension.

Parameters
filenameThe name of the file to check.
extensionsA vector of extensions to check against.
Returns
true if the filename has one of the specified extensions, false otherwise.
Note
Extensions are matched exactly as provided (case-sensitive).

Definition at line 475 of file gutilities.cc.

◆ is_unset()

bool gutilities::is_unset ( std::string_view s)

The matching rules are intentionally more permissive than a single sentinel: they typically include a conventional sentinel token and common YAML-style null spellings. See the implementation in the corresponding translation unit for the exact matching rules.

Parameters
sInput view.
Returns
true if s represents an "unset" value, false otherwise.
Note
This is used for robust configuration parsing where users may specify "NULL", "null", "~", or empty values.

Definition at line 580 of file gutilities.cc.

◆ makeG4Colour()

G4Colour gutilities::makeG4Colour ( std::string_view code,
double opacity )

Accepted formats (case-insensitive):

  • "#RRGGBB" or "RRGGBB" (six hex digits; leading '#' optional)

The opacity component is provided explicitly via opacity.

Parameters
codeHex RGB string.
opacityAlpha value passed to G4Colour.
Returns
Constructed G4Colour.
Exceptions
std::invalid_argumenton malformed input.
Note
This helper is intended for configuration-driven color selection.

Definition at line 534 of file gutilities.cc.

◆ parseFileAndRemoveComments()

string gutilities::parseFileAndRemoveComments ( const string & filename,
const string & commentChars = "#",
int verbosity = 0 )

The entire file is read into a string and then comment lines are removed by treating commentChars as the start-of-comment marker.

Parameters
filenameThe name of the file to parse.
commentCharsThe characters indicating the start of a comment in the file.
verbosityThe verbosity level for logging information.
Returns
A string representing the content of the file with comments removed.
Warning
This performs a textual removal strategy. It is appropriate for simple configuration formats but should not be used as a general-purpose parser for languages with nested quoting rules.

Definition at line 368 of file gutilities.cc.

◆ removeAllSpacesFromString()

std::string gutilities::removeAllSpacesFromString ( const std::string & str)

This function removes all literal space characters (' ') from the input string and returns the result. It does not remove other whitespace (tabs/newlines).

Parameters
strThe input string from which spaces will be removed.
Returns
A new string with all spaces removed.

Definition at line 60 of file gutilities.cc.

◆ removeLeadingAndTrailingSpacesFromString() [1/2]

std::string gutilities::removeLeadingAndTrailingSpacesFromString ( const std::string & input)

This overload returns a new owning string after trimming.

Whitespace considered:

  • Space (' ')
  • Tab (the tab character)

If the input contains only whitespace (or is empty), an empty string is returned.

Parameters
inputThe string to be trimmed.
Returns
A new string with leading and trailing spaces and tabs removed.
See also
removeLeadingAndTrailingSpacesFromString(std::string_view)

Definition at line 29 of file gutilities.cc.

◆ removeLeadingAndTrailingSpacesFromString() [2/2]

std::string_view gutilities::removeLeadingAndTrailingSpacesFromString ( const std::string_view input)

This overload adjusts the view bounds by removing whitespace from both ends. The returned view references the original underlying buffer.

Whitespace classification is based on std::isspace.

Parameters
inputThe string_view to be trimmed.
Returns
A trimmed view of the original input.
Warning
The returned view is only valid as long as the referenced buffer remains valid.

Definition at line 49 of file gutilities.cc.

◆ replaceAllStringsWithString()

string gutilities::replaceAllStringsWithString ( const string & source,
const string & from,
const string & to )

This function performs non-overlapping, left-to-right replacement of all occurrences of from with to.

Parameters
sourceThe original string where replacements will occur.
fromThe substring to be replaced.
toThe string to replace each occurrence of the substring.
Returns
A new string with all occurrences of the substring replaced.
Warning
If from is empty, the function returns source to avoid an infinite loop.

Definition at line 130 of file gutilities.cc.

◆ replaceCharInStringWithChars()

std::string gutilities::replaceCharInStringWithChars ( const std::string & input,
const std::string & toReplace,
const std::string & replacement )

Every character in input is checked against the set of characters in toReplace. When a match is found, replacement is appended to the output string.

Parameters
inputThe input string in which characters are to be replaced.
toReplaceA string containing characters to be replaced.
replacementThe string to replace each occurrence of characters in toReplace.
Returns
A new string with specified characters replaced by the replacement string.
Note
This function replaces characters (not substrings) and may increase the output size if replacement is longer than one character.

Definition at line 115 of file gutilities.cc.

◆ retrieveStringBetweenChars()

string gutilities::retrieveStringBetweenChars ( const string & input,
const string & firstDelimiter,
const string & secondDelimiter )

This function extracts and returns the substring found between the first and second delimiters within the input string. If either delimiter is not found, an empty string is returned.

Parameters
inputThe input string containing the delimiters.
firstDelimiterThe delimiter marking the start of the substring.
secondDelimiterThe delimiter marking the end of the substring.
Returns
The substring found between the specified delimiters, or an empty string if delimiters are not found.
Note
Only the first occurrence of each delimiter is considered.

Definition at line 394 of file gutilities.cc.

◆ searchForDirInLocations()

string gutilities::searchForDirInLocations ( const string & dirName,
const vector< string > & possibleLocations )

For each candidate base path, the function checks for "<base>/<dirName>".

Parameters
dirNameThe name of the directory to search for.
possibleLocationsA vector of paths where the directory might be located.
Returns
The path to the found directory or the literal string "UNINITIALIZEDSTRINGQUANTITY" if not found.
Warning
The "not found" case returns a literal marker string (not the macro value). Treat this as a legacy behavior and compare against the exact returned token if needed.

Definition at line 466 of file gutilities.cc.

◆ searchForFileInLocations()

std::optional< std::string > gutilities::searchForFileInLocations ( const std::vector< std::string > & locations,
std::string_view filename )

Each entry in locations may be either:

  • A directory path, in which case filename is appended and tested.
  • A full path to a file candidate, tested directly.

The first candidate that exists and is a regular file is returned.

Parameters
locationsCandidate directories and/or file paths.
filenameFilename to append when probing directory entries.
Returns
Full path string for the first match, or std::nullopt if no match is found.
Note
This function probes the filesystem. It is appropriate for "search path" style logic.

Definition at line 560 of file gutilities.cc.

◆ stringToRandomModel()

randomModel gutilities::stringToRandomModel ( const std::string & str)

The mapping is strict and case-sensitive in the current implementation. If the string does not match any known model, an exception is thrown.

Parameters
strThe string representation of the random model.
Returns
The corresponding randomModel enum value.
Exceptions
std::invalid_argumentif the string does not match any valid model.

Definition at line 520 of file gutilities.cc.

◆ success_or_fail()

std::string gutilities::success_or_fail ( bool condition)
inline
Parameters
conditionBoolean test.
Returns
"success" when condition is true; otherwise "fail".
Note
Intended for short, human-readable status reporting and logs.

Definition at line 593 of file gutilities.h.

◆ to_string()

constexpr const char * gutilities::to_string ( randomModel m)
inlineconstexprnoexcept

The returned strings match those accepted by stringToRandomModel().

Parameters
mEnum value.
Returns
String token for m.

Definition at line 426 of file gutilities.h.