6 #include "CLHEP/Units/PhysicalConstants.h"
12 #include <unordered_map>
22 size_t startPos = input.find_first_not_of(
" \t");
23 size_t endPos = input.find_last_not_of(
" \t");
26 if (startPos == std::string::npos || endPos == std::string::npos) {
return ""; }
29 return input.substr(startPos, endPos - startPos + 1);
34 result.erase(std::remove(result.begin(), result.end(),
' '), result.end());
39 std::size_t lastSlashPos = path.find_last_of(
'/');
40 if (lastSlashPos == std::string::npos) {
44 return path.substr(lastSlashPos + 1);
48 auto lastSlash = path.find_last_of(
'/');
49 if (lastSlash == std::string::npos)
return ".";
50 return path.substr(0, lastSlash);
53 namespace fs = std::filesystem;
57 std::vector<std::string> pvalues;
58 std::stringstream plist(input);
60 while (plist >> tmp) {
62 if (!trimmed.empty()) { pvalues.push_back(trimmed); }
69 const std::string& replacement) {
71 for (
const char& ch : input) {
72 if (toReplace.find(ch) != std::string::npos) { output.append(replacement); }
73 else { output.push_back(ch); }
79 if (from.empty())
return source;
83 size_t findPos = source.find(from, lastPos);
85 while (findPos != string::npos) {
87 newString.append(source, lastPos, findPos - lastPos);
89 lastPos = findPos + from.length();
90 findPos = source.find(from, lastPos);
94 newString += source.substr(lastPos);
100 string fillDigits(
const string& word,
const string& c,
int ndigits) {
101 if (c.empty() || ndigits <=
static_cast<int>(word.size()))
return word;
105 int toFill = ndigits -
static_cast<int>(word.size());
106 filled.reserve(ndigits);
108 filled.append(toFill, c[0]);
119 if (value.find(
'*') == string::npos) {
120 if (!value.empty() && warnIfNotUnit && stod(value) != 0) { std::cerr <<
" ! Warning: value " << v <<
" does not contain units." << std::endl; }
122 try {
return stod(value); }
123 catch (
const std::exception& e) {
124 std::cerr <<
FATALERRORL <<
"stod exception in gutilities: could not convert string to double. "
125 <<
"Value: >" << v <<
"<, error: " << e.what() << std::endl;
131 size_t pos = value.find(
'*');
132 string rootValue = value.substr(0, pos);
133 string units = value.substr(pos + 1);
136 try { answer = stod(rootValue); }
137 catch (
const std::exception& e) {
138 std::cerr <<
FATALERRORL <<
"stod exception in gutilities: could not convert string to double. "
139 <<
"Value: >" << v <<
"<, error: " << e.what() << std::endl;
144 static const std::unordered_map<string, double> unitConversion = {
148 {
"um", 1E-6 * CLHEP::m},
149 {
"fm", 1E-15 * CLHEP::m},
150 {
"inches", 2.54 * CLHEP::cm},
151 {
"inch", 2.54 * CLHEP::cm},
153 {
"degrees", CLHEP::deg},
154 {
"arcmin", CLHEP::deg / 60.0},
156 {
"mrad", CLHEP::mrad},
159 {
"KeV", 0.001 * CLHEP::MeV},
162 {
"T/m", CLHEP::tesla / CLHEP::m},
163 {
"Tesla", CLHEP::tesla},
164 {
"gauss", CLHEP::gauss},
165 {
"kilogauss", CLHEP::gauss * 1000},
173 auto it = unitConversion.find(units);
174 if (it != unitConversion.end()) { answer *= it->second; }
175 else { std::cerr <<
GWARNING <<
">" << units <<
"<: unit not recognized for string <" << v <<
">" << std::endl; }
187 vector<double> output;
188 output.reserve(vstring.size());
190 for (
const auto& s : vstring) { output.push_back(
getG4Number(s, warnIfNotUnit)); }
202 std::ifstream in(filename);
204 std::cerr <<
FATALERRORL <<
"can't open input file " << filename <<
". Check your spelling. " << std::endl;
208 std::stringstream strStream;
209 if (verbosity > 0) { std::cout << std::endl <<
CIRCLEITEM <<
" Loading string from " << filename << std::endl; }
210 strStream << in.rdbuf();
213 string parsedString = strStream.str();
217 while ((nFPos = parsedString.find(commentChars)) != string::npos) {
218 size_t firstNL = parsedString.rfind(
'\n', nFPos);
219 size_t secondNL = parsedString.find(
'\n', nFPos);
220 parsedString.erase(firstNL, secondNL - firstNL);
227 size_t firstpos = input.find(firstDelimiter);
228 size_t secondpos = input.find(secondDelimiter);
230 if (firstpos == string::npos || secondpos == string::npos) {
return ""; }
231 return input.substr(firstpos + firstDelimiter.length(), secondpos - firstpos - firstDelimiter.length());
235 vector<string> pvalues;
238 for (
char ch : input) {
239 if (ch != x[0]) { tmp += ch; }
288 #include <sys/stat.h>
292 if (stat(path.c_str(), &info) != 0) {
295 return (info.st_mode & S_IFDIR) != 0;
299 for (
const auto& trialLocation : possibleLocations) {
300 string possibleDir = trialLocation +
"/" + dirName;
303 return "UNINITIALIZEDSTRINGQUANTITY";
307 bool hasExtension(
const std::string& filename,
const std::vector<std::string>& extensions) {
308 for (
const auto& ext : extensions) {
309 if (filename.size() >= ext.size() &&
310 filename.compare(filename.size() - ext.size(), ext.size(), ext) == 0) {
return true; }
316 vector<string> fileList;
318 DIR* dir = opendir(dirName.c_str());
320 struct dirent* entry;
321 while ((entry = readdir(dir)) !=
nullptr) {
323 string filepath = dirName +
"/" + entry->d_name;
324 if (stat(filepath.c_str(), &info) == 0 && S_ISREG(info.st_mode)) {
325 string filename = entry->d_name;
326 if (
hasExtension(filename, extensions)) { fileList.push_back(filename); }
337 transform(lower.begin(), lower.end(), lower.begin(), ::tolower);
342 template <
class KEY,
class VALUE>
343 vector<KEY>
getKeys(
const map<KEY, VALUE>& map) {
345 keys.reserve(map.size());
347 for (
const auto& it : map) { keys.push_back(it.first); }
353 static const std::unordered_map<std::string, randomModel> strToEnum = {
360 auto it = strToEnum.find(str);
361 if (it != strToEnum.end()) {
return it->second; }
362 else {
throw std::invalid_argument(
"Invalid string for randomModel: " + str); }
367 if (code.empty())
throw std::invalid_argument(
"empty colour string");
368 if (code.front() ==
'#') code.remove_prefix(1);
369 if (code.size() != 6 && code.size() != 7)
370 throw std::invalid_argument(
"colour must have 6 or 7 hex digits");
372 auto hexNibble = [](
char c) ->
unsigned {
373 if (
'0' <= c && c <=
'9')
return c -
'0';
374 c =
static_cast<char>(std::toupper(
static_cast<unsigned char>(c)));
375 if (
'A' <= c && c <=
'F')
return c -
'A' + 10;
376 throw std::invalid_argument(
"invalid hex digit");
381 for (
int i = 0; i < 6; ++i)
382 rgb = (rgb << 4) | hexNibble(code[i]);
384 auto byteToDouble = [](
unsigned byte) {
return byte / 255.0; };
385 double r = byteToDouble((rgb >> 16) & 0xFF);
386 double g = byteToDouble((rgb >> 8) & 0xFF);
387 double b = byteToDouble(rgb & 0xFF);
391 if (code.size() == 7)
392 a = hexNibble(code[6]) / 15.0;
#define GWARNING
Warning label.
#define EC__FILENOTFOUND
File not found error code.
#define CIRCLEITEM
Symbol for circle item.
#define EC__G4NUMBERERROR
G4 number error code.
#define FATALERRORL
Fatal error label.
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.
vector< string > getStringVectorFromStringWithDelimiter(const string &input, const string &x)
Splits a string into a vector of substrings using a specified delimiter.
randomModel stringToRandomModel(const std::string &str)
Converts a string to a corresponding randomModel enum value.
constexpr const char * to_string(randomModel m) noexcept
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.
randomModel
Enumeration of random models.
@ gaussian
Gaussian distribution.
@ uniform
Uniform distribution.
@ sphere
Sphere distribution.
@ cosine
Cosine distribution.
string getDirFromPath(const std::string &path)
Extracts the directory path from a given file path.
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.
G4Colour makeColour(std::string_view code)
Convert a hex colour string to G4Colour.
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.
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.
vector< std::string > getStringVectorFromString(const std::string &input)
Splits a string into a vector of strings using spaces as delimiters.