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
120
134string replaceAllStringsWithString(const string& source, const string& from, const string& to);
135
147string fillDigits(const string& word, const string& c, int ndigits);
148
150
155
167std::string getFileFromPath(const std::string& path);
168
181std::string getDirFromPath(const std::string& path);
182
198std::optional<std::string> searchForFileInLocations(
199 const std::vector<std::string>& locations,
200 std::string_view filename);
201
211bool directoryExists(const std::string& path);
212
222std::optional<std::filesystem::path> searchForDirInLocations(
223 const string& dirName, const vector<string>& possibleLocations);
224
236bool hasExtension(const string& filename, const vector<string>& extensions);
237
249vector<string> getListOfFilesInDirectory(const string& dirName, const vector<string>& extensions);
250
252
257
281double getG4Number(const string& v, bool warnIfNotUnit = false);
282
293double getG4Number(double input, const string& unit);
294
304vector<double> getG4NumbersFromStringVector(const vector<string>& vstring, bool warnIfNotUnit = false);
305
317vector<double> getG4NumbersFromString(const string& vstring, bool warnIfNotUnit = false);
318
320
325
340string parseFileAndRemoveComments(const string& filename, const string& commentChars = "#", int verbosity = 0);
341
342
357string retrieveStringBetweenChars(const string& input, const string& firstDelimiter,
358 const string& secondDelimiter);
359
360
372vector<string> getStringVectorFromStringWithDelimiter(const string& input, const string& x);
373
375
380
390string convertToLowercase(const string& str);
391
402template <class KEY, class VALUE>
403vector<KEY> getKeys(const map<KEY, VALUE>& map);
404
418
429randomModel stringToRandomModel(const std::string& str);
430
439inline constexpr const char* to_string(randomModel m) noexcept {
440 switch (m) {
441 case uniform: return "uniform";
442 case gaussian: return "gaussian";
443 case cosine: return "cosine";
444 case sphere: return "sphere";
445 }
446 return "<unknown>";
447}
448
464G4Colour makeG4Colour(std::string_view code, double opacity);
465
467};
468
469
470#include <filesystem>
471
472#if defined(__APPLE__)
473#include <mach-o/dyld.h> // _NSGetExecutablePath
474#elif defined(__linux__)
475#include <unistd.h> // readlink
476#include <limits.h>
477#elif defined(_WIN32)
478#include <windows.h>
479#include <vector>
480#else
481#error "Unsupported platform"
482#endif
483
484namespace gutilities {
500inline std::filesystem::path executable_path() {
501#if defined(__APPLE__)
502 char buf[PATH_MAX];
503 uint32_t sz = sizeof(buf);
504 if (_NSGetExecutablePath(buf, &sz) != 0) {
505 // buffer too small
506 std::string big(sz, '\0');
507 if (_NSGetExecutablePath(big.data(), &sz) != 0)
508 throw std::runtime_error("_NSGetExecutablePath failed");
509 return std::filesystem::canonical(big);
510 }
511 return std::filesystem::canonical(buf);
512
513#elif defined(__linux__)
514 char buf[PATH_MAX];
515 ssize_t len = ::readlink("/proc/self/exe", buf, sizeof(buf) - 1);
516 if (len == -1)
517 throw std::runtime_error("readlink(/proc/self/exe) failed");
518 buf[len] = '\0';
519 return std::filesystem::canonical(buf);
520
521#elif defined(_WIN32)
522 std::wstring buf(MAX_PATH, L'\0');
523 DWORD len = ::GetModuleFileNameW(nullptr, buf.data(), buf.size());
524 if (len == 0)
525 throw std::runtime_error("GetModuleFileNameW failed");
526 // If the path is longer than MAX_PATH the buffer is truncated;
527 // do a second call with the returned length to get the full path.
528 if (len == buf.size()) {
529 buf.resize(len * 2);
530 len = ::GetModuleFileNameW(nullptr, buf.data(), buf.size());
531 }
532 buf.resize(len);
533 return std::filesystem::canonical(std::filesystem::path(buf));
534#endif
535}
536
552inline std::filesystem::path gemc_root() {
553 const auto exe_dir = executable_path().parent_path();
554
555 std::filesystem::path root;
556
557 // Case 1: executable is directly in the build directory (legacy build-tree layout)
558 if (exe_dir.filename() == "build") {
559 root = exe_dir.parent_path();
560 }
561 // Case 2: executable is in a bin/ subdirectory — installed or build/bin/
562 else if (exe_dir.filename() == "bin") {
563 root = exe_dir.parent_path();
564 if (std::filesystem::exists(root / "build.ninja")) {
565 // Running from build/bin/: step up one more level to match the legacy build-tree root
566 root = root.parent_path();
567 } else if (!std::filesystem::exists(root / "lib")) {
568 throw std::runtime_error(
569 "Cannot locate directory <lib> under " + root.string() +
570 ". Check installation layout."
571 );
572 }
573 }
574
575 return root;
576}
577
578
592bool is_unset(std::string_view s);
593
602inline std::string success_or_fail(bool condition) { return condition ? "success" : "fail"; }
603
614void apply_uimanager_commands(const std::string& commands);
615}
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:500
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:552
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:602
bool is_unset(std::string_view s)
Determine whether a string should be treated as "unset".
randomModel
Enumeration of random models.
Definition gutilities.h:412
@ gaussian
Gaussian distribution.
Definition gutilities.h:414
@ uniform
Uniform distribution.
Definition gutilities.h:413
@ sphere
Sphere distribution.
Definition gutilities.h:416
@ cosine
Cosine distribution.
Definition gutilities.h:415
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:439
vector< std::string > getStringVectorFromString(const std::string &input)
Splits a string into a vector of strings using whitespace as delimiters.