Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-11-17 09:23:10

0001 // This file is part of the ACTS project.
0002 //
0003 // Copyright (C) 2016 CERN for the benefit of the ACTS project
0004 //
0005 // This Source Code Form is subject to the terms of the Mozilla Public
0006 // License, v. 2.0. If a copy of the MPL was not distributed with this
0007 // file, You can obtain one at https://mozilla.org/MPL/2.0/.
0008 
0009 #include "ActsExamples/Geant4/SensitiveSurfaceMapper.hpp"
0010 
0011 #include "Acts/Definitions/Units.hpp"
0012 #include "Acts/Geometry/Layer.hpp"
0013 #include "Acts/Geometry/TrackingVolume.hpp"
0014 #include "Acts/Surfaces/AnnulusBounds.hpp"
0015 #include "Acts/Surfaces/SurfaceArray.hpp"
0016 #include "Acts/Utilities/Enumerate.hpp"
0017 #include "Acts/Utilities/Helpers.hpp"
0018 #include "Acts/Utilities/KDTree.hpp"
0019 #include "Acts/Utilities/TransformHelpers.hpp"
0020 #include "Acts/Visualization/GeometryView3D.hpp"
0021 #include "Acts/Visualization/ObjVisualization3D.hpp"
0022 #include "ActsExamples/Geant4/AlgebraConverters.hpp"
0023 
0024 #include <algorithm>
0025 #include <cmath>
0026 #include <limits>
0027 #include <optional>
0028 #include <ostream>
0029 #include <tuple>
0030 #include <type_traits>
0031 #include <utility>
0032 
0033 #include <G4LogicalVolume.hh>
0034 #include <G4Material.hh>
0035 #include <G4Polyhedron.hh>
0036 #include <G4VPhysicalVolume.hh>
0037 #include <G4VSolid.hh>
0038 #include <boost/container/flat_set.hpp>
0039 #include <boost/geometry.hpp>
0040 
0041 // Add some type traits for boost::geometry, so we can use the machinery
0042 // directly with Acts::Vector2 / Eigen::Matrix
0043 namespace boost::geometry::traits {
0044 
0045 template <typename T, int D>
0046 struct tag<Eigen::Matrix<T, D, 1>> {
0047   using type = point_tag;
0048 };
0049 template <typename T, int D>
0050 struct dimension<Eigen::Matrix<T, D, 1>> : std::integral_constant<int, D> {};
0051 template <typename T, int D>
0052 struct coordinate_type<Eigen::Matrix<T, D, 1>> {
0053   using type = T;
0054 };
0055 template <typename T, int D>
0056 struct coordinate_system<Eigen::Matrix<T, D, 1>> {
0057   using type = boost::geometry::cs::cartesian;
0058 };
0059 
0060 template <typename T, int D, std::size_t Index>
0061 struct access<Eigen::Matrix<T, D, 1>, Index> {
0062   static_assert(Index < D, "Out of range");
0063   using Point = Eigen::Matrix<T, D, 1>;
0064   using CoordinateType = typename coordinate_type<Point>::type;
0065   static inline CoordinateType get(Point const& p) { return p[Index]; }
0066   static inline void set(Point& p, CoordinateType const& value) {
0067     p[Index] = value;
0068   }
0069 };
0070 
0071 }  // namespace boost::geometry::traits
0072 
0073 namespace {
0074 
0075 void writeG4Polyhedron(
0076     Acts::IVisualization3D& visualizer, const G4Polyhedron& polyhedron,
0077     const Acts::Transform3& trafo = Acts::Transform3::Identity(),
0078     Acts::Color color = {0, 0, 0}) {
0079   constexpr double convertLength = CLHEP::mm / Acts::UnitConstants::mm;
0080 
0081   for (int i = 1; i <= polyhedron.GetNoFacets(); ++i) {
0082     // This is a bit ugly but I didn't find an easy way to compute this
0083     // beforehand.
0084     constexpr std::size_t maxPoints = 1000;
0085     G4Point3D points[maxPoints];
0086     int nPoints = 0;
0087     polyhedron.GetFacet(i, nPoints, points);
0088     assert(static_cast<std::size_t>(nPoints) < maxPoints);
0089 
0090     std::vector<Acts::Vector3> faces;
0091     for (int j = 0; j < nPoints; ++j) {
0092       faces.emplace_back(points[j][0] * convertLength,
0093                          points[j][1] * convertLength,
0094                          points[j][2] * convertLength);
0095       faces.back() = trafo * faces.back();
0096     }
0097 
0098     visualizer.face(faces, color);
0099   }
0100 }
0101 
0102 }  // namespace
0103 
0104 namespace ActsExamples::Geant4 {
0105 
0106 SensitiveCandidates::SensitiveCandidates(
0107     const std::shared_ptr<const Acts::TrackingGeometry>& trackingGeometry,
0108     std::unique_ptr<const Acts::Logger> _logger)
0109     : m_trackingGeo{trackingGeometry}, m_logger{std::move(_logger)} {}
0110 std::vector<const Acts::Surface*> SensitiveCandidates::queryPosition(
0111     const Acts::GeometryContext& gctx, const Acts::Vector3& position) const {
0112   std::vector<const Acts::Surface*> surfaces{};
0113   ACTS_VERBOSE("Try to fetch the surfaces close to " << position.transpose());
0114 
0115   switch (m_trackingGeo->geometryVersion()) {
0116     using enum Acts::TrackingGeometry::GeometryVersion;
0117     case Gen1: {
0118       // In case we do not find a layer at this position for whatever reason
0119       const auto layer = m_trackingGeo->associatedLayer(gctx, position);
0120       if (layer == nullptr) {
0121         return surfaces;
0122       }
0123 
0124       const auto surfaceArray = layer->surfaceArray();
0125       if (surfaceArray == nullptr) {
0126         return surfaces;
0127       }
0128 
0129       for (const auto& surface : surfaceArray->surfaces()) {
0130         if (surface->isSensitive()) {
0131           surfaces.push_back(surface);
0132         }
0133       }
0134       break;
0135     }
0136     case Gen3: {
0137       const auto* refVolume =
0138           m_trackingGeo->resolveLowestTrackingVolume(gctx, position).value();
0139       if (refVolume != nullptr) {
0140         constexpr bool restrictToSensitives = true;
0141         refVolume->visitSurfaces(
0142             [&](const Acts::Surface* surface) { surfaces.push_back(surface); },
0143             restrictToSensitives);
0144       }
0145       break;
0146     }
0147   }
0148   return surfaces;
0149 }
0150 const Acts::GeometryObject* SensitiveCandidatesBase::queryRegion(
0151     const Acts::GeometryContext& /*gctx*/,
0152     const Acts::Vector3& /*position*/) const {
0153   return nullptr;
0154 }
0155 
0156 const Acts::GeometryObject* SensitiveCandidates::queryRegion(
0157     const Acts::GeometryContext& gctx, const Acts::Vector3& position) const {
0158   // Must resolve the same object that `queryPosition` takes the surfaces from
0159   switch (m_trackingGeo->geometryVersion()) {
0160     using enum Acts::TrackingGeometry::GeometryVersion;
0161     case Gen1:
0162       return m_trackingGeo->associatedLayer(gctx, position);
0163     case Gen3:
0164       return m_trackingGeo->resolveLowestTrackingVolume(gctx, position).value();
0165   }
0166   return nullptr;
0167 }
0168 
0169 std::vector<const Acts::Surface*> SensitiveCandidates::queryAll() const {
0170   std::vector<const Acts::Surface*> surfaces;
0171 
0172   constexpr bool restrictToSensitives = true;
0173   m_trackingGeo->visitSurfaces(
0174       [&](auto surface) { surfaces.push_back(surface); }, restrictToSensitives);
0175 
0176   return surfaces;
0177 }
0178 
0179 /// Candidate surfaces of one region together with their centers, and a k-d
0180 /// tree over the centers. It finds the first candidate centered at a position
0181 /// without computing and comparing the centers of all candidates.
0182 class SensitiveSurfaceMapper::CandidateIndex {
0183  public:
0184   /// @param surfaces the candidate surfaces, in the order they are matched
0185   /// @param gctx the geometry context to compute the centers
0186   /// @param buildTree whether to build the tree; without it the center lookup
0187   ///        is a linear scan, which is cheaper for a single lookup
0188   CandidateIndex(std::vector<const Acts::Surface*> surfaces,
0189                  const Acts::GeometryContext& gctx, bool buildTree)
0190       : m_surfaces{std::move(surfaces)} {
0191     m_centers.reserve(m_surfaces.size());
0192     for (const auto [i, surface] : Acts::enumerate(m_surfaces)) {
0193       m_centers.push_back(surface->center(gctx));
0194       if (surface->bounds().type() == Acts::SurfaceBounds::eAnnulus) {
0195         m_annulusIndices.push_back(i);
0196       }
0197     }
0198     if (!buildTree) {
0199       return;
0200     }
0201     std::vector<std::size_t> indexed;
0202     for (const auto [i, center] : Acts::enumerate(m_centers)) {
0203       if (isIndexable(center)) {
0204         indexed.push_back(i);
0205       } else {
0206         m_unindexed.push_back(i);
0207       }
0208     }
0209     // Identical centers share one tree entry: the tree construction can
0210     // recurse without end on many identical points
0211     const auto lexicographic = [&](std::size_t a, std::size_t b) {
0212       const Acts::Vector3& ca = m_centers[a];
0213       const Acts::Vector3& cb = m_centers[b];
0214       return std::tie(ca.x(), ca.y(), ca.z()) <
0215              std::tie(cb.x(), cb.y(), cb.z());
0216     };
0217     std::ranges::sort(indexed, lexicographic);
0218     CenterTree::vector_t entries;
0219     for (const std::size_t i : indexed) {
0220       const Acts::Vector3& center = m_centers[i];
0221       if (m_groups.empty() || center != m_centers[m_groups.back().front()]) {
0222         m_groups.emplace_back();
0223         entries.push_back(
0224             {{center.x(), center.y(), center.z()}, m_groups.size() - 1});
0225       }
0226       m_groups.back().push_back(i);
0227     }
0228     m_tree.emplace(std::move(entries));
0229   }
0230 
0231   bool empty() const { return m_surfaces.empty(); }
0232   std::size_t size() const { return m_surfaces.size(); }
0233   const Acts::Surface& surface(std::size_t i) const { return *m_surfaces[i]; }
0234   const Acts::Vector3& center(std::size_t i) const { return m_centers[i]; }
0235 
0236   /// Indices of the candidates with annulus bounds, in ascending order
0237   const std::vector<std::size_t>& annulusIndices() const {
0238     return m_annulusIndices;
0239   }
0240 
0241   /// Indices of all candidates whose center compares equal to @p position,
0242   /// in ascending order. The first one is what a linear scan in candidate
0243   /// order would find.
0244   std::vector<std::size_t> centerMatches(const Acts::Vector3& position) const {
0245     std::vector<std::size_t> result;
0246     const auto check = [&](std::size_t i) {
0247       if (m_comparator.compare<3>(m_centers[i], position) == 0) {
0248         result.push_back(i);
0249       }
0250     };
0251     if (!m_tree.has_value() || !isIndexable(position)) {
0252       for (std::size_t i = 0; i < m_centers.size(); ++i) {
0253         check(i);
0254       }
0255       return result;
0256     }
0257     std::ranges::for_each(m_unindexed, check);
0258     CenterTree::range_t range;
0259     for (std::size_t d = 0; d < 3; ++d) {
0260       range.set(d, position[d] - s_searchMargin, position[d] + s_searchMargin);
0261     }
0262     m_tree->rangeSearchMapDiscard(
0263         range,
0264         [&](const CenterTree::coordinate_t& /*center*/, std::size_t group) {
0265           std::ranges::for_each(m_groups[group], check);
0266         });
0267     std::ranges::sort(result);
0268     return result;
0269   }
0270 
0271  private:
0272   using CenterTree = Acts::KDTree<3, std::size_t>;
0273 
0274   /// Translation tolerance of the center comparison
0275   static constexpr double s_tolerance = 0.1 * Acts::UnitConstants::um;
0276   /// Half width of the tree search range around a position, larger than the
0277   /// tolerance so that rounding of the range bounds can not exclude a match
0278   static constexpr double s_searchMargin = 2. * s_tolerance;
0279   /// Larger coordinates are not indexed: their rounding error would no
0280   /// longer be negligible against the tolerance
0281   static constexpr double s_maxCoordinate = 1000. * Acts::UnitConstants::km;
0282 
0283   /// Whether a position can be indexed. Other centers are always compared,
0284   /// other positions use the linear scan.
0285   static bool isIndexable(const Acts::Vector3& position) {
0286     // Also false for NaN
0287     return (position.array().abs() < s_maxCoordinate).all();
0288   }
0289 
0290   std::vector<const Acts::Surface*> m_surfaces;
0291   std::vector<Acts::Vector3> m_centers;
0292   std::vector<std::size_t> m_annulusIndices;
0293   /// Compares only positions, the rotation tolerance is not used
0294   Acts::detail::TransformComparator m_comparator{
0295       s_tolerance, 0.01 * Acts::UnitConstants::mrad};
0296   /// Candidates with identical, indexable centers, by tree entry
0297   std::vector<std::vector<std::size_t>> m_groups;
0298   std::optional<CenterTree> m_tree;
0299   std::vector<std::size_t> m_unindexed;
0300 };
0301 
0302 /// Candidate lookups shared over one traversal of the Geant4 tree
0303 struct SensitiveSurfaceMapper::Cache {
0304   /// Per region returned by `SensitiveCandidatesBase::queryRegion`
0305   std::unordered_map<const Acts::GeometryObject*, CandidateIndex> regions;
0306   /// All sensitive surfaces, the fallback if no region has candidates
0307   std::optional<CandidateIndex> all;
0308 };
0309 
0310 SensitiveSurfaceMapper::SensitiveSurfaceMapper(
0311     const Config& cfg, std::unique_ptr<const Acts::Logger> logger)
0312     : m_cfg(cfg), m_logger(std::move(logger)) {}
0313 
0314 void SensitiveSurfaceMapper::remapSensitiveNames(
0315     State& state, const Acts::GeometryContext& gctx,
0316     G4VPhysicalVolume* g4PhysicalVolume,
0317     const Acts::Transform3& motherTransform) const {
0318   Cache cache;
0319   remapSensitiveNames(state, cache, gctx, g4PhysicalVolume, motherTransform);
0320 }
0321 
0322 void SensitiveSurfaceMapper::remapSensitiveNames(
0323     State& state, Cache& cache, const Acts::GeometryContext& gctx,
0324     G4VPhysicalVolume* g4PhysicalVolume,
0325     const Acts::Transform3& motherTransform) const {
0326   // Make sure the unit conversion is correct
0327 
0328   auto g4LogicalVolume = g4PhysicalVolume->GetLogicalVolume();
0329   auto g4SensitiveDetector = g4LogicalVolume->GetSensitiveDetector();
0330 
0331   // Get the transform of the G4 object
0332   Acts::Transform3 localG4ToGlobal{Acts::Transform3::Identity()};
0333   {
0334     auto g4Translation = g4PhysicalVolume->GetTranslation();
0335     auto g4Rotation = g4PhysicalVolume->GetRotation();
0336     Acts::Vector3 g4RelPosition = convertPosition(g4Translation);
0337     Acts::Translation3 translation(g4RelPosition);
0338     if (g4Rotation == nullptr) {
0339       localG4ToGlobal = motherTransform * translation;
0340     } else {
0341       Acts::RotationMatrix3 rotation;
0342       rotation << g4Rotation->xx(), g4Rotation->yx(), g4Rotation->zx(),
0343           g4Rotation->xy(), g4Rotation->yy(), g4Rotation->zy(),
0344           g4Rotation->xz(), g4Rotation->yz(), g4Rotation->zz();
0345       localG4ToGlobal =
0346           motherTransform * Acts::makeTransform3(rotation, g4RelPosition);
0347     }
0348   }
0349 
0350   const Acts::Vector3 g4AbsPosition = localG4ToGlobal.translation();
0351 
0352   if (G4int nDaughters = g4LogicalVolume->GetNoDaughters(); nDaughters > 0) {
0353     // Step down to all daughters
0354     for (G4int id = 0; id < nDaughters; ++id) {
0355       remapSensitiveNames(state, cache, gctx, g4LogicalVolume->GetDaughter(id),
0356                           localG4ToGlobal);
0357     }
0358   }
0359 
0360   const std::string& volumeName{g4LogicalVolume->GetName()};
0361   const std::string& volumeMaterialName{
0362       g4LogicalVolume->GetMaterial()->GetName()};
0363 
0364   const bool isSensitive = g4SensitiveDetector != nullptr;
0365   const bool isMappedMaterial =
0366       Acts::rangeContainsValue(m_cfg.materialMappings, volumeMaterialName);
0367   const bool isMappedVolume =
0368       Acts::rangeContainsSubstring(m_cfg.volumeMappings, volumeName);
0369 
0370   if (!(isSensitive || isMappedMaterial || isMappedVolume)) {
0371     ACTS_VERBOSE("Did not try mapping '"
0372                  << g4PhysicalVolume->GetName() << "' at "
0373                  << g4AbsPosition.transpose()
0374                  << " because g4SensitiveDetector (=" << g4SensitiveDetector
0375                  << ") is null and volume name (=" << volumeName
0376                  << ") and material name (=" << volumeMaterialName
0377                  << ") were not found");
0378     return;
0379   }
0380   ACTS_VERBOSE("Attempt to map " << g4PhysicalVolume->GetName() << "' at "
0381                                  << g4AbsPosition.transpose()
0382                                  << " to the tracking geometry");
0383 
0384   // Query the candidates at the first polyhedron vertex that has any. They
0385   // are cached per region, so the lookup is built only once per region.
0386   const CandidateIndex* candidates = nullptr;
0387   std::optional<CandidateIndex> uncachedCandidates;
0388   const auto g4Polyhedron = g4LogicalVolume->GetSolid()->GetPolyhedron();
0389   for (int i = 1; i < g4Polyhedron->GetNoVertices(); ++i) {
0390     auto vtx = convertPosition(g4Polyhedron->GetVertex(i));
0391     auto vtxGlobal = localG4ToGlobal * vtx;
0392 
0393     if (const auto* region =
0394             m_cfg.candidateSurfaces->queryRegion(gctx, vtxGlobal);
0395         region != nullptr) {
0396       auto it = cache.regions.find(region);
0397       if (it == cache.regions.end()) {
0398         it = cache.regions
0399                  .try_emplace(
0400                      region,
0401                      m_cfg.candidateSurfaces->queryPosition(gctx, vtxGlobal),
0402                      gctx, true)
0403                  .first;
0404       }
0405       candidates = &it->second;
0406     } else {
0407       uncachedCandidates.emplace(
0408           m_cfg.candidateSurfaces->queryPosition(gctx, vtxGlobal), gctx, false);
0409       candidates = &*uncachedCandidates;
0410     }
0411 
0412     if (!candidates->empty()) {
0413       break;
0414     }
0415   }
0416 
0417   // Fall back to query all surfaces
0418   if (candidates == nullptr || candidates->empty()) {
0419     ACTS_DEBUG("No candidate surfaces for volume '" << volumeName << "' at "
0420                                                     << g4AbsPosition.transpose()
0421                                                     << ", query all surfaces");
0422     if (!cache.all.has_value()) {
0423       cache.all.emplace(m_cfg.candidateSurfaces->queryAll(), gctx, true);
0424     }
0425     candidates = &*cache.all;
0426   }
0427 
0428   ACTS_VERBOSE("Found " << candidates->size() << " candidate surfaces for "
0429                         << volumeName);
0430 
0431   // The match is the first candidate that either has its center at the G4
0432   // position or, for annulus bounds, has its bounds centroid inside the G4
0433   // solid. So only annulus candidates before the first center match need the
0434   // centroid check.
0435   const Acts::Surface* mappedSurface = nullptr;
0436   const auto centerMatches = candidates->centerMatches(g4AbsPosition);
0437   const std::size_t nBeforeCenterMatch =
0438       centerMatches.empty() ? candidates->size() : centerMatches.front();
0439   for (const std::size_t i : candidates->annulusIndices()) {
0440     if (i >= nBeforeCenterMatch) {
0441       break;
0442     }
0443     const Acts::Surface& candidateSurface = candidates->surface(i);
0444     const auto& bounds =
0445         *static_cast<const Acts::AnnulusBounds*>(&candidateSurface.bounds());
0446 
0447     const auto vertices = bounds.vertices(0);
0448 
0449     constexpr bool clockwise = false;
0450     constexpr bool closed = false;
0451     using Polygon =
0452         boost::geometry::model::polygon<Acts::Vector2, clockwise, closed>;
0453 
0454     Polygon poly;
0455     boost::geometry::assign_points(poly, vertices);
0456 
0457     Acts::Vector2 boundsCentroidSurfaceFrame = Acts::Vector2::Zero();
0458     boost::geometry::centroid(poly, boundsCentroidSurfaceFrame);
0459 
0460     Acts::Vector3 boundsCentroidGlobal{boundsCentroidSurfaceFrame[0],
0461                                        boundsCentroidSurfaceFrame[1], 0.0};
0462     boundsCentroidGlobal =
0463         candidateSurface.localToGlobalTransform(gctx) * boundsCentroidGlobal;
0464 
0465     const auto boundsCentroidG4Frame =
0466         localG4ToGlobal.inverse() * boundsCentroidGlobal;
0467 
0468     if (g4LogicalVolume->GetSolid()->Inside(
0469             convertPosition(boundsCentroidG4Frame)) != EInside::kOutside) {
0470       ACTS_VERBOSE("Successful match with centroid matching");
0471       mappedSurface = &candidateSurface;
0472       break;
0473     }
0474   }
0475   if (mappedSurface == nullptr && !centerMatches.empty()) {
0476     std::size_t centerMatch = centerMatches.front();
0477     if (centerMatches.size() > 1) {
0478       // Several surfaces share this center, e.g. concentric cylinders. Take
0479       // the one whose extent, in the frame of the G4 volume, is closest to
0480       // the bounding box of the G4 solid. Ties keep the candidate order.
0481       G4ThreeVector g4SolidMin;
0482       G4ThreeVector g4SolidMax;
0483       g4LogicalVolume->GetSolid()->BoundingLimits(g4SolidMin, g4SolidMax);
0484       const Acts::Vector3 solidMin = convertPosition(g4SolidMin);
0485       const Acts::Vector3 solidMax = convertPosition(g4SolidMax);
0486       const Acts::Transform3 globalToG4 = localG4ToGlobal.inverse();
0487 
0488       double bestDistance = std::numeric_limits<double>::infinity();
0489       for (const std::size_t i : centerMatches) {
0490         Acts::Vector3 surfaceMin =
0491             Acts::Vector3::Constant(std::numeric_limits<double>::infinity());
0492         Acts::Vector3 surfaceMax = -surfaceMin;
0493         for (const auto& vertex :
0494              candidates->surface(i).polyhedronRepresentation(gctx).vertices) {
0495           const Acts::Vector3 vertexG4 = globalToG4 * vertex;
0496           surfaceMin = surfaceMin.cwiseMin(vertexG4);
0497           surfaceMax = surfaceMax.cwiseMax(vertexG4);
0498         }
0499         const double distance = (surfaceMin - solidMin).cwiseAbs().sum() +
0500                                 (surfaceMax - solidMax).cwiseAbs().sum();
0501         ACTS_VERBOSE("Surface " << candidates->surface(i).geometryId()
0502                                 << " has extent distance " << distance);
0503         // False for a non-finite distance, e.g. NaN vertices or none at all
0504         if (distance < bestDistance) {
0505           bestDistance = distance;
0506           centerMatch = i;
0507         }
0508       }
0509       ACTS_DEBUG(centerMatches.size()
0510                  << " surfaces share the center, chose "
0511                  << candidates->surface(centerMatch).geometryId()
0512                  << " by extent for " << volumeName);
0513     }
0514     ACTS_DEBUG("Successful match with center: "
0515                << candidates->center(centerMatch).transpose()
0516                << ", G4-position: " << g4AbsPosition.transpose());
0517     mappedSurface = &candidates->surface(centerMatch);
0518   }
0519 
0520   Acts::detail::TransformComparator trfSorter{};
0521 
0522   if (mappedSurface == nullptr) {
0523     ACTS_DEBUG("No mapping found for '"
0524                << volumeName << "' with material '" << volumeMaterialName
0525                << "' at position " << g4AbsPosition.transpose());
0526     state.missingVolumes.emplace_back(g4PhysicalVolume, localG4ToGlobal);
0527     return;
0528   }
0529 
0530   // A mapped surface was found, a new name will be set that G4PhysVolume
0531   ACTS_DEBUG("Matched " << volumeName << " to " << mappedSurface->geometryId()
0532                         << " at position " << g4AbsPosition.transpose());
0533   // Check if the prefix is not yet assigned
0534   if (volumeName.find(mappingPrefix) == std::string::npos) {
0535     // Set the new name
0536     std::string mappedName = std::string(mappingPrefix) + volumeName;
0537     g4PhysicalVolume->SetName(mappedName);
0538   }
0539   if (state.g4VolumeToSurfaces.find(g4PhysicalVolume) ==
0540       state.g4VolumeToSurfaces.end()) {
0541     state.g4VolumeToSurfaces.insert(
0542         std::make_pair(g4PhysicalVolume, SurfacePosMap_t{trfSorter}));
0543   }
0544   // Insert into the multi-map
0545   if (!state.g4VolumeToSurfaces[g4PhysicalVolume]
0546            .insert(std::make_pair(g4AbsPosition, mappedSurface))
0547            .second) {
0548     ACTS_WARNING("Duplicate surface found for " << volumeName << " @ "
0549                                                 << g4AbsPosition.transpose());
0550   }
0551 }
0552 
0553 bool SensitiveSurfaceMapper::checkMapping(
0554     const State& state, const Acts::GeometryContext& gctx,
0555     bool writeMissingG4VolsAsObj, bool writeMissingSurfacesAsObj) const {
0556   // Candidates have a sensitive geometry id. Only those also flagged
0557   // sensitive (e.g. by their placement) are sensors that need a mapping;
0558   // others, like passive surfaces that a Gen3 layer gives a sensitive id,
0559   // are not.
0560   std::vector<const Acts::Surface*> allSurfaces;
0561   std::size_t nNotFlaggedSensitive = 0;
0562   for (const auto* surface : m_cfg.candidateSurfaces->queryAll()) {
0563     if (surface->isSensitive()) {
0564       allSurfaces.push_back(surface);
0565     } else {
0566       ++nNotFlaggedSensitive;
0567     }
0568   }
0569   std::ranges::sort(allSurfaces);
0570 
0571   std::vector<const Acts::Surface*> found;
0572   for (const auto& [_, surfaceMap] : state.g4VolumeToSurfaces) {
0573     for (const auto& [__, surfacePtr] : surfaceMap) {
0574       found.push_back(surfacePtr);
0575     }
0576   }
0577   std::ranges::sort(found);
0578   auto newEnd = std::unique(found.begin(), found.end());
0579   found.erase(newEnd, found.end());
0580 
0581   std::vector<const Acts::Surface*> missing;
0582   std::set_difference(allSurfaces.begin(), allSurfaces.end(), found.begin(),
0583                       found.end(), std::back_inserter(missing));
0584 
0585   ACTS_INFO("Number of overall sensitive surfaces: " << allSurfaces.size());
0586   if (nNotFlaggedSensitive > 0) {
0587     ACTS_INFO(
0588         "Number of surfaces with a sensitive geometry id that are not "
0589         "flagged sensitive, not required to be mapped: "
0590         << nNotFlaggedSensitive);
0591   }
0592   ACTS_INFO("Number of mapped volume->surface mappings: " << found.size());
0593   ACTS_INFO(
0594       "Number of sensitive surfaces that are not mapped: " << missing.size());
0595   ACTS_INFO("Number of G4 volumes without a matching Surface: "
0596             << state.missingVolumes.size());
0597 
0598   if (writeMissingG4VolsAsObj) {
0599     Acts::ObjVisualization3D visualizer;
0600     for (const auto& [g4vol, trafo] : state.missingVolumes) {
0601       auto polyhedron = g4vol->GetLogicalVolume()->GetSolid()->GetPolyhedron();
0602       writeG4Polyhedron(visualizer, *polyhedron, trafo);
0603     }
0604 
0605     std::ofstream os("missing_g4_volumes.obj");
0606     visualizer.write(os);
0607   }
0608 
0609   if (writeMissingSurfacesAsObj) {
0610     Acts::ObjVisualization3D visualizer;
0611     Acts::ViewConfig vcfg;
0612     vcfg.quarterSegments = 720;
0613     for (auto srf : missing) {
0614       Acts::GeometryView3D::drawSurface(visualizer, *srf, gctx,
0615                                         Acts::Transform3::Identity(), vcfg);
0616     }
0617 
0618     std::ofstream os("missing_acts_surfaces.obj");
0619     visualizer.write(os);
0620   }
0621 
0622   return missing.empty();
0623 }
0624 
0625 }  // namespace ActsExamples::Geant4