gsystem
Loading...
Searching...
No Matches
loadGeometry.cc
Go to the documentation of this file.
1
7
8// gsystem
9#include "systemCadFactory.h"
10#include "gsystemConventions.h"
11
12// gemc
13#include "gutilities.h"
14
15// sqlite
16#include "sqlite3.h"
17
18// c++
19#include <filesystem>
20#include <unordered_map>
21
22using namespace std;
23
24namespace {
25 bool numeric_value(const std::string& value) {
26 try {
27 size_t parsed = 0;
28 std::stod(value, &parsed);
29 return parsed == value.size();
30 }
31 catch (const std::exception&) { return false; }
32 }
33
34 void set_resolved_cad_mesh(std::vector<std::string>& row, const std::string& resolved) {
35 constexpr int PARAMETERS_INDEX = 2;
36 constexpr int DESCRIPTION_INDEX = 19;
37 const auto values =
39 if (values.empty() ||
40 (values.size() == 1 && (values[0] == "NULL" || numeric_value(values[0])))) {
41 row[DESCRIPTION_INDEX] = resolved;
42 return;
43 }
44
45 const auto delimiter = row[PARAMETERS_INDEX].find(',');
46 const auto suffix = delimiter == std::string::npos ? "" : row[PARAMETERS_INDEX].substr(delimiter);
47 row[PARAMETERS_INDEX] = resolved + suffix;
48 }
49
51 bool geometry_column_exists(sqlite3* db, const std::string& column_name) {
52 sqlite3_stmt* stmt = nullptr;
53 if (sqlite3_prepare_v2(db, "SELECT name FROM PRAGMA_TABLE_INFO('geometry')", -1, &stmt, nullptr) != SQLITE_OK) {
54 return false;
55 }
56 bool exists = false;
57 while (sqlite3_step(stmt) == SQLITE_ROW) {
58 const unsigned char* colText = sqlite3_column_text(stmt, 0);
59 if (colText != nullptr && column_name == reinterpret_cast<const char*>(colText)) {
60 exists = true;
61 break;
62 }
63 }
64 sqlite3_finalize(stmt);
65 return exists;
66 }
67}
68
69void GSystemCADFactory::loadGeometry(GSystem* s) {
70 // skip ROOT system
71 if (s->getName() == gsystem::ROOTWORLDGVOLUMENAME) { return; }
72
73 // Resolve the directory holding the CAD meshes.
75 if (!dirLocation) {
76 log->error(gsystem::ERR_GDIRNOTFOUND, "CAD Directory >" + s->getFilePath() + "< not found.");
77 }
78
79 // Map each available mesh file to its stem (filename without extension), which is the volume name.
80 unordered_map<string, string> meshByName;
81 for (const auto& cf : gutilities::getListOfFilesInDirectory(dirLocation->string(), {".stl", ".ply"})) {
82 meshByName[filesystem::path(cf).stem().string()] = cf;
83 }
84
85 // The list of volumes to load - and their metadata - comes from the sqlite database, not from the
86 // directory listing: only meshes that have a matching row in the geometry table are imported.
87 string dbhost = s->get_dbhost();
88 if (dbhost.empty() || dbhost == "na") { dbhost = gsystem::GSYSTEMSQLITETDEFAULTFILE; }
89
90 vector<string> dirs = {
91 ".",
92 gutilities::gemc_root().string(),
93 (gutilities::gemc_root() / "examples").string()
94 };
95 auto dbPath = gutilities::searchForFileInLocations(dirs, dbhost);
96 if (!dbPath) {
97 log->error(gsystem::ERR_GSQLITEERROR, "CAD factory: sqlite database <" + dbhost + "> not found.");
98 return;
99 }
100
101 sqlite3* db = nullptr;
102 if (sqlite3_open_v2(dbPath.value().c_str(), &db, SQLITE_OPEN_READONLY, nullptr) != SQLITE_OK) {
103 sqlite3_close(db);
104 log->error(gsystem::ERR_GSQLITEERROR, "CAD factory: failed to open sqlite database <" + dbhost + ">.");
105 return;
106 }
107 log->info(1, "CAD factory: reading definitions from sqlite database ", dbPath.value());
108
109 const string placement_column = geometry_column_exists(db, "g4placement_type")
110 ? "g4placement_type"
111 : "'" + string(gsystem::DEFAULTG4PLACEMENTTYPE) +
112 "' AS g4placement_type";
113 const string sql_query =
114 "SELECT DISTINCT name, solid, parameters, material, mother, position, rotations, " +
115 placement_column +
116 ", mfield, visible, style, color, opacity, digitization, identifier, copyOf, solidsOpr, mirror, "
117 "exist, description FROM geometry WHERE experiment = ? AND system = ? AND variation = ? AND run = ?";
118
119 sqlite3_stmt* stmt = nullptr;
120 if (sqlite3_prepare_v2(db, sql_query.c_str(), -1, &stmt, nullptr) != SQLITE_OK) {
121 log->error(gsystem::ERR_GSQLITEERROR, "CAD factory: error preparing query: ", sqlite3_errmsg(db));
122 sqlite3_close(db);
123 return;
124 }
125
126 string experiment = s->getExperiment();
127 string system_name = s->getName();
128 string variation = s->getVariation();
129 int runno = s->getRunno();
130
131 sqlite3_bind_text(stmt, 1, experiment.c_str(), -1, SQLITE_TRANSIENT);
132 sqlite3_bind_text(stmt, 2, system_name.c_str(), -1, SQLITE_TRANSIENT);
133 sqlite3_bind_text(stmt, 3, variation.c_str(), -1, SQLITE_TRANSIENT);
134 sqlite3_bind_int(stmt, 4, runno);
135
136 int loaded = 0;
137 int rc;
138 while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) {
139 vector<string> gvolumePars;
140 const int colCount = sqlite3_column_count(stmt);
141 for (int i = 0; i < colCount; i++) {
142 const unsigned char* colText = sqlite3_column_text(stmt, i);
143 gvolumePars.emplace_back(colText ? reinterpret_cast<const char*>(colText) : "");
144 }
145
146 const string& volumeName = gvolumePars[0];
147 const string& solidType = gvolumePars[1];
148
149 // Only CAD volumes are resolved against the mesh directory. A CAD volume defined in the
150 // database but missing its mesh file is skipped with a warning.
151 if (solidType == gsystem::GSYSTEMCADTFACTORYLABEL) {
152 auto it = meshByName.find(volumeName);
153 if (it == meshByName.end()) {
154 log->warning("CAD factory: volume <", volumeName,
155 "> is defined in the database but no mesh file was found in <",
156 dirLocation->string(), ">; skipping.");
157 continue;
158 }
159 set_resolved_cad_mesh(gvolumePars, (*dirLocation / it->second).string());
160 }
161
162 s->addGVolume(gvolumePars);
163 loaded++;
164 }
165
166 if (rc != SQLITE_DONE) {
168 "CAD factory: sqlite error while reading geometry: ", sqlite3_errmsg(db));
169 }
170
171 sqlite3_finalize(stmt);
172 sqlite3_close(db);
173
174 log->info(0, "CAD factory: loaded ", loaded, " volume(s) for system <", system_name,
175 ">, variation <", variation, ">, run ", runno,
176 " (", meshByName.size(), " mesh file(s) present in <", dirLocation->string(), ">).");
177}
std::shared_ptr< GLogger > log
std::vector< std::string > possibleLocationOfFiles
List of candidate directories used by file-based factories.
Represents a single detector system (e.g., calorimeter, tracker).
Definition gsystem.h:34
std::string getFilePath() const
Gets the full file path of the system.
Definition gsystem.cc:236
int getRunno() const
Definition gsystem.h:128
std::string getExperiment() const
Definition gsystem.h:126
std::string getVariation() const
Definition gsystem.h:125
void addGVolume(std::vector< std::string > pars)
Build and add a volume from a serialized parameter list.
Definition gsystem.cc:90
std::string getName() const
Definition gsystem.h:123
std::string get_dbhost() const
Definition gsystem.h:129
Conventions and shared constants for the detector-system module.
constexpr char GSYSTEMSQLITETDEFAULTFILE[]
Default sqlite DB filename used when the user does not specify one.
constexpr char DEFAULTG4PLACEMENTTYPE[]
constexpr char GSYSTEMCADTFACTORYLABEL[]
constexpr int ERR_GSQLITEERROR
constexpr char ROOTWORLDGVOLUMENAME[]
Canonical name for the ROOT/world gvolume entry.
constexpr int ERR_GDIRNOTFOUND
vector< string > getStringVectorFromStringWithDelimiter(const string &input, const string &x)
std::filesystem::path gemc_root()
vector< string > getListOfFilesInDirectory(const string &dirName, const vector< string > &extensions)
std::optional< std::string > searchForFileInLocations(const std::vector< std::string > &locations, std::string_view filename)
std::optional< std::filesystem::path > searchForDirInLocations(const string &dirName, const vector< string > &possibleLocations)