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 "G4SystemOfUnits.hh"
13#include "G4UnitsTable.hh"
14
15namespace gemc_units {
16 inline constexpr G4double milligray = 1.e-3 * gray;
17 inline constexpr G4double microgray = 1.e-6 * gray;
18 inline constexpr G4double nanogray = 1.e-9 * gray;
19 inline constexpr G4double picogray = 1.e-12 * gray;
20}
21
22
23
36
37namespace gutilities {
38using std::string;
39using std::vector;
40using std::map;
41
46
63std::string removeLeadingAndTrailingSpacesFromString(const std::string& input);
64
78std::string_view removeLeadingAndTrailingSpacesFromString(const std::string_view input);
79
89std::string removeAllSpacesFromString(const std::string& str);
90
100std::vector<std::string> getStringVectorFromString(const std::string& input);
101
116std::string replaceCharInStringWithChars(const std::string& input, const std::string& toReplace,
117 const std::string& replacement);
118
119
133string replaceAllStringsWithString(const string& source, const string& from, const string& to);
134
146string fillDigits(const string& word, const string& c, int ndigits);
147
149
154
166std::string getFileFromPath(const std::string& path);
167
180std::string getDirFromPath(const std::string& path);
181
197std::optional<std::string> searchForFileInLocations(
198 const std::vector<std::string>& locations,
199 std::string_view filename);
200
210bool directoryExists(const std::string& path);
211
224string searchForDirInLocations(const string& dirName, const vector<string>& possibleLocations);
225
237bool hasExtension(const string& filename, const vector<string>& extensions);
238
250vector<string> getListOfFilesInDirectory(const string& dirName, const vector<string>& extensions);
251
253
258
282double getG4Number(const string& v, bool warnIfNotUnit = false);
283
294double getG4Number(double input, const string& unit);
295
305vector<double> getG4NumbersFromStringVector(const vector<string>& vstring, bool warnIfNotUnit = false);
306
318vector<double> getG4NumbersFromString(const string& vstring, bool warnIfNotUnit = false);
319
321
326
341string parseFileAndRemoveComments(const string& filename, const string& commentChars = "#", int verbosity = 0);
342
343
358string retrieveStringBetweenChars(const string& input, const string& firstDelimiter,
359 const string& secondDelimiter);
360
361
373vector<string> getStringVectorFromStringWithDelimiter(const string& input, const string& x);
374
376
381
391string convertToLowercase(const string& str);
392
403template <class KEY, class VALUE>
404vector<KEY> getKeys(const map<KEY, VALUE>& map);
405
419
430randomModel stringToRandomModel(const std::string& str);
431
440inline constexpr const char* to_string(randomModel m) noexcept {
441 switch (m) {
442 case uniform: return "uniform";
443 case gaussian: return "gaussian";
444 case cosine: return "cosine";
445 case sphere: return "sphere";
446 }
447 return "<unknown>";
448}
449
465G4Colour makeG4Colour(std::string_view code, double opacity);
466
468};
469
470
471#include <filesystem>
472
473#if defined(__APPLE__)
474#include <mach-o/dyld.h> // _NSGetExecutablePath
475#elif defined(__linux__)
476#include <unistd.h> // readlink
477#include <limits.h>
478#elif defined(_WIN32)
479#include <windows.h>
480#include <vector>
481#else
482#error "Unsupported platform"
483#endif
484
485namespace gutilities {
501inline std::filesystem::path executable_path() {
502#if defined(__APPLE__)
503 char buf[PATH_MAX];
504 uint32_t sz = sizeof(buf);
505 if (_NSGetExecutablePath(buf, &sz) != 0) {
506 // buffer too small
507 std::string big(sz, '\0');
508 if (_NSGetExecutablePath(big.data(), &sz) != 0)
509 throw std::runtime_error("_NSGetExecutablePath failed");
510 return std::filesystem::canonical(big);
511 }
512 return std::filesystem::canonical(buf);
513
514#elif defined(__linux__)
515 char buf[PATH_MAX];
516 ssize_t len = ::readlink("/proc/self/exe", buf, sizeof(buf) - 1);
517 if (len == -1)
518 throw std::runtime_error("readlink(/proc/self/exe) failed");
519 buf[len] = '\0';
520 return std::filesystem::canonical(buf);
521
522#elif defined(_WIN32)
523 std::wstring buf(MAX_PATH, L'\0');
524 DWORD len = ::GetModuleFileNameW(nullptr, buf.data(), buf.size());
525 if (len == 0)
526 throw std::runtime_error("GetModuleFileNameW failed");
527 // If the path is longer than MAX_PATH the buffer is truncated;
528 // do a second call with the returned length to get the full path.
529 if (len == buf.size()) {
530 buf.resize(len * 2);
531 len = ::GetModuleFileNameW(nullptr, buf.data(), buf.size());
532 }
533 buf.resize(len);
534 return std::filesystem::canonical(std::filesystem::path(buf));
535#endif
536}
537
553inline std::filesystem::path gemc_root() {
554 const auto exe_dir = executable_path().parent_path();
555
556 std::filesystem::path root;
557
558 // Case 1: executable is directly in the build directory (legacy build-tree layout)
559 if (exe_dir.filename() == "build") {
560 root = exe_dir.parent_path();
561 }
562 // Case 2: executable is in a bin/ subdirectory — installed or build/bin/
563 else if (exe_dir.filename() == "bin") {
564 root = exe_dir.parent_path();
565 if (std::filesystem::exists(root / "build.ninja")) {
566 // Running from build/bin/: step up one more level to match the legacy build-tree root
567 root = root.parent_path();
568 } else if (!std::filesystem::exists(root / "lib")) {
569 throw std::runtime_error(
570 "Cannot locate directory <lib> under " + root.string() +
571 ". Check installation layout."
572 );
573 }
574 }
575
576 return root;
577}
578
579
593bool is_unset(std::string_view s);
594
603inline std::string success_or_fail(bool condition) { return condition ? "success" : "fail"; }
604
615void apply_uimanager_commands(const std::string& commands);
616}
constexpr G4double milligray
Definition gutilities.h:16
constexpr G4double nanogray
Definition gutilities.h:18
constexpr G4double microgray
Definition gutilities.h:17
constexpr G4double picogray
Definition gutilities.h:19
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:501
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:553
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:603
bool is_unset(std::string_view s)
Determine whether a string should be treated as "unset".
randomModel
Enumeration of random models.
Definition gutilities.h:413
@ gaussian
Gaussian distribution.
Definition gutilities.h:415
@ uniform
Uniform distribution.
Definition gutilities.h:414
@ sphere
Sphere distribution.
Definition gutilities.h:417
@ cosine
Cosine distribution.
Definition gutilities.h:416
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.
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.
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:440
vector< std::string > getStringVectorFromString(const std::string &input)
Splits a string into a vector of strings using whitespace as delimiters.