Back to home page

sPhenix code displayed by LXR

 
 

    


File indexing completed on 2025-08-05 08:10:16

0001 // This file is part of the Acts project.
0002 //
0003 // Copyright (C) 2023 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 http://mozilla.org/MPL/2.0/.
0008 
0009 #include "Acts/Plugins/DD4hep/DD4hepBlueprintFactory.hpp"
0010 
0011 #include "Acts/Detector/GeometryIdGenerator.hpp"
0012 #include "Acts/Detector/IndexedRootVolumeFinderBuilder.hpp"
0013 #include "Acts/Plugins/DD4hep/DD4hepBinningHelpers.hpp"
0014 #include "Acts/Plugins/DD4hep/DD4hepConversionHelpers.hpp"
0015 #include "Acts/Utilities/BinningData.hpp"
0016 #include "Acts/Utilities/StringHelpers.hpp"
0017 
0018 #include <sstream>
0019 
0020 Acts::Experimental::DD4hepBlueprintFactory::DD4hepBlueprintFactory(
0021     const Config& cfg, std::unique_ptr<const Logger> mlogger)
0022     : m_cfg(cfg), m_logger(std::move(mlogger)) {
0023   ACTS_DEBUG("UnitLength conversion factor (DD4hep -> Acts): " << unitLength);
0024 }
0025 
0026 std::unique_ptr<Acts::Experimental::Blueprint::Node>
0027 Acts::Experimental::DD4hepBlueprintFactory::create(
0028     Cache& cache, const GeometryContext& gctx,
0029     const dd4hep::DetElement& dd4hepElement) const {
0030   ACTS_DEBUG("Drawing a blueprint from the DD4hep element '"
0031              << dd4hepElement.name() << "'.");
0032 
0033   // Create the root node
0034   std::vector<ActsScalar> bValues = {0., 150., 1000.};
0035   std::vector<BinningValue> binning = {Acts::binR};
0036   auto root = std::make_unique<Acts::Experimental::Blueprint::Node>(
0037       dd4hepElement.name(), Acts::Transform3::Identity(),
0038       Acts::VolumeBounds::eCylinder, bValues, binning);
0039 
0040   // Recursively parse the tree
0041   recursiveParse(cache, *root, gctx, dd4hepElement);
0042   // Return the top node
0043   return root;
0044 }
0045 
0046 void Acts::Experimental::DD4hepBlueprintFactory::recursiveParse(
0047     Cache& cache, Blueprint::Node& mother, const GeometryContext& gctx,
0048     const dd4hep::DetElement& dd4hepElement, unsigned int hiearchyLevel) const {
0049   // This will allow to skip empty hierarchy levels
0050   Blueprint::Node* current = &mother;
0051   unsigned int hierarchyAddOn = 0;
0052 
0053   std::string ofs(hiearchyLevel * 2u, ' ');
0054 
0055   // Node types
0056   std::vector<std::string> nodeTypes = {"acts_world", "acts_container",
0057                                         "acts_volume"};
0058   for (const auto& nType : nodeTypes) {
0059     // Check if it complies with the given definition
0060     bool ntt = getParamOr<bool>(nType, dd4hepElement, false);
0061     if (ntt) {
0062       ACTS_DEBUG(ofs << "ACTS node '" << nType
0063                      << "' attached to dd4hep element '" << dd4hepElement.name()
0064                      << "',");
0065       // Extract potential internal builders and tools
0066       auto [internalsBuilder, rootsFinderBuilder, geoIdGenerator, auxInt,
0067             extOpt] =
0068           extractInternals(cache.dd4hepStore, gctx, dd4hepElement, nType);
0069       // Extract the bounds type, values and binning
0070       auto [transform, bValueType, bValues, binning, auxExt] =
0071           extractExternals(gctx, dd4hepElement, nType, extOpt);
0072       // Screen output of position and shape
0073       ACTS_DEBUG(ofs << " - translation  : "
0074                      << toString(transform.translation()));
0075       ACTS_DEBUG(ofs << " - bounds type  : " << bValueType);
0076       ACTS_DEBUG(ofs << " - bound values : " << toString(bValues));
0077       // If it is not the world node, create a new one
0078       if (nType == "acts_world") {
0079         mother.transform = transform;
0080         mother.boundsType = bValueType;
0081         mother.boundaryValues = bValues;
0082         mother.binning = binning;
0083 
0084       } else if (nType == "acts_container") {
0085         // Creating the branch node
0086         auto branch = std::make_unique<Acts::Experimental::Blueprint::Node>(
0087             dd4hepElement.name(), transform, bValueType, bValues, binning);
0088         current = branch.get();
0089         mother.add(std::move(branch));
0090 
0091       } else if (nType == "acts_volume") {
0092         // Crreating a leaf node
0093         auto leaf = std::make_unique<Acts::Experimental::Blueprint::Node>(
0094             dd4hepElement.name(), transform, bValueType, bValues);
0095         current = leaf.get();
0096         mother.add(std::move(leaf));
0097       }
0098       // Current is set now appropriately, adding auxiliary information
0099       if (!auxExt.empty()) {
0100         ACTS_VERBOSE(ofs << " - " << auxExt);
0101         current->auxiliary.push_back(auxExt);
0102       }
0103       // Adding the internals builder - if present
0104       if (internalsBuilder != nullptr) {
0105         ACTS_VERBOSE(ofs << " - " << auxInt[0u]);
0106         current->internalsBuilder = internalsBuilder;
0107       }
0108       // Adding root finder builder - if present
0109       if (rootsFinderBuilder != nullptr) {
0110         ACTS_VERBOSE(ofs << " - " << auxInt[1u]);
0111         current->rootVolumeFinderBuilder = rootsFinderBuilder;
0112       }
0113 
0114       // Check for proto material for the portals, max portal number
0115       // can be changed in configuration
0116       for (unsigned int p = 0u; p < m_cfg.maxPortals; ++p) {
0117         std::string pmName = "acts_portal_proto_material_" + std::to_string(p);
0118         auto protoMaterial = getParamOr<bool>(pmName, dd4hepElement, false);
0119         if (protoMaterial) {
0120           ACTS_VERBOSE(ofs << " - proto material binning for portal " << p
0121                            << " found");
0122           auto pmProtoBinnings = DD4hepBinningHelpers::convertBinning(
0123               dd4hepElement, pmName + "_binning");
0124           current->portalMaterialBinning[p] =
0125               BinningDescription{pmProtoBinnings};
0126           ACTS_VERBOSE(ofs << " - binning description is "
0127                            << current->portalMaterialBinning[p].toString());
0128         }
0129       }
0130 
0131       // Adding geo Id generator - if present
0132       if (geoIdGenerator != nullptr) {
0133         ACTS_VERBOSE(ofs << " - " << auxInt[2u]);
0134         current->geoIdGenerator = geoIdGenerator;
0135       }
0136     }
0137   }
0138 
0139   // Step down to the children - not possible for leaf nodes
0140   const dd4hep::DetElement::Children& children = dd4hepElement.children();
0141   if (!children.empty()) {
0142     ACTS_VERBOSE(ofs << "dd4hep element '" << dd4hepElement.name() << "' has "
0143                      << children.size() << " children.");
0144     for (auto& child : children) {
0145       dd4hep::DetElement dd4hepChild = child.second;
0146       recursiveParse(cache, *current, gctx, dd4hepChild,
0147                      hiearchyLevel + hierarchyAddOn);
0148     }
0149   }
0150 }
0151 
0152 std::tuple<Acts::Transform3, Acts::VolumeBounds::BoundsType,
0153            std::vector<Acts::ActsScalar>, std::vector<Acts::BinningValue>,
0154            std::string>
0155 Acts::Experimental::DD4hepBlueprintFactory::extractExternals(
0156     [[maybe_unused]] const GeometryContext& gctx,
0157     const dd4hep::DetElement& dd4hepElement, const std::string& baseName,
0158     const std::optional<Extent>& extOpt) const {
0159   std::string aux = "";
0160 
0161   /// Get the transform - extract from values first
0162   auto transform = extractTransform(dd4hepElement, baseName, unitLength);
0163 
0164   // Get the bounds type
0165   auto bValueInt =
0166       getParamOr<int>(baseName + "_type", dd4hepElement,
0167                       static_cast<int>(VolumeBounds::BoundsType::eOther));
0168   auto bValueType = static_cast<VolumeBounds::BoundsType>(bValueInt);
0169   std::vector<ActsScalar> bValues = {};
0170 
0171   // Get the bound values from parsed internals if possible
0172   if (extOpt.has_value() && bValueType == VolumeBounds::BoundsType::eCylinder) {
0173     // Set as defaults
0174     bValues = {0., 0., 0.};
0175     auto parsedExtent = extOpt.value();
0176     if (parsedExtent.constrains(binR)) {
0177       bValues[0u] = std::floor(parsedExtent.min(binR));
0178       bValues[1u] = std::ceil(parsedExtent.max(binR));
0179     }
0180     if (parsedExtent.constrains(binZ)) {
0181       ActsScalar minZ = parsedExtent.min(binZ) > 0.
0182                             ? std::floor(parsedExtent.min(binZ))
0183                             : std::ceil(parsedExtent.min(binZ));
0184       ActsScalar maxZ = parsedExtent.max(binZ) > 0.
0185                             ? std::floor(parsedExtent.max(binZ))
0186                             : std::ceil(parsedExtent.max(binZ));
0187       bValues[2u] = 0.5 * (maxZ - minZ);
0188       transform.translation().z() = 0.5 * (maxZ + minZ);
0189     }
0190     ACTS_VERBOSE("   cylindrical bounds determined from internals as "
0191                  << toString(bValues));
0192   }
0193 
0194   // Get the bounds values from the series if not found before
0195   if (bValues.empty()) {
0196     bValues = extractSeries<ActsScalar>(dd4hepElement, baseName + "_bvalues",
0197                                         unitLength);
0198     ACTS_VERBOSE(" - cylindrical determined from variant parameters as "
0199                  << toString(bValues));
0200   }
0201 
0202   // Get the binning values
0203   auto binningString =
0204       getParamOr<std::string>(baseName + "_binning", dd4hepElement, "");
0205   std::vector<BinningValue> bBinning =
0206       Acts::stringToBinningValues(binningString);
0207   if (!binningString.empty()) {
0208     aux += "vol. binning : " + binningString;
0209   }
0210   // Return the tuple
0211   return std::make_tuple(transform, bValueType, bValues, bBinning, aux);
0212 }
0213 
0214 std::tuple<std::shared_ptr<const Acts::Experimental::IInternalStructureBuilder>,
0215            std::shared_ptr<const Acts::Experimental::IRootVolumeFinderBuilder>,
0216            std::shared_ptr<const Acts::Experimental::IGeometryIdGenerator>,
0217            std::array<std::string, 3u>, std::optional<Acts::Extent>>
0218 Acts::Experimental::DD4hepBlueprintFactory::extractInternals(
0219     Acts::DD4hepDetectorElement::Store& dd4hepStore,
0220     const GeometryContext& gctx, const dd4hep::DetElement& dd4hepElement,
0221     const std::string& baseName) const {
0222   // Return objects
0223   std::shared_ptr<const Acts::Experimental::IInternalStructureBuilder>
0224       internalsBuilder = nullptr;
0225   std::shared_ptr<const Acts::Experimental::IRootVolumeFinderBuilder>
0226       rootsFinderBuilder = nullptr;
0227   std::shared_ptr<const Acts::Experimental::IGeometryIdGenerator>
0228       geoIdGenerator = nullptr;
0229   /// The hand-over information for externals
0230   std::optional<Extent> ext = std::nullopt;
0231   /// Auxiliary information
0232   std::array<std::string, 3u> aux = {"", "", ""};
0233 
0234   // Check for internal structure builder
0235   auto internals =
0236       Acts::getParamOr<bool>(baseName + "_internals", dd4hepElement, false);
0237   if (internals) {
0238     auto internalsType = Acts::getParamOr<std::string>(
0239         baseName + "_internals_type", dd4hepElement, "");
0240     if (internalsType == "layer") {
0241       aux[0u] = "int. struct : layer";
0242       // Create a new layer builder
0243       DD4hepLayerStructure::Options lOptions;
0244       lOptions.name = dd4hepElement.name();
0245       // Check whether internal/sensitive surfaces should have directly
0246       // translated material
0247       auto convertMaterial = Acts::getParamOr<bool>(
0248           "acts_surface_material_conversion", dd4hepElement, false);
0249       lOptions.conversionOptions.convertMaterial = convertMaterial;
0250       // Check if the extent should be measured
0251       auto interenalsMeasure = Acts::getParamOr<std::string>(
0252           baseName + "_internals_measure", dd4hepElement, "");
0253       auto internalsClearance =
0254           unitLength *
0255           Acts::getParamOr<ActsScalar>(baseName + "_internals_clearance",
0256                                        dd4hepElement, 0.);
0257       auto internalBinningValues = stringToBinningValues(interenalsMeasure);
0258       if (!internalBinningValues.empty()) {
0259         ACTS_VERBOSE(" - internals extent measurement requested");
0260         Extent internalsExtent;
0261         ExtentEnvelope clearance = zeroEnvelopes;
0262         for (const auto& bv : internalBinningValues) {
0263           ACTS_VERBOSE("   -> measuring extent for "
0264                        << binningValueNames()[bv]);
0265           ACTS_VERBOSE("   -> with clearance :" << internalsClearance);
0266           clearance[bv] = {internalsClearance, internalsClearance};
0267         }
0268         internalsExtent.setEnvelope(clearance);
0269         lOptions.extent = internalsExtent;
0270         lOptions.extentConstraints = internalBinningValues;
0271       }
0272       // Create the builder from the dd4hep element
0273       auto [ib, extOpt] = m_cfg.layerStructure->builder(
0274           dd4hepStore, gctx, dd4hepElement, lOptions);
0275       internalsBuilder = std::move(ib);
0276       if (extOpt.has_value()) {
0277         ACTS_VERBOSE(" - internals extent measured as "
0278                      << extOpt.value().toString());
0279       }
0280       ext = extOpt;
0281     }
0282   }
0283 
0284   // Check for root volume finder
0285   auto rootFinder = Acts::getParamOr<std::string>(
0286       baseName + "_root_volume_finder", dd4hepElement, "");
0287   if (rootFinder == "indexed") {
0288     aux[1u] = "root finder : indexed";
0289     std::vector<BinningValue> binning = {binZ, binR};
0290     rootsFinderBuilder =
0291         std::make_shared<Acts::Experimental::IndexedRootVolumeFinderBuilder>(
0292             binning);
0293   }
0294 
0295   // Check for geo Id generator
0296   auto geoIdGen =
0297       Acts::getParamOr<std::string>(baseName + "_geo_id", dd4hepElement, "");
0298   if (geoIdGen == "incremental") {
0299     aux[2u] = "geo_id gen. : incremental";
0300     Acts::Experimental::GeometryIdGenerator::Config geoIdCfg;
0301     geoIdGenerator =
0302         std::make_shared<Acts::Experimental::GeometryIdGenerator>(geoIdCfg);
0303   }
0304 
0305   return std::make_tuple(internalsBuilder, rootsFinderBuilder, geoIdGenerator,
0306                          aux, ext);
0307 }