From f1ceb5d7611d67dad803b5151f46a3bf799fab16 Mon Sep 17 00:00:00 2001 From: Sandro Wenzel Date: Fri, 20 Nov 2026 09:17:28 +0100 Subject: [PATCH 1/4] Start a new run of zero steps after a push into another volume This makes the VecGeom navigator start a new run of zero steps when a stuck-track push moved the track into a volume the run did not alternate between. - The new run counts from zero and decides again between chords and momentum steps. - A run restarts only if the track moved by at least half the push, and at most three times until the next finite step, so a track cannot be held forever. - The volumes of a run are recorded from its eighth zero step only. - The 10 um cap and the chord/momentum rule are unchanged. - This changes the output of the current locate too. - Two unit test cases cover the restart, the two conditions that prevent it, and the abort after the fourth run. Co-Authored-By: Claude Opus 5.5 --- Detectors/gconfig/src/VecGeomG4Navigator.cxx | 26 +++- Detectors/gconfig/src/VecGeomG4Navigator.h | 19 +++ .../gconfig/test/testVecGeomG4Navigator.cxx | 112 ++++++++++++++++++ 3 files changed, 155 insertions(+), 2 deletions(-) diff --git a/Detectors/gconfig/src/VecGeomG4Navigator.cxx b/Detectors/gconfig/src/VecGeomG4Navigator.cxx index b7bc6aed2b223..296b383b83149 100644 --- a/Detectors/gconfig/src/VecGeomG4Navigator.cxx +++ b/Detectors/gconfig/src/VecGeomG4Navigator.cxx @@ -64,6 +64,9 @@ VecGeomG4Navigator::~VecGeomG4Navigator() LOG(info) << "VecGeom parallel world: " << mParallelEntries << " steps ended on a node, " << mParallelRelocated << " locates overridden"; } + if (mPushRestartCount > 0) { + LOG(info) << "VecGeom stuck tracks: " << mPushRestartCount << " runs of zero steps restarted after a push"; + } } G4VPhysicalVolume* VecGeomG4Navigator::updateG4History() @@ -192,11 +195,26 @@ G4double VecGeomG4Navigator::ComputeStep(const G4ThreeVector& globalPoint, const // lengthened, after twenty-five the event is aborted. if (step < 0.05 * kCarTolerance) { ++mZeroStepCount; + // A push that took the track off its face and into a volume this run of zero steps did not alternate + // between starts a new run there, with its own chords and momentum. Bounded until the next finite step. + if (mPushPending && mPushRestarts < kMaxPushRestarts && + (globalPoint - mPushOrigin).mag2() >= 0.25 * mPushLength * mPushLength && !inZeroRun(mCurState)) { + mNzeroSteps = 0; + mZeroLinearSeen = false; + mZeroRunSize = 0; + ++mPushRestarts; + ++mPushRestartCount; + } + mPushPending = false; // Without a field Geant4 asks along the momentum it located the track with, and takes a lengthened step. // The field propagator asks along chords and takes a step longer than its chord for a miss. const bool linear = (direction - mLastLocatedDir).mag2() < 1.e-18; mZeroLinearSeen = mZeroLinearSeen || linear; - if (++mNzeroSteps >= kActionThresholdNoZeroSteps) { + // The volumes the run alternates between, recorded only when it gets near the threshold. + if (++mNzeroSteps >= kRecordZeroRun && mZeroRunSize < 2 && !inZeroRun(mCurState)) { + mZeroRun[mZeroRunSize++] = mCurState; + } + if (mNzeroSteps >= kActionThresholdNoZeroSteps) { // A track going back and forth over a face between a medium with a field and one without is tangent // to the face: the chord crosses it one way and the momentum the other way. The crossing along the // chord is left at zero length, so that it takes place, and the step along the momentum is lengthened. @@ -205,7 +223,11 @@ G4double VecGeomG4Navigator::ComputeStep(const G4ThreeVector& globalPoint, const // The push grows fourfold per try from 100 kCarTolerance, capped below the thinnest layers (15 um). constexpr double kMaxStuckPush = 10. * CLHEP::um; const int tries = mNzeroSteps - kActionThresholdNoZeroSteps; - step += std::min(100. * kCarTolerance * std::pow(4., tries), kMaxStuckPush); + const double push = std::min(100. * kCarTolerance * std::pow(4., tries), kMaxStuckPush); + step += push; + mPushPending = true; + mPushOrigin = globalPoint; + mPushLength = push; } if (mNzeroSteps >= kAbandonThresholdNoZeroSteps) { ++mAbandonCount; diff --git a/Detectors/gconfig/src/VecGeomG4Navigator.h b/Detectors/gconfig/src/VecGeomG4Navigator.h index 2e7c33921acf6..3d64f75856da4 100644 --- a/Detectors/gconfig/src/VecGeomG4Navigator.h +++ b/Detectors/gconfig/src/VecGeomG4Navigator.h @@ -134,10 +134,28 @@ class VecGeomG4Navigator : public VecGeomG4NavigatorBase static constexpr int kAbandonThresholdNoZeroSteps = 25; int mNzeroSteps = 0; bool mZeroLinearSeen = false; ///< a step along the located momentum occurred in the current run of zero steps + /// Restarts of a run of zero steps after a push, at most this many until the next finite step. + static constexpr int kMaxPushRestarts = 3; + int mPushRestarts = 0; + bool mPushPending = false; ///< the last zero step was lengthened + G4ThreeVector mPushOrigin; ///< where that step started + double mPushLength = 0.; ///< mm + static constexpr int kRecordZeroRun = kActionThresholdNoZeroSteps - 2; + /// The volumes the current run of zero steps alternates between, from its kRecordZeroRun-th step. + vecgeom::NavigationState mZeroRun[2]; + int mZeroRunSize = 0; + bool inZeroRun(vecgeom::NavigationState const& st) const + { + return (mZeroRunSize > 0 && mZeroRun[0].HasSamePathAsOther(st)) || + (mZeroRunSize > 1 && mZeroRun[1].HasSamePathAsOther(st)); + } void resetZeroSteps() { mNzeroSteps = 0; mZeroLinearSeen = false; + mPushRestarts = 0; + mPushPending = false; + mZeroRunSize = 0; } G4ThreeVector mLastLocatedDir; ///< the direction the last locate was given @@ -151,6 +169,7 @@ class VecGeomG4Navigator : public VecGeomG4NavigatorBase long mNoNormalCount = 0; long mParallelEntries = 0; ///< steps that ended on a parallel world node long mParallelRelocated = 0; ///< locates the parallel world overrode + long mPushRestartCount = 0; ///< runs of zero steps restarted after a push }; } // namespace o2::simsetup diff --git a/Detectors/gconfig/test/testVecGeomG4Navigator.cxx b/Detectors/gconfig/test/testVecGeomG4Navigator.cxx index b1cc9b90da0f8..8ae221c08269f 100644 --- a/Detectors/gconfig/test/testVecGeomG4Navigator.cxx +++ b/Detectors/gconfig/test/testVecGeomG4Navigator.cxx @@ -27,8 +27,10 @@ #include "TG4RootDetectorConstruction.h" +#include "G4StateManager.hh" #include "G4SystemOfUnits.hh" #include "G4TouchableHistory.hh" +#include "G4VExceptionHandler.hh" #include "G4VPhysicalVolume.hh" #include @@ -182,6 +184,53 @@ std::vector withTGeo(const double* p, const double* d) } return visits; } +/// Counts the events Geant4 would abort instead of aborting the test. +struct AbortCounter : public G4VExceptionHandler { + int aborts = 0; + G4bool Notify(const char*, const char* code, G4ExceptionSeverity severity, const char*) override + { + aborts += severity == EventMustBeAborted && std::string(code) == "GeomNav0003"; + return false; + } +}; + +/// The top face of the lead tile of the first paper of a tower: module (1-3), tower (1, 2), x offset (cm). +G4ThreeVector leadFace(int module, int tower, double dx = 0.) +{ + const double mx[] = {0., 0., 40.}, my[] = {-5., 5., 0.}; + return G4ThreeVector((mx[module - 1] + (tower == 1 ? -5. : 5.) + dx) * cm, my[module - 1] * cm, -8.45 * cm); +} + +/// Puts the track at \a p, as a boundary step there would, without a crossing. +void moveTo(G4Navigator& nav, const G4ThreeVector& p) +{ + const G4ThreeVector momentum(0., 1., 0.); + nav.LocateGlobalPointWithinVolume(p); + nav.SetGeometricallyLimitedStep(); + nav.LocateGlobalPointAndSetup(p, &momentum, true, false); +} + +/// Chords only, as under a field, alternately into the lead tile below \a p and out of it, at \a p. Returns the +/// first lengthened step (0 if none in \a maxSteps) and counts the zero steps before it. +double chordsUntilPush(G4Navigator& nav, const G4ThreeVector& p, int& zeroSteps, int maxSteps = 30) +{ + // Along y, parallel to the faces between towers, so that a push along them stays in the tower. + const G4ThreeVector in = G4ThreeVector(0., 1., -1.e-3).unit(), out = G4ThreeVector(0., 1., 2.e-3).unit(); + const G4ThreeVector momentum(0., 1., 0.); // never the direction of a step: every step is a chord + zeroSteps = 0; + for (int k = 0; k < maxSteps; ++k) { + G4double safety = 0.; + const bool inLead = touchablePath(nav).find("LEAD") != std::string::npos; + const double step = nav.ComputeStep(p, inLead ? out : in, 1.e6 * cm, safety); + nav.SetGeometricallyLimitedStep(); + nav.LocateGlobalPointAndSetup(p, &momentum, true, false); + if (step > 1.e-10 * mm) { + return step; + } + ++zeroSteps; + } + return 0.; +} } // namespace BOOST_AUTO_TEST_CASE(rays_visit_the_volumes_tgeo_visits) @@ -312,3 +361,66 @@ BOOST_AUTO_TEST_CASE(a_track_tangent_to_a_field_boundary_is_freed_along_its_mome BOOST_CHECK_EQUAL(pushedChords, 0); BOOST_CHECK(freed); } + +BOOST_AUTO_TEST_CASE(a_push_restarts_the_run_of_zero_steps_only_in_another_volume_it_reached) +{ + auto& nav = *fixture().navigator; + const G4ThreeVector momentum(0., 1., 0.); + int zero = 0; + // A run of chords on the lead face of tower 1, 2 nm from tower 2: the tenth zero step is pushed by 0.1 nm. + const G4ThreeVector p(-2.e-7 * cm, -5. * cm, -8.45 * cm); + nav.LocateGlobalPointAndSetup(p, &momentum, false, false); + BOOST_CHECK_CLOSE(chordsUntilPush(nav, p, zero), 1.e-7 * mm, 0.01); + BOOST_CHECK_EQUAL(zero, 9); + // Moved along the same face by ten times the push, still in the volumes of the run: no restart, the next zero + // step is pushed at once, and the push goes on growing. + const G4ThreeVector same(-1.e-7 * cm, -5. * cm, -8.45 * cm); + moveTo(nav, same); + double push = 0.; + for (int k = 1; k < 4; ++k) { + push = chordsUntilPush(nav, same, zero); + BOOST_CHECK_EQUAL(zero, 0); + BOOST_CHECK_CLOSE(push, 1.e-7 * mm * std::pow(4., k), 0.01); + } + // Into tower 2, a volume the run never visited, but by less than half the last push: no restart either. + const G4ThreeVector close(1.e-7 * cm, -5. * cm, -8.45 * cm); + BOOST_REQUIRE_LT((close - same).mag(), 0.5 * push); + moveTo(nav, close); + BOOST_CHECK_NE(touchablePath(nav).find("TOWR_2"), std::string::npos); + BOOST_CHECK_GT(chordsUntilPush(nav, close, zero), 0.); + BOOST_CHECK_EQUAL(zero, 0); + // Into another module, far and new: the run starts again. + const G4ThreeVector far = leadFace(2, 1); + moveTo(nav, far); + BOOST_CHECK_GT(chordsUntilPush(nav, far, zero), 0.); + BOOST_CHECK_EQUAL(zero, 9); +} + +BOOST_AUTO_TEST_CASE(a_track_pushed_from_place_to_place_is_aborted_after_its_fourth_run) +{ + auto& nav = *fixture().navigator; + static AbortCounter handler; // registered with Geant4 for the rest of the process + handler.aborts = 0; + const G4ThreeVector momentum(0., 1., 0.); + int zero = 0; + // Four places, each reached by a push and each a volume the previous run did not visit: three restarts. + const G4ThreeVector places[] = {leadFace(1, 1), leadFace(1, 2), leadFace(2, 1), leadFace(2, 2)}; + nav.LocateGlobalPointAndSetup(places[0], &momentum, false, false); + for (const auto& p : places) { + if (&p != &places[0]) { + moveTo(nav, p); + } + BOOST_CHECK_GT(chordsUntilPush(nav, p, zero), 0.); + BOOST_CHECK_EQUAL(zero, 9); + } + // A fifth place does not restart the run: it goes on to the abort. + const G4ThreeVector last = leadFace(3, 1); + moveTo(nav, last); + int steps = 0; + for (; steps < 30 && handler.aborts == 0; ++steps) { + chordsUntilPush(nav, last, zero, 1); + } + BOOST_CHECK_EQUAL(handler.aborts, 1); + // The fourth run had reached ten zero steps, so fifteen more reach the abort at twenty-five. + BOOST_CHECK_EQUAL(steps, 15); +} From c856da20fa87e03ebaf4a2d0fd73b0828bc67104 Mon Sep 17 00:00:00 2001 From: Sandro Wenzel Date: Fri, 20 Nov 2026 19:46:01 +0100 Subject: [PATCH 2/4] Update the Geant4 history of the VecGeom navigators incrementally This makes both VecGeom navigators update the Geant4 history incrementally for the three common transitions. - Entering a daughter of the current volume adds that placement's chain of Geant4 levels. - Leaving to the mother removes it, and moving into a sibling replaces it. - Every other change still goes through historyFromState, which walked every level on every crossing. - The update lives in the base class, so the relocating and the propagating navigator share it. - The history is the same as before: the levels and their transforms are made by the same NewLevel calls. Co-Authored-By: Claude Opus 5.5 --- Detectors/gconfig/src/VecGeomG4Navigator.cxx | 22 ++--- Detectors/gconfig/src/VecGeomG4Navigator.h | 26 +++--- .../gconfig/src/VecGeomG4NavigatorBase.cxx | 84 +++++++++++++++++-- .../gconfig/src/VecGeomG4NavigatorBase.h | 30 +++++++ .../src/VecGeomG4PropagatingNavigator.cxx | 5 +- 5 files changed, 126 insertions(+), 41 deletions(-) diff --git a/Detectors/gconfig/src/VecGeomG4Navigator.cxx b/Detectors/gconfig/src/VecGeomG4Navigator.cxx index 296b383b83149..653fe16c88a1c 100644 --- a/Detectors/gconfig/src/VecGeomG4Navigator.cxx +++ b/Detectors/gconfig/src/VecGeomG4Navigator.cxx @@ -67,17 +67,8 @@ VecGeomG4Navigator::~VecGeomG4Navigator() if (mPushRestartCount > 0) { LOG(info) << "VecGeom stuck tracks: " << mPushRestartCount << " runs of zero steps restarted after a push"; } -} - -G4VPhysicalVolume* VecGeomG4Navigator::updateG4History() -{ - // The history is a function of the VecGeom state alone, so it is rebuilt only when that changed. - if (mHistoryValid && mCurState.HasSamePathAsOther(mHistoryState)) { - return fHistory.GetTopVolume(); - } - mHistoryState = mCurState; - mHistoryValid = true; - return historyFromState(mCurState); + LOG(debug) << "VecGeom history: " << mHistoryStepCount << " updated by one level, " << mHistoryRebuildCount + << " rebuilt"; } void VecGeomG4Navigator::locateFromWorld(const V3& point) @@ -439,7 +430,7 @@ G4VPhysicalVolume* VecGeomG4Navigator::LocateGlobalPointAndSetup(const G4ThreeVe } mWouldEnter = false; mWouldExit = false; - return updateG4History(); + return updateHistory(mCurState); } /// TGeo's rule: the node added first among those holding the point is where the track is. The @@ -525,12 +516,11 @@ G4VPhysicalVolume* VecGeomG4Navigator::ResetHierarchyAndLocate(const G4ThreeVect } if (kept) { // The touchable's history is the path of the state: keep it rather than rebuild it. - mHistoryState = mCurState; - mHistoryValid = true; + keepTouchableHistory(mCurState); return fHistory.GetTopVolume(); } - mHistoryValid = false; - return updateG4History(); + invalidateHistory(); + return updateHistory(mCurState); } void VecGeomG4Navigator::LocateGlobalPointWithinVolume(const G4ThreeVector& position) diff --git a/Detectors/gconfig/src/VecGeomG4Navigator.h b/Detectors/gconfig/src/VecGeomG4Navigator.h index 3d64f75856da4..44f3c39fbd045 100644 --- a/Detectors/gconfig/src/VecGeomG4Navigator.h +++ b/Detectors/gconfig/src/VecGeomG4Navigator.h @@ -65,8 +65,6 @@ class VecGeomG4Navigator : public VecGeomG4NavigatorBase G4ThreeVector GetGlobalExitNormal(const G4ThreeVector& point, G4bool* valid) override; private: - /// Rewrites the Geant4 history from mCurState, unless it already stands for it. - G4VPhysicalVolume* updateG4History(); void locateFromWorld(const V3& point); /// Go up past every volume the point is on the surface of and heading out of, then down again. void leaveFlushVolumes(const V3& point, const V3& dir, int minLevel, vecgeom::NavigationState const* avoid); @@ -101,20 +99,18 @@ class VecGeomG4Navigator : public VecGeomG4NavigatorBase VecGeomParallelWorld const* mParallelWorld = nullptr; bool mInParallelNode = false; ///< the track is in a parallel world node; changed by the locates only - vecgeom::NavigationState mCurState; ///< the volume the track is in; changed by the locates only - vecgeom::NavigationState mNextState; ///< the state entering the daughter the last ComputeStep hit - vecgeom::NavigationState mStepState; ///< scratch: a trial step - vecgeom::NavigationState mReloScratch; ///< scratch: the state before a crossing - vecgeom::NavigationState mPathScratch; ///< scratch: path comparisons - vecgeom::NavigationState mHistoryState; ///< the state fHistory was built from - vecgeom::NavigationState mEmptyState; ///< permanently empty; its last-exited entry clears others - vecgeom::NavigationState mNormalState; ///< the volume whose surface the last boundary step ended on - vecgeom::NavigationState mExitedState; ///< the volume the last crossing left - bool mExitBlockPending = false; ///< the next ComputeStep is the first after that exit - bool mExitNormalFromPush = false; ///< mPushNormal is the outward normal of the volume left - V3 mPushNormal; ///< global normal of the face the last push crossed + vecgeom::NavigationState mCurState; ///< the volume the track is in; changed by the locates only + vecgeom::NavigationState mNextState; ///< the state entering the daughter the last ComputeStep hit + vecgeom::NavigationState mStepState; ///< scratch: a trial step + vecgeom::NavigationState mReloScratch; ///< scratch: the state before a crossing + vecgeom::NavigationState mPathScratch; ///< scratch: path comparisons + vecgeom::NavigationState mEmptyState; ///< permanently empty; its last-exited entry clears others + vecgeom::NavigationState mNormalState; ///< the volume whose surface the last boundary step ended on + vecgeom::NavigationState mExitedState; ///< the volume the last crossing left + bool mExitBlockPending = false; ///< the next ComputeStep is the first after that exit + bool mExitNormalFromPush = false; ///< mPushNormal is the outward normal of the volume left + V3 mPushNormal; ///< global normal of the face the last push crossed bool mPushNormalValid = false; - bool mHistoryValid = false; bool mWouldEnter = false; ///< the last ComputeStep ends by entering a daughter bool mWouldExit = false; ///< the last ComputeStep ends by leaving the current volume diff --git a/Detectors/gconfig/src/VecGeomG4NavigatorBase.cxx b/Detectors/gconfig/src/VecGeomG4NavigatorBase.cxx index 673236905552b..4fb4786600ad6 100644 --- a/Detectors/gconfig/src/VecGeomG4NavigatorBase.cxx +++ b/Detectors/gconfig/src/VecGeomG4NavigatorBase.cxx @@ -24,12 +24,6 @@ #include -namespace -{ -/// Deepest Geant4 touchable the ALICE geometry can produce, with headroom. -constexpr int kMaxDepth = 64; -} // namespace - namespace o2::simsetup { @@ -61,11 +55,11 @@ G4VPhysicalVolume* VecGeomG4NavigatorBase::historyFromState(vecgeom::NavigationS { // Collect the Geant4 volumes the state stands for, then keep the levels the history already has // right and rebuild only from the first difference down: NewLevel composes a transform per level. - G4VPhysicalVolume* want[kMaxDepth]; + G4VPhysicalVolume* want[kMaxHistoryDepth]; int n = 0; if (!state.IsOutside()) { const int levels = state.GetCurrentLevel(); - for (int l = 0; l < levels && n < kMaxDepth; ++l) { + for (int l = 0; l < levels && n < kMaxHistoryDepth; ++l) { auto const* placed = state.At(l); if (placed == nullptr) { break; @@ -76,7 +70,7 @@ G4VPhysicalVolume* VecGeomG4NavigatorBase::historyFromState(vecgeom::NavigationS LOG(fatal) << "VecGeom placement " << placed->GetLabel() << " (id " << placed->id() << ") at level " << l << " has no Geant4 counterpart"; } - for (unsigned c = 0; c < size && n < kMaxDepth; ++c) { + for (unsigned c = 0; c < size && n < kMaxHistoryDepth; ++c) { want[n++] = chain[c]; } } @@ -109,6 +103,78 @@ G4VPhysicalVolume* VecGeomG4NavigatorBase::historyFromState(vecgeom::NavigationS return fHistory.GetTopVolume(); } +G4VPhysicalVolume* VecGeomG4NavigatorBase::updateHistory(vecgeom::NavigationState const& state) +{ + if (mHistoryValid && state.HasSamePathAsOther(mHistoryState)) { + return fHistory.GetTopVolume(); + } + if (mHistoryExact && updateHistoryByOneLevel(state)) { + ++mHistoryStepCount; + return fHistory.GetTopVolume(); + } + ++mHistoryRebuildCount; + mHistoryState = state; + mHistoryValid = true; + auto* top = historyFromState(state); + // A history at the depth limit may have been cut short. + mHistoryExact = static_cast(fHistory.GetDepth()) + 1 < kMaxHistoryDepth; + return top; +} + +/// The levels and transforms are those historyFromState makes: it keeps the common Geant4 levels and calls +/// NewLevel for the rest, as here. +bool VecGeomG4NavigatorBase::updateHistoryByOneLevel(vecgeom::NavigationState const& state) +{ + if (state.IsOutside() || mHistoryState.IsOutside()) { + return false; + } + const int cur = state.GetCurrentLevel(); + const int old = mHistoryState.GetCurrentLevel(); + const int levels = static_cast(fHistory.GetDepth()) + 1; + unsigned left = 0, size = 0; + G4VPhysicalVolume* const* chain = nullptr; + if (cur == old + 1) { // into a daughter + mHistoryChild = state; + mHistoryChild.Pop(); + if (!mHistoryChild.HasSamePathAsOther(mHistoryState)) { + return false; + } + chain = mMap.chain(state.Top()->id(), size); + } else if (cur + 1 == old) { // out to the mother + mHistoryParent = mHistoryState; + mHistoryParent.Pop(); + if (!mHistoryParent.HasSamePathAsOther(state)) { + return false; + } + mMap.chain(mHistoryState.Top()->id(), left); + } else if (cur == old && cur > 1) { // into a sibling + mHistoryChild = state; + mHistoryChild.Pop(); + mHistoryParent = mHistoryState; + mHistoryParent.Pop(); + if (!mHistoryChild.HasSamePathAsOther(mHistoryParent)) { + return false; + } + mMap.chain(mHistoryState.Top()->id(), left); + chain = mMap.chain(state.Top()->id(), size); + } else { + return false; + } + if ((chain != nullptr && size == 0) || (cur <= old && left == 0) || static_cast(left) >= levels || + levels - static_cast(left) + static_cast(size) > kMaxHistoryDepth) { + return false; + } + if (left > 0) { + fHistory.BackLevel(left); + } + for (unsigned c = 0; c < size; ++c) { + // The copy number is filled exactly as historyFromState fills it. + fHistory.NewLevel(chain[c], kNormal, chain[c]->GetCopyNo()); + } + mHistoryState = state; + return true; +} + bool VecGeomG4NavigatorBase::stateFromHistory(vecgeom::NavigationState& state) const { return mMap.stateFromPath([this](std::size_t level) { return fHistory.GetVolume(level); }, fHistory.GetDepth(), state); diff --git a/Detectors/gconfig/src/VecGeomG4NavigatorBase.h b/Detectors/gconfig/src/VecGeomG4NavigatorBase.h index f3ebeb1dcc9d7..c38bcbd598fa4 100644 --- a/Detectors/gconfig/src/VecGeomG4NavigatorBase.h +++ b/Detectors/gconfig/src/VecGeomG4NavigatorBase.h @@ -36,6 +36,8 @@ class VecGeomG4NavigatorBase : public G4Navigator using V3 = vecgeom::Vector3D; static constexpr double kG4ToVG = 1. / CLHEP::cm; static constexpr double kVGToG4 = CLHEP::cm; + /// Deepest Geant4 touchable the ALICE geometry can produce, with headroom. + static constexpr int kMaxHistoryDepth = 64; explicit VecGeomG4NavigatorBase(VecGeomG4Map const& map) : mMap(map) {} @@ -46,6 +48,23 @@ class VecGeomG4NavigatorBase : public G4Navigator /// top volume, or null if the state is outside the world. G4VPhysicalVolume* historyFromState(vecgeom::NavigationState const& state); + /// Makes fHistory stand for \a state: nothing if it already does, one placement's chain of Geant4 levels for + /// a step into a daughter, out to the mother or into a sibling, historyFromState otherwise. + G4VPhysicalVolume* updateHistory(vecgeom::NavigationState const& state); + /// fHistory was taken from a touchable that names \a state; it is kept, but not changed by one level. + void keepTouchableHistory(vecgeom::NavigationState const& state) + { + mHistoryState = state; + mHistoryValid = true; + mHistoryExact = false; + } + /// fHistory no longer follows the states updateHistory was given. + void invalidateHistory() + { + mHistoryValid = false; + mHistoryExact = false; + } + /// Builds \a state from fHistory, extending past the Geant4 levels assembly flattening dissolved. /// False if a level matches no VecGeom placement; \a state is then empty. bool stateFromHistory(vecgeom::NavigationState& state) const; @@ -80,6 +99,17 @@ class VecGeomG4NavigatorBase : public G4Navigator } VecGeomG4Map const& mMap; + long mHistoryStepCount = 0; ///< history updates by one level + long mHistoryRebuildCount = 0; ///< history updates by historyFromState + + private: + bool updateHistoryByOneLevel(vecgeom::NavigationState const& state); + + vecgeom::NavigationState mHistoryState; ///< the state fHistory was built from + vecgeom::NavigationState mHistoryChild; ///< scratch + vecgeom::NavigationState mHistoryParent; ///< scratch + bool mHistoryValid = false; + bool mHistoryExact = false; ///< fHistory is what historyFromState makes of mHistoryState }; } // namespace o2::simsetup diff --git a/Detectors/gconfig/src/VecGeomG4PropagatingNavigator.cxx b/Detectors/gconfig/src/VecGeomG4PropagatingNavigator.cxx index b03fa14b0b959..1cbc24951a999 100644 --- a/Detectors/gconfig/src/VecGeomG4PropagatingNavigator.cxx +++ b/Detectors/gconfig/src/VecGeomG4PropagatingNavigator.cxx @@ -47,6 +47,8 @@ VecGeomG4PropagatingNavigator::~VecGeomG4PropagatingNavigator() { LOG(info) << "VecGeom navigation: " << mNudgedSteps << " stalled steps nudged forward, " << mGlobalRelocates << " relocations restarted from the world"; + LOG(debug) << "VecGeom history: " << mHistoryStepCount << " updated by one level, " << mHistoryRebuildCount + << " rebuilt"; } G4double VecGeomG4PropagatingNavigator::ComputeStep(const G4ThreeVector& globalPoint, const G4ThreeVector& direction, @@ -136,6 +138,7 @@ G4VPhysicalVolume* VecGeomG4PropagatingNavigator::ResetHierarchyAndLocate(const mHaveNextState = false; mLastSafety = -1.; fHistory = *history.GetHistory(); + invalidateHistory(); if (!stateFromHistory(mCurState) && fHistory.GetVolume(0) != nullptr) { LOG(fatal) << "Geant4 handed back a touchable that matches no VecGeom path"; } @@ -170,7 +173,7 @@ G4VPhysicalVolume* VecGeomG4PropagatingNavigator::LocateGlobalPointAndSetup(cons } // Otherwise the point only moved inside the volume the state already names. - auto* target = historyFromState(mCurState); + auto* target = updateHistory(mCurState); mCrossed = onBoundary; if (onBoundary) { fExitedMother = mWouldExit; From 125348a88e3367a3b709a27bb7285f44931afe9c Mon Sep 17 00:00:00 2001 From: Sandro Wenzel Date: Thu, 19 Nov 2026 19:41:05 +0100 Subject: [PATCH 3/4] Add a lean crossing locate to the relocating VecGeom navigator This adds a run-time switch G4.vecgeomLeanLocate (default off) that locates a boundary crossing of the relocating VecGeom navigator the way VecGeom relocates. - The point is pushed 1e-6 cm along the step direction, VecGeom's own push, instead of one tolerance across the face. - No face normal is computed for the push, and the flush-volume loop is not run: at that depth containment pops every flush mother. - An exit no longer records a block for the next step. Every mother with daughters is stepped with BVHNavigatorV, which refuses at zero distance a daughter the ray leaves. - A parallel world node just left is still refused while the direction leaves it, with the normal computed only for that node. - The navigator unit test runs every case with both locates. Co-Authored-By: Claude Opus 5.5 --- Common/SimConfig/include/SimConfig/G4Params.h | 2 + Detectors/gconfig/src/VecGeomG4Navigator.cxx | 39 +- Detectors/gconfig/src/VecGeomG4Navigator.h | 11 +- Detectors/gconfig/src/VecGeomNavigation.cxx | 6 +- .../gconfig/test/testVecGeomG4Navigator.cxx | 352 ++++++++++-------- 5 files changed, 243 insertions(+), 167 deletions(-) diff --git a/Common/SimConfig/include/SimConfig/G4Params.h b/Common/SimConfig/include/SimConfig/G4Params.h index 216f6f8d71cf2..a2e82ab61845e 100644 --- a/Common/SimConfig/include/SimConfig/G4Params.h +++ b/Common/SimConfig/include/SimConfig/G4Params.h @@ -62,6 +62,8 @@ struct G4Params : public o2::conf::ConfigurableParamHelper { EVecGeomNav vecgeomNavigator = EVecGeomNav::kRelocating; double vecgeomPushDepth = 1.e-9; // cm; how far past a face, measured across it, a boundary // point is pushed before it is located + bool vecgeomLeanLocate = false; // kRelocating: locate a crossing 10 nm along the step, as VecGeom + // relocates, instead of across the face with the flush-volume loop bool vecgeomZeroSafety = false; // answer zero to every safety query; conservative, but it // shortens steps and so changes the random history bool vecgeomFlattenAssemblies = true; // dissolve TGeo assemblies into their content when converting diff --git a/Detectors/gconfig/src/VecGeomG4Navigator.cxx b/Detectors/gconfig/src/VecGeomG4Navigator.cxx index 653fe16c88a1c..fa883a34718cd 100644 --- a/Detectors/gconfig/src/VecGeomG4Navigator.cxx +++ b/Detectors/gconfig/src/VecGeomG4Navigator.cxx @@ -19,6 +19,7 @@ #include #include +#include #include #include #include @@ -48,8 +49,12 @@ namespace o2::simsetup { VecGeomG4Navigator::VecGeomG4Navigator(VecGeomG4Map const& map, double pushDepth, bool zeroSafety, - VecGeomParallelWorld const* parallelWorld) - : VecGeomG4NavigatorBase(map), mPushDepth(pushDepth), mZeroSafety(zeroSafety), mParallelWorld(parallelWorld) + VecGeomParallelWorld const* parallelWorld, bool leanLocate) + : VecGeomG4NavigatorBase(map), + mPushDepth(pushDepth), + mZeroSafety(zeroSafety), + mLeanLocate(leanLocate), + mParallelWorld(parallelWorld) { mEmptyState.Clear(); } @@ -119,7 +124,10 @@ G4double VecGeomG4Navigator::ComputeStep(const G4ThreeVector& globalPoint, const if (top == nullptr) { // the track is outside the world return kInfinity; } - auto const* navigator = top->GetLogicalVolume()->GetNavigator(); + auto const* lvol = top->GetLogicalVolume(); + // The lean locate relies on the BVH navigator refusing a daughter the ray leaves, also for small mothers. + auto const* navigator = mLeanLocate && lvol->GetDaughtersp()->size() > 0 ? vecgeom::BVHNavigatorV<>::Instance() + : lvol->GetNavigator(); // On the point a boundary locate left the track on, the safety is zero; a point seen before // reuses its safety. Otherwise the navigator computes it with the step. @@ -135,7 +143,11 @@ G4double VecGeomG4Navigator::ComputeStep(const G4ThreeVector& globalPoint, const // while the direction points away from it; a track turning back into it must see its boundary. mStepState = mCurState; bool blockExited = false; - if (mExitBlockPending) { + bool leanExitPending = false; // a parallel world node left by the lean locate is blocked by the same rule + if (mExitBlockPending && mLeanLocate) { + leanExitPending = samePoint(globalPoint, mLastLocatedPoint); + mExitBlockPending = false; + } else if (mExitBlockPending) { const bool block = samePoint(globalPoint, mLastLocatedPoint) && (mExitNormalFromPush ? directionLeaves(mPushNormal, toDir(direction)) : directionLeaves(mExitedState, toVG(globalPoint), toDir(direction))); @@ -158,6 +170,9 @@ G4double VecGeomG4Navigator::ComputeStep(const G4ThreeVector& globalPoint, const const V3 p = toVG(globalPoint); double pwStep = std::min(std::max(vgStep, 0.), limit); parallelHit = mParallelWorld->distanceToIn(p, toDir(direction), pwStep, [&](int node) { + if (leanExitPending) { + return mParallelWorld->isInNode(node, mExitedState) && directionLeaves(mExitedState, p, toDir(direction)); + } return blockExited && mParallelWorld->isInNode(node, mExitedState); }); if (parallelHit >= 0) { @@ -355,7 +370,7 @@ G4VPhysicalVolume* VecGeomG4Navigator::LocateGlobalPointAndSetup(const G4ThreeVe // here is the one after the step, which multiple scattering can have turned back into the volume left; // the track then belongs to what lies behind the face, as G4Navigator does, not to the mother of the two. const V3 dir = crossing ? mNextDir : (direction != nullptr ? toDir(*direction) : V3(0., 0., 0.)); - const double push = (onBoundary && direction != nullptr) ? boundaryPush(p, dir) : 0.; + const double push = (onBoundary && direction != nullptr) ? (mLeanLocate ? kLeanPush : boundaryPush(p, dir)) : 0.; const V3 q = p + push * dir; fWasLimitedByGeometry = false; @@ -388,6 +403,18 @@ G4VPhysicalVolume* VecGeomG4Navigator::LocateGlobalPointAndSetup(const G4ThreeVe mReloScratch = mCurState; if (mCurState.GetCurrentLevel() <= 1) { mCurState.Clear(); // left the world + } else if (mLeanLocate) { + // The volume left is popped whatever the point; ten nanometres past the face, containment pops + // every flush mother too. The next step refuses the volume left by the BVH navigator's rule. + vecgeom::Transformation3D m; + mCurState.TopMatrix(m); + vecgeom::GlobalLocator::RelocatePointFromPathForceDifferent(m.Transform(q), mCurState); + if (topOf(mCurState) == nullptr) { + mCurState.Clear(); + } + if (mParallelWorld != nullptr) { + setExited(mReloScratch, false); + } } else { vecgeom::Transformation3D m; mCurState.TopMatrix(m); @@ -418,7 +445,7 @@ G4VPhysicalVolume* VecGeomG4Navigator::LocateGlobalPointAndSetup(const G4ThreeVe } mLocatedOnBoundary = onBoundary; } - if (crossing) { + if (crossing && !mLeanLocate) { leaveFlushVolumes(q, dir, entering ? static_cast(mNextState.GetCurrentLevel()) : 0, entering || topOf(mReloScratch) == nullptr ? nullptr : &mReloScratch); } diff --git a/Detectors/gconfig/src/VecGeomG4Navigator.h b/Detectors/gconfig/src/VecGeomG4Navigator.h index 44f3c39fbd045..8a1eeb6785c2c 100644 --- a/Detectors/gconfig/src/VecGeomG4Navigator.h +++ b/Detectors/gconfig/src/VecGeomG4Navigator.h @@ -30,6 +30,10 @@ class VecGeomParallelWorld; /// The point is first pushed across the face by a small depth, and afterwards leaves every volume /// it is flush with and heading out of. As in Geant4, the volume left is blocked only in the first /// ComputeStep after the exit, and only while the direction points away from it. +/// - With the lean locate (G4.vecgeomLeanLocate) the point is pushed 10 nm along the step instead, +/// which takes it past every coincident face, so no flush-volume loop is needed. Every mother with +/// daughters is then stepped with the BVH navigator, whose daughter query refuses at zero distance a +/// daughter the ray is leaving; that is the block of the volume just left, without a normal. /// - Safety is zero only at the boundary point itself. A bounded query is answered from the last safety /// computed in the same volume when that covers the bound. /// @@ -41,8 +45,10 @@ class VecGeomG4Navigator : public VecGeomG4NavigatorBase /// \param pushDepth how far past a face (cm, measured across it) a boundary point is pushed before /// it is located. \param zeroSafety answers zero to every safety query. /// \param parallelWorld the prioritised placements, or null if there are none. + /// \param leanLocate locates a crossing as VecGeom relocates: 10 nm along the step, no face normal, no + /// flush-volume loop; the volume left is refused by the BVH navigator's rule for a daughter the ray leaves. VecGeomG4Navigator(VecGeomG4Map const& map, double pushDepth, bool zeroSafety, - VecGeomParallelWorld const* parallelWorld = nullptr); + VecGeomParallelWorld const* parallelWorld = nullptr, bool leanLocate = false); ~VecGeomG4Navigator() override; G4double ComputeStep(const G4ThreeVector& globalPoint, const G4ThreeVector& direction, @@ -96,6 +102,9 @@ class VecGeomG4Navigator : public VecGeomG4NavigatorBase double mPushDepth = 1.e-9; ///< cm bool mZeroSafety = false; + bool mLeanLocate = false; + /// The push of the lean locate, VecGeom's own after a boundary (VNavigator::MovePointAfterBoundary), cm. + static constexpr double kLeanPush = 1.e-6; VecGeomParallelWorld const* mParallelWorld = nullptr; bool mInParallelNode = false; ///< the track is in a parallel world node; changed by the locates only diff --git a/Detectors/gconfig/src/VecGeomNavigation.cxx b/Detectors/gconfig/src/VecGeomNavigation.cxx index 3478e54a70fa9..5210efaf650eb 100644 --- a/Detectors/gconfig/src/VecGeomNavigation.cxx +++ b/Detectors/gconfig/src/VecGeomNavigation.cxx @@ -123,7 +123,11 @@ void installVecGeomNavigator() LOG(info) << "VecGeom navigation: propagating navigator"; navigator = new VecGeomG4PropagatingNavigator(map, g4Params.vecgeomZeroSafety); } else { - navigator = new VecGeomG4Navigator(map, g4Params.vecgeomPushDepth, g4Params.vecgeomZeroSafety, parallelWorldPtr); + if (g4Params.vecgeomLeanLocate) { + LOG(info) << "VecGeom relocating navigator with the lean locate"; + } + navigator = new VecGeomG4Navigator(map, g4Params.vecgeomPushDepth, g4Params.vecgeomZeroSafety, parallelWorldPtr, + g4Params.vecgeomLeanLocate); } navigator->SetWorldVolume(detConstruction->GetTopPV()); diff --git a/Detectors/gconfig/test/testVecGeomG4Navigator.cxx b/Detectors/gconfig/test/testVecGeomG4Navigator.cxx index 8ae221c08269f..2ddccd2ff2fc1 100644 --- a/Detectors/gconfig/test/testVecGeomG4Navigator.cxx +++ b/Detectors/gconfig/test/testVecGeomG4Navigator.cxx @@ -12,7 +12,7 @@ /// The relocating VecGeom navigator against TGeo on a geometry of coinciding faces: two copies of a tower /// side by side that fill their mother, each a stack of tiles that reach the tower's faces, as in a sampling /// calorimeter. A ray has to visit the same volumes in the same order, and never stop for a zero-length step -/// in a mother it only touches. +/// in a mother it only touches. Every case runs with the default locate and with the lean one. #define BOOST_TEST_MODULE Test SimSetup VecGeomG4Navigator #define BOOST_TEST_MAIN @@ -56,6 +56,7 @@ struct Fixture { std::unique_ptr construction; VecGeomG4Map map; std::unique_ptr navigator; + std::unique_ptr lean; // the same with G4.vecgeomLeanLocate Fixture() { @@ -90,6 +91,8 @@ struct Fixture { map.build(*construction, true); navigator = std::make_unique(map, 1.e-9, false); navigator->SetWorldVolume(world); + lean = std::make_unique(map, 1.e-9, false, nullptr, true); + lean->SetWorldVolume(world); } }; @@ -99,6 +102,12 @@ Fixture& fixture() return f; } +/// Both locates: the default one and the lean one. +std::vector> navigators() +{ + return {{"default locate", fixture().navigator.get()}, {"lean locate", fixture().lean.get()}}; +} + /// The path of the navigator's touchable, in TGeo's notation. std::string touchablePath(G4Navigator& nav) { @@ -235,192 +244,217 @@ double chordsUntilPush(G4Navigator& nav, const G4ThreeVector& p, int& zeroSteps, BOOST_AUTO_TEST_CASE(rays_visit_the_volumes_tgeo_visits) { - auto& f = fixture(); - std::mt19937_64 gen(1); - std::uniform_real_distribution u(-1., 1.); - std::normal_distribution g; - int rays = 0, differentCount = 0, differentPath = 0, differentLength = 0, zeroSteps = 0, crossings = 0; - std::string firstDifference; - for (int r = 0; r < 20000; ++r) { - // start inside the two touching modules, off every face - const double p[3] = {9.9 * u(gen), 9.9 * u(gen), 9.9 * u(gen)}; - double d[3] = {g(gen), g(gen), 0.3 * g(gen)}; - const double norm = std::sqrt(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]); - for (auto& x : d) { - x /= norm; - } - const auto expected = withTGeo(p, d); - const auto found = withNavigator(*f.navigator, p, d, zeroSteps); - ++rays; - crossings += expected.size(); - if (found.size() != expected.size()) { - ++differentCount; - if (firstDifference.empty()) { - firstDifference = Form("ray %d: %zu visits, TGeo %zu", r, found.size(), expected.size()); - } - continue; - } - for (std::size_t i = 0; i < found.size(); ++i) { - if (found[i].path != expected[i].path) { - ++differentPath; - if (firstDifference.empty()) { - firstDifference = Form("ray %d visit %zu: %s, TGeo %s", r, i, found[i].path.c_str(), expected[i].path.c_str()); + for (auto& [name, navp] : navigators()) { + auto& nav = *navp; + BOOST_TEST_CONTEXT(name) + { + std::mt19937_64 gen(1); + std::uniform_real_distribution u(-1., 1.); + std::normal_distribution g; + int rays = 0, differentCount = 0, differentPath = 0, differentLength = 0, zeroSteps = 0, crossings = 0; + std::string firstDifference; + for (int r = 0; r < 20000; ++r) { + // start inside the two touching modules, off every face + const double p[3] = {9.9 * u(gen), 9.9 * u(gen), 9.9 * u(gen)}; + double d[3] = {g(gen), g(gen), 0.3 * g(gen)}; + const double norm = std::sqrt(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]); + for (auto& x : d) { + x /= norm; + } + const auto expected = withTGeo(p, d); + const auto found = withNavigator(nav, p, d, zeroSteps); + ++rays; + crossings += expected.size(); + if (found.size() != expected.size()) { + ++differentCount; + if (firstDifference.empty()) { + firstDifference = Form("ray %d: %zu visits, TGeo %zu", r, found.size(), expected.size()); + } + continue; + } + for (std::size_t i = 0; i < found.size(); ++i) { + if (found[i].path != expected[i].path) { + ++differentPath; + if (firstDifference.empty()) { + firstDifference = Form("ray %d visit %zu: %s, TGeo %s", r, i, found[i].path.c_str(), expected[i].path.c_str()); + } + break; + } + differentLength += std::abs(found[i].length - expected[i].length) > 1.e-6; } - break; } - differentLength += std::abs(found[i].length - expected[i].length) > 1.e-6; + BOOST_TEST_MESSAGE("rays " << rays << ", volumes crossed " << crossings << ", zero-length steps " << zeroSteps << " " << firstDifference); + BOOST_CHECK_GT(crossings, 100000); + BOOST_CHECK_MESSAGE(differentCount == 0, differentCount << " rays with a different number of volumes; " << firstDifference); + BOOST_CHECK_MESSAGE(differentPath == 0, differentPath << " rays with a different volume; " << firstDifference); + BOOST_CHECK_EQUAL(differentLength, 0); + // every face here coincides with others, and none of them is a place to stop + BOOST_CHECK_EQUAL(zeroSteps, 0); } } - BOOST_TEST_MESSAGE("rays " << rays << ", volumes crossed " << crossings << ", zero-length steps " << zeroSteps << " " << firstDifference); - BOOST_CHECK_GT(crossings, 100000); - BOOST_CHECK_MESSAGE(differentCount == 0, differentCount << " rays with a different number of volumes; " << firstDifference); - BOOST_CHECK_MESSAGE(differentPath == 0, differentPath << " rays with a different volume; " << firstDifference); - BOOST_CHECK_EQUAL(differentLength, 0); - // every face here coincides with others, and none of them is a place to stop - BOOST_CHECK_EQUAL(zeroSteps, 0); } BOOST_AUTO_TEST_CASE(a_turn_at_the_face_does_not_change_the_volume_entered) { - auto& f = fixture(); - std::mt19937_64 gen(2); - std::uniform_real_distribution u(-1., 1.); - std::normal_distribution g; - int boundaries = 0, different = 0; - std::string firstDifference; - for (int r = 0; r < 2000; ++r) { - const double p[3] = {9.9 * u(gen), 9.9 * u(gen), 9.9 * u(gen)}; - double d[3] = {g(gen), g(gen), 0.3 * g(gen)}; - const double norm = std::sqrt(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]); - for (auto& x : d) { - x /= norm; - } - const auto straight = afterBoundaries(*f.navigator, p, d, -1); - for (int k = 0; k < static_cast(straight.size()); ++k) { - const auto turned = afterBoundaries(*f.navigator, p, d, k); - ++boundaries; - if (turned.size() != static_cast(k) + 1 || turned.back() != straight[k]) { - ++different; - if (firstDifference.empty()) { - firstDifference = Form("ray %d boundary %d: %s, without the turn %s", r, k, turned.empty() ? "-" : turned.back().c_str(), straight[k].c_str()); + for (auto& [name, navp] : navigators()) { + auto& nav = *navp; + BOOST_TEST_CONTEXT(name) + { + std::mt19937_64 gen(2); + std::uniform_real_distribution u(-1., 1.); + std::normal_distribution g; + int boundaries = 0, different = 0; + std::string firstDifference; + for (int r = 0; r < 2000; ++r) { + const double p[3] = {9.9 * u(gen), 9.9 * u(gen), 9.9 * u(gen)}; + double d[3] = {g(gen), g(gen), 0.3 * g(gen)}; + const double norm = std::sqrt(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]); + for (auto& x : d) { + x /= norm; + } + const auto straight = afterBoundaries(nav, p, d, -1); + for (int k = 0; k < static_cast(straight.size()); ++k) { + const auto turned = afterBoundaries(nav, p, d, k); + ++boundaries; + if (turned.size() != static_cast(k) + 1 || turned.back() != straight[k]) { + ++different; + if (firstDifference.empty()) { + firstDifference = Form("ray %d boundary %d: %s, without the turn %s", r, k, turned.empty() ? "-" : turned.back().c_str(), straight[k].c_str()); + } + } } } + BOOST_TEST_MESSAGE("boundaries " << boundaries << " " << firstDifference); + BOOST_CHECK_GT(boundaries, 10000); + // the step decides which volume is entered, not the direction the track has after it + BOOST_CHECK_MESSAGE(different == 0, different << " boundaries where the turn changed the volume; " << firstDifference); } } - BOOST_TEST_MESSAGE("boundaries " << boundaries << " " << firstDifference); - BOOST_CHECK_GT(boundaries, 10000); - // the step decides which volume is entered, not the direction the track has after it - BOOST_CHECK_MESSAGE(different == 0, different << " boundaries where the turn changed the volume; " << firstDifference); } BOOST_AUTO_TEST_CASE(a_track_tangent_to_a_field_boundary_is_freed_along_its_momentum) { - // A track on the top face of a lead tile, as under a field: the chord points into the tile, the momentum out of it. - auto& nav = *fixture().navigator; - const G4ThreeVector face(-5. * cm, -5. * cm, -8.45 * cm); - const G4ThreeVector chord = G4ThreeVector(1., 0., -1.e-3).unit(); - const G4ThreeVector momentum = G4ThreeVector(1., 0., 1.e-3).unit(); - G4double safety = 0.; - // reach the face along the chord from the paper above, so the track ends in the lead - G4ThreeVector point = face - 1. * mm * chord; - nav.LocateGlobalPointAndSetup(point, &chord, false, false); - const double first = nav.ComputeStep(point, chord, 1.e6 * cm, safety); - BOOST_REQUIRE_CLOSE(first, 1. * mm, 1.e-6); - point += first * chord; - nav.SetGeometricallyLimitedStep(); - nav.LocateGlobalPointAndSetup(point, &momentum, true, false); - BOOST_REQUIRE_EQUAL(touchablePath(nav).substr(touchablePath(nav).rfind('/')), "/LEAD_1"); + for (auto& [name, navp] : navigators()) { + auto& nav = *navp; + BOOST_TEST_CONTEXT(name) + { + // A track on the top face of a lead tile, as under a field: the chord points into the tile, the momentum out of it. + const G4ThreeVector face(-5. * cm, -5. * cm, -8.45 * cm); + const G4ThreeVector chord = G4ThreeVector(1., 0., -1.e-3).unit(); + const G4ThreeVector momentum = G4ThreeVector(1., 0., 1.e-3).unit(); + G4double safety = 0.; + // reach the face along the chord from the paper above, so the track ends in the lead + G4ThreeVector point = face - 1. * mm * chord; + nav.LocateGlobalPointAndSetup(point, &chord, false, false); + const double first = nav.ComputeStep(point, chord, 1.e6 * cm, safety); + BOOST_REQUIRE_CLOSE(first, 1. * mm, 1.e-6); + point += first * chord; + nav.SetGeometricallyLimitedStep(); + nav.LocateGlobalPointAndSetup(point, &momentum, true, false); + BOOST_REQUIRE_EQUAL(touchablePath(nav).substr(touchablePath(nav).rfind('/')), "/LEAD_1"); - // Geant4 alternates a straight step along the momentum, which leaves the lead, and a chord step, which enters it again. - int zeroSteps = 0, pushedChords = 0; - bool moved = false, freed = false; - for (int k = 0; k < 24 && !freed; ++k) { - const bool alongMomentum = k % 2 == 0; - const G4ThreeVector& dir = alongMomentum ? momentum : chord; - const double step = nav.ComputeStep(point, dir, 1.e6 * cm, safety); - BOOST_TEST_MESSAGE("step " << k << (alongMomentum ? " momentum " : " chord ") << step << " mm in " << touchablePath(nav)); - if (step < 1.e-10 * mm) { - ++zeroSteps; - } else if (alongMomentum) { - // the lengthened momentum step moves the track off the face - point += step * dir; - moved = true; - } else if (moved) { - // the chord reaches the lead only after a real step: the track is off the face - freed = true; - } else { - ++pushedChords; - break; + // Geant4 alternates a straight step along the momentum, which leaves the lead, and a chord step, which enters it again. + int zeroSteps = 0, pushedChords = 0; + bool moved = false, freed = false; + for (int k = 0; k < 24 && !freed; ++k) { + const bool alongMomentum = k % 2 == 0; + const G4ThreeVector& dir = alongMomentum ? momentum : chord; + const double step = nav.ComputeStep(point, dir, 1.e6 * cm, safety); + BOOST_TEST_MESSAGE("step " << k << (alongMomentum ? " momentum " : " chord ") << step << " mm in " << touchablePath(nav)); + if (step < 1.e-10 * mm) { + ++zeroSteps; + } else if (alongMomentum) { + // the lengthened momentum step moves the track off the face + point += step * dir; + moved = true; + } else if (moved) { + // the chord reaches the lead only after a real step: the track is off the face + freed = true; + } else { + ++pushedChords; + break; + } + nav.SetGeometricallyLimitedStep(); + nav.LocateGlobalPointAndSetup(point, &momentum, true, false); + } + BOOST_TEST_MESSAGE("zero steps " << zeroSteps); + BOOST_CHECK_GE(zeroSteps, 10); + // a lengthened chord step is a miss for the field propagator, which then never crosses + BOOST_CHECK_EQUAL(pushedChords, 0); + BOOST_CHECK(freed); } - nav.SetGeometricallyLimitedStep(); - nav.LocateGlobalPointAndSetup(point, &momentum, true, false); } - BOOST_TEST_MESSAGE("zero steps " << zeroSteps); - BOOST_CHECK_GE(zeroSteps, 10); - // a lengthened chord step is a miss for the field propagator, which then never crosses - BOOST_CHECK_EQUAL(pushedChords, 0); - BOOST_CHECK(freed); } BOOST_AUTO_TEST_CASE(a_push_restarts_the_run_of_zero_steps_only_in_another_volume_it_reached) { - auto& nav = *fixture().navigator; - const G4ThreeVector momentum(0., 1., 0.); - int zero = 0; - // A run of chords on the lead face of tower 1, 2 nm from tower 2: the tenth zero step is pushed by 0.1 nm. - const G4ThreeVector p(-2.e-7 * cm, -5. * cm, -8.45 * cm); - nav.LocateGlobalPointAndSetup(p, &momentum, false, false); - BOOST_CHECK_CLOSE(chordsUntilPush(nav, p, zero), 1.e-7 * mm, 0.01); - BOOST_CHECK_EQUAL(zero, 9); - // Moved along the same face by ten times the push, still in the volumes of the run: no restart, the next zero - // step is pushed at once, and the push goes on growing. - const G4ThreeVector same(-1.e-7 * cm, -5. * cm, -8.45 * cm); - moveTo(nav, same); - double push = 0.; - for (int k = 1; k < 4; ++k) { - push = chordsUntilPush(nav, same, zero); - BOOST_CHECK_EQUAL(zero, 0); - BOOST_CHECK_CLOSE(push, 1.e-7 * mm * std::pow(4., k), 0.01); + for (auto& [name, navp] : navigators()) { + auto& nav = *navp; + BOOST_TEST_CONTEXT(name) + { + const G4ThreeVector momentum(0., 1., 0.); + int zero = 0; + // A run of chords on the lead face of tower 1, 2 nm from tower 2: the tenth zero step is pushed by 0.1 nm. + const G4ThreeVector p(-2.e-7 * cm, -5. * cm, -8.45 * cm); + nav.LocateGlobalPointAndSetup(p, &momentum, false, false); + BOOST_CHECK_CLOSE(chordsUntilPush(nav, p, zero), 1.e-7 * mm, 0.01); + BOOST_CHECK_EQUAL(zero, 9); + // Moved along the same face by ten times the push, still in the volumes of the run: no restart, the next zero + // step is pushed at once, and the push goes on growing. + const G4ThreeVector same(-1.e-7 * cm, -5. * cm, -8.45 * cm); + moveTo(nav, same); + double push = 0.; + for (int k = 1; k < 4; ++k) { + push = chordsUntilPush(nav, same, zero); + BOOST_CHECK_EQUAL(zero, 0); + BOOST_CHECK_CLOSE(push, 1.e-7 * mm * std::pow(4., k), 0.01); + } + // Into tower 2, a volume the run never visited, but by less than half the last push: no restart either. + const G4ThreeVector close(1.e-7 * cm, -5. * cm, -8.45 * cm); + BOOST_REQUIRE_LT((close - same).mag(), 0.5 * push); + moveTo(nav, close); + BOOST_CHECK_NE(touchablePath(nav).find("TOWR_2"), std::string::npos); + BOOST_CHECK_GT(chordsUntilPush(nav, close, zero), 0.); + BOOST_CHECK_EQUAL(zero, 0); + // Into another module, far and new: the run starts again. + const G4ThreeVector far = leadFace(2, 1); + moveTo(nav, far); + BOOST_CHECK_GT(chordsUntilPush(nav, far, zero), 0.); + BOOST_CHECK_EQUAL(zero, 9); + } } - // Into tower 2, a volume the run never visited, but by less than half the last push: no restart either. - const G4ThreeVector close(1.e-7 * cm, -5. * cm, -8.45 * cm); - BOOST_REQUIRE_LT((close - same).mag(), 0.5 * push); - moveTo(nav, close); - BOOST_CHECK_NE(touchablePath(nav).find("TOWR_2"), std::string::npos); - BOOST_CHECK_GT(chordsUntilPush(nav, close, zero), 0.); - BOOST_CHECK_EQUAL(zero, 0); - // Into another module, far and new: the run starts again. - const G4ThreeVector far = leadFace(2, 1); - moveTo(nav, far); - BOOST_CHECK_GT(chordsUntilPush(nav, far, zero), 0.); - BOOST_CHECK_EQUAL(zero, 9); } BOOST_AUTO_TEST_CASE(a_track_pushed_from_place_to_place_is_aborted_after_its_fourth_run) { - auto& nav = *fixture().navigator; - static AbortCounter handler; // registered with Geant4 for the rest of the process - handler.aborts = 0; - const G4ThreeVector momentum(0., 1., 0.); - int zero = 0; - // Four places, each reached by a push and each a volume the previous run did not visit: three restarts. - const G4ThreeVector places[] = {leadFace(1, 1), leadFace(1, 2), leadFace(2, 1), leadFace(2, 2)}; - nav.LocateGlobalPointAndSetup(places[0], &momentum, false, false); - for (const auto& p : places) { - if (&p != &places[0]) { - moveTo(nav, p); + for (auto& [name, navp] : navigators()) { + auto& nav = *navp; + BOOST_TEST_CONTEXT(name) + { + static AbortCounter handler; // registered with Geant4 for the rest of the process + handler.aborts = 0; + const G4ThreeVector momentum(0., 1., 0.); + int zero = 0; + // Four places, each reached by a push and each a volume the previous run did not visit: three restarts. + const G4ThreeVector places[] = {leadFace(1, 1), leadFace(1, 2), leadFace(2, 1), leadFace(2, 2)}; + nav.LocateGlobalPointAndSetup(places[0], &momentum, false, false); + for (const auto& p : places) { + if (&p != &places[0]) { + moveTo(nav, p); + } + BOOST_CHECK_GT(chordsUntilPush(nav, p, zero), 0.); + BOOST_CHECK_EQUAL(zero, 9); + } + // A fifth place does not restart the run: it goes on to the abort. + const G4ThreeVector last = leadFace(3, 1); + moveTo(nav, last); + int steps = 0; + for (; steps < 30 && handler.aborts == 0; ++steps) { + chordsUntilPush(nav, last, zero, 1); + } + BOOST_CHECK_EQUAL(handler.aborts, 1); + // The fourth run had reached ten zero steps, so fifteen more reach the abort at twenty-five. + BOOST_CHECK_EQUAL(steps, 15); } - BOOST_CHECK_GT(chordsUntilPush(nav, p, zero), 0.); - BOOST_CHECK_EQUAL(zero, 9); - } - // A fifth place does not restart the run: it goes on to the abort. - const G4ThreeVector last = leadFace(3, 1); - moveTo(nav, last); - int steps = 0; - for (; steps < 30 && handler.aborts == 0; ++steps) { - chordsUntilPush(nav, last, zero, 1); } - BOOST_CHECK_EQUAL(handler.aborts, 1); - // The fourth run had reached ten zero steps, so fifteen more reach the abort at twenty-five. - BOOST_CHECK_EQUAL(steps, 15); } From 01e6aa89ee0cd8fd0bfaf3a55cb3aebefe80f24f Mon Sep 17 00:00:00 2001 From: Sandro Wenzel Date: Thu, 19 Nov 2026 15:26:19 +0100 Subject: [PATCH 4/4] Fix the safety after a crossing in the propagating VecGeom navigator This fixes the safety of the propagating VecGeom navigator (G4.vecgeomNavigator=kPropagated) and adds unit tests. - ComputeSafety answered 0 at every point until the next within-volume locate after a crossing, so the end point of the first step in a new volume had no safety. - It now answers 0 only at the point where the crossing was located and at the end point of a step that ends on a boundary, as VecGeomG4Navigator does. - The locate now consumes fWasLimitedByGeometry as G4Navigator does, so a new track is no longer taken for a crossing with the previous track's flags. - ResetHierarchyAndLocate now clears the crossing state left by the previous track. Co-Authored-By: Claude Opus 5.5 --- .../src/VecGeomG4PropagatingNavigator.cxx | 43 +++++++++---- .../src/VecGeomG4PropagatingNavigator.h | 6 +- .../gconfig/test/testVecGeomG4Navigator.cxx | 60 ++++++++++++++++++- 3 files changed, 92 insertions(+), 17 deletions(-) diff --git a/Detectors/gconfig/src/VecGeomG4PropagatingNavigator.cxx b/Detectors/gconfig/src/VecGeomG4PropagatingNavigator.cxx index 1cbc24951a999..f9700da3ca7bc 100644 --- a/Detectors/gconfig/src/VecGeomG4PropagatingNavigator.cxx +++ b/Detectors/gconfig/src/VecGeomG4PropagatingNavigator.cxx @@ -32,6 +32,13 @@ namespace /// Geant4 abandons a track after ~50 zero steps, so a stalled step is nudged forward by this much /// (in Geant4 units) rather than returned as zero. const double kNudge = 1.e-3; + +/// Two points closer than 1e-10 mm are the same point. +constexpr double kSamePointDist2 = 1.e-20; +/// A located point within 1e-8 mm of the end point of the last step is that end point. +constexpr double kStepEndDist2 = 1.e-16; + +bool samePoint(const G4ThreeVector& a, const G4ThreeVector& b) { return a.diff2(b) < kSamePointDist2; } } // namespace namespace o2::simsetup @@ -76,7 +83,7 @@ G4double VecGeomG4PropagatingNavigator::ComputeStep(const G4ThreeVector& globalP // The adopted state marks the volume the crossing left. As in Geant4, it is blocked in the first // step after the exit only, and only while the direction points away from it; a track turning // back into it must see its boundary. - const bool block = mExitBlockPending && globalPoint.diff2(mLocatedPoint) < 1.e-20 && + const bool block = mExitBlockPending && samePoint(globalPoint, mLocatedPoint) && directionLeaves(mPrevState, toVG(globalPoint), toDir(direction)); mExitBlockPending = false; if (!block) { @@ -130,11 +137,14 @@ G4VPhysicalVolume* VecGeomG4PropagatingNavigator::ResetHierarchyAndLocate(const { // Geant4 hands back a touchable it saved earlier, e.g. when resuming a track whose secondaries // were followed first. The VecGeom state is rebuilt from it. + fWasLimitedByGeometry = false; fEnteredDaughter = false; fExitedMother = false; mWouldEnter = false; mWouldExit = false; mOnBoundary = false; + mCrossed = false; + mExitBlockPending = false; mHaveNextState = false; mLastSafety = -1.; fHistory = *history.GetHistory(); @@ -150,35 +160,35 @@ G4VPhysicalVolume* VecGeomG4PropagatingNavigator::LocateGlobalPointAndSetup(cons const G4ThreeVector*, const G4bool relativeSearch, const G4bool) { - bool onBoundary = fWasLimitedByGeometry; - if (mHaveNextState && point.diff2(mNextPoint) < 1.e-16) { - onBoundary = true; - } + // As in G4Navigator, only a relative search can cross a boundary, and the locate consumes the flag. + const bool onBoundary = relativeSearch && (fWasLimitedByGeometry || (mHaveNextState && point.diff2(mNextPoint) < kStepEndDist2)); + fWasLimitedByGeometry = false; mPrevState = mCurState; mLocatedPoint = point; mExitBlockPending = false; mLastSafety = -1.; - if (!mForceReInit && relativeSearch && onBoundary && mHaveNextState) { + if (!mForceReInit && onBoundary && mHaveNextState) { // The state on the far side of the boundary was already worked out, and relocated, by the step // that found it. Adopting it is cheaper than locating again. mCurState = mNextState; mExitBlockPending = mWouldExit; - } else if (mForceReInit || !relativeSearch || onBoundary) { + } else { mCurState.Clear(); vecgeom::GlobalLocator::LocateGlobalPoint(vecgeom::GeoManager::Instance().GetWorld(), toVG(point), mCurState, true); mForceReInit = false; ++mGlobalRelocates; } - // Otherwise the point only moved inside the volume the state already names. auto* target = updateHistory(mCurState); mCrossed = onBoundary; - if (onBoundary) { - fExitedMother = mWouldExit; - fEnteredDaughter = mWouldEnter; - mOnBoundary = true; + mOnBoundary = onBoundary; + fExitedMother = onBoundary && mWouldExit; + fEnteredDaughter = onBoundary && mWouldEnter; + if (!onBoundary) { + // Kept after a crossing only, where GetGlobalExitNormal still reads mWouldExit. + mWouldEnter = mWouldExit = false; } mHaveNextState = false; return target; @@ -199,7 +209,14 @@ void VecGeomG4PropagatingNavigator::LocateGlobalPointWithinVolume(const G4ThreeV G4double VecGeomG4PropagatingNavigator::ComputeSafety(const G4ThreeVector& globalPoint, const G4double proposedMaxLength, const G4bool) { - if (mZeroSafety || mOnBoundary || mCrossed || fEnteredDaughter || fExitedMother || mWouldEnter || mWouldExit) { + if (mZeroSafety) { + return 0.; + } + // Zero only on the face: where a crossing was located, or where the last step ends on a boundary. + if (mCrossed && samePoint(globalPoint, mLocatedPoint)) { + return 0.; + } + if ((mWouldEnter || mWouldExit) && samePoint(globalPoint, mNextPoint)) { return 0.; } if (mCurState.Top() == nullptr) { diff --git a/Detectors/gconfig/src/VecGeomG4PropagatingNavigator.h b/Detectors/gconfig/src/VecGeomG4PropagatingNavigator.h index 2a5133d6d4514..64f2ec1d4cda5 100644 --- a/Detectors/gconfig/src/VecGeomG4PropagatingNavigator.h +++ b/Detectors/gconfig/src/VecGeomG4PropagatingNavigator.h @@ -19,9 +19,9 @@ namespace o2::simsetup /// A lighter VecGeom navigator for Geant4, selected with G4.vecgeomNavigator=kPropagated. ComputeStep /// uses VecGeom's combined step-and-relocate, and a boundary locate adopts the state that step -/// propagated instead of locating again. Safety is zero for the whole step after a crossing, a stuck -/// step is nudged forward, and the exit normal follows the direction of motion. It does less work per -/// step and per crossing than VecGeomG4Navigator. +/// propagated instead of locating again. Safety is zero only on the face of a crossing, a stuck step +/// is nudged forward, and the exit normal follows the direction of motion. It does less work per step +/// and per crossing than VecGeomG4Navigator. class VecGeomG4PropagatingNavigator : public VecGeomG4NavigatorBase { public: diff --git a/Detectors/gconfig/test/testVecGeomG4Navigator.cxx b/Detectors/gconfig/test/testVecGeomG4Navigator.cxx index 2ddccd2ff2fc1..a6c41e7348027 100644 --- a/Detectors/gconfig/test/testVecGeomG4Navigator.cxx +++ b/Detectors/gconfig/test/testVecGeomG4Navigator.cxx @@ -12,7 +12,8 @@ /// The relocating VecGeom navigator against TGeo on a geometry of coinciding faces: two copies of a tower /// side by side that fill their mother, each a stack of tiles that reach the tower's faces, as in a sampling /// calorimeter. A ray has to visit the same volumes in the same order, and never stop for a zero-length step -/// in a mother it only touches. Every case runs with the default locate and with the lean one. +/// in a mother it only touches. Every case runs with the default locate and with the lean one. The propagating +/// navigator has to answer a zero safety only on the face it crossed. #define BOOST_TEST_MODULE Test SimSetup VecGeomG4Navigator #define BOOST_TEST_MAIN @@ -24,6 +25,7 @@ #include "../src/VecGeomG4Map.h" #include "../src/VecGeomG4Navigator.h" +#include "../src/VecGeomG4PropagatingNavigator.h" #include "TG4RootDetectorConstruction.h" @@ -49,6 +51,7 @@ using o2::simsetup::VecGeomG4Map; using o2::simsetup::VecGeomG4Navigator; +using o2::simsetup::VecGeomG4PropagatingNavigator; namespace { @@ -57,6 +60,7 @@ struct Fixture { VecGeomG4Map map; std::unique_ptr navigator; std::unique_ptr lean; // the same with G4.vecgeomLeanLocate + std::unique_ptr propagating; Fixture() { @@ -93,6 +97,8 @@ struct Fixture { navigator->SetWorldVolume(world); lean = std::make_unique(map, 1.e-9, false, nullptr, true); lean->SetWorldVolume(world); + propagating = std::make_unique(map, false); + propagating->SetWorldVolume(world); } }; @@ -180,6 +186,24 @@ std::vector afterBoundaries(G4Navigator& nav, const double* p, cons return paths; } +/// A new track in the paper of the first tile, 1 mm above its lead, steps down into the lead; returns the crossing point. +G4ThreeVector enterLead(G4Navigator& nav) +{ + const G4ThreeVector down(0., 0., -1.); + G4ThreeVector point(-5. * cm, -5. * cm, -8.35 * cm); + nav.LocateGlobalPointAndSetup(point, &down, false, false); + G4double safety = 0.; + point += nav.ComputeStep(point, down, 1.e6 * cm, safety) * down; + nav.SetGeometricallyLimitedStep(); + nav.LocateGlobalPointAndSetup(point, &down, true, false); + BOOST_REQUIRE(nav.EnteredDaughterVolume()); + BOOST_REQUIRE_EQUAL(touchablePath(nav).substr(touchablePath(nav).rfind('/')), "/LEAD_1"); + return point; +} + +/// A point in the paper of the fourth tile, 0.5 mm above its lower face and 1.5 mm below its lead. +const G4ThreeVector inPaper(-5. * cm, -5. * cm, -1.70 * cm); + std::vector withTGeo(const double* p, const double* d) { std::vector visits; @@ -458,3 +482,37 @@ BOOST_AUTO_TEST_CASE(a_track_pushed_from_place_to_place_is_aborted_after_its_fou } } } + +BOOST_AUTO_TEST_CASE(the_propagating_navigator_has_a_zero_safety_only_on_the_face_it_crossed) +{ + auto& nav = *fixture().propagating; + const G4ThreeVector down(0., 0., -1.); + const G4ThreeVector face = enterLead(nav); + BOOST_CHECK_EQUAL(nav.ComputeSafety(face), 0.); + // a 0.2 mm step into the lead; Geant4 asks for the safety at its end before the next locate + G4double safety = 0.; + BOOST_REQUIRE_GT(nav.ComputeStep(face, down, 0.2 * mm, safety), 0.2 * mm); + BOOST_CHECK_CLOSE(nav.ComputeSafety(face + 0.2 * mm * down), 0.2 * mm, 1.e-4); +} + +BOOST_AUTO_TEST_CASE(a_new_track_after_a_crossing_is_not_on_a_boundary) +{ + auto& nav = *fixture().propagating; + enterLead(nav); + const G4ThreeVector up(0., 0., 1.); + nav.LocateGlobalPointAndSetup(inPaper, &up, false, false); + BOOST_CHECK(!nav.EnteredDaughterVolume()); + BOOST_CHECK(!nav.ExitedMotherVolume()); + BOOST_CHECK_CLOSE(nav.ComputeSafety(inPaper), 0.5 * mm, 1.e-4); +} + +BOOST_AUTO_TEST_CASE(a_resumed_track_after_a_crossing_is_not_on_a_boundary) +{ + auto& nav = *fixture().propagating; + const G4ThreeVector up(0., 0., 1.); + nav.LocateGlobalPointAndSetup(inPaper, &up, false, false); + std::unique_ptr touchable(nav.CreateTouchableHistory()); + enterLead(nav); + nav.ResetHierarchyAndLocate(inPaper, up, *touchable); + BOOST_CHECK_CLOSE(nav.ComputeSafety(inPaper), 0.5 * mm, 1.e-4); +}