Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-08-24 08:27:08

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