Skip to content
Draft
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
11 changes: 10 additions & 1 deletion Detectors/gconfig/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ set(G4SETUP_SOURCES src/G4Config.cxx src/G4RunConfiguration.cxx src/G4LocalField
src/VecGeomNavigation.cxx src/O2MonopolePhysics.cxx)
if(G4SETUP_WITH_VECGEOM)
list(APPEND G4SETUP_SOURCES src/VecGeomG4Map.cxx src/VecGeomChecks.cxx src/VecGeomG4NavigatorBase.cxx
src/VecGeomG4Navigator.cxx
src/VecGeomG4Navigator.cxx src/VecGeomParallelWorld.cxx
src/VecGeomG4PropagatingNavigator.cxx)
endif()

Expand Down Expand Up @@ -90,6 +90,15 @@ if(G4SETUP_WITH_VECGEOM)
if(targetNavigatorTest)
target_compile_definitions(${targetNavigatorTest} PRIVATE O2_WITH_VECGEOM)
endif()
o2_add_test(VecGeomParallelWorld
SOURCES test/testVecGeomParallelWorld.cxx
COMPONENT_NAME SimSetup
TARGETVARNAME targetParallelWorldTest
PUBLIC_LINK_LIBRARIES O2::G4Setup TGeo2VecGeom::TGeo2VecGeom
LABELS simsetup)
if(targetParallelWorldTest)
target_compile_definitions(${targetParallelWorldTest} PRIVATE O2_WITH_VECGEOM)
endif()
endif()

o2_add_test_root_macro(UserDecay.C
Expand Down
60 changes: 59 additions & 1 deletion Detectors/gconfig/src/VecGeomG4Map.h
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,16 @@
#ifndef O2_SIMSETUP_VECGEOMG4MAP_H_
#define O2_SIMSETUP_VECGEOMG4MAP_H_

#include "G4VPhysicalVolume.hh"

#include <VecGeom/navigation/NavigationState.h>
#include <VecGeom/volumes/PlacedVolume.h>

#include <cstddef>
#include <cstdint>
#include <unordered_map>
#include <vector>

class G4VPhysicalVolume;
class TG4RootDetectorConstruction;
class TGeoNode;

Expand Down Expand Up @@ -91,6 +93,12 @@ class VecGeomG4Map
return true;
}

/// Builds \a state from a Geant4 path, extending past the levels assembly flattening dissolved.
/// \a volumeAt(level) gives the Geant4 volume at a level, 0 being the world, \a depth the deepest
/// level. False if a level matches no VecGeom placement; \a state is then empty.
template <typename VolumeAt>
bool stateFromPath(VolumeAt&& volumeAt, std::size_t depth, vecgeom::NavigationState& state) const;

/// How many Geant4 levels a VecGeom placement accounts for.
unsigned chainSize(int vgId) const
{
Expand Down Expand Up @@ -119,6 +127,56 @@ class VecGeomG4Map
std::size_t mMispaired = 0;
};

template <typename VolumeAt>
bool VecGeomG4Map::stateFromPath(VolumeAt&& volumeAt, std::size_t depth, vecgeom::NavigationState& state) const
{
// A run of levels that ends in a Geant4 volume several placements share is settled by comparing
// the run against the placements' recorded chains, which is exact.
constexpr std::size_t kMaxChain = 16; // longest run of Geant4 levels one flattened placement stands for
state.Clear();
if (mWorld == nullptr || volumeAt(0) == nullptr) {
return false;
}
state.Push(mWorld);
std::size_t l = chainSize(mWorld->id());
while (l <= depth) {
G4VPhysicalVolume* run[kMaxChain];
vecgeom::VPlacedVolume const* found = nullptr;
std::size_t n = 0;
for (std::size_t e = l; e <= depth && n < kMaxChain; ++e, ++n) {
run[n] = volumeAt(e);
if (run[n] == nullptr) {
state.Clear();
return false;
}
auto const* candidate = toVecGeom(run[n]->GetInstanceID());
if (candidate == nullptr) {
continue; // an assembly level; the chain reaches further down
}
if (candidate == ambiguous()) {
for (auto const* c : candidates(run[n]->GetInstanceID())) {
if (chainMatches(c, run, n + 1)) {
found = c;
break;
}
}
} else if (chainMatches(candidate, run, n + 1)) {
found = candidate;
}
if (found != nullptr) {
break;
}
}
if (found == nullptr) {
state.Clear();
return false;
}
state.Push(found);
l += chainSize(found->id());
}
return true;
}

} // namespace o2::simsetup

#endif
142 changes: 116 additions & 26 deletions Detectors/gconfig/src/VecGeomG4Navigator.cxx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@

#include "VecGeomG4Navigator.h"

#include "VecGeomParallelWorld.h"

#include "G4Exception.hh"
#include "G4TouchableHistory.hh"
#include "G4VPhysicalVolume.hh"
Expand Down Expand Up @@ -45,8 +47,9 @@ vecgeom::VPlacedVolume const* topOf(vecgeom::NavigationState const& st)
namespace o2::simsetup
{

VecGeomG4Navigator::VecGeomG4Navigator(VecGeomG4Map const& map, double pushDepth, bool zeroSafety)
: VecGeomG4NavigatorBase(map), mPushDepth(pushDepth), mZeroSafety(zeroSafety)
VecGeomG4Navigator::VecGeomG4Navigator(VecGeomG4Map const& map, double pushDepth, bool zeroSafety,
VecGeomParallelWorld const* parallelWorld)
: VecGeomG4NavigatorBase(map), mPushDepth(pushDepth), mZeroSafety(zeroSafety), mParallelWorld(parallelWorld)
{
mEmptyState.Clear();
}
Expand All @@ -57,6 +60,10 @@ VecGeomG4Navigator::~VecGeomG4Navigator()
<< ", abandoned " << mAbandonCount << ", negative safeties " << mNegativeSafetyCount
<< ", unmappable touchables " << mUnmappableHistoryCount << ", relocated resumes "
<< mRelocatedResumeCount << ", missing exit normals " << mNoNormalCount;
if (mParallelWorld != nullptr) {
LOG(info) << "VecGeom parallel world: " << mParallelEntries << " steps ended on a node, " << mParallelRelocated
<< " locates overridden";
}
}

G4VPhysicalVolume* VecGeomG4Navigator::updateG4History()
Expand Down Expand Up @@ -133,19 +140,40 @@ G4double VecGeomG4Navigator::ComputeStep(const G4ThreeVector& globalPoint, const
// along the curve. The volume the last crossing left is blocked in the first call only, and only
// while the direction points away from it; a track turning back into it must see its boundary.
mStepState = mCurState;
bool blockExited = false;
if (mExitBlockPending) {
const bool block = samePoint(globalPoint, mLastLocatedPoint) &&
(mExitNormalFromPush ? directionLeaves(mPushNormal, toDir(direction))
: directionLeaves(mExitedState, toVG(globalPoint), toDir(direction)));
if (!block) {
mStepState.SetLastExited(mEmptyState.GetLastExitedState());
}
blockExited = block;
clearLastExited();
}
const double limit = std::min(proposedStepLength * kG4ToVG, static_cast<double>(vecgeom::kInfLength));
double safety = 0.;
double vgStep = navigator->ComputeStepAndSafety(toVG(globalPoint), toDir(direction), limit, mStepState, calcSafety,
safety, true);
// Outside the parallel world its nodes limit the step and the safety like daughters of every volume;
// inside a node they are not seen, as in TGeo. A node at the distance of the main boundary is left to
// the main hierarchy, which is safe because the locate descends from what was entered and then asks the
// parallel world again. The nodes just left are blocked by the rule of the volume just left.
int parallelHit = -1;
if (mParallelWorld != nullptr && !mInParallelNode) {
const V3 p = toVG(globalPoint);
double pwStep = std::min(std::max(vgStep, 0.), limit);
parallelHit = mParallelWorld->distanceToIn(p, toDir(direction), pwStep, [&](int node) {
return blockExited && mParallelWorld->isInNode(node, mExitedState);
});
if (parallelHit >= 0) {
vgStep = pwStep;
++mParallelEntries;
}
if (calcSafety && safety > 0.) {
safety = mParallelWorld->safetyToIn(p, safety);
}
}
if (calcSafety) {
if (safety < 0.) {
++mNegativeSafetyCount;
Expand All @@ -158,40 +186,49 @@ G4double VecGeomG4Navigator::ComputeStep(const G4ThreeVector& globalPoint, const
}
const bool boundaryLimited = vgStep < limit;
G4double step = std::max(vgStep, 0.) * kVGToG4;
const bool entering = mStepState.GetCurrentLevel() > mCurState.GetCurrentLevel();
const bool entering = parallelHit >= 0 || mStepState.GetCurrentLevel() > mCurState.GetCurrentLevel();

// A track that is not moving, with G4Navigator's thresholds: after ten zero steps the step is
// lengthened, after twenty-five the event is aborted.
if (step < 0.05 * kCarTolerance) {
++mZeroStepCount;
// 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) {
++mStuckPushCount;
// The push grows from Geant4's 100 kCarTolerance fourfold per try to a micron and doubles from the
// eleventh try on: a track tangent to a curved face stays within the tolerance of it for microns.
const int tries = mNzeroSteps - kActionThresholdNoZeroSteps;
constexpr double kMicron = 1.e-3 * CLHEP::mm;
step += tries < 10 ? std::min(100. * kCarTolerance * std::pow(4., tries), kMicron)
: kMicron * static_cast<double>(2 << (tries - 10));
// 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.
if (linear || !mZeroLinearSeen) {
++mStuckPushCount;
// 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);
}
if (mNzeroSteps >= kAbandonThresholdNoZeroSteps) {
++mAbandonCount;
std::ostringstream msg;
msg << "Track stuck or not moving: " << mNzeroSteps << " zero steps in " << top->GetLabel() << " at ("
<< globalPoint.x() << ", " << globalPoint.y() << ", " << globalPoint.z() << ") mm. Event aborted, as "
<< "G4Navigator does.";
mNzeroSteps = 0;
resetZeroSteps();
G4Exception("VecGeomG4Navigator::ComputeStep()", "GeomNav0003", EventMustBeAborted, msg.str().c_str());
}
}
} else {
mNzeroSteps = 0;
resetZeroSteps();
}

if (boundaryLimited) {
mWouldEnter = entering;
mWouldExit = !entering;
mNextPoint = globalPoint + step * direction;
mNextDir = toDir(direction);
if (entering) {
mNextState = mStepState;
// A parallel world node is entered from anywhere in the hierarchy, not only from its mother.
mNextState = parallelHit >= 0 ? mParallelWorld->state(parallelHit) : mStepState;
}
// The surface this step ends on, for the exit normal: the entered daughter's or our own.
mNormalState = entering ? mNextState : mCurState;
Expand All @@ -209,9 +246,9 @@ G4double VecGeomG4Navigator::ComputeStep(const G4ThreeVector& globalPoint, const
/// the surface of and heading out of, then look down again from there, never back into the volume
/// just left, which stays blocked for the next step. Bounded, because popping and descending can
/// meet another flush face. It never pops to or above minLevel: a daughter the step entered stays
/// entered, because the step decided that with the chord direction, and the direction a locate gets
/// under a field is the momentum. Nor does it descend back into `avoid`, the volume the crossing
/// exited: on a face a helix touches tangentially chord and momentum disagree about the side.
/// entered, as the step decided. Nor does it descend back into `avoid`, the volume the crossing
/// exited. Both guard the decision of the step against a locate direction that disagrees with it
/// about the side of the face.
void VecGeomG4Navigator::leaveFlushVolumes(const V3& point, const V3& dir, int minLevel,
vecgeom::NavigationState const* avoid)
{
Expand Down Expand Up @@ -301,7 +338,10 @@ G4VPhysicalVolume* VecGeomG4Navigator::LocateGlobalPointAndSetup(const G4ThreeVe
const bool crossing = onBoundary && (mWouldEnter || mWouldExit) && direction != nullptr;
const bool entering = crossing && mWouldEnter;
const V3 p = toVG(point);
const V3 dir = direction != nullptr ? toDir(*direction) : V3(0., 0., 0.);
// A crossing is located along the direction of the step that found the boundary. The direction given
// 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 V3 q = p + push * dir;

Expand All @@ -310,11 +350,12 @@ G4VPhysicalVolume* VecGeomG4Navigator::LocateGlobalPointAndSetup(const G4ThreeVe
fExitedMother = false;
mLocatedOnBoundary = false;
mLastLocatedPoint = point;
mLastLocatedDir = direction != nullptr ? *direction : G4ThreeVector(0., 0., 0.);
mSafetyOrig = kNoPoint;
clearLastExited();

if (!relativeSearch) {
mNzeroSteps = 0; // a new track: nothing of the previous one applies
resetZeroSteps(); // a new track: nothing of the previous one applies
locateFromWorld(p);
} else if (topOf(mCurState) == nullptr) {
locateFromWorld(p);
Expand All @@ -325,12 +366,7 @@ G4VPhysicalVolume* VecGeomG4Navigator::LocateGlobalPointAndSetup(const G4ThreeVe
// mNextState is a copy of the step state and can still carry the block of the volume the previous
// crossing left, which was meant for the first step after that exit only.
mCurState.SetLastExited(mEmptyState.GetLastExitedState());
auto const* daughter = mCurState.Top();
mCurState.Pop();
vecgeom::Transformation3D m;
mCurState.TopMatrix(m);
vecgeom::GlobalLocator::LocateGlobalPoint(daughter, daughter->GetTransformation()->Transform(m.Transform(q)),
mCurState, false);
descendInto(mCurState, q);
mLocatedOnBoundary = true;
} else if (crossing) {
// Out of the current volume: up until the point is contained, then down, never back into the
Expand Down Expand Up @@ -372,14 +408,59 @@ G4VPhysicalVolume* VecGeomG4Navigator::LocateGlobalPointAndSetup(const G4ThreeVe
if (crossing) {
leaveFlushVolumes(q, dir, entering ? static_cast<int>(mNextState.GetCurrentLevel()) : 0,
entering || topOf(mReloScratch) == nullptr ? nullptr : &mReloScratch);
}
if (mParallelWorld != nullptr) {
applyParallelWorld(q, crossing && !entering);
}
if (crossing) {
updateCrossingFlags(entering);
}
mWouldEnter = false;
mWouldExit = false;
return updateG4History();
}

G4VPhysicalVolume* VecGeomG4Navigator::ResetHierarchyAndLocate(const G4ThreeVector& point, const G4ThreeVector&,
/// TGeo's rule: the node added first among those holding the point is where the track is. The
/// locate then goes on into the node's daughters, which TGeo leaves out; with sensors and metal
/// layers added before their chips, as ITS does, the result is the same.
bool VecGeomG4Navigator::applyParallelWorld(const V3& point, bool exiting)
{
mInParallelNode = false;
if (topOf(mCurState) == nullptr || !mParallelWorld->nearNodes(point)) {
return false;
}
// The pushed point can still be within the tolerance of a node the step just left.
const int node = mParallelWorld->findNode(point, [&](int k) {
return exiting && mParallelWorld->isInNode(k, mReloScratch) && !mParallelWorld->isInNode(k, mCurState);
});
if (node < 0) {
// No node holds the point, but the main hierarchy may have put the track in one within its tolerance.
mInParallelNode = mParallelWorld->isInAnyNode(mCurState);
return false;
}
mInParallelNode = true;
if (mParallelWorld->isInNode(node, mCurState)) {
return false;
}
mCurState = mParallelWorld->state(node);
descendInto(mCurState, point);
clearLastExited(); // the volume left is no daughter of this branch
++mParallelRelocated;
return true;
}

void VecGeomG4Navigator::descendInto(vecgeom::NavigationState& state, const V3& point)
{
auto const* placed = state.Top();
state.Pop();
vecgeom::Transformation3D m;
state.TopMatrix(m);
vecgeom::GlobalLocator::LocateGlobalPoint(placed, placed->GetTransformation()->Transform(m.Transform(point)), state,
false);
}

G4VPhysicalVolume* VecGeomG4Navigator::ResetHierarchyAndLocate(const G4ThreeVector& point,
const G4ThreeVector& direction,
const G4TouchableHistory& history)
{
// A track resumes from a stored touchable, usually a secondary starting where its parent's step
Expand All @@ -391,8 +472,9 @@ G4VPhysicalVolume* VecGeomG4Navigator::ResetHierarchyAndLocate(const G4ThreeVect
mWouldExit = false;
mLocatedOnBoundary = false;
mLastLocatedPoint = point;
mLastLocatedDir = direction;
mSafetyOrig = kNoPoint;
mNzeroSteps = 0;
resetZeroSteps();
fHistory = *history.GetHistory();
const V3 p = toVG(point);
bool kept = false;
Expand All @@ -415,6 +497,10 @@ G4VPhysicalVolume* VecGeomG4Navigator::ResetHierarchyAndLocate(const G4ThreeVect
locateFromWorld(p);
}
clearLastExited();
if (mParallelWorld != nullptr) {
// A node holding the point has priority over the touchable too, as in TGeo's search on a resume.
kept = !applyParallelWorld(p, false) && kept;
}
if (kept) {
// The touchable's history is the path of the state: keep it rather than rebuild it.
mHistoryState = mCurState;
Expand Down Expand Up @@ -463,6 +549,10 @@ G4double VecGeomG4Navigator::ComputeSafety(const G4ThreeVector& globalPoint, con
return rest;
}
double safety = boundedSafety(mCurState, globalPoint, proposedMaxLength);
if (mParallelWorld != nullptr && !mInParallelNode && safety > 0.) {
// Up to the caller's bound only; the bound returned for a farther node is a valid lower bound.
safety = mParallelWorld->safetyToIn(toVG(globalPoint), std::min(safety, proposedMaxLength) * kG4ToVG) * kVGToG4;
}
if (safety < 0.) {
++mNegativeSafetyCount;
safety = 0.;
Expand Down
Loading
Loading