Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-11-26 09:30:05

0001 // SPDX-License-Identifier: LGPL-3.0-or-later
0002 // Copyright (C) 2022 - 2024 Whitney Armstrong, Wouter Deconinck, Dmitry Romanov
0003 
0004 #if Acts_VERSION_MAJOR < 45
0005 #include <Acts/Geometry/DetectorElementBase.hpp>
0006 #endif
0007 #include <Acts/Geometry/GeometryIdentifier.hpp>
0008 #include <Acts/Geometry/TrackingGeometry.hpp>
0009 #include <Acts/Geometry/TrackingVolume.hpp>
0010 #include <Acts/MagneticField/MagneticFieldContext.hpp>
0011 #include <Acts/Material/IMaterialDecorator.hpp>
0012 #include <fmt/format.h>
0013 #if Acts_VERSION_MAJOR >= 45
0014 #include <Acts/Surfaces/SurfacePlacementBase.hpp>
0015 #endif
0016 #include <Acts/Surfaces/Surface.hpp>
0017 #include <Acts/Utilities/BinningType.hpp>
0018 #include <Acts/Utilities/Logger.hpp>
0019 #include <Acts/Utilities/Result.hpp>
0020 #include <Acts/Visualization/GeometryView3D.hpp>
0021 #include <Acts/Visualization/ObjVisualization3D.hpp>
0022 #include <Acts/Visualization/PlyVisualization3D.hpp>
0023 #include <ActsPlugins/DD4hep/ConvertDD4hepDetector.hpp>
0024 #include <ActsPlugins/DD4hep/DD4hepDetectorElement.hpp>
0025 #include <ActsPlugins/DD4hep/DD4hepFieldAdapter.hpp>
0026 #include <ActsPlugins/Json/JsonMaterialDecorator.hpp>
0027 #include <ActsPlugins/Json/MaterialMapJsonConverter.hpp>
0028 #include <DD4hep/DetElement.h>
0029 #include <DD4hep/Readout.h>
0030 #include <DD4hep/VolumeManager.h>
0031 #include <TGeoManager.h>
0032 #include <boost/container/detail/std_fwd.hpp>
0033 #include <fmt/ostream.h>
0034 #include <spdlog/common.h>
0035 // Formatter for Eigen matrices
0036 #include <Eigen/Core>
0037 #include <exception>
0038 #include <filesystem>
0039 #include <functional>
0040 #include <initializer_list>
0041 #include <map>
0042 #include <ranges>
0043 #include <set>
0044 #include <stdexcept>
0045 #include <type_traits>
0046 #include <utility>
0047 
0048 #include "ActsGeometryProvider.h"
0049 #include "extensions/spdlog/SpdlogToActs.h"
0050 
0051 template <typename T>
0052 struct fmt::formatter<T, std::enable_if_t<std::is_base_of_v<Eigen::MatrixBase<T>, T>, char>>
0053     : fmt::ostream_formatter {};
0054 
0055 /// @brief Material decorator wrapper that tracks per-layer material assignment
0056 ///
0057 /// Wraps Acts::JsonMaterialDecorator and, for each decorate() call, records
0058 /// whether material was assigned to any approach surface in each
0059 /// (volume, layer) pair. After geometry conversion, call check() to emit
0060 /// critical log messages for every layer that was visited but never had
0061 /// material assigned to any of its approach surfaces.
0062 class EpicJsonMaterialDecorator : public Acts::IMaterialDecorator {
0063 public:
0064   /// Key identifying a layer: (volume id, layer id)
0065   using LayerKey = std::pair<Acts::GeometryIdentifier::Value, Acts::GeometryIdentifier::Value>;
0066 
0067   EpicJsonMaterialDecorator(const Acts::MaterialMapJsonConverter::Config& rConfig,
0068                             const std::string& jFileName, Acts::Logging::Level level,
0069                             std::shared_ptr<spdlog::logger> logger)
0070       : m_inner(rConfig, jFileName, level), m_log(std::move(logger)) {}
0071 
0072   void decorate(Acts::Surface& surface) const override {
0073     m_inner.decorate(surface);
0074     const auto id = surface.geometryId();
0075     m_log->trace("{} assigned to surface with geometryId=(volume={}, boundary={}, layer={}, "
0076                  "approach={}, sensitive={}, extra={})",
0077                  (surface.surfaceMaterial() != nullptr) ? "Material" : "No material", id.volume(),
0078                  id.boundary(), id.layer(), id.approach(), id.sensitive(), id.extra());
0079     // Only consider approach surfaces
0080     if (id.approach() == 0) {
0081       return;
0082     }
0083     LayerKey key{id.volume(), id.layer()};
0084     // Record that this layer was visited
0085     m_decoratedLayers.insert(key);
0086     // If material was assigned, record that
0087     if (surface.surfaceMaterial() != nullptr) {
0088       m_layersWithMaterial.insert(key);
0089     }
0090   }
0091 
0092   void decorate(Acts::TrackingVolume& volume) const override { m_inner.decorate(volume); }
0093 
0094   /// Report every decorated layer that never received material on any approach surface.
0095   void check() const {
0096     for (const auto& key : m_decoratedLayers) {
0097       if (m_layersWithMaterial.find(key) == m_layersWithMaterial.end()) {
0098         m_log->critical(
0099             "No material assigned to any approach surface in layer (volume={}, layer={})",
0100             key.first, key.second);
0101       }
0102     }
0103   }
0104 
0105 private:
0106   Acts::JsonMaterialDecorator m_inner;
0107   std::shared_ptr<spdlog::logger> m_log;
0108   /// All (volume, layer) pairs seen during decoration
0109   mutable std::set<LayerKey> m_decoratedLayers;
0110   /// Subset of decorated layers that had at least one surface with material
0111   mutable std::set<LayerKey> m_layersWithMaterial;
0112 };
0113 
0114 void ActsGeometryProvider::initialize(const dd4hep::Detector* dd4hep_geo, std::string material_file,
0115                                       std::shared_ptr<spdlog::logger> log,
0116                                       std::shared_ptr<spdlog::logger> init_log) {
0117   // LOGGING
0118   m_log      = log;
0119   m_init_log = init_log;
0120 
0121   m_init_log->debug("ActsGeometryProvider initializing...");
0122 
0123   m_init_log->debug("Set TGeoManager and acts_init_log_level log levels");
0124   // Turn off TGeo printouts if appropriate for the msg level
0125   if (m_log->level() >= (int)spdlog::level::info) {
0126     TGeoManager::SetVerboseLevel(0);
0127   }
0128 
0129   // Set ACTS logging level
0130   auto acts_init_log_level = eicrecon::SpdlogToActsLevel(m_init_log->level());
0131 
0132   m_dd4hepDetector = dd4hep_geo;
0133 
0134   // Load ACTS materials maps
0135   std::shared_ptr<const Acts::IMaterialDecorator> materialDeco{nullptr};
0136   if (!material_file.empty()) {
0137     m_init_log->info("loading materials map from file: '{}'", material_file);
0138     // Set up the converter first
0139     Acts::MaterialMapJsonConverter::Config jsonGeoConvConfig;
0140     // Set up the json-based decorator, wrapped to report undecorated layers
0141     materialDeco = std::make_shared<const EpicJsonMaterialDecorator>(
0142         jsonGeoConvConfig, material_file, acts_init_log_level, m_init_log);
0143   }
0144 
0145   // Geometry identifier hook to write detector ID to extra field
0146   class ConvertDD4hepDetectorGeometryIdentifierHook : public Acts::GeometryIdentifierHook {
0147     Acts::GeometryIdentifier decorateIdentifier(Acts::GeometryIdentifier identifier,
0148                                                 const Acts::Surface& surface) const override {
0149 #if Acts_VERSION_MAJOR >= 45
0150       const auto* placement = surface.surfacePlacement();
0151       const auto* dd4hep_det_element =
0152           dynamic_cast<const ActsPlugins::DD4hepDetectorElement*>(placement);
0153 #else
0154       const auto* dd4hep_det_element = dynamic_cast<const ActsPlugins::DD4hepDetectorElement*>(
0155           surface.associatedDetectorElement());
0156 #endif
0157       if (dd4hep_det_element == nullptr) {
0158         return identifier;
0159       }
0160       // set 8-bit extra field to 8-bit DD4hep detector ID
0161       return identifier.withExtra(geometryIdExtra(dd4hep_det_element->identifier()));
0162     };
0163   };
0164   auto geometryIdHook = std::make_shared<ConvertDD4hepDetectorGeometryIdentifierHook>();
0165 
0166   // Convert DD4hep geometry to ACTS
0167   m_init_log->info("Converting DD4Hep geometry to ACTS...");
0168   auto logger                  = eicrecon::getSpdlogLogger("CONV", m_log);
0169   Acts::BinningType bTypePhi   = Acts::equidistant;
0170   Acts::BinningType bTypeR     = Acts::equidistant;
0171   Acts::BinningType bTypeZ     = Acts::equidistant;
0172   double layerEnvelopeR        = Acts::UnitConstants::mm;
0173   double layerEnvelopeZ        = Acts::UnitConstants::mm;
0174   double defaultLayerThickness = Acts::UnitConstants::fm;
0175 
0176   try {
0177     m_trackingGeo = ActsPlugins::convertDD4hepDetector(
0178         m_dd4hepDetector->world(), *logger, bTypePhi, bTypeR, bTypeZ, layerEnvelopeR,
0179         layerEnvelopeZ, defaultLayerThickness, ActsPlugins::sortDetElementsByID, m_trackingGeoCtx,
0180         materialDeco, geometryIdHook);
0181   } catch (const std::exception& ex) {
0182     m_init_log->error("Error during DD4Hep -> ACTS geometry conversion: {}", ex.what());
0183     m_init_log->info("Set parameter acts:LogLevel=trace to see conversion info and possibly "
0184                      "identify failing geometry");
0185     throw;
0186   }
0187 
0188   m_init_log->info("DD4Hep geometry converted!");
0189 
0190   // Report layers that were visited but never had material assigned
0191   if (auto epicDeco = std::dynamic_pointer_cast<const EpicJsonMaterialDecorator>(materialDeco)) {
0192     epicDeco->check();
0193   }
0194 
0195   // Visit surfaces
0196   m_init_log->info("Checking surfaces...");
0197   if (m_trackingGeo) {
0198     // Write tracking geometry to collection of obj or ply files
0199     const Acts::TrackingVolume* world = m_trackingGeo->highestTrackingVolume();
0200     if (m_objWriteIt) {
0201       m_init_log->info("Writing obj files to {}...", m_outputDir);
0202       Acts::ObjVisualization3D objVis;
0203       Acts::GeometryView3D::drawTrackingVolume(objVis, *world, m_trackingGeoCtx, m_containerView,
0204                                                m_volumeView, m_passiveView, m_sensitiveView,
0205                                                m_gridView, m_objWriteIt, m_outputTag, m_outputDir);
0206     }
0207     if (m_plyWriteIt) {
0208       m_init_log->info("Writing ply files to {}...", m_outputDir);
0209       Acts::PlyVisualization3D plyVis;
0210       Acts::GeometryView3D::drawTrackingVolume(plyVis, *world, m_trackingGeoCtx, m_containerView,
0211                                                m_volumeView, m_passiveView, m_sensitiveView,
0212                                                m_gridView, m_plyWriteIt, m_outputTag, m_outputDir);
0213     }
0214 
0215     m_init_log->debug("visiting all the surfaces  ");
0216     m_trackingGeo->visitSurfaces([this](const Acts::Surface* surface) {
0217       // for now we just require a valid surface
0218       if (surface == nullptr) {
0219         m_init_log->info("no surface??? ");
0220         return;
0221       }
0222 #if Acts_VERSION_MAJOR >= 45
0223       const auto* placement   = surface->surfacePlacement();
0224       const auto* det_element = dynamic_cast<const ActsPlugins::DD4hepDetectorElement*>(placement);
0225 #else
0226       const auto* det_element = dynamic_cast<const ActsPlugins::DD4hepDetectorElement*>(
0227           surface->associatedDetectorElement());
0228 #endif
0229 
0230       if (det_element == nullptr) {
0231         m_init_log->error("invalid det_element!!! det_element == nullptr ");
0232         return;
0233       }
0234 
0235       // more verbose output is lower enum value
0236       m_init_log->debug(" det_element->identifier() = {} ", det_element->identifier());
0237       auto volman   = m_dd4hepDetector->volumeManager();
0238       auto* vol_ctx = volman.lookupContext(det_element->identifier());
0239       auto vol_id   = vol_ctx->identifier;
0240 
0241       if (m_init_log->level() <= spdlog::level::debug) {
0242         auto de = vol_ctx->element;
0243         m_init_log->debug("  de.path          = {}", de.path());
0244         m_init_log->debug("  de.placementPath = {}", de.placementPath());
0245       }
0246 
0247       this->m_surfaces.insert_or_assign(vol_id, surface);
0248     });
0249   } else {
0250     m_init_log->error("m_trackingGeo==null why am I still alive???");
0251   }
0252 
0253   // Load ACTS magnetic field
0254   m_init_log->info("Loading magnetic field...");
0255   m_magneticField = std::make_shared<ActsPlugins::DD4hepFieldAdapter>(m_dd4hepDetector->field());
0256   auto bCache     = m_magneticField->makeCache(Acts::MagneticFieldContext{});
0257   for (int z : {0, 500, 1000, 1500, 2000, 3000, 4000}) {
0258     auto b = m_magneticField->getField({0.0, 0.0, double(z)}, bCache).value();
0259     m_init_log->debug("B(z = {:>5} [mm]) = {} T", z, b.transpose() / Acts::UnitConstants::T);
0260   }
0261 
0262   m_init_log->info("ActsGeometryProvider initialization complete");
0263 }
0264 
0265 std::shared_ptr<const Acts::MagneticFieldProvider> ActsGeometryProvider::getFieldProvider() const {
0266   return m_magneticField;
0267 }
0268 
0269 std::set<std::uint8_t>
0270 ActsGeometryProvider::geometryIdExtrasForReadouts(const dd4hep::Detector& detector,
0271                                                   const std::vector<std::string>& readouts) {
0272   std::set<std::uint8_t> extras;
0273   // System ID that each extra value was obtained from, to detect truncation collisions
0274   std::map<std::uint8_t, std::uint64_t> systemIDs;
0275   for (const auto& readout : readouts) {
0276     // Sensitive detectors are named after the DetElement they belong to
0277     std::vector<std::string> detectorNames;
0278     for (const auto& [name, handle] : detector.sensitiveDetectors()) {
0279       const dd4hep::SensitiveDetector sd{handle};
0280       if (sd.isValid() && sd.readout().isValid() && sd.readout().name() == readout) {
0281         detectorNames.push_back(name);
0282       }
0283     }
0284 
0285     // DetElements may be nested in assemblies, so search the whole tree by name
0286     bool found                                                 = false;
0287     const std::function<void(const dd4hep::DetElement&)> visit = [&](const dd4hep::DetElement& de) {
0288       if (std::ranges::find(detectorNames, de.name()) != detectorNames.end()) {
0289         const std::uint64_t systemID = de.id();
0290         const std::uint8_t extra     = geometryIdExtra(systemID);
0291         const auto [it, inserted]    = systemIDs.emplace(extra, systemID);
0292         if (!inserted && it->second != systemID) {
0293           throw std::runtime_error(
0294               fmt::format("System IDs {} and {} map to the same geometry identifier extra {}",
0295                           it->second, systemID, extra));
0296         }
0297         extras.insert(extra);
0298         found = true;
0299         return;
0300       }
0301       for (const auto& [_, child] : de.children()) {
0302         visit(child);
0303       }
0304     };
0305     visit(detector.world());
0306 
0307     if (!found) {
0308       throw std::runtime_error(
0309           fmt::format("Readout \"{}\" is not used by any detector in the geometry", readout));
0310     }
0311   }
0312   return extras;
0313 }