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#include <filesystem>
10
11// geant4
12#include "G4Colour.hh"
13#include "G4SystemOfUnits.hh"
14#include "G4UnitsTable.hh"
15
16namespace gemc_units {
17 inline constexpr G4double milligray = 1.e-3 * gray;
18 inline constexpr G4double microgray = 1.e-6 * gray;
19 inline constexpr G4double nanogray = 1.e-9 * gray;
20 inline constexpr G4double picogray = 1.e-12 * gray;
21}
22
23
24
37
38namespace gutilities {
39using std::string;
40using std::vector;
41using std::map;
42
47
64std::string removeLeadingAndTrailingSpacesFromString(const std::string& input);
65
79std::string_view removeLeadingAndTrailingSpacesFromString(const std::string_view input);
80
90std::string removeAllSpacesFromString(const std::string& str);
91
101std::vector<std::string> getStringVectorFromString(const std::string& input);
102
117std::string replaceCharInStringWithChars(const std::string& input, const std::string& toReplace,
118 const std::string& replacement);
119
134std::optional<std::string> closestMatch(const std::string& query,
135 const std::vector<std::string>& candidates,
136 std::size_t max_distance = 3);
137
138
152string replaceAllStringsWithString(const string& source, const string& from, const string& to);
153
165string fillDigits(const string& word, const string& c, int ndigits);
166
168
173
185std::string getFileFromPath(const std::string& path);
186
199std::string getDirFromPath(const std::string& path);
200
216std::optional<std::string> searchForFileInLocations(
217 const std::vector<std::string>& locations,
218 std::string_view filename);
219
229bool directoryExists(const std::string& path);
230
240std::optional<std::filesystem::path> searchForDirInLocations(
241 const string& dirName, const vector<string>& possibleLocations);
242
254bool hasExtension(const string& filename, const vector<string>& extensions);
255
267vector<string> getListOfFilesInDirectory(const string& dirName, const vector<string>& extensions);
268
270
275
299double getG4Number(const string& v, bool warnIfNotUnit = false);
300
311double getG4Number(double input, const string& unit);
312
322vector<double> getG4NumbersFromStringVector(const vector<string>& vstring, bool warnIfNotUnit = false);
323
335vector<double> getG4NumbersFromString(const string& vstring, bool warnIfNotUnit = false);
336
338
343
358string parseFileAndRemoveComments(const string& filename, const string& commentChars = "#", int verbosity = 0);
359
360
375string retrieveStringBetweenChars(const string& input, const string& firstDelimiter,
376 const string& secondDelimiter);
377
378
390vector<string> getStringVectorFromStringWithDelimiter(const string& input, const string& x);
391
393
398
408string convertToLowercase(const string& str);
409
420template <class KEY, class VALUE>
421vector<KEY> getKeys(const map<KEY, VALUE>& map);
422
436
447randomModel stringToRandomModel(const std::string& str);
448
457inline constexpr const char* to_string(randomModel m) noexcept {
458 switch (m) {
459 case uniform: return "uniform";
460 case gaussian: return "gaussian";
461 case cosine: return "cosine";
462 case sphere: return "sphere";
463 }
464 return "<unknown>";
465}
466
482G4Colour makeG4Colour(std::string_view code, double opacity);
483
485};
486
487
488#include <filesystem>
489
490#if defined(__APPLE__)
491#include <mach-o/dyld.h> // _NSGetExecutablePath
492#elif defined(__linux__)
493#include <unistd.h> // readlink
494#include <limits.h>
495#elif defined(_WIN32)
496#include <windows.h>
497#include <vector>
498#else
499#error "Unsupported platform"
500#endif
501
502namespace gutilities {
518inline std::filesystem::path executable_path() {
519#if defined(__APPLE__)
520 char buf[PATH_MAX];
521 uint32_t sz = sizeof(buf);
522 if (_NSGetExecutablePath(buf, &sz) != 0) {
523 // buffer too small
524 std::string big(sz, '\0');
525 if (_NSGetExecutablePath(big.data(), &sz) != 0)
526 throw std::runtime_error("_NSGetExecutablePath failed");
527 return std::filesystem::canonical(big);
528 }
529 return std::filesystem::canonical(buf);
530
531#elif defined(__linux__)
532 char buf[PATH_MAX];
533 ssize_t len = ::readlink("/proc/self/exe", buf, sizeof(buf) - 1);
534 if (len == -1)
535 throw std::runtime_error("readlink(/proc/self/exe) failed");
536 buf[len] = '\0';
537 return std::filesystem::canonical(buf);
538
539#elif defined(_WIN32)
540 std::wstring buf(MAX_PATH, L'\0');
541 DWORD len = ::GetModuleFileNameW(nullptr, buf.data(), buf.size());
542 if (len == 0)
543 throw std::runtime_error("GetModuleFileNameW failed");
544 // If the path is longer than MAX_PATH the buffer is truncated;
545 // do a second call with the returned length to get the full path.
546 if (len == buf.size()) {
547 buf.resize(len * 2);
548 len = ::GetModuleFileNameW(nullptr, buf.data(), buf.size());
549 }
550 buf.resize(len);
551 return std::filesystem::canonical(std::filesystem::path(buf));
552#endif
553}
554
570inline std::filesystem::path gemc_root() {
571 const auto exe_dir = executable_path().parent_path();
572
573 std::filesystem::path root;
574
575 // Case 1: executable is directly in the build directory (legacy build-tree layout)
576 if (exe_dir.filename() == "build") {
577 root = exe_dir.parent_path();
578 }
579 // Case 2: executable is in a bin/ subdirectory — installed or build/bin/
580 else if (exe_dir.filename() == "bin") {
581 root = exe_dir.parent_path();
582 if (std::filesystem::exists(root / "build.ninja")) {
583 // Running from build/bin/: step up one more level to match the legacy build-tree root
584 root = root.parent_path();
585 } else if (!std::filesystem::exists(root / "lib")) {
586 throw std::runtime_error(
587 "Cannot locate directory <lib> under " + root.string() +
588 ". Check installation layout."
589 );
590 }
591 }
592
593 return root;
594}
595
596
610bool is_unset(std::string_view s);
611
620inline std::string success_or_fail(bool condition) { return condition ? "success" : "fail"; }
621
632void apply_uimanager_commands(const std::string& commands);
633}
constexpr G4double milligray
Definition gutilities.h:17
constexpr G4double nanogray
Definition gutilities.h:19
constexpr G4double microgray
Definition gutilities.h:18
constexpr G4double picogray
Definition gutilities.h:20
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.
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:68
std::filesystem::path executable_path()
Get the absolute canonical path to the current executable.
Definition gutilities.h:518
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:570
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.
std::optional< std::string > closestMatch(const std::string &query, const std::vector< std::string > &candidates, std::size_t max_distance)
Returns the candidate closest to query, for "did you mean ...?" suggestions.
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:620
bool is_unset(std::string_view s)
Determine whether a string should be treated as "unset".
randomModel
Enumeration of random models.
Definition gutilities.h:430
@ gaussian
Gaussian distribution.
Definition gutilities.h:432
@ uniform
Uniform distribution.
Definition gutilities.h:431
@ sphere
Sphere distribution.
Definition gutilities.h:434
@ cosine
Cosine distribution.
Definition gutilities.h:433
string getDirFromPath(const std::string &path)
Extracts the directory path from a given file path.
Definition gutilities.cc:93
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:37
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.
std::optional< std::filesystem::path > 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.
bool hasExtension(const std::string &filename, const std::vector< std::string > &extensions)
string getFileFromPath(const std::string &path)
Extracts the filename from a given file path.
Definition gutilities.cc:79
constexpr const char * to_string(randomModel m) noexcept
Convert a randomModel enum value to a stable string token.
Definition gutilities.h:457
vector< std::string > getStringVectorFromString(const std::string &input)
Splits a string into a vector of strings using whitespace as delimiters.