15#include "TGeoManager.h"
16#include "TGeoMatrix.h"
18#include "TGeoVolume.h"
21bool Finite(
const TVector3& v) {
22 return std::isfinite(
v.X()) && std::isfinite(
v.Y()) && std::isfinite(
v.Z());
25bool FindVolume(TGeoNode* node,
const TGeoHMatrix& parent,
26 const std::string& name,
double& z) {
27 TGeoHMatrix transform(parent);
28 transform.Multiply(node->GetMatrix());
29 if (name == node->GetVolume()->GetName()) {
30 const double origin[3] = {0., 0., 0.};
32 transform.LocalToMaster(origin, global);
36 for (
int i = 0;
i < node->GetNdaughters(); ++
i)
37 if (FindVolume(node->GetDaughter(i), transform, name, z))
return true;
41bool FindVolumeRange(TGeoNode* node,
const TGeoHMatrix& parent,
42 const std::string& name,
43 std::pair<double, double>& range) {
44 TGeoHMatrix transform(parent);
45 transform.Multiply(node->GetMatrix());
46 if (name == node->GetVolume()->GetName()) {
47 auto* box =
dynamic_cast<TGeoBBox*
>(node->GetVolume()->GetShape());
48 if (!box)
throw std::runtime_error(
"Volume has no bounding box: " + name);
50 const auto*
origin = box->GetOrigin();
51 range = {std::numeric_limits<double>::infinity(),
52 -std::numeric_limits<double>::infinity()};
53 for (
double x : {-box->GetDX(), box->GetDX()})
54 for (
double y : {-box->GetDY(), box->GetDY()})
55 for (
double z : {-box->GetDZ(), box->GetDZ()}) {
58 transform.LocalToMaster(local, global);
59 range.first = std::min(range.first, global[2]);
60 range.second = std::max(range.second, global[2]);
62 return std::isfinite(range.first) && std::isfinite(range.second) &&
63 range.first < range.second;
65 for (
int i = 0;
i < node->GetNdaughters(); ++
i)
66 if (FindVolumeRange(node->GetDaughter(i), transform, name, range))
71bool FindVolumeExitFaceXY(TGeoNode* node,
const TGeoHMatrix& parent,
72 const std::string& name,
73 std::array<double, 4>& bounds) {
74 TGeoHMatrix transform(parent);
75 transform.Multiply(node->GetMatrix());
76 if (name == node->GetVolume()->GetName()) {
77 auto* box =
dynamic_cast<TGeoBBox*
>(node->GetVolume()->GetShape());
78 if (!box)
throw std::runtime_error(
"Volume has no bounding box: " + name);
80 const auto*
origin = box->GetOrigin();
81 bounds = {std::numeric_limits<double>::infinity(),
82 -std::numeric_limits<double>::infinity(),
83 std::numeric_limits<double>::infinity(),
84 -std::numeric_limits<double>::infinity()};
85 for (
double x : {-box->GetDX(), box->GetDX()})
86 for (
double y : {-box->GetDY(), box->GetDY()}) {
90 transform.LocalToMaster(local, global);
91 bounds[0] = std::min(bounds[0], global[0]);
92 bounds[1] = std::max(bounds[1], global[0]);
93 bounds[2] = std::min(bounds[2], global[1]);
94 bounds[3] = std::max(bounds[3], global[1]);
96 return std::isfinite(bounds[0]) && std::isfinite(bounds[1]) &&
97 std::isfinite(bounds[2]) && std::isfinite(bounds[3]) &&
98 bounds[0] < bounds[1] && bounds[2] < bounds[3];
100 for (
int i = 0;
i < node->GetNdaughters(); ++
i)
101 if (FindVolumeExitFaceXY(node->GetDaughter(i), transform, name, bounds))
108 TGeoManager* geometry,
111 AddFieldMap(field, -std::numeric_limits<double>::infinity());
112 if (muonShieldField) {
113 if (!geometry || !geometry->GetTopNode() ||
114 !FindVolumeRange(geometry->GetTopNode(), TGeoHMatrix(),
116 throw std::runtime_error(
"MuonShieldArea z range not found in geometry");
117 if (muonShieldField == field)
118 throw std::invalid_argument(
"SST and muon shield maps must be distinct");
122 TGeoTranslation translation(muonShieldField->
GetXOffset(),
125 TGeoRotation rotation(
"shieldBounds", muonShieldField->
GetPhi(),
127 muonShieldField->
GetPsi());
128 TGeoCombiTrans transform(translation, rotation);
129 double low = std::numeric_limits<double>::infinity(), high = -low;
131 ? -
static_cast<double>(muonShieldField->
GetXMax())
132 :
static_cast<double>(muonShieldField->
GetXMin()),
133 static_cast<double>(muonShieldField->
GetXMax())})
135 ? -
static_cast<double>(muonShieldField->
GetYMax())
136 :
static_cast<double>(muonShieldField->
GetYMin()),
137 static_cast<double>(muonShieldField->
GetYMax())})
138 for (
double z : {
static_cast<double>(muonShieldField->
GetZMin()),
139 static_cast<double>(muonShieldField->
GetZMax())}) {
140 const double local[3] = {x, y, z};
142 transform.LocalToMaster(local, global);
143 low = std::min(low, global[2]);
144 high = std::max(high, global[2]);
147 throw std::invalid_argument(
148 "Muon shield field does not overlap MuonShieldArea; check its z "
154 double relativeMomentumTolerance,
156 if (!std::isfinite(positionTolerance) || positionTolerance <= 0. ||
157 !std::isfinite(relativeMomentumTolerance) ||
158 relativeMomentumTolerance <= 0. || !std::isfinite(maxStep) ||
160 throw std::invalid_argument(
161 "Propagation tolerances and step must be finite and positive");
171 !FindVolume(
fGeometry->GetTopNode(), TGeoHMatrix(), volumeName, z))
172 throw std::runtime_error(
"Detector plane volume not found in geometry");
177 const char* volumeName)
const {
178 std::pair<double, double> range;
180 !FindVolumeRange(
fGeometry->GetTopNode(), TGeoHMatrix(), volumeName,
182 throw std::runtime_error(
183 std::string(
"Volume z range not found in geometry: ") +
184 (volumeName ? volumeName :
"null"));
189 const char* volumeName)
const {
190 std::array<double, 4> bounds;
192 !FindVolumeExitFaceXY(
fGeometry->GetTopNode(), TGeoHMatrix(), volumeName,
194 throw std::runtime_error(
195 std::string(
"Volume exit face not found in geometry: ") +
196 (volumeName ? volumeName :
"null"));
202 for (
int axis = 0; axis < 3; ++axis)
203 if (position[axis] < box.
minimum[axis] ||
204 position[axis] > box.
maximum[axis])
216 const double lo = std::max(0., std::min(t1, t2)),
217 hi = std::min(1., std::max(t1, t2));
218 if (lo > hi)
return false;
221 double coefficients[2][4];
222 std::vector<double> candidates{lo, hi};
223 for (
int axis = 0; axis < 2; ++axis) {
227 auto& c = coefficients[axis];
230 c[2] = 3. * (b - a) - 2. * da - db;
231 c[3] = 2. * (a - b) + da + db;
232 const auto value = [&c](
double t) {
233 return ((c[3] * t + c[2]) * t + c[1]) * t + c[0];
235 std::vector<double> knots{lo, hi};
236 const auto addKnot = [&knots, lo, hi](
double t) {
237 if (t > lo && t < hi) knots.push_back(t);
241 if (c[2] != 0.) addKnot(-c[1] / (2. * c[2]));
243 const double discriminant = 4. * c[2] * c[2] - 12. * c[3] * c[1];
244 if (discriminant >= 0.) {
245 addKnot((-2. * c[2] - std::sqrt(discriminant)) / (6. * c[3]));
246 addKnot((-2. * c[2] + std::sqrt(discriminant)) / (6. * c[3]));
249 std::sort(knots.begin(), knots.end());
250 candidates.insert(candidates.end(), knots.begin(), knots.end());
252 for (std::size_t i = 1; i < knots.size(); ++i) {
253 double left = knots[i - 1], right = knots[i];
254 double fleft = value(left) - face, fright = value(right) - face;
255 if ((fleft < 0. && fright > 0.) || (fleft > 0. && fright < 0.)) {
256 for (
int iteration = 0; iteration < 50; ++iteration) {
257 const double middle = (left + right) / 2.,
258 fmiddle = value(middle) - face;
259 if ((fleft < 0.) == (fmiddle < 0.)) {
265 candidates.push_back((left + right) / 2.);
270 const auto inside = [&coefficients, &box](
double t) {
271 for (
int axis = 0; axis < 2; ++axis) {
272 const auto& c = coefficients[axis];
273 const double value = ((c[3] * t + c[2]) * t + c[1]) * t + c[0];
274 if (value < box.
minimum[axis] - 1.e-9 ||
275 value > box.
maximum[axis] + 1.e-9)
280 std::sort(candidates.begin(), candidates.end());
281 for (std::size_t i = 0; i < candidates.size(); ++i) {
282 if (inside(candidates[i]))
return true;
283 if (i && inside((candidates[i - 1] + candidates[i]) / 2.))
return true;
289 const TVector3& position,
290 const TVector3& momentum,
291 const TVector3& minimum,
292 const TVector3& maximum)
const {
293 if (!Finite(position) || !Finite(momentum) || !Finite(minimum) ||
294 !Finite(maximum) || !std::isfinite(charge) ||
295 !std::isfinite(momentum.Mag()) || momentum.Mag() <= 0.)
297 for (
int axis = 0; axis < 3; ++axis)
298 if (minimum[axis] >= maximum[axis])
299 throw std::invalid_argument(
"Invalid detector box extent");
300 const Box box{minimum, maximum};
301 if (
InsideBox(position, box))
return true;
303 const bool zeroField =
304 std::all_of(
fFields.begin(),
fFields.end(), [&](
const auto& map) {
306 map.regions.begin(), map.regions.end(), [&](const auto& region) {
308 return RayBoxInterval(position, momentum, region, entry, exit);
311 if (charge == 0. || zeroField) {
313 return RayBoxInterval(position, momentum, box, entry, exit);
315 const double z =
momentum.Z() >= 0. ? maximum.Z() : minimum.Z();
316 if ((z - position.Z()) *
momentum.Z() < 0.)
return false;
318 return Propagate(charge, position, momentum, z, result,
nullptr, &box);
322 const TVector3& direction,
323 const Box& box,
double& entry,
326 exit = std::numeric_limits<double>::infinity();
327 for (
int axis = 0; axis < 3; ++axis) {
328 if (direction[axis] == 0.) {
329 if (position[axis] < box.
minimum[axis] ||
330 position[axis] > box.
maximum[axis])
333 const double a = (box.
minimum[axis] - position[axis]) / direction[axis];
334 const double b = (box.
maximum[axis] - position[axis]) / direction[axis];
335 entry = std::max(entry, std::min(a, b));
336 exit = std::min(exit, std::max(a, b));
339 return entry <= exit;
343 if (std::isnan(minimumZ) ||
344 minimumZ == std::numeric_limits<double>::infinity())
345 throw std::invalid_argument(
"Invalid muon shield minimum z");
367 double minimumZ)
const {
370 const int nx = field->
GetNx(), ny = field->
GetNy(), nz = field->
GetNz();
371 if (nx < 2 || ny < 2 || nz < 2 || !data ||
372 data->size() != std::size_t(nx) * ny * nz || !(field->
GetdX() > 0.) ||
373 !(field->
GetdY() > 0.) || !(field->
GetdZ() > 0.))
374 throw std::invalid_argument(
"Invalid magnetic field grid");
381 TGeoRotation rotation(
"propagationRotation", field->
GetPhi(),
383 TGeoCombiTrans transform(translation, rotation);
391 for (
int iz = 0; iz < nz; ++iz) {
392 const double zlo = field->
GetZMin() + std::max(0, iz - 1) * field->
GetdZ();
394 field->
GetZMin() + std::min(nz - 1, iz + 1) * field->
GetdZ();
395 const double inf = std::numeric_limits<double>::infinity();
396 Box region{TVector3(inf, inf, inf), TVector3(-inf, -inf, -inf)};
397 for (
double x : {xmin,
static_cast<double>(field->
GetXMax())})
398 for (
double y : {ymin,
static_cast<double>(field->
GetYMax())})
399 for (
double z : {zlo, zhi}) {
400 const double local[3] = {x, y, z};
402 transform.LocalToMaster(local, global);
403 for (
int axis = 0; axis < 3; ++axis) {
404 region.
minimum[axis] = std::min(region.
minimum[axis], global[axis]);
405 region.
maximum[axis] = std::max(region.
maximum[axis], global[axis]);
408 if (region.
maximum.Z() < minimumZ)
continue;
410 for (
int ix = 0; ix < nx; ++ix)
411 for (
int iy = 0; iy < ny; ++iy) {
412 const auto& b = data->at((std::size_t(ix) * ny + iy) * nz + iz);
413 if (!std::isfinite(b[0]) || !std::isfinite(b[1]) ||
414 !std::isfinite(b[2]))
415 throw std::invalid_argument(
"Non-finite magnetic field value");
416 active = active || b[0] != 0. || b[1] != 0. || b[2] != 0.;
418 if (!active)
continue;
424 [](
const Box& a,
const Box& b) { return a.minimum.Z() < b.minimum.Z(); });
425 std::vector<Box> merged;
426 for (
const auto& region : map.
regions) {
427 if (!merged.empty() && region.minimum.Z() <= merged.back().maximum.Z()) {
428 for (
int axis = 0; axis < 3; ++axis) {
429 merged.back().minimum[axis] =
430 std::min(merged.back().minimum[axis], region.minimum[axis]);
431 merged.back().maximum[axis] =
432 std::max(merged.back().maximum[axis], region.maximum[axis]);
435 merged.push_back(region);
438 fFields.push_back(std::move(map));
443 State& derivative)
const {
444 if (!Finite(state.position) || !Finite(state.momentum) ||
445 state.momentum.Z() * pzSign <= 1.e-10 * state.momentum.Mag())
447 const double point[3] = {state.position.X(), state.position.Y(),
449 double b[3] = {0., 0., 0.};
450 for (
const auto& map :
fFields) {
451 if (std::none_of(map.regions.begin(), map.regions.end(),
452 [&state](
const auto& region) {
453 return InsideBox(state.position, region);
456 double component[3] = {0., 0., 0.};
457 map.field->Field(point, component);
458 for (
int i = 0; i < 3; ++i) b[i] += component[i];
460 derivative.
position = state.momentum * (1. / state.momentum.Z());
462 derivative.
momentum = state.momentum.Cross(TVector3(b[0], b[1], b[2])) *
463 (0.000299792458 * charge / state.momentum.Z());
468 double pzSign,
double dz,
469 State& result)
const {
470 const auto advance = [](
const State& a,
const State& b,
double step) {
474 State k1, k2, k3, k4;
476 !
Derivative(advance(state, k1, dz / 2.), charge, pzSign, k2) ||
477 !
Derivative(advance(state, k2, dz / 2.), charge, pzSign, k3) ||
478 !
Derivative(advance(state, k3, dz), charge, pzSign, k4))
486 result.position.SetZ(state.position.Z() + dz);
487 return Finite(result.position) && Finite(result.momentum) &&
488 result.momentum.Z() * pzSign > 1.e-10 * result.momentum.Mag();
492 const TVector3& momentum,
double z,
494 std::vector<State>* trajectory,
495 const Box* box)
const {
496 if (!Finite(position) || !Finite(momentum) || !std::isfinite(z) ||
497 !std::isfinite(charge) || !std::isfinite(momentum.Mag()) ||
498 momentum.Mag() <= 0.)
501 result = {position, momentum};
502 if (trajectory) trajectory->push_back(result);
503 if (box &&
InsideBox(position, *box))
return true;
504 if (z == position.Z())
return box ==
nullptr;
505 const double p = momentum.Mag(), pzSign = momentum.Z() >= 0. ? 1. : -1.;
506 if (std::abs(momentum.Z()) <= 1.e-10 * p)
return false;
507 const double direction = z > position.Z() ? 1. : -1.;
509 for (
unsigned step = 0; step < 100000; ++step) {
510 const double currentZ = result.position.Z();
511 if (currentZ == z)
return box ==
nullptr;
512 const State previous = result;
514 bool inField =
false;
517 for (
const auto& map :
fFields) {
518 for (
const auto& region : map.regions) {
520 const TVector3 travel =
521 (direction / result.momentum.Z()) * result.momentum;
522 if (!
RayBoxInterval(result.position, travel, region, entry, exit) ||
525 if (entry <= 1.e-7) {
527 gridStep = std::min(gridStep, map.gridStep);
529 direction > 0. ? region.maximum.Z() : region.minimum.Z();
530 if (direction * (leave - boundary) < 0.) boundary = leave;
531 }
else if (entry < direction * (boundary - currentZ)) {
532 boundary = currentZ + direction * entry;
539 ((boundary - currentZ) / result.momentum.Z()) * result.momentum;
540 result.position.SetZ(boundary);
541 if (!Finite(result.position))
return false;
544 direction * std::min({std::abs(boundary - currentZ), nextStep,
545 gridStep * std::abs(result.momentum.Z()) / p});
546 State full, half, fine;
547 bool accepted =
false;
548 for (
int retry = 0; retry < 40; ++retry) {
549 if (std::abs(dz) < 1.e-8 || currentZ + dz == currentZ)
return false;
550 if (
RKStep(result, charge, pzSign, dz, full) &&
551 RKStep(result, charge, pzSign, dz / 2., half) &&
552 RKStep(half, charge, pzSign, dz / 2., fine)) {
553 const double error = std::max(
557 fine.momentum *= p / fine.momentum.Mag();
558 fine.position.SetZ(currentZ + dz);
560 nextStep = std::abs(dz) * (error < 0.03 ? 2. : 1.);
567 if (!accepted)
return false;
570 if (trajectory) trajectory->push_back(result);
576 const TVector3& position,
577 const TVector3& momentum,
double z,
579 TVector3& resultMomentum)
const {
581 if (!
Propagate(charge, position, momentum, z, end,
nullptr))
return false;
588 const TVector3& position,
589 const TVector3& momentum,
607 [](
const State& state,
double value) {
608 return state.position.Z() < value;
610 if (upper->position.Z() == z) {
611 position = upper->position;
614 const auto& a = *(upper - 1);
615 const auto& b = *upper;
616 const double dz = b.position.Z() - a.position.Z(),
617 t = (z - a.position.Z()) / dz;
618 position = (2 * t * t * t - 3 * t * t + 1) * a.position +
619 (t * t * t - 2 * t * t + t) * dz / a.momentum.Z() * a.momentum +
620 (-2 * t * t * t + 3 * t * t) * b.position +
621 (t * t * t - t * t) * dz / b.momentum.Z() * b.momentum;
623 return Finite(position);
628 TVector3& momentum)
const {
636 if (!std::isfinite(minimumZ))
637 throw std::invalid_argument(
"Field extent requires a finite minimum z");
639 double end = minimumZ;
640 for (
const auto& map :
fFields)
641 for (
const auto& region : map.regions)
642 end = std::max(end, region.maximum.Z());
647 if (!Finite(position))
648 throw std::invalid_argument(
"Field query requires a finite position");
650 const double point[3] = {position.X(), position.Y(), position.Z()};
652 for (
const auto& map :
fFields) {
653 double component[3] = {0., 0., 0.};
654 map.field->Field(point, component);
655 field += TVector3(component[0], component[1], component[2]);
657 return field.Mag2() != 0.;
bool PositionAt(double z, TVector3 &position) const
void EnsureMuonShield(double minimumZ) const
bool fMuonShieldReady
Borrowed; scanned on first transport.
MagneticTrackPropagator(ShipBFieldMap *field=nullptr, TGeoManager *geometry=nullptr, ShipBFieldMap *muonShieldField=nullptr)
bool Propagate(double charge, const TVector3 &position, const TVector3 &momentum, double z, State &result, std::vector< State > *trajectory, const Box *box=nullptr) const
bool HasFieldAt(const TVector3 &position) const
double GetPlaneZ(const char *volumeName="Tr1") const
bool GetTrajectoryState(std::size_t index, TVector3 &position, TVector3 &momentum) const
static bool RayBoxInterval(const TVector3 &position, const TVector3 &direction, const Box &box, double &entry, double &exit)
ShipBFieldMap * fMuonShieldField
Maps and conservative nonzero 3D regions.
double GetFieldEndZ(double minimumZ) const
bool RKStep(const State &state, double charge, double pzSign, double dz, State &result) const
double fMomentumTolerance
bool IntersectsBox(double charge, const TVector3 &position, const TVector3 &momentum, const TVector3 &minimum, const TVector3 &maximum) const
bool Extrapolate(double charge, const TVector3 &position, const TVector3 &momentum, double z, TVector3 &result, TVector3 &resultMomentum) const
void AddFieldMap(ShipBFieldMap *field, double minimumZ) const
std::pair< double, double > GetVolumeZRange(const char *volumeName) const
void SetMuonShieldMinZ(double minimumZ)
std::vector< FieldMap > fFields
Borrowed geometry.
std::array< double, 4 > GetVolumeExitFaceXY(const char *volumeName) const
std::pair< double, double > fMuonShieldZRange
static bool InsideBox(const TVector3 &position, const Box &box)
bool BuildTrajectory(double charge, const TVector3 &position, const TVector3 &momentum, double endZ)
double fPositionTolerance
std::vector< State > fTrajectory
static bool SegmentIntersectsBox(const State &start, const State &end, const Box &box)
void SetAccuracy(double positionTolerance=1.e-3, double relativeMomentumTolerance=1.e-6, double maxStep=5.)
bool Derivative(const State &state, double charge, double pzSign, State &derivative) const
Class that defines a (3d) magnetic field map (distances in cm, fields in tesla).
Float_t GetZMin() const
Get the minimum value of z for the map.
Float_t GetXMax() const
Get the maximum value of x for the map.
Bool_t HasSymmetry() const
Get the boolean flag to specify if we have quadrant symmetry.
Float_t GetYOffset() const
Get the y offset coordinate of the map for global positioning.
Int_t GetNy() const
Get the number of bins along y.
Float_t GetdX() const
Get the bin width along x for the map.
Int_t GetNz() const
Get the number of bins along z.
floatArray * getFieldMap() const
Retrieve the field map.
Float_t GetdY() const
Get the bin width along y for the map.
Float_t GetPhi() const
Get the first Euler rotation angle about the z axis for global positioning.
Float_t GetdZ() const
Get the bin width along z for the map.
Float_t GetXOffset() const
Get the x offset coordinate of the map for global positioning.
Float_t GetZMax() const
Get the maximum value of z for the map.
Float_t GetYMax() const
Get the maximum value of y for the map.
Float_t GetYMin() const
Get the minimum value of y for the map.
Float_t GetXMin() const
Get the minimum value of x for the map.
Int_t GetNx() const
Get the number of bins along x.
Float_t GetZOffset() const
Get the z offset coordinate of the map for global positioning.
std::vector< Box > regions