41 if (!gGeoManager || !gGeoManager->GetTopNode())
42 throw std::runtime_error(
"Muon path discovery requires a closed geometry");
45 throw std::runtime_error(
46 "Configure the shield field again after changing geometry");
48 fTopNode = gGeoManager->GetTopNode();
50 fShieldMinZ = std::numeric_limits<double>::infinity();
51 std::function<void(TGeoNode*,
const TGeoHMatrix&,
bool)> visit;
52 visit = [&](TGeoNode* node,
const TGeoHMatrix& parent,
bool inShield) {
53 TGeoHMatrix transform(parent);
54 transform.Multiply(node->GetMatrix());
55 auto* volume = node->GetVolume();
56 const std::string name = volume->GetName();
57 inShield = inShield || name ==
"MuonShieldArea";
58 if (inShield && name.find(
"Magn") != std::string::npos &&
59 !volume->IsAssembly()) {
63 auto* box =
dynamic_cast<TGeoBBox*
>(volume->GetShape());
65 throw std::runtime_error(
"Shield magnet has no bounding box: " + name);
67 const auto* origin = box->GetOrigin();
68 for (
double x : {-box->GetDX(), box->GetDX()})
69 for (
double y : {-box->GetDY(), box->GetDY()})
70 for (
double z : {-box->GetDZ(), box->GetDZ()}) {
71 const double local[3] = {origin[0] + x, origin[1] + y,
74 transform.LocalToMaster(local, global);
78 for (
int i = 0; i < node->GetNdaughters(); ++i)
79 visit(node->GetDaughter(i), transform, inShield);
81 visit(
fTopNode, TGeoHMatrix(),
false);
85 double momentum,
double& time,
89 for (
double fraction : {0.25, 0.5, 0.75}) {
91 if (!
fPropagator->PositionAt(a.Z() + fraction * (b.Z() - a.Z()), point))
93 error = std::max(error, (point - (a + fraction * (b - a))).Mag());
94 if (fraction == 0.5) middle = point;
97 if (depth == 30)
return false;
101 const TVector3 displacement = b - a;
103 {{a, momentum * displacement.Unit(), time}, a.Z(), b.Z(),
false});
106 time += displacement.Mag() / speed;
111 double charge,
double endZ) {
115 double time = start.
time;
116 TVector3 previous = start.
position, position, momentum;
117 for (std::size_t i = 1; i <
fPropagator->GetTrajectorySize(); ++i) {
118 if (!
fPropagator->GetTrajectoryState(i, position, momentum) ||
128 const TVector3 direction = hit.
momentum.Unit();
129 double bestDistance = std::numeric_limits<double>::infinity();
130 double pocaZ =
fStart.position.Z();
134 const auto&
m = segment.measurement;
135 const TVector3 delta =
m.position - hit.
position;
136 const TVector3 slope =
m.momentum * (1. /
m.momentum.Z());
137 const TVector3 transverse = slope - slope.Dot(direction) * direction;
138 const double denominator = transverse.Mag2();
139 const double dz = denominator < 1.e-12
141 : std::clamp(-delta.Dot(transverse) / denominator, 0.,
142 segment.endZ - segment.startZ);
143 const TVector3 onTrack =
m.position + dz * slope;
144 const TVector3 onLine =
146 const double distance = (onTrack - onLine).Mag2();
147 if (distance < bestDistance) {
148 bestDistance = distance;
150 denominator < 1.e-12 ? onTrack.Z() : 0.5 * (onTrack.Z() + onLine.Z());
215 if (aEvt.
mcTrks.empty()) {
221 std::array<Measurement, 8> measurements;
223 aEvt.
mcTrks[0].GetStartVertex(measurements[0].position);
224 aEvt.
mcTrks[0].GetMomentum(measurements[0].momentum);
225 measurements[0].time = aEvt.
mcTrks[0].GetStartT();
226 const auto addHit = [&](
const auto& hit) {
227 auto& measurement = measurements[count++];
228 hit.Position(measurement.position);
229 hit.Momentum(measurement.momentum);
230 measurement.time = hit.GetTime();
232 if (!aEvt.
ubtPt.empty()) addHit(aEvt.
ubtPt.front());
233 if (!aEvt.
sbtPt.empty()) addHit(aEvt.
sbtPt.front());
234 std::array<bool, 4> found = {};
235 unsigned stations = 0;
236 for (
const auto& hit : aEvt.
sstPt) {
237 const int station = hit.GetDetectorID() / 1000000;
238 if (station < 1 || station > 4 || found[station - 1])
continue;
239 found[station - 1] =
true;
241 if (++stations == 4)
break;
243 if (!aEvt.
tdPt.empty()) addHit(aEvt.
tdPt.front());
245 for (
unsigned i = 0; i < count; ++i) {
246 const auto&
m = measurements[i];
247 if (!std::isfinite(
m.position.X()) || !std::isfinite(
m.position.Y()) ||
248 !std::isfinite(
m.position.Z()) || !std::isfinite(
m.momentum.X()) ||
249 !std::isfinite(
m.momentum.Y()) || !std::isfinite(
m.momentum.Z()) ||
250 !std::isfinite(
m.momentum.Mag()) || !std::isfinite(
m.time) ||
251 m.momentum.Mag() == 0.) {
256 if (
m.momentum.Z() <= 0.) {
261 if (
m.position.Z() < measurements[0].position.Z()) {
268 for (
unsigned i = 2; i < count; ++i) {
269 const auto measurement = measurements[i];
272 measurements[j - 1].position.Z() > measurement.position.Z()) {
273 measurements[j] = measurements[j - 1];
276 measurements[j] = measurement;
286 const bool hasUBT = !aEvt.
ubtPt.empty();
288 aEvt.
ubtPt.front().Position(
fUBT.position);
289 aEvt.
ubtPt.front().Momentum(
fUBT.momentum);
290 fUBT.time = aEvt.
ubtPt.front().GetTime();
292 double startZ =
fStart.position.Z();
298 for (
unsigned i = 1; i < count; ++i)
299 if (measurements[i].position.Z() >
fUBT.position.Z())
300 measurements[kept++] = measurements[i];
301 measurements[0] =
fUBT;
303 startZ =
fUBT.position.Z();
311 count > 1 ? std::min(
fZmax, measurements[1].position.Z()) :
fZmax;
312 const double charge = aEvt.
mcTrks[0].GetPdgCode() == 13 ? -1. : 1.;
314 LOG(error) <<
"Muon shield magnetic propagation failed at start z = "
340 throw std::runtime_error(
341 "Muon without UBT requires a configured shield field map");
345 for (
unsigned i = first; i < count && startZ <
fZmax; ++i) {
346 const auto&
m = measurements[i];
349 measurements[i + 1].position,
350 measurements[i + 1].momentum)
354 const double endZ = std::max(startZ, pocaZ);
355 fSegments.push_back({
m, startZ, endZ, i > 0});
362 const TVector3& r2,
const TVector3& p2) {
363 TVector3 u1 = p1.Unit();
364 TVector3 u2 = p2.Unit();
366 TVector3 w0 = r1 - r2;
375 double denom = a * c - b * b;
378 if (std::abs(denom) < 1e-12) {
379 LOG(
debug) <<
"GetVertex(): nearly parallel tracks (denominator = " << denom
380 <<
"). Returning first measurement.";
384 double t = (b * e - c * d) / denom;
385 double s = (a * e - b * d) / denom;
387 TVector3 poca1 = r1 + t * u1;
388 TVector3 poca2 = r2 + s * u2;
390 TVector3 vertex = 0.5 * (poca1 + poca2);
392 double zmin = std::min(r1.Z(), r2.Z());
393 double zmax = std::max(r1.Z(), r2.Z());
396 if (vertex.Z() < zmin) {
397 return (r1.Z() < r2.Z()) ? r1 : r2;
400 if (vertex.Z() > zmax) {
401 return (r1.Z() > r2.Z()) ? r1 : r2;
408 std::map<std::string, double> lMap;
409 std::map<std::pair<std::string, std::string>,
double> volumeMaterials;
411 LOG(error) <<
"gGeoManager does not exist!";
420 for (
int ix(-nS); ix < nS + 1; ++ix) {
421 for (
int iy(-nS); iy < nS + 1; ++iy) {
422 for (
int idx(-nSD); idx < nSD + 1; ++idx) {
423 for (
int idy(-nSD); idy < nSD + 1; ++idy) {
424 if (pow(idx * stepd, 2) + pow(idy * stepd, 2) > 1)
continue;
425 double dz = sqrt(1 - pow(idx * stepd, 2) - pow(idy * stepd, 2));
426 TGeoNode* startnode = gGeoManager->InitTrack(
427 ix * step, iy * step, z, idx * stepd, idy * stepd, dz);
429 LOG(error) <<
"Muon start point out of geometry: " << ix * step
430 <<
" " << iy * step <<
" " << z <<
" " << idx * stepd
431 <<
" " << idy * stepd <<
" " << dz;
434 TGeoNode* currentnode = gGeoManager->GetCurrentNode();
438 while (currentnode) {
439 const auto* geoMaterial =
440 currentnode->GetVolume()->GetMedium()->GetMaterial();
441 std::string material = geoMaterial->GetName();
442 std::string volName = currentnode->GetVolume()->GetName();
443 volumeMaterials.emplace(std::make_pair(volName, material),
444 geoMaterial->GetDensity());
447 volName.append(material);
448 lMap.emplace(volName, snext);
449 currentnode = gGeoManager->FindNextBoundaryAndStep();
450 snext += gGeoManager->GetStep() * dz;
454 LOG(info) <<
"Reached 1000 iterations in checking all volumes, "
456 << snext <<
" cm, x=" << ix * step <<
" y=" << iy * step
457 <<
" z=" << z <<
" dir_x=" << idx * stepd
458 <<
" dir_y=" << idy * stepd <<
" dir_z=" << dz;
468 LOG(info) <<
" -- All volumes found in geometry: n=" << lMap.size();
469 for (
auto lele = lMap.begin(); lele != lMap.end(); ++lele) {
470 LOG(info) << lele->first <<
" " << lele->second;
473 std::map<std::string, std::ostringstream> categoryOutput;
475 for (
const auto& entry : volumeMaterials) {
476 const auto& volName = entry.first.first;
477 const auto& material = entry.first.second;
478 categoryOutput[path.GetLabel(volName, material)]
479 <<
" volume=" << volName <<
", material=" << material
480 <<
", density=" << entry.second <<
" g/cm^3\n";
482 std::ostringstream summary;
483 summary <<
" -- Unique volumes and materials by MatType:\n";
485 summary <<
"MatType " << category.Data() <<
":\n"
486 << categoryOutput[category.Data()].str();
488 LOG(info) << summary.str();
489 std::ofstream output(
"CheckAllVolumes.txt");
490 output << summary.str();
493 LOG(warning) <<
"Could not write volume summary to CheckAllVolumes.txt";
503 double endZ,
bool backward) {
504 if (startZ == endZ)
return true;
505 const TVector3 forward = measurement.
momentum.Unit();
506 const TVector3 direction = backward ? -forward : forward;
507 const TVector3 start =
509 ((startZ - measurement.
position.Z()) / forward.Z()) * forward;
511 gGeoManager->InitTrack(start.X(), start.Y(), start.Z(), direction.X(),
512 direction.Y(), direction.Z());
513 std::vector<MuonPath> reverse;
515 bool reachedEnd =
false;
518 const auto* point = gGeoManager->GetCurrentPoint();
519 const TVector3 current(point[0], point[1], point[2]);
520 const double remaining = (endZ - current.Z()) / direction.Z();
521 if (remaining <= 1.e-8) {
525 if (++steps > 10000) {
526 LOG(error) <<
"Muon geometry stepping did not converge at z = "
530 const auto* volume = node->GetVolume();
531 const auto* material = volume->GetMaterial();
532 if (!material)
break;
533 const std::string name = volume->GetName();
535 double limit = remaining;
536 if (backward && shield)
538 node = gGeoManager->FindNextBoundaryAndStep(limit, kFALSE);
539 const double step = std::min(gGeoManager->GetStep(), limit);
540 if (!std::isfinite(step) || step < 0.)
break;
543 path.AddVolume(name, material->GetName(), material->GetDensity());
545 if (path.GetLabel() ==
"MS" && !shield) path.SetLabel(
"REST");
548 path.SetLength(step, backward ? current + step * direction : current,
550 fVolMap[path.GetLabel()].insert(name +
"_" + material->GetName());
552 reverse.push_back(path);
555 if (shield) shieldZ += step * forward.Z();
557 if (remaining - step <= 1.e-8 ||
564 if (!node && gGeoManager->IsOutside()) reachedEnd =
true;
566 for (
auto it = reverse.rbegin(); it != reverse.rend(); ++it)
AddPath(*it);
577 LOG(
debug) <<
"Muon starts at z = " <<
fStart.position.Z()
578 <<
" cm, before z_min = " <<
fZmin <<
" cm";
582 const double high = std::min(
fUBT.position.Z(),
fZmax);
584 if (high > low && !
Trace(
fUBT, high, low,
true)) {
592 <<
"UBT backward extrapolation does not cross MS: start position ("
593 <<
fStart.position.X() <<
", " <<
fStart.position.Y() <<
", "
594 <<
fStart.position.Z() <<
"), start momentum (" <<
fStart.momentum.X()
595 <<
", " <<
fStart.momentum.Y() <<
", " <<
fStart.momentum.Z()
596 <<
"), UBT position (" <<
fUBT.position.X() <<
", "
597 <<
fUBT.position.Y() <<
", " <<
fUBT.position.Z()
598 <<
"), UBT momentum (" <<
fUBT.momentum.X() <<
", "
599 <<
fUBT.momentum.Y() <<
", " <<
fUBT.momentum.Z() <<
"), start time "
604 bool hasPrevious =
false;
605 bool hasLargeJump =
false;
606 TVector3 previousEnd;
608 const auto&
m = segment.measurement;
609 const TVector3 direction =
m.momentum.Unit();
610 const TVector3 start =
612 ((segment.startZ -
m.position.Z()) / direction.Z()) * direction;
613 if (hasPrevious && segment.measurementTransition) {
614 const double jump = (start - previousEnd).Perp();
622 if (!
Trace(
m, segment.startZ, segment.endZ)) {
626 previousEnd =
m.position +
627 ((segment.endZ -
m.position.Z()) / direction.Z()) * direction;