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
37namespace gutilities {
38using std::string;
39using std::vector;
40using std::map;
41
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
166std::string getFileFromPath(const std::string& path);
167
179std::string getDirFromPath(const std::string& path);
180
196std::optional<std::string> searchForFileInLocations(
197 const std::vector<std::string>& locations,
198 std::string_view filename);
199
209bool directoryExists(const std::string& path);
210
223string searchForDirInLocations(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
280double getG4Number(const string& v, bool warnIfNotUnit = false);
281
292double getG4Number(double input, const string& unit);
293
303vector<double> getG4NumbersFromStringVector(const vector<string>& vstring, bool warnIfNotUnit = false);
304
316vector<double> getG4NumbersFromString(const string& vstring, bool warnIfNotUnit = false);
317
339string parseFileAndRemoveComments(const string& filename, const string& commentChars = "#", int verbosity = 0);
340
341
355string retrieveStringBetweenChars(const string& input, const string& firstDelimiter, const string& secondDelimiter);
356
357
369vector<string> getStringVectorFromStringWithDelimiter(const string& input, const string& x);
370
387string convertToLowercase(const string& str);
388
399template <class KEY, class VALUE>
400vector<KEY> getKeys(const map<KEY, VALUE>& map);
401
415
426randomModel stringToRandomModel(const std::string& str);
427
436inline constexpr const char* to_string(randomModel m) noexcept {
437 switch (m) {
438 case uniform: return "uniform";
439 case gaussian: return "gaussian";
440 case cosine: return "cosine";
441 case sphere: return "sphere";
442 }
443 return "<unknown>";
444}
445
461G4Colour makeG4Colour(std::string_view code, double opacity);
462
464};
465
466
467#include <filesystem>
468
469#if defined(__APPLE__)
470#include <mach-o/dyld.h> // _NSGetExecutablePath
471#elif defined(__linux__)
472#include <unistd.h> // readlink
473#include <limits.h>
474#elif defined(_WIN32)
475#include <windows.h>
476#include <vector>
477#else
478#error "Unsupported platform"
479#endif
480
481namespace gutilities {
497inline std::filesystem::path executable_path() {
498#if defined(__APPLE__)
499 char buf[PATH_MAX];
500 uint32_t sz = sizeof(buf);
501 if (_NSGetExecutablePath(buf, &sz) != 0) {
502 // buffer too small
503 std::string big(sz, '\0');
504 if (_NSGetExecutablePath(big.data(), &sz) != 0)
505 throw std::runtime_error("_NSGetExecutablePath failed");
506 return std::filesystem::canonical(big);
507 }
508 return std::filesystem::canonical(buf);
509
510#elif defined(__linux__)
511 char buf[PATH_MAX];
512 ssize_t len = ::readlink("/proc/self/exe", buf, sizeof(buf) - 1);
513 if (len == -1)
514 throw std::runtime_error("readlink(/proc/self/exe) failed");
515 buf[len] = '\0';
516 return std::filesystem::canonical(buf);
517
518#elif defined(_WIN32)
519 std::wstring buf(MAX_PATH, L'\0');
520 DWORD len = ::GetModuleFileNameW(nullptr, buf.data(), buf.size());
521 if (len == 0)
522 throw std::runtime_error("GetModuleFileNameW failed");
523 // If the path is longer than MAX_PATH the buffer is truncated;
524 // do a second call with the returned length to get the full path.
525 if (len == buf.size()) {
526 buf.resize(len * 2);
527 len = ::GetModuleFileNameW(nullptr, buf.data(), buf.size());
528 }
529 buf.resize(len);
530 return std::filesystem::canonical(std::filesystem::path(buf));
531#endif
532}
533
549inline std::filesystem::path gemc_root() {
550 const auto exe_dir = executable_path().parent_path();
551
552 std::filesystem::path root;
553
554 // Case 1: executable came from ../bin or (for tests) build
555 if (exe_dir.filename() == "bin" || exe_dir.filename() == "build") {
556 root = exe_dir.parent_path();
557 }
558 // else {
559 // // Case 2: use GEMC environment variable
560 // const char* env = std::getenv("GEMC");
561 // if (!env || std::string(env).empty()) {
562 // throw std::runtime_error(
563 // "GEMC executable not in <.../bin>. Environment variable GEMC is required."
564 // );
565 // }
566 // root = std::filesystem::path(env);
567 // }
568
569 // Sanity check
570 if (!std::filesystem::exists(root / "api")) {
571 throw std::runtime_error(
572 "Cannot locate directory <api> under " + root.string() +
573 ". Check installation layout or GEMC environment variable."
574 );
575 }
576
577 return root;
578}
579
580
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.
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:64
std::filesystem::path executable_path()
Get the absolute canonical path to the current executable.
Definition gutilities.h:497
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:549
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:409
@ gaussian
Gaussian distribution.
Definition gutilities.h:411
@ uniform
Uniform distribution.
Definition gutilities.h:410
@ sphere
Sphere distribution.
Definition gutilities.h:413
@ cosine
Cosine distribution.
Definition gutilities.h:412
string getDirFromPath(const std::string &path)
Extracts the directory path from a given file path.
Definition gutilities.cc:89
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:33
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:75
constexpr const char * to_string(randomModel m) noexcept
Convert a randomModel enum value to a stable string token.
Definition gutilities.h:436
vector< std::string > getStringVectorFromString(const std::string &input)
Splits a string into a vector of strings using whitespace as delimiters.