guts
Loading...
Searching...
No Matches
gutilities.h
Go to the documentation of this file.
1#pragma once
2
3// c++
4#include <vector>
5#include <string>
6#include <map>
7#include <string_view>
8#include <optional>
9
10// geant4
11#include "G4Colour.hh"
12#include "G4UImanager.hh" // Geant4 UI manager access
13
27namespace gutilities {
28using std::string;
29using std::vector;
30using std::map;
31
53std::string removeLeadingAndTrailingSpacesFromString(const std::string& input);
54
68std::string_view removeLeadingAndTrailingSpacesFromString(const std::string_view input);
69
79std::string removeAllSpacesFromString(const std::string& str);
80
90std::vector<std::string> getStringVectorFromString(const std::string& input);
91
106std::string replaceCharInStringWithChars(const std::string& input, const std::string& toReplace,
107 const std::string& replacement);
108
109
123string replaceAllStringsWithString(const string& source, const string& from, const string& to);
124
136string fillDigits(const string& word, const string& c, int ndigits);
137
156std::string getFileFromPath(const std::string& path);
157
169std::string getDirFromPath(const std::string& path);
170
186std::optional<std::string> searchForFileInLocations(
187 const std::vector<std::string>& locations,
188 std::string_view filename);
189
199bool directoryExists(const std::string& path);
200
213string searchForDirInLocations(const string& dirName, const vector<string>& possibleLocations);
214
226bool hasExtension(const string& filename, const vector<string>& extensions);
227
239vector<string> getListOfFilesInDirectory(const string& dirName, const vector<string>& extensions);
240
270double getG4Number(const string& v, bool warnIfNotUnit = false);
271
282double getG4Number(double input, const string& unit);
283
293vector<double> getG4NumbersFromStringVector(const vector<string>& vstring, bool warnIfNotUnit = false);
294
306vector<double> getG4NumbersFromString(const string& vstring, bool warnIfNotUnit = false);
307
329string parseFileAndRemoveComments(const string& filename, const string& commentChars = "#", int verbosity = 0);
330
331
345string retrieveStringBetweenChars(const string& input, const string& firstDelimiter, const string& secondDelimiter);
346
347
359vector<string> getStringVectorFromStringWithDelimiter(const string& input, const string& x);
360
377string convertToLowercase(const string& str);
378
389template <class KEY, class VALUE>
390vector<KEY> getKeys(const map<KEY, VALUE>& map);
391
405
416randomModel stringToRandomModel(const std::string& str);
417
426inline constexpr const char* to_string(randomModel m) noexcept {
427 switch (m) {
428 case uniform: return "uniform";
429 case gaussian: return "gaussian";
430 case cosine: return "cosine";
431 case sphere: return "sphere";
432 }
433 return "<unknown>";
434}
435
451G4Colour makeG4Colour(std::string_view code, double opacity);
452
454};
455
456
457#include <filesystem>
458
459#if defined(__APPLE__)
460#include <mach-o/dyld.h> // _NSGetExecutablePath
461#elif defined(__linux__)
462#include <unistd.h> // readlink
463#include <limits.h>
464#elif defined(_WIN32)
465#include <windows.h>
466#include <vector>
467#else
468#error "Unsupported platform"
469#endif
470
471namespace gutilities {
487inline std::filesystem::path executable_path() {
488#if defined(__APPLE__)
489 char buf[PATH_MAX];
490 uint32_t sz = sizeof(buf);
491 if (_NSGetExecutablePath(buf, &sz) != 0) {
492 // buffer too small
493 std::string big(sz, '\0');
494 if (_NSGetExecutablePath(big.data(), &sz) != 0)
495 throw std::runtime_error("_NSGetExecutablePath failed");
496 return std::filesystem::canonical(big);
497 }
498 return std::filesystem::canonical(buf);
499
500#elif defined(__linux__)
501 char buf[PATH_MAX];
502 ssize_t len = ::readlink("/proc/self/exe", buf, sizeof(buf) - 1);
503 if (len == -1)
504 throw std::runtime_error("readlink(/proc/self/exe) failed");
505 buf[len] = '\0';
506 return std::filesystem::canonical(buf);
507
508#elif defined(_WIN32)
509 std::wstring buf(MAX_PATH, L'\0');
510 DWORD len = ::GetModuleFileNameW(nullptr, buf.data(), buf.size());
511 if (len == 0)
512 throw std::runtime_error("GetModuleFileNameW failed");
513 // If the path is longer than MAX_PATH the buffer is truncated;
514 // do a second call with the returned length to get the full path.
515 if (len == buf.size()) {
516 buf.resize(len * 2);
517 len = ::GetModuleFileNameW(nullptr, buf.data(), buf.size());
518 }
519 buf.resize(len);
520 return std::filesystem::canonical(std::filesystem::path(buf));
521#endif
522}
523
539inline std::filesystem::path gemc_root() {
540 const auto exe_dir = executable_path().parent_path();
541
542 std::filesystem::path root;
543
544 // Case 1: executable came from ../bin or (for tests) build
545 if (exe_dir.filename() == "bin" || exe_dir.filename() == "build") {
546 root = exe_dir.parent_path();
547 }
548 // else {
549 // // Case 2: use GEMC environment variable
550 // const char* env = std::getenv("GEMC");
551 // if (!env || std::string(env).empty()) {
552 // throw std::runtime_error(
553 // "GEMC executable not in <.../bin>. Environment variable GEMC is required."
554 // );
555 // }
556 // root = std::filesystem::path(env);
557 // }
558
559 // Sanity check
560 if (!std::filesystem::exists(root / "api")) {
561 throw std::runtime_error(
562 "Cannot locate directory <api> under " + root.string() +
563 ". Check installation layout or GEMC environment variable."
564 );
565 }
566
567 return root;
568}
569
570
583bool is_unset(std::string_view s);
584
593inline std::string success_or_fail(bool condition) { return condition ? "success" : "fail"; }
594
605void apply_uimanager_commands(const std::string& commands);
606}
string replaceAllStringsWithString(const string &source, const string &from, const string &to)
Replaces all occurrences of a substring with another string.
double getG4Number(const string &v, bool warnIfNotUnit)
Converts a string representation of a number with optional units to a double.
bool hasExtension(const std::string &filename, const std::vector< std::string > &extensions)
Checks if a filename has one of the specified extensions.
vector< double > getG4NumbersFromString(const string &vstring, bool warnIfNotUnit)
Converts a comma-separated string of numbers with units to a vector of doubles.
string removeAllSpacesFromString(const std::string &str)
Removes all spaces from a string.
Definition gutilities.cc:60
std::filesystem::path executable_path()
Get the absolute canonical path to the current executable.
Definition gutilities.h:487
vector< string > getStringVectorFromStringWithDelimiter(const string &input, const string &x)
Splits a string into a vector of substrings using a specified delimiter.
G4Colour makeG4Colour(std::string_view code, double opacity)
Convert a hex colour string to G4Colour.
randomModel stringToRandomModel(const std::string &str)
Converts a string to a corresponding randomModel enum value.
std::filesystem::path gemc_root()
Infer the GEMC installation root directory from the executable location.
Definition gutilities.h:539
vector< string > getListOfFilesInDirectory(const string &dirName, const vector< string > &extensions)
Retrieves a list of files with specific extensions from a directory.
vector< double > getG4NumbersFromStringVector(const vector< string > &vstring, bool warnIfNotUnit)
Converts a vector of strings representing numbers with units to a vector of doubles.
string retrieveStringBetweenChars(const string &input, const string &firstDelimiter, const string &secondDelimiter)
Retrieves a substring between two specified delimiters in a string.
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 fillDigits(const string &word, const string &c, int ndigits)
Pads a string with a specified character until it reaches a desired length.
std::string success_or_fail(bool condition)
Convert a boolean condition to a stable status string.
Definition gutilities.h:593
bool is_unset(std::string_view s)
Determine whether a string should be treated as "unset".
randomModel
Enumeration of random models.
Definition gutilities.h:399
@ gaussian
Gaussian distribution.
Definition gutilities.h:401
@ uniform
Uniform distribution.
Definition gutilities.h:400
@ sphere
Sphere distribution.
Definition gutilities.h:403
@ cosine
Cosine distribution.
Definition gutilities.h:402
string getDirFromPath(const std::string &path)
Extracts the directory path from a given file path.
Definition gutilities.cc:85
string convertToLowercase(const string &str)
Converts a string to lowercase.
bool directoryExists(const std::string &path)
Checks if a directory exists at the given path.
vector< KEY > getKeys(const map< KEY, VALUE > &map)
Retrieves all keys from a map.
string removeLeadingAndTrailingSpacesFromString(const std::string &input)
Removes leading and trailing spaces and tabs from a string.
Definition gutilities.cc:29
std::optional< std::string > searchForFileInLocations(const std::vector< std::string > &locations, std::string_view filename)
Search for a regular file across candidate locations.
void apply_uimanager_commands(const std::string &command)
Apply a single Geant4 UI command if a UI manager is available.
string searchForDirInLocations(const string &dirName, const vector< string > &possibleLocations)
Searches for a directory within a list of possible locations.
string parseFileAndRemoveComments(const string &filename, const string &commentChars, int verbosity)
Parses a file and removes all lines containing specified comment characters.
string getFileFromPath(const std::string &path)
Extracts the filename from a given file path.
Definition gutilities.cc:71
constexpr const char * to_string(randomModel m) noexcept
Convert a randomModel enum value to a stable string token.
Definition gutilities.h:426
vector< std::string > getStringVectorFromString(const std::string &input)
Splits a string into a vector of strings using whitespace as delimiters.
Definition gutilities.cc:99