FairShip
Loading...
Searching...
No Matches
MagneticTrackPropagator.cxx
Go to the documentation of this file.
1// SPDX-License-Identifier: LGPL-3.0-or-later
2// SPDX-FileCopyrightText: Copyright CERN for the benefit of the SHiP
3// Collaboration
4
6
7#include <algorithm>
8#include <cmath>
9#include <limits>
10#include <stdexcept>
11#include <string>
12
13#include "ShipBFieldMap.h"
14#include "TGeoBBox.h"
15#include "TGeoManager.h"
16#include "TGeoMatrix.h"
17#include "TGeoNode.h"
18#include "TGeoVolume.h"
19
20namespace {
21bool Finite(const TVector3& v) {
22 return std::isfinite(v.X()) && std::isfinite(v.Y()) && std::isfinite(v.Z());
23}
24
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.};
31 double global[3];
32 transform.LocalToMaster(origin, global);
33 z = global[2];
34 return true;
35 }
36 for (int i = 0; i < node->GetNdaughters(); ++i)
37 if (FindVolume(node->GetDaughter(i), transform, name, z)) return true;
38 return false;
39}
40
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);
49 box->ComputeBBox();
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()}) {
56 const double local[3] = {origin[0] + x, origin[1] + y, origin[2] + z};
57 double global[3];
58 transform.LocalToMaster(local, global);
59 range.first = std::min(range.first, global[2]);
60 range.second = std::max(range.second, global[2]);
61 }
62 return std::isfinite(range.first) && std::isfinite(range.second) &&
63 range.first < range.second;
64 }
65 for (int i = 0; i < node->GetNdaughters(); ++i)
66 if (FindVolumeRange(node->GetDaughter(i), transform, name, range))
67 return true;
68 return false;
69}
70
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);
79 box->ComputeBBox();
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()}) {
87 const double local[3] = {origin[0] + x, origin[1] + y,
88 origin[2] + box->GetDZ()};
89 double global[3];
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]);
95 }
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];
99 }
100 for (int i = 0; i < node->GetNdaughters(); ++i)
101 if (FindVolumeExitFaceXY(node->GetDaughter(i), transform, name, bounds))
102 return true;
103 return false;
104}
105} // namespace
106
108 TGeoManager* geometry,
109 ShipBFieldMap* muonShieldField)
110 : fGeometry(geometry) {
111 AddFieldMap(field, -std::numeric_limits<double>::infinity());
112 if (muonShieldField) {
113 if (!geometry || !geometry->GetTopNode() ||
114 !FindVolumeRange(geometry->GetTopNode(), TGeoHMatrix(),
115 "MuonShieldArea", fMuonShieldZRange))
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");
119 fMuonShieldField = muonShieldField;
120 // Check alignment without scanning the field values. The shield cache is
121 // built after the input vertex range is known.
122 TGeoTranslation translation(muonShieldField->GetXOffset(),
123 muonShieldField->GetYOffset(),
124 muonShieldField->GetZOffset());
125 TGeoRotation rotation("shieldBounds", muonShieldField->GetPhi(),
126 muonShieldField->GetTheta(),
127 muonShieldField->GetPsi());
128 TGeoCombiTrans transform(translation, rotation);
129 double low = std::numeric_limits<double>::infinity(), high = -low;
130 for (double x : {muonShieldField->HasSymmetry()
131 ? -static_cast<double>(muonShieldField->GetXMax())
132 : static_cast<double>(muonShieldField->GetXMin()),
133 static_cast<double>(muonShieldField->GetXMax())})
134 for (double y : {muonShieldField->HasSymmetry()
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};
141 double global[3];
142 transform.LocalToMaster(local, global);
143 low = std::min(low, global[2]);
144 high = std::max(high, global[2]);
145 }
146 if (low >= fMuonShieldZRange.second || high <= fMuonShieldZRange.first)
147 throw std::invalid_argument(
148 "Muon shield field does not overlap MuonShieldArea; check its z "
149 "offset");
150 }
151}
152
153void MagneticTrackPropagator::SetAccuracy(double positionTolerance,
154 double relativeMomentumTolerance,
155 double maxStep) {
156 if (!std::isfinite(positionTolerance) || positionTolerance <= 0. ||
157 !std::isfinite(relativeMomentumTolerance) ||
158 relativeMomentumTolerance <= 0. || !std::isfinite(maxStep) ||
159 maxStep <= 0.)
160 throw std::invalid_argument(
161 "Propagation tolerances and step must be finite and positive");
162 fPositionTolerance = positionTolerance;
163 fMomentumTolerance = relativeMomentumTolerance;
164 fMaxStep = maxStep;
165 fTrajectory.clear();
166}
167
168double MagneticTrackPropagator::GetPlaneZ(const char* volumeName) const {
169 double z;
170 if (!volumeName || !fGeometry || !fGeometry->GetTopNode() ||
171 !FindVolume(fGeometry->GetTopNode(), TGeoHMatrix(), volumeName, z))
172 throw std::runtime_error("Detector plane volume not found in geometry");
173 return z;
174}
175
177 const char* volumeName) const {
178 std::pair<double, double> range;
179 if (!volumeName || !fGeometry || !fGeometry->GetTopNode() ||
180 !FindVolumeRange(fGeometry->GetTopNode(), TGeoHMatrix(), volumeName,
181 range))
182 throw std::runtime_error(
183 std::string("Volume z range not found in geometry: ") +
184 (volumeName ? volumeName : "null"));
185 return range;
186}
187
189 const char* volumeName) const {
190 std::array<double, 4> bounds;
191 if (!volumeName || !fGeometry || !fGeometry->GetTopNode() ||
192 !FindVolumeExitFaceXY(fGeometry->GetTopNode(), TGeoHMatrix(), volumeName,
193 bounds))
194 throw std::runtime_error(
195 std::string("Volume exit face not found in geometry: ") +
196 (volumeName ? volumeName : "null"));
197 return bounds;
198}
199
200bool MagneticTrackPropagator::InsideBox(const TVector3& position,
201 const Box& box) {
202 for (int axis = 0; axis < 3; ++axis)
203 if (position[axis] < box.minimum[axis] ||
204 position[axis] > box.maximum[axis])
205 return false;
206 return true;
207}
208
210 const State& end,
211 const Box& box) {
212 const double dz = end.position.Z() - start.position.Z();
213 if (dz == 0.) return InsideBox(start.position, box);
214 const double t1 = (box.minimum.Z() - start.position.Z()) / dz;
215 const double t2 = (box.maximum.Z() - start.position.Z()) / dz;
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;
219 // The same cubic Hermite curve used by PositionAt. Solve for crossings of
220 // all four side faces, including curved tracks whose endpoints both miss.
221 double coefficients[2][4];
222 std::vector<double> candidates{lo, hi};
223 for (int axis = 0; axis < 2; ++axis) {
224 const double a = start.position[axis], b = end.position[axis];
225 const double da = dz * start.momentum[axis] / start.momentum.Z();
226 const double db = dz * end.momentum[axis] / end.momentum.Z();
227 auto& c = coefficients[axis];
228 c[0] = a;
229 c[1] = da;
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];
234 };
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);
238 };
239 // Split at derivative roots, so each interval is monotonic for bisection.
240 if (c[3] == 0.) {
241 if (c[2] != 0.) addKnot(-c[1] / (2. * c[2]));
242 } else {
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]));
247 }
248 }
249 std::sort(knots.begin(), knots.end());
250 candidates.insert(candidates.end(), knots.begin(), knots.end());
251 for (double face : {box.minimum[axis], box.maximum[axis]}) {
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.)) {
260 left = middle;
261 fleft = fmiddle;
262 } else
263 right = middle;
264 }
265 candidates.push_back((left + right) / 2.);
266 }
267 }
268 }
269 }
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)
276 return false;
277 }
278 return true;
279 };
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;
284 }
285 return false;
286}
287
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.)
296 return false;
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;
302 if (charge != 0.) EnsureMuonShield(std::min(position.Z(), minimum.Z()));
303 const bool zeroField =
304 std::all_of(fFields.begin(), fFields.end(), [&](const auto& map) {
305 return std::none_of(
306 map.regions.begin(), map.regions.end(), [&](const auto& region) {
307 double entry, exit;
308 return RayBoxInterval(position, momentum, region, entry, exit);
309 });
310 });
311 if (charge == 0. || zeroField) {
312 double entry, exit;
313 return RayBoxInterval(position, momentum, box, entry, exit);
314 }
315 const double z = momentum.Z() >= 0. ? maximum.Z() : minimum.Z();
316 if ((z - position.Z()) * momentum.Z() < 0.) return false;
317 State result;
318 return Propagate(charge, position, momentum, z, result, nullptr, &box);
319}
320
321bool MagneticTrackPropagator::RayBoxInterval(const TVector3& position,
322 const TVector3& direction,
323 const Box& box, double& entry,
324 double& exit) {
325 entry = 0.;
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])
331 return false;
332 } else {
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));
337 }
338 }
339 return entry <= exit;
340}
341
343 if (std::isnan(minimumZ) ||
344 minimumZ == std::numeric_limits<double>::infinity())
345 throw std::invalid_argument("Invalid muon shield minimum z");
346 if (fMuonShieldReady) fFields.pop_back();
347 fMuonShieldReady = false;
348 fMuonShieldMinZ = minimumZ;
349 fTrajectory.clear();
350}
351
352void MagneticTrackPropagator::EnsureMuonShield(double minimumZ) const {
353 if (!fMuonShieldField) return;
354 // Reused propagators and backward tracks can request an earlier range.
355 if (minimumZ < fMuonShieldMinZ) {
356 if (fMuonShieldReady) fFields.pop_back();
357 fMuonShieldReady = false;
358 fMuonShieldMinZ = minimumZ;
359 }
360 if (!fMuonShieldReady) {
362 fMuonShieldReady = true;
363 }
364}
365
367 double minimumZ) const {
368 if (!field) return;
369 const auto* data = field->getFieldMap();
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");
375 FieldMap map{
376 field,
377 {},
378 0.5 * std::min({field->GetdX(), field->GetdY(), field->GetdZ()})};
379 TGeoTranslation translation(field->GetXOffset(), field->GetYOffset(),
380 field->GetZOffset());
381 TGeoRotation rotation("propagationRotation", field->GetPhi(),
382 field->GetTheta(), field->GetPsi());
383 TGeoCombiTrans transform(translation, rotation);
384 const double xmin =
385 field->HasSymmetry() ? -field->GetXMax() : field->GetXMin();
386 const double ymin =
387 field->HasSymmetry() ? -field->GetYMax() : field->GetYMin();
388 // Each nonzero node contributes to both neighbouring interpolation cells.
389 // Transform all corners, retaining a conservative 3D envelope for rotations
390 // and quadrant symmetry. Skip reading layers wholly below the input range.
391 for (int iz = 0; iz < nz; ++iz) {
392 const double zlo = field->GetZMin() + std::max(0, iz - 1) * field->GetdZ();
393 const double zhi =
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};
401 double global[3];
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]);
406 }
407 }
408 if (region.maximum.Z() < minimumZ) continue;
409 bool active = false;
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.;
417 }
418 if (!active) continue;
419 region.minimum.SetZ(std::max(region.minimum.Z(), minimumZ));
420 map.regions.push_back(region);
421 }
422 std::sort(
423 map.regions.begin(), map.regions.end(),
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]);
433 }
434 } else
435 merged.push_back(region);
436 }
437 map.regions.swap(merged);
438 fFields.push_back(std::move(map));
439}
440
441bool MagneticTrackPropagator::Derivative(const State& state, double charge,
442 double pzSign,
443 State& derivative) const {
444 if (!Finite(state.position) || !Finite(state.momentum) ||
445 state.momentum.Z() * pzSign <= 1.e-10 * state.momentum.Mag())
446 return false;
447 const double point[3] = {state.position.X(), state.position.Y(),
448 state.position.Z()};
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);
454 }))
455 continue;
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];
459 }
460 derivative.position = state.momentum * (1. / state.momentum.Z());
461 // dp/dz = 0.000299792458 q (p cross B)/pz for cm, GeV/c and kGauss.
462 derivative.momentum = state.momentum.Cross(TVector3(b[0], b[1], b[2])) *
463 (0.000299792458 * charge / state.momentum.Z());
464 return Finite(derivative.position) && Finite(derivative.momentum);
465}
466
467bool MagneticTrackPropagator::RKStep(const State& state, double charge,
468 double pzSign, double dz,
469 State& result) const {
470 const auto advance = [](const State& a, const State& b, double step) {
471 return State{a.position + step * b.position,
472 a.momentum + step * b.momentum};
473 };
474 State k1, k2, k3, k4;
475 if (!Derivative(state, charge, pzSign, k1) ||
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))
479 return false;
480 result.position =
481 state.position + (dz / 6.) * (k1.position + 2. * k2.position +
482 2. * k3.position + k4.position);
483 result.momentum =
484 state.momentum + (dz / 6.) * (k1.momentum + 2. * k2.momentum +
485 2. * k3.momentum + k4.momentum);
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();
489}
490
491bool MagneticTrackPropagator::Propagate(double charge, const TVector3& position,
492 const TVector3& momentum, double z,
493 State& result,
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.)
499 return false;
500 if (charge != 0.) EnsureMuonShield(std::min(position.Z(), z));
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.;
508 double nextStep = fMaxStep;
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;
513 double boundary = z;
514 bool inField = false;
515 double gridStep = fMaxStep;
516 if (charge != 0.) {
517 for (const auto& map : fFields) {
518 for (const auto& region : map.regions) {
519 double entry, exit;
520 const TVector3 travel =
521 (direction / result.momentum.Z()) * result.momentum;
522 if (!RayBoxInterval(result.position, travel, region, entry, exit) ||
523 exit <= 0.)
524 continue;
525 if (entry <= 1.e-7) {
526 inField = true;
527 gridStep = std::min(gridStep, map.gridStep);
528 const double leave =
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;
533 }
534 }
535 }
536 }
537 if (!inField) {
538 result.position +=
539 ((boundary - currentZ) / result.momentum.Z()) * result.momentum;
540 result.position.SetZ(boundary);
541 if (!Finite(result.position)) return false;
542 } else {
543 double dz =
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(
554 (fine.position - full.position).Mag() / fPositionTolerance,
555 (fine.momentum - full.momentum).Mag() / (fMomentumTolerance * p));
556 if (error <= 1.) {
557 fine.momentum *= p / fine.momentum.Mag();
558 fine.position.SetZ(currentZ + dz);
559 result = fine;
560 nextStep = std::abs(dz) * (error < 0.03 ? 2. : 1.);
561 accepted = true;
562 break;
563 }
564 }
565 dz *= 0.5;
566 }
567 if (!accepted) return false;
568 }
569 if (box && SegmentIntersectsBox(previous, result, *box)) return true;
570 if (trajectory) trajectory->push_back(result);
571 }
572 return false;
573}
574
576 const TVector3& position,
577 const TVector3& momentum, double z,
578 TVector3& result,
579 TVector3& resultMomentum) const {
580 State end;
581 if (!Propagate(charge, position, momentum, z, end, nullptr)) return false;
582 result = end.position;
583 resultMomentum = end.momentum;
584 return true;
585}
586
588 const TVector3& position,
589 const TVector3& momentum,
590 double endZ) {
591 fTrajectory.clear();
592 State end;
593 if (!Propagate(charge, position, momentum, endZ, end, &fTrajectory)) {
594 fTrajectory.clear();
595 return false;
596 }
597 if (endZ < position.Z()) std::reverse(fTrajectory.begin(), fTrajectory.end());
598 return true;
599}
600
601bool MagneticTrackPropagator::PositionAt(double z, TVector3& position) const {
602 if (!std::isfinite(z) || fTrajectory.empty() ||
603 z < fTrajectory.front().position.Z() ||
604 z > fTrajectory.back().position.Z())
605 return false;
606 const auto upper = std::lower_bound(fTrajectory.begin(), fTrajectory.end(), z,
607 [](const State& state, double value) {
608 return state.position.Z() < value;
609 });
610 if (upper->position.Z() == z) {
611 position = upper->position;
612 return true;
613 }
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;
622 position.SetZ(z);
623 return Finite(position);
624}
625
627 TVector3& position,
628 TVector3& momentum) const {
629 if (index >= fTrajectory.size()) return false;
630 position = fTrajectory[index].position;
631 momentum = fTrajectory[index].momentum;
632 return true;
633}
634
635double MagneticTrackPropagator::GetFieldEndZ(double minimumZ) const {
636 if (!std::isfinite(minimumZ))
637 throw std::invalid_argument("Field extent requires a finite minimum z");
638 EnsureMuonShield(minimumZ);
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());
643 return end;
644}
645
646bool MagneticTrackPropagator::HasFieldAt(const TVector3& position) const {
647 if (!Finite(position))
648 throw std::invalid_argument("Field query requires a finite position");
649 EnsureMuonShield(position.Z());
650 const double point[3] = {position.X(), position.Y(), position.Z()};
651 TVector3 field;
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]);
656 }
657 return field.Mag2() != 0.;
658}
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
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)
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.
Float_t GetTheta() const
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 GetPsi() const
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.
int i
Definition ShipAna.py:108
origin(sTree, it)