13#include "G4ThreeVector.hh"
14#include "CLHEP/Units/SystemOfUnits.h"
35std::string GField_AsciiMapFactory::param_string(
const std::string& key,
const std::string& dflt)
const {
37 return (it !=
gfield_definitions.field_parameters.end() && !it->second.empty()) ? it->second : dflt;
40double GField_AsciiMapFactory::param_g4number(
const std::string& key,
const std::string& dflt)
const {
44std::string GField_AsciiMapFactory::field_maps_directory()
const {
48 if (dladdr(
reinterpret_cast<const void*
>(&
GFieldFactory), &info) != 0 && info.dli_fname !=
nullptr) {
49 const std::string plugin_path = info.dli_fname;
50 const auto slash = plugin_path.find_last_of(
'/');
51 if (slash != std::string::npos) {
return plugin_path.substr(0, slash) +
"/../fields"; }
53 log->warning(
"GField_AsciiMapFactory: could not resolve plugin path; using ./fields for the map.");
57std::optional<unsigned> GField_AsciiMapFactory::axis_of_coordinate(
const std::string& name)
const {
59 case Symmetry::dipole_x:
60 case Symmetry::dipole_y:
61 case Symmetry::dipole_z:
62 if (name ==
"longitudinal")
return 0;
63 if (name ==
"transverse")
return 1;
68 if (name ==
"transverse")
return 0;
69 if (name ==
"longitudinal")
return 1;
71 case Symmetry::phi_segmented:
72 if (name ==
"azimuthal")
return 0;
73 if (name ==
"transverse")
return 1;
74 if (name ==
"longitudinal")
return 2;
76 case Symmetry::cartesian_3d:
77 case Symmetry::cartesian_3d_quadrant:
78 if (name ==
"X")
return 0;
79 if (name ==
"Y")
return 1;
80 if (name ==
"Z")
return 2;
91void GField_AsciiMapFactory::load_coordinate(
const std::string& key) {
92 const std::string value = param_string(key,
"");
96 "GField_AsciiMapFactory: missing coordinate <%1> for field <%2>.", key,
gfield_definitions.name);
101 if (tokens.size() != 4) {
104 "GField_AsciiMapFactory: coordinate <%1> must be \"name, npoints, min, max\". Got <%2>.", key,
108 const std::string name = tokens[0];
109 const int npoints = std::stoi(tokens[1]);
113 const auto axis = axis_of_coordinate(name);
117 "GField_AsciiMapFactory: coordinate name <%1> is not valid for symmetry <%2>.", name,
124 "GField_AsciiMapFactory: coordinate <%1> needs at least 2 points; got %2.", name, npoints);
127 np[*axis] =
static_cast<unsigned>(npoints);
128 startMap[*axis] = min;
130 cellSize[*axis] = (max - min) / (npoints - 1);
134 const std::string unit = [&]() {
135 for (
const std::string& expr : {tokens[3], tokens[2]}) {
136 const auto star = expr.find(
'*');
137 if (star != std::string::npos) {
141 return std::string(
"mm");
147void GField_AsciiMapFactory::load_map_file() {
148 const std::string map_name = param_string(
"map",
"");
149 if (map_name.empty()) {
159 std::string path = map_name;
160 if (map_name.find(
'/') == std::string::npos) {
161 std::vector<std::string> candidates;
162 if (
const std::string dir = param_string(
"dir",
""); !dir.empty()) { candidates.push_back(dir); }
164 candidates.push_back(field_maps_directory());
167 for (
const auto& dir : candidates) {
168 const std::string trial = dir +
"/" + map_name;
169 if (std::ifstream(trial).good()) { path = trial;
break; }
174 "GField_AsciiMapFactory: cannot find map <%1> for field <%2> in dir/config/plugin locations.",
179 std::ifstream in(path);
184 1,
"Loading ASCII field map <%1> with symmetry <%2>.", path,
188 std::size_t total = np[0];
189 for (
int d = 1; d < ndim; ++d) { total *= np[d]; }
191 const double field_scale = param_g4number(
"scale",
"1") *
194 B1.assign(total, 0.0f);
195 if (ncomp >= 2) { B2.assign(total, 0.0f); }
196 if (ncomp >= 3) { B3.assign(total, 0.0f); }
198 const double tolerance = 0.001;
200 std::size_t read_points = 0;
203 while (std::getline(in, line)) {
206 if (trimmed.empty() || trimmed[0] ==
'#') {
continue; }
208 std::istringstream tokens(trimmed);
212 unsigned grid_index[3] = {0, 0, 0};
214 for (
int c = 0; c < ndim; ++c) {
216 if (!(tokens >> raw)) { line_ok =
false;
break; }
217 const double coord = raw * columns[c].unitFactor;
218 const int axis = columns[c].axis;
219 const unsigned i =
static_cast<unsigned>(
220 std::floor((coord - startMap[axis] + cellSize[axis] / 2) / cellSize[axis]));
221 grid_index[axis] = i;
223 const double expected = startMap[axis] + i * cellSize[axis];
224 if (cellSize[axis] != 0.0 && std::fabs(expected - coord) > tolerance * std::fabs(cellSize[axis])) {
226 "GField_AsciiMapFactory: %1:%2 axis %3 value %4 does not match grid point %5.", path,
227 line_number, axis, coord, expected);
231 double comp[3] = {0.0, 0.0, 0.0};
232 for (
int k = 0; k < ncomp && line_ok; ++k) {
233 if (!(tokens >> comp[k])) { line_ok =
false; }
238 path, line_number, ndim + ncomp);
241 std::size_t flat = (ndim == 2) ? idx2(grid_index[0], grid_index[1])
242 : idx3(grid_index[0], grid_index[1], grid_index[2]);
244 log->warning(
"GField_AsciiMapFactory: %1:%2 maps outside the grid; skipped.", path, line_number);
248 B1[flat] =
static_cast<float>(comp[0] * field_scale);
249 if (ncomp >= 2) { B2[flat] =
static_cast<float>(comp[1] * field_scale); }
250 if (ncomp >= 3) { B3[flat] =
static_cast<float>(comp[2] * field_scale); }
254 if (read_points != total) {
256 "GField_AsciiMapFactory: %1 provided %2 points but the grid expects %3.", path, read_points, total);
265 const std::string sym = param_string(
"symmetry",
"");
266 if (sym ==
"dipole-x") { symmetry = Symmetry::dipole_x; ndim = 2; ncomp = 1; }
267 else if (sym ==
"dipole-y") { symmetry = Symmetry::dipole_y; ndim = 2; ncomp = 1; }
268 else if (sym ==
"dipole-z") { symmetry = Symmetry::dipole_z; ndim = 2; ncomp = 1; }
269 else if (sym ==
"cylindrical-x") { symmetry = Symmetry::cyl_x; ndim = 2; ncomp = 2; }
270 else if (sym ==
"cylindrical-y") { symmetry = Symmetry::cyl_y; ndim = 2; ncomp = 2; }
271 else if (sym ==
"cylindrical-z") { symmetry = Symmetry::cyl_z; ndim = 2; ncomp = 2; }
272 else if (sym ==
"phi-segmented") { symmetry = Symmetry::phi_segmented; ndim = 3; ncomp = 3; }
273 else if (sym ==
"cartesian_3D") { symmetry = Symmetry::cartesian_3d; ndim = 3; ncomp = 3; }
274 else if (sym ==
"cartesian_3D_quadrant") { symmetry = Symmetry::cartesian_3d_quadrant; ndim = 3; ncomp = 3; }
283 columns.reserve(ndim);
284 load_coordinate(
"coordinate1");
285 load_coordinate(
"coordinate2");
286 if (ndim == 3) { load_coordinate(
"coordinate3"); }
289 linear = (param_string(
"interpolation",
"linear") !=
"none");
292 mapOrigin[0] = param_g4number(
"vx",
"0");
293 mapOrigin[1] = param_g4number(
"vy",
"0");
294 mapOrigin[2] = param_g4number(
"vz",
"0");
295 mapRotation[0] = param_g4number(
"rx",
"0*deg");
296 mapRotation[1] = param_g4number(
"ry",
"0*deg");
297 mapRotation[2] = param_g4number(
"rz",
"0*deg");
298 sinAlpha = std::sin(mapRotation[0]); cosAlpha = std::cos(mapRotation[0]);
299 sinBeta = std::sin(mapRotation[1]); cosBeta = std::cos(mapRotation[1]);
300 sinGamma = std::sin(mapRotation[2]); cosGamma = std::cos(mapRotation[2]);
311 bfield[0] = bfield[1] = bfield[2] = 0.0;
313 if (std::isnan(pos[0]) || std::isnan(pos[1]) || std::isnan(pos[2])) {
314 log->warning(
"GField_AsciiMapFactory: field coordinates requested are nan.");
319 const double x[3] = {pos[0] - mapOrigin[0], pos[1] - mapOrigin[1], pos[2] - mapOrigin[2]};
322 case Symmetry::dipole_x:
323 case Symmetry::dipole_y:
324 case Symmetry::dipole_z:
325 value_dipole(x, bfield);
327 case Symmetry::cyl_x:
328 case Symmetry::cyl_y:
329 case Symmetry::cyl_z:
330 value_cylindrical(x, bfield);
332 case Symmetry::phi_segmented:
333 value_phi_segmented(x, bfield);
335 case Symmetry::cartesian_3d:
336 case Symmetry::cartesian_3d_quadrant:
337 value_cartesian3d(x, bfield);
342 2,
"ASCII field <%1> at (%2, %3, %4) cm = (%5, %6, %7) gauss",
gfield_definitions.name, pos[0] / cm,
343 pos[1] / cm, pos[2] / cm, bfield[0] / gauss, bfield[1] / gauss, bfield[2] / gauss);
347void GField_AsciiMapFactory::value_dipole(
const double x[3],
double* bfield)
const {
349 double LC = 0.0, TC = 0.0;
350 if (symmetry == Symmetry::dipole_z) { TC = std::fabs(x[0]); LC = x[1]; }
351 else if (symmetry == Symmetry::dipole_x) { TC = std::fabs(x[1]); LC = x[2]; }
352 else { TC = std::fabs(x[0]); LC = x[2]; }
354 if (LC < startMap[0] || TC < startMap[1]) {
return; }
355 unsigned IL =
static_cast<unsigned>(std::floor((LC - startMap[0]) / cellSize[0]));
356 unsigned IT =
static_cast<unsigned>(std::floor((TC - startMap[1]) / cellSize[1]));
357 if (IL >= np[0] - 1 || IT >= np[1] - 1) {
return; }
361 if (std::fabs(startMap[0] + IL * cellSize[0] - LC) > std::fabs(startMap[0] + (IL + 1) * cellSize[0] - LC)) IL++;
362 if (std::fabs(startMap[1] + IT * cellSize[1] - TC) > std::fabs(startMap[1] + (IT + 1) * cellSize[1] - TC)) IT++;
363 b = B1[idx2(IL, IT)];
366 const double xlr = (LC - (startMap[0] + IL * cellSize[0])) / cellSize[0];
367 const double xtr = (TC - (startMap[1] + IT * cellSize[1])) / cellSize[1];
368 const double b10 = B1[idx2(IL, IT)] * (1.0 - xtr) + B1[idx2(IL, IT + 1)] * xtr;
369 const double b11 = B1[idx2(IL + 1, IT)] * (1.0 - xtr) + B1[idx2(IL + 1, IT + 1)] * xtr;
370 b = b10 * (1.0 - xlr) + b11 * xlr;
373 if (symmetry == Symmetry::dipole_x) { bfield[0] = b; }
374 else if (symmetry == Symmetry::dipole_y) { bfield[1] = b; }
375 else { bfield[2] = b; }
377 rotate_field(bfield);
381void GField_AsciiMapFactory::value_cylindrical(
const double x[3],
double* bfield)
const {
383 double LC = 0.0, TC = 0.0, phi = 0.0;
384 if (symmetry == Symmetry::cyl_z) {
385 LC = x[2]; TC = std::sqrt(x[0] * x[0] + x[1] * x[1]); phi = G4ThreeVector(x[0], x[1], x[2]).phi();
387 else if (symmetry == Symmetry::cyl_x) {
388 LC = x[0]; TC = std::sqrt(x[1] * x[1] + x[2] * x[2]); phi = G4ThreeVector(x[1], x[2], x[0]).phi();
391 LC = x[1]; TC = std::sqrt(x[0] * x[0] + x[2] * x[2]); phi = G4ThreeVector(x[2], x[0], x[1]).phi();
394 if (TC < startMap[0] || LC < startMap[1]) {
return; }
395 unsigned IT =
static_cast<unsigned>(std::floor((TC - startMap[0]) / cellSize[0]));
396 unsigned IL =
static_cast<unsigned>(std::floor((LC - startMap[1]) / cellSize[1]));
397 if (IT >= np[0] - 1 || IL >= np[1] - 1) {
return; }
399 double b1 = 0.0, b2 = 0.0;
401 if (std::fabs(startMap[0] + IT * cellSize[0] - TC) > std::fabs(startMap[0] + (IT + 1) * cellSize[0] - TC)) IT++;
402 if (std::fabs(startMap[1] + IL * cellSize[1] - LC) > std::fabs(startMap[1] + (IL + 1) * cellSize[1] - LC)) IL++;
403 b1 = B1[idx2(IT, IL)];
404 b2 = B2[idx2(IT, IL)];
407 const double xtr = (TC - (startMap[0] + IT * cellSize[0])) / cellSize[0];
408 const double xlr = (LC - (startMap[1] + IL * cellSize[1])) / cellSize[1];
409 const double b10 = B1[idx2(IT, IL)] * (1.0 - xtr) + B1[idx2(IT + 1, IL)] * xtr;
410 const double b11 = B1[idx2(IT, IL + 1)] * (1.0 - xtr) + B1[idx2(IT + 1, IL + 1)] * xtr;
411 b1 = b10 * (1.0 - xlr) + b11 * xlr;
412 const double b20 = B2[idx2(IT, IL)] * (1.0 - xtr) + B2[idx2(IT + 1, IL)] * xtr;
413 const double b21 = B2[idx2(IT, IL + 1)] * (1.0 - xtr) + B2[idx2(IT + 1, IL + 1)] * xtr;
414 b2 = b20 * (1.0 - xlr) + b21 * xlr;
417 if (symmetry == Symmetry::cyl_z) {
418 bfield[0] = b1 * std::cos(phi); bfield[1] = b1 * std::sin(phi); bfield[2] = b2;
420 else if (symmetry == Symmetry::cyl_x) {
421 bfield[0] = b2; bfield[1] = b1 * std::cos(phi); bfield[2] = b1 * std::sin(phi);
424 bfield[1] = b2; bfield[0] = b1 * std::sin(phi); bfield[2] = b1 * std::cos(phi);
427 rotate_field(bfield);
431void GField_AsciiMapFactory::value_phi_segmented(
const double x[3],
double* bfield)
const {
434 double aC = std::atan2(x[1], x[0]) * rad;
435 if (aC < 0) { aC += 360 * deg; }
436 const double tC = std::sqrt(x[0] * x[0] + x[1] * x[1]);
437 const double lC = x[2];
441 while (aLC / deg > 30) { aLC -= 60 * deg; }
442 const double dphi = aC - aLC;
443 const double aaLC = std::fabs(aLC);
444 const int sign = (aLC >= 0 ? 1 : -1);
446 if (aC < startMap[0] || tC < startMap[1] || lC < startMap[2]) {
return; }
447 unsigned aI =
static_cast<unsigned>(std::floor((aaLC - startMap[0]) / cellSize[0]));
448 unsigned tI =
static_cast<unsigned>(std::floor((tC - startMap[1]) / cellSize[1]));
449 unsigned lI =
static_cast<unsigned>(std::floor((lC - startMap[2]) / cellSize[2]));
450 if (aI >= np[0] - 1 || tI >= np[1] - 1 || lI >= np[2] - 1) {
return; }
452 double mfield[3] = {0.0, 0.0, 0.0};
454 if (std::fabs(startMap[0] + aI * cellSize[0] - aaLC) > std::fabs(startMap[0] + (aI + 1) * cellSize[0] - aaLC)) aI++;
455 if (std::fabs(startMap[1] + tI * cellSize[1] - tC) > std::fabs(startMap[1] + (tI + 1) * cellSize[1] - tC)) tI++;
456 if (std::fabs(startMap[2] + lI * cellSize[2] - lC) > std::fabs(startMap[2] + (lI + 1) * cellSize[2] - lC)) lI++;
457 mfield[0] = B1[idx3(aI, tI, lI)];
458 mfield[1] = B2[idx3(aI, tI, lI)];
459 mfield[2] = B3[idx3(aI, tI, lI)];
462 const double xaz = (aaLC - (startMap[0] + aI * cellSize[0])) / cellSize[0];
463 const double xtr = (tC - (startMap[1] + tI * cellSize[1])) / cellSize[1];
464 const double xlr = (lC - (startMap[2] + lI * cellSize[2])) / cellSize[2];
466 const std::vector<float>* comps[3] = {&B1, &B2, &B3};
467 for (
int k = 0; k < 3; ++k) {
468 const std::vector<float>& B = *comps[k];
469 const double b00 = B[idx3(aI, tI, lI)] * (1 - xaz) + B[idx3(aI + 1, tI, lI)] * xaz;
470 const double b01 = B[idx3(aI, tI, lI + 1)] * (1 - xaz) + B[idx3(aI + 1, tI, lI + 1)] * xaz;
471 const double b10 = B[idx3(aI, tI + 1, lI)] * (1 - xaz) + B[idx3(aI + 1, tI + 1, lI)] * xaz;
472 const double b11 = B[idx3(aI, tI + 1, lI + 1)] * (1 - xaz) + B[idx3(aI + 1, tI + 1, lI + 1)] * xaz;
473 const double b0 = b00 * (1 - xtr) + b10 * xtr;
474 const double b1 = b01 * (1 - xtr) + b11 * xtr;
475 mfield[k] = b0 * (1 - xlr) + b1 * xlr;
480 bfield[0] = sign * mfield[0] * std::cos(dphi / rad) - mfield[1] * std::sin(dphi / rad);
481 bfield[1] = sign * mfield[0] * std::sin(dphi / rad) + mfield[1] * std::cos(dphi / rad);
482 bfield[2] = sign * mfield[2];
484 rotate_field(bfield);
488void GField_AsciiMapFactory::value_cartesian3d(
const double x[3],
double* bfield)
const {
490 double XX = x[0], YY = x[1], ZZ = x[2];
492 if (symmetry == Symmetry::cartesian_3d_quadrant) {
494 if (x[0] >= 0 && x[1] >= 0) { XX = x[0]; YY = x[1]; }
495 else if (x[0] >= 0 && x[1] < 0) { XX = -x[1]; YY = x[0]; }
496 else if (x[0] < 0 && x[1] < 0) { XX = -x[0]; YY = -x[1]; }
497 else { XX = x[1]; YY = -x[0]; }
499 if (XX < 0 || YY < 0) {
return; }
502 if (XX < startMap[0] || YY < startMap[1] || ZZ < startMap[2]) {
return; }
503 if (XX >= endMap[0] || YY >= endMap[1] || ZZ >= endMap[2]) {
return; }
504 const unsigned IXX =
static_cast<unsigned>(std::floor((XX - startMap[0]) / cellSize[0]));
505 const unsigned IYY =
static_cast<unsigned>(std::floor((YY - startMap[1]) / cellSize[1]));
506 const unsigned IZZ =
static_cast<unsigned>(std::floor((ZZ - startMap[2]) / cellSize[2]));
508 double B[3] = {0.0, 0.0, 0.0};
510 unsigned ix = IXX, iy = IYY, iz = IZZ;
511 if (std::fabs(startMap[0] + ix * cellSize[0] - XX) > std::fabs(startMap[0] + (ix + 1) * cellSize[0] - XX)) ix++;
512 if (std::fabs(startMap[1] + iy * cellSize[1] - YY) > std::fabs(startMap[1] + (iy + 1) * cellSize[1] - YY)) iy++;
513 if (std::fabs(startMap[2] + iz * cellSize[2] - ZZ) > std::fabs(startMap[2] + (iz + 1) * cellSize[2] - ZZ)) iz++;
514 B[0] = B1[idx3(ix, iy, iz)];
515 B[1] = B2[idx3(ix, iy, iz)];
516 B[2] = B3[idx3(ix, iy, iz)];
519 const double Xd = (XX - (startMap[0] + IXX * cellSize[0])) / cellSize[0];
520 const double Yd = (YY - (startMap[1] + IYY * cellSize[1])) / cellSize[1];
521 const double Zd = (ZZ - (startMap[2] + IZZ * cellSize[2])) / cellSize[2];
523 const std::vector<float>* comps[3] = {&B1, &B2, &B3};
524 for (
int k = 0; k < 3; ++k) {
525 const std::vector<float>& Bk = *comps[k];
526 const double c00 = Bk[idx3(IXX, IYY, IZZ)] * (1 - Xd) + Bk[idx3(IXX + 1, IYY, IZZ)] * Xd;
527 const double c01 = Bk[idx3(IXX, IYY, IZZ + 1)] * (1 - Xd) + Bk[idx3(IXX + 1, IYY, IZZ + 1)] * Xd;
528 const double c10 = Bk[idx3(IXX, IYY + 1, IZZ)] * (1 - Xd) + Bk[idx3(IXX + 1, IYY + 1, IZZ)] * Xd;
529 const double c11 = Bk[idx3(IXX, IYY + 1, IZZ + 1)] * (1 - Xd) + Bk[idx3(IXX + 1, IYY + 1, IZZ + 1)] * Xd;
530 const double c0 = c00 * (1 - Yd) + c10 * Yd;
531 const double c1 = c01 * (1 - Yd) + c11 * Yd;
532 B[k] = c0 * (1 - Zd) + c1 * Zd;
536 if (symmetry == Symmetry::cartesian_3d_quadrant) {
538 if (x[0] >= 0 && x[1] >= 0) { bfield[0] = B[0]; bfield[1] = B[1]; }
539 else if (x[0] >= 0 && x[1] < 0) { bfield[0] = B[1]; bfield[1] = -B[0]; }
540 else if (x[0] < 0 && x[1] < 0) { bfield[0] = -B[0]; bfield[1] = -B[1]; }
541 else { bfield[0] = -B[1]; bfield[1] = B[0]; }
545 bfield[0] = B[0]; bfield[1] = B[1]; bfield[2] = B[2];
548 rotate_field(bfield);
552void GField_AsciiMapFactory::rotate_field(
double* bfield)
const {
554 if (mapRotation[0] != 0) {
555 const double yPrime = bfield[1] * cosAlpha + bfield[2] * sinAlpha;
556 const double zPrime = -bfield[1] * sinAlpha + bfield[2] * cosAlpha;
557 bfield[1] = yPrime; bfield[2] = zPrime;
559 if (mapRotation[1] != 0) {
560 const double xPrime = bfield[0] * cosBeta - bfield[2] * sinBeta;
561 const double zPrime = bfield[0] * sinBeta + bfield[2] * cosBeta;
562 bfield[0] = xPrime; bfield[2] = zPrime;
564 if (mapRotation[2] != 0) {
565 const double xPrime = bfield[0] * cosGamma + bfield[1] * sinGamma;
566 const double yPrime = -bfield[0] * sinGamma + bfield[1] * cosGamma;
567 bfield[0] = xPrime; bfield[1] = yPrime;
std::shared_ptr< GLogger > log
Concrete GField reading a magnetic field from an ASCII map and a YAML definition.
void load_field_definitions(GFieldDefinition gfd) override
Parse the YAML definition, build the grid and read the map file.
void GetFieldValue(const double pos[3], G4double *bfield) const override
Compute the field at the lab-frame point pos, writing {Bx,By,Bz} (Geant4 units) into bfield.
Abstract base class representing a magnetic field.
GFieldDefinition gfield_definitions
Stored field definition used for configuration and logging.
GField * GFieldFactory(const std::shared_ptr< GOptions > &g)
constexpr int ERR_WRONG_FIELD_SYMMETRY
constexpr int ERR_MAP_FILE_NOT_FOUND
constexpr int ERR_WRONG_COORDINATE_DEF
double getG4Number(const string &v, bool warnIfNotUnit=false)
vector< string > getStringVectorFromStringWithDelimiter(const string &input, const string &x)
string removeLeadingAndTrailingSpacesFromString(const std::string &input)
Lightweight configuration carrier used to load and configure a GField plugin.