Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion Common/SimConfig/include/SimConfig/G4Params.h
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,10 @@ struct G4Params : public o2::conf::ConfigurableParamHelper<G4Params> {
// which of the two VecGeom navigators
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
// point is pushed before it is located (previous locate only)
bool vecgeomLeanLocate = true; // kRelocating: locate a crossing 10 nm along the step, as VecGeom
// relocates; false is the previous locate across the face with the
// flush-volume loop, kept as a fallback
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
Expand Down
4 changes: 4 additions & 0 deletions Detectors/Base/include/DetectorsBase/GeometryManager.h
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,10 @@ class GeometryManager : public TObject
/// assemblies into their content. \param booleanThreshold lets VecGeom turn Boolean solids with at
/// least this many components into MultiUnions; 0 keeps them as converted.
static void buildVecGeomGeometry(bool flattenAssemblies, int booleanThreshold = 0);
/// BVH navigator and safety estimator (true) or the simple ones (false, as built) for volumes with one or two daughters.
static void setVecGeomBvhForSmallMothers(bool bvh);
/// Whether volumes with one or two daughters currently have the BVH pair.
static bool vecGeomSmallMothersUseBvh();
#else
static constexpr bool isVecGeomAvailable() { return false; }
#endif
Expand Down
36 changes: 34 additions & 2 deletions Detectors/Base/src/GeometryManager.cxx
Original file line number Diff line number Diff line change
Expand Up @@ -737,6 +737,23 @@ bool usesBvhAcceleration(vecgeom::LogicalVolume const* vol)
return vol->GetDaughtersp()->size() > 2;
}

/// The current choice of setVecGeomBvhForSmallMothers.
bool sSmallMothersUseBvh = false;

/// Navigator and safety estimator of a volume below the BVH threshold, always as a matched pair.
void setSmallVolumeNavigation(vecgeom::LogicalVolume* vol, bool bvh)
{
#ifdef O2_VECGEOM_HAS_BVH_VNAVIGATOR
vol->SetNavigator(bvh ? vecgeom::BVHNavigatorV<>::Instance() : vecgeom::NewSimpleNavigator<>::Instance());
vol->SetSafetyEstimator(bvh ? vecgeom::BVHSafetyEstimator::Instance() : vecgeom::SimpleSafetyEstimator::Instance());
#else
if (bvh) {
LOG(fatal) << "The BVH navigator for small volumes needs a VecGeom with BVHNavigatorV";
}
vol->SetNavigator(vecgeom::NewSimpleNavigator<>::Instance());
#endif
}

/// Converts the currently loaded TGeo geometry to VecGeom and sets up navigators, once per
/// process, the first time the VecGeom backend is requested. Not part of loadGeometry(),
/// which every job calls regardless of whether it ever uses the VecGeom backend.
Expand Down Expand Up @@ -783,11 +800,10 @@ void GeometryManager::buildVecGeomGeometry(bool flattenAssemblies, int booleanTh
for (auto& lvol : vecgeom::GeoManager::Instance().GetLogicalVolumesMap()) {
auto* vol = lvol.second;
if (!usesBvhAcceleration(vol)) {
vol->SetNavigator(vecgeom::NewSimpleNavigator<>::Instance());
setSmallVolumeNavigation(vol, false);
#ifdef O2_VECGEOM_HAS_BVH_VNAVIGATOR
vol->SetLevelLocator(vol->ContainsAssembly() ? vecgeom::SimpleAssemblyLevelLocator::GetInstance()
: vecgeom::SimpleLevelLocator::GetInstance());
vol->SetSafetyEstimator(vecgeom::SimpleSafetyEstimator::Instance());
#else
vol->SetLevelLocator(vecgeom::SimpleLevelLocator::GetInstance());
#endif
Expand Down Expand Up @@ -824,6 +840,21 @@ void GeometryManager::buildVecGeomGeometry(bool flattenAssemblies, int booleanTh
});
}

//_____________________________________________________________________________________
void GeometryManager::setVecGeomBvhForSmallMothers(bool bvh)
{
sSmallMothersUseBvh = bvh;
for (auto& lvol : vecgeom::GeoManager::Instance().GetLogicalVolumesMap()) {
auto* vol = lvol.second;
if (!usesBvhAcceleration(vol) && vol->GetDaughtersp()->size() > 0) {
setSmallVolumeNavigation(vol, bvh);
}
}
}

//_____________________________________________________________________________________
bool GeometryManager::vecGeomSmallMothersUseBvh() { return sSmallMothersUseBvh; }

//_____________________________________________________________________________________
o2::base::MatBudget GeometryManager::vecGeomMaterialBudget(float x0, float y0, float z0, float x1, float y1, float z1)
{
Expand Down Expand Up @@ -904,6 +935,7 @@ o2::base::MatBudget GeometryManager::vecGeomMaterialBudget(float x0, float y0, f
? static_cast<double>(vecgeom::BVHNavigator::ComputeStepAndPropagatedState(currPoint, dirr, remainingDist, *currnavstate, *newnavstate))
: static_cast<double>(lvol->GetNavigator()->ComputeStepAndPropagatedState(currPoint, dirr, remainingDist, *currnavstate, *newnavstate));
#else
// After setVecGeomBvhForSmallMothers(true) small mothers step with BVHNavigatorV here too: same answer.
const double step = static_cast<double>(lvol->GetNavigator()->ComputeStepAndPropagatedState(currPoint, dirr, remainingDist, *currnavstate, *newnavstate));
#endif
if (step < 2.E-10) {
Expand Down
86 changes: 64 additions & 22 deletions Detectors/gconfig/src/VecGeomG4Navigator.cxx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@
// granted to it by virtue of its status as an Intergovernmental Organization
// or submit itself to any jurisdiction.

// before the VecGeom headers, which define a VECGEOM macro
#include "DetectorsBase/GeometryManager.h"

#include "VecGeomG4Navigator.h"

#include "VecGeomParallelWorld.h"
Expand Down Expand Up @@ -48,8 +51,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();
}
Expand All @@ -64,17 +71,11 @@ VecGeomG4Navigator::~VecGeomG4Navigator()
LOG(info) << "VecGeom parallel world: " << mParallelEntries << " steps ended on a node, " << mParallelRelocated
<< " locates overridden";
}
}

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();
if (mPushRestartCount > 0) {
LOG(info) << "VecGeom stuck tracks: " << mPushRestartCount << " runs of zero steps restarted after a push";
}
mHistoryState = mCurState;
mHistoryValid = true;
return historyFromState(mCurState);
LOG(debug) << "VecGeom history: " << mHistoryStepCount << " updated by one level, " << mHistoryRebuildCount
<< " rebuilt";
}

void VecGeomG4Navigator::locateFromWorld(const V3& point)
Expand Down Expand Up @@ -125,6 +126,7 @@ G4double VecGeomG4Navigator::ComputeStep(const G4ThreeVector& globalPoint, const
if (top == nullptr) { // the track is outside the world
return kInfinity;
}
// With the lean locate, the geometry setup gives every mother with daughters the BVH navigator.
auto const* navigator = top->GetLogicalVolume()->GetNavigator();

// On the point a boundary locate left the track on, the safety is zero; a point seen before
Expand All @@ -141,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)));
Expand All @@ -164,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) {
Expand Down Expand Up @@ -192,11 +201,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.
Expand All @@ -205,7 +229,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;
Expand Down Expand Up @@ -342,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;
Expand All @@ -356,6 +384,9 @@ G4VPhysicalVolume* VecGeomG4Navigator::LocateGlobalPointAndSetup(const G4ThreeVe

if (!relativeSearch) {
resetZeroSteps(); // a new track: nothing of the previous one applies
if (mLeanLocate && !o2::base::GeometryManager::vecGeomSmallMothersUseBvh()) {
LOG(fatal) << "The lean locate needs GeometryManager::setVecGeomBvhForSmallMothers(true)";
}
locateFromWorld(p);
} else if (topOf(mCurState) == nullptr) {
locateFromWorld(p);
Expand All @@ -375,6 +406,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);
Expand Down Expand Up @@ -405,7 +448,7 @@ G4VPhysicalVolume* VecGeomG4Navigator::LocateGlobalPointAndSetup(const G4ThreeVe
}
mLocatedOnBoundary = onBoundary;
}
if (crossing) {
if (crossing && !mLeanLocate) {
leaveFlushVolumes(q, dir, entering ? static_cast<int>(mNextState.GetCurrentLevel()) : 0,
entering || topOf(mReloScratch) == nullptr ? nullptr : &mReloScratch);
}
Expand All @@ -417,7 +460,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
Expand Down Expand Up @@ -503,12 +546,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)
Expand Down
Loading