Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-11-24 09:33:34

0001 // SPDX-License-Identifier: LGPL-3.0-or-later
0002 // Copyright (C) 2022, 2023 Wenqing Fan, Barak Schmookler, Whitney Armstrong, Sylvester Joosten, Dmitry Romanov, Christopher Dilks, Wouter Deconinck
0003 
0004 #include <Acts/Definitions/Algebra.hpp>
0005 #include <Acts/Definitions/Direction.hpp>
0006 #include <Acts/Definitions/TrackParametrization.hpp>
0007 #include <Acts/Definitions/Units.hpp>
0008 #include <Acts/Utilities/MathHelpers.hpp>
0009 #if Acts_VERSION_MAJOR >= 46
0010 #include <Acts/EventData/BoundTrackParameters.hpp>
0011 #else
0012 #include <Acts/EventData/GenericBoundTrackParameters.hpp>
0013 #endif
0014 #include <Acts/EventData/MultiTrajectoryHelpers.hpp>
0015 #include <Acts/EventData/VectorMultiTrajectory.hpp>
0016 #include <Acts/Geometry/GeometryIdentifier.hpp>
0017 #include <Acts/Geometry/TrackingGeometry.hpp>
0018 #include <Acts/MagneticField/MagneticFieldProvider.hpp>
0019 #include <Acts/Material/MaterialInteraction.hpp>
0020 #include <Acts/Propagator/ActorList.hpp>
0021 #if __has_include(<Acts/Propagator/DefaultActor.hpp>)
0022 #include <Acts/Propagator/DefaultActor.hpp>
0023 #endif
0024 #include <Acts/Propagator/EigenStepper.hpp>
0025 #include <Acts/Propagator/MaterialInteractor.hpp>
0026 #include <Acts/Propagator/Navigator.hpp>
0027 #include <Acts/Propagator/Propagator.hpp>
0028 #include <Acts/Propagator/PropagatorResult.hpp>
0029 #include <Acts/Surfaces/CylinderBounds.hpp>
0030 #include <Acts/Surfaces/CylinderSurface.hpp>
0031 #include <Acts/Surfaces/DiscSurface.hpp>
0032 #include <Acts/Surfaces/RadialBounds.hpp>
0033 #include <Acts/Utilities/Logger.hpp>
0034 #include <DD4hep/Handle.h>
0035 #include <Evaluator/DD4hepUnits.h>
0036 #include <edm4eic/Cov2f.h>
0037 #include <edm4eic/Cov3f.h>
0038 #include <edm4hep/Vector3f.h>
0039 #include <edm4hep/utils/vector_utils.h>
0040 #include <spdlog/common.h>
0041 #include <Eigen/Core>
0042 #include <Eigen/Geometry>
0043 #include <algorithm>
0044 #include <any>
0045 #include <cmath>
0046 #include <cstdint>
0047 #include <functional>
0048 #include <iterator>
0049 #include <map>
0050 #include <optional>
0051 #include <stdexcept>
0052 #include <string>
0053 #include <tuple>
0054 #include <typeinfo>
0055 #include <utility>
0056 #include <variant>
0057 
0058 #include "algorithms/interfaces/detail/multilambda.h"
0059 #include "algorithms/tracking/ActsGeometryProvider.h"
0060 #include "algorithms/tracking/TrackPropagation.h"
0061 #include "algorithms/tracking/TrackPropagationConfig.h"
0062 #include "extensions/spdlog/SpdlogToActs.h"
0063 
0064 namespace eicrecon {
0065 
0066 void TrackPropagation::init() {
0067   const auto* detector = m_detector;
0068 
0069   std::map<uint32_t, std::size_t> system_id_layers;
0070 
0071   multilambda _toDouble = {
0072       [](const std::string& v) { return dd4hep::_toDouble(v); },
0073       [](const double& v) { return v; },
0074   };
0075 
0076   auto _toActsSurface =
0077       [&_toDouble, &detector, &system_id_layers](
0078           const std::variant<CylinderSurfaceConfig, DiscSurfaceConfig> surface_variant)
0079       -> std::shared_ptr<Acts::Surface> {
0080     if (std::holds_alternative<CylinderSurfaceConfig>(surface_variant)) {
0081       CylinderSurfaceConfig surface = std::get<CylinderSurfaceConfig>(surface_variant);
0082       const double rmin =
0083           std::visit(_toDouble, surface.rmin) / dd4hep::mm * Acts::UnitConstants::mm;
0084       const double zmin =
0085           std::visit(_toDouble, surface.zmin) / dd4hep::mm * Acts::UnitConstants::mm;
0086       const double zmax =
0087           std::visit(_toDouble, surface.zmax) / dd4hep::mm * Acts::UnitConstants::mm;
0088       const uint32_t system_id = detector->constant<uint32_t>(surface.id);
0089       auto bounds              = std::make_shared<Acts::CylinderBounds>(rmin, (zmax - zmin) / 2);
0090       auto t                   = Acts::Translation3(Acts::Vector3(0, 0, (zmax + zmin) / 2));
0091       auto tf                  = Acts::Transform3(t);
0092       auto acts_surface        = Acts::Surface::makeShared<Acts::CylinderSurface>(tf, bounds);
0093       acts_surface->assignGeometryId(
0094           Acts::GeometryIdentifier().withExtra(system_id).withLayer(++system_id_layers[system_id]));
0095       return acts_surface;
0096     }
0097     if (std::holds_alternative<DiscSurfaceConfig>(surface_variant)) {
0098       DiscSurfaceConfig surface = std::get<DiscSurfaceConfig>(surface_variant);
0099       const double zmin =
0100           std::visit(_toDouble, surface.zmin) / dd4hep::mm * Acts::UnitConstants::mm;
0101       const double rmin =
0102           std::visit(_toDouble, surface.rmin) / dd4hep::mm * Acts::UnitConstants::mm;
0103       const double rmax =
0104           std::visit(_toDouble, surface.rmax) / dd4hep::mm * Acts::UnitConstants::mm;
0105       const uint32_t system_id = detector->constant<uint32_t>(surface.id);
0106       auto bounds              = std::make_shared<Acts::RadialBounds>(rmin, rmax);
0107       auto t                   = Acts::Translation3(Acts::Vector3(0, 0, zmin));
0108       auto tf                  = Acts::Transform3(t);
0109       auto acts_surface        = Acts::Surface::makeShared<Acts::DiscSurface>(tf, bounds);
0110       acts_surface->assignGeometryId(
0111           Acts::GeometryIdentifier().withExtra(system_id).withLayer(++system_id_layers[system_id]));
0112       return acts_surface;
0113     }
0114     throw std::domain_error("Unknown surface type");
0115   };
0116   m_target_surfaces.resize(m_cfg.target_surfaces.size());
0117   std::ranges::transform(m_cfg.target_surfaces, m_target_surfaces.begin(), _toActsSurface);
0118   m_filter_surfaces.resize(m_cfg.filter_surfaces.size());
0119   std::ranges::transform(m_cfg.filter_surfaces, m_filter_surfaces.begin(), _toActsSurface);
0120 
0121   trace("Initialized");
0122 }
0123 
0124 void TrackPropagation::propagateToSurfaceList(const Input& input, const Output& output) const {
0125   const auto [tracks, track_states, tracks_acts] = input;
0126   auto [track_segments]                          = output;
0127 
0128   // logging
0129   trace("Propagate tracks: --------------------");
0130   trace("number of tracks: {}", tracks->size());
0131 
0132   // Construct ConstTrackContainer from underlying containers
0133   auto trackStateContainer = std::make_shared<Acts::ConstVectorMultiTrajectory>(*track_states);
0134   auto trackContainer      = std::make_shared<Acts::ConstVectorTrackContainer>(*tracks_acts);
0135   ActsExamples::ConstTrackContainer constTracks(trackContainer, trackStateContainer);
0136 
0137   // loop over input tracks
0138   std::size_t i = 0;
0139   for (const auto& track : constTracks) {
0140 
0141     // check if this track can be propagated to any filter surface
0142     bool track_reaches_filter_surface{false};
0143     for (const auto& filter_surface : m_filter_surfaces) {
0144       auto point = propagate(edm4eic::Track{}, track, constTracks, filter_surface);
0145       if (point) {
0146         track_reaches_filter_surface = true;
0147         break;
0148       }
0149     }
0150     if (!track_reaches_filter_surface) {
0151       ++i;
0152       continue;
0153     }
0154 
0155     // start a mutable TrackSegment
0156     auto track_segment = track_segments->create();
0157 
0158     // corresponding track
0159     if (tracks->size() == constTracks.size()) {
0160       trace("track segment connected to track {}", i);
0161       track_segment.setTrack((*tracks)[i]);
0162       ++i;
0163     }
0164 
0165     // zero measurements of segment length
0166     decltype(edm4eic::TrackSegmentData::length) length            = 0;
0167     decltype(edm4eic::TrackSegmentData::lengthError) length_error = 0;
0168 
0169     // loop over projection-target surfaces
0170     for (const auto& target_surface : m_target_surfaces) {
0171 
0172       // project the track to this surface
0173       auto point = propagate(edm4eic::Track{}, track, constTracks, target_surface);
0174       if (!point) {
0175         trace("<> Failed to propagate track to this plane");
0176         continue;
0177       }
0178 
0179       // logging
0180       trace("<> track: x=( {:>10.2f} {:>10.2f} {:>10.2f} )", point->position.x, point->position.y,
0181             point->position.z);
0182       trace("               p=( {:>10.2f} {:>10.2f} {:>10.2f} )", point->momentum.x,
0183             point->momentum.y, point->momentum.z);
0184 
0185       // track point cut
0186       if (!m_cfg.track_point_cut(*point)) {
0187         trace("                 => REJECTED by trackPointCut");
0188         if (m_cfg.skip_track_on_track_point_cut_failure) {
0189           break;
0190         }
0191         continue;
0192       }
0193 
0194       // update the `TrackSegment` length
0195       // FIXME: `length` and `length_error` are currently not used by any callers, and may not be correctly calculated here
0196       if (track_segment.points_size() > 0) {
0197         auto pos0 = point->position;
0198         auto pos1 = std::prev(track_segment.points_end())->position;
0199         auto dist = edm4hep::utils::magnitude(pos0 - pos1);
0200         length += dist;
0201         trace("               dist to previous point: {}", dist);
0202       }
0203 
0204       // add the `TrackPoint` to the `TrackSegment`
0205       track_segment.addToPoints(*point);
0206 
0207     } // end `targetSurfaces` loop
0208 
0209     // set final length and length error
0210     track_segment.setLength(length);
0211     track_segment.setLengthError(length_error);
0212 
0213   } // end loop over input tracks
0214 }
0215 
0216 std::unique_ptr<edm4eic::TrackPoint>
0217 TrackPropagation::propagate(const edm4eic::Track& /* track */,
0218                             const ActsExamples::ConstTrackProxy& acts_track,
0219                             const ActsExamples::ConstTrackContainer& trackContainer,
0220                             const std::shared_ptr<const Acts::Surface>& targetSurf) const {
0221 
0222   auto tipIndex = acts_track.tipIndex();
0223 
0224   trace("  Propagating track with tip index {}", tipIndex);
0225 
0226   // Collect the trajectory summary info
0227   auto trajState =
0228       Acts::MultiTrajectoryHelpers::trajectoryState(trackContainer.trackStateContainer(), tipIndex);
0229   int m_nMeasurements = trajState.nMeasurements;
0230   int m_nStates       = trajState.nStates;
0231 
0232   trace("  Num measurement in trajectory: {}", m_nMeasurements);
0233   trace("  Num states in trajectory     : {}", m_nStates);
0234 
0235   // Get track state at last measurement surface
0236   // For last measurement surface, filtered and smoothed results are equivalent
0237   auto trackState        = trackContainer.trackStateContainer().getTrackState(tipIndex);
0238   auto initSurface       = trackState.referenceSurface().getSharedPtr();
0239   const auto& initParams = trackState.filtered();
0240   const auto& initCov    = trackState.filteredCovariance();
0241 
0242   Acts::BoundTrackParameters initBoundParams(initSurface, initParams, initCov,
0243                                              acts_track.particleHypothesis());
0244 
0245   // Get pathlength of last track state with respect to perigee surface
0246   const auto initPathLength = trackState.pathLength();
0247 
0248   trace("    TrackPropagation. Propagating to surface # {}", typeid(targetSurf->type()).name());
0249 
0250   std::shared_ptr<const Acts::TrackingGeometry> trackingGeometry   = m_geoSvc->trackingGeometry();
0251   std::shared_ptr<const Acts::MagneticFieldProvider> magneticField = m_geoSvc->getFieldProvider();
0252 
0253   // Convert algorithm log level to Acts log level
0254   const auto spdlog_level = static_cast<spdlog::level::level_enum>(this->level());
0255   const auto acts_level   = eicrecon::SpdlogToActsLevel(spdlog_level);
0256   ACTS_LOCAL_LOGGER(Acts::getDefaultLogger("PROP", acts_level));
0257 
0258   using Propagator = Acts::Propagator<Acts::EigenStepper<>, Acts::Navigator>;
0259 #if __has_include(<Acts/Propagator/DefaultActor.hpp>)
0260   // Acts >= PR #6410: a single actor per propagation; DefaultActor provides
0261   // the target surface and path limit abort conditions previously injected
0262   using PropagatorOptions =
0263       Propagator::template Options<Acts::ActorList<Acts::DefaultActor, Acts::MaterialInteractor>>;
0264 #else
0265   using PropagatorOptions = Propagator::template Options<Acts::ActorList<Acts::MaterialInteractor>>;
0266 #endif
0267   Propagator propagator(Acts::EigenStepper<>(magneticField),
0268                         Acts::Navigator({.trackingGeometry = m_geoSvc->trackingGeometry()},
0269                                         logger().cloneWithSuffix("Navigator")),
0270                         logger().cloneWithSuffix("Propagator"));
0271 
0272   // Get run-scoped contexts from service
0273   const auto& gctx = m_geoSvc->getActsGeometryContext();
0274   const auto& mctx = m_geoSvc->getActsMagneticFieldContext();
0275 
0276   PropagatorOptions propagationOptions(gctx, mctx);
0277 
0278   // Some target surfaces (e.g. DIRC) may be inside the last measurement surface (e.g. BIC),
0279   // so we use a straight line intersection from the last measurement surface to the target
0280   // surface to determine if we have to propagate backwards.
0281   auto initPosition  = initBoundParams.position(gctx);
0282   auto initDirection = initBoundParams.direction();
0283   auto intersections = targetSurf->intersect(gctx, initPosition, initDirection);
0284 
0285   // Determine closest forward intersection (positive pathlength from perigee)
0286   auto intersection = intersections.closestForward();
0287   auto difference   = intersection.position() - initPosition;
0288   auto dot          = difference.dot(initBoundParams.direction());
0289 
0290   // Propagate forwards by default
0291   propagationOptions.direction = Acts::Direction::Forward();
0292 
0293   // but invert if the position difference is opposite to direction
0294   if (intersection.isValid() && dot < 0) {
0295 
0296     // The extra fields of the surface geometry ID contain the DD4hep system
0297     auto initSurfaceExtra   = initSurface->geometryId().extra();
0298     auto targetSurfaceExtra = targetSurf->geometryId().extra();
0299     debug("    inverting direction for propagator from surface {} to {}", initSurfaceExtra,
0300           targetSurfaceExtra);
0301     auto p1 = initBoundParams.position(gctx);
0302     debug("      initial position {} {} {}", p1.x(), p1.y(), p1.z());
0303     auto p2 = intersection.position();
0304     debug("      straight line intersection at {} {} {}", p2.x(), p2.y(), p2.z());
0305 
0306     // Propagate backwards
0307     propagationOptions.direction = Acts::Direction::Backward();
0308   }
0309 
0310   auto result = propagator.propagate(initBoundParams, *targetSurf, propagationOptions);
0311 
0312   // check propagation result
0313   if (!result.ok()) {
0314     trace("    propagation failed (!result.ok())");
0315     return nullptr;
0316   }
0317   trace("    propagation result is OK");
0318 
0319   // Pulling results to convenient variables
0320   auto trackStateParams  = *((*result).endParameters);
0321   const auto& parameter  = trackStateParams.parameters();
0322   const auto& covariance = *trackStateParams.covariance();
0323 
0324   // Path length
0325   const float pathLength      = initPathLength + (*result).pathLength;
0326   const float pathLengthError = 0;
0327   trace("    path len = {}", pathLength);
0328 
0329   // Position:
0330   auto projectionPos = trackStateParams.position(gctx);
0331   const decltype(edm4eic::TrackPoint::position) position{static_cast<float>(projectionPos(0)),
0332                                                          static_cast<float>(projectionPos(1)),
0333                                                          static_cast<float>(projectionPos(2))};
0334   const decltype(edm4eic::TrackPoint::positionError) positionError{0, 0, 0};
0335   trace("    pos x = {}", position.x);
0336   trace("    pos y = {}", position.y);
0337   trace("    pos z = {}", position.z);
0338 
0339   // Momentum
0340   const decltype(edm4eic::TrackPoint::momentum) momentum = edm4hep::utils::sphericalToVector(
0341       static_cast<float>(1.0 / std::abs(parameter[Acts::eBoundQOverP] * Acts::UnitConstants::GeV)),
0342       static_cast<float>(parameter[Acts::eBoundTheta] / Acts::UnitConstants::rad),
0343       static_cast<float>(parameter[Acts::eBoundPhi] / Acts::UnitConstants::rad));
0344   const decltype(edm4eic::TrackPoint::momentumError) momentumError{
0345       static_cast<float>(covariance(Acts::eBoundTheta, Acts::eBoundTheta) /
0346                          Acts::UnitConstants::rad / Acts::UnitConstants::rad),
0347       static_cast<float>(covariance(Acts::eBoundPhi, Acts::eBoundPhi) / Acts::UnitConstants::rad /
0348                          Acts::UnitConstants::rad),
0349       static_cast<float>(covariance(Acts::eBoundQOverP, Acts::eBoundQOverP) *
0350                          Acts::UnitConstants::GeV * Acts::UnitConstants::GeV),
0351       static_cast<float>(covariance(Acts::eBoundTheta, Acts::eBoundPhi) / Acts::UnitConstants::rad /
0352                          Acts::UnitConstants::rad),
0353       static_cast<float>(covariance(Acts::eBoundTheta, Acts::eBoundQOverP) /
0354                          Acts::UnitConstants::rad * Acts::UnitConstants::GeV),
0355       static_cast<float>(covariance(Acts::eBoundPhi, Acts::eBoundQOverP) /
0356                          Acts::UnitConstants::rad * Acts::UnitConstants::GeV)};
0357 
0358   // time
0359   const float time{static_cast<float>(parameter(Acts::eBoundTime) / Acts::UnitConstants::ns)};
0360   const float timeError{static_cast<float>(sqrt(covariance(Acts::eBoundTime, Acts::eBoundTime)) /
0361                                            Acts::UnitConstants::ns)};
0362 
0363   // Direction
0364   const float theta(parameter[Acts::eBoundTheta]);
0365   const float phi(parameter[Acts::eBoundPhi]);
0366   const decltype(edm4eic::TrackPoint::directionError) directionError{
0367       static_cast<float>(covariance(Acts::eBoundTheta, Acts::eBoundTheta) /
0368                          Acts::UnitConstants::rad / Acts::UnitConstants::rad),
0369       static_cast<float>(covariance(Acts::eBoundPhi, Acts::eBoundPhi) / Acts::UnitConstants::rad /
0370                          Acts::UnitConstants::rad),
0371       static_cast<float>(covariance(Acts::eBoundTheta, Acts::eBoundPhi) / Acts::UnitConstants::rad /
0372                          Acts::UnitConstants::rad)};
0373 
0374   // >oO debug print
0375   trace("    loc 0   = {:.4f} mm", parameter[Acts::eBoundLoc0] / Acts::UnitConstants::mm);
0376   trace("    loc 1   = {:.4f} mm", parameter[Acts::eBoundLoc1] / Acts::UnitConstants::mm);
0377   trace("    phi     = {:.4f} rad", parameter[Acts::eBoundPhi] / Acts::UnitConstants::rad);
0378   trace("    theta   = {:.4f} rad", parameter[Acts::eBoundTheta] / Acts::UnitConstants::rad);
0379   trace("    q/p     = {:.4f} / GeV", parameter[Acts::eBoundQOverP] * Acts::UnitConstants::GeV);
0380   trace("    p       = {:.4f} GeV", 1.0 / parameter[Acts::eBoundQOverP] / Acts::UnitConstants::GeV);
0381   trace("    err phi = {:.4f} rad", sqrt(covariance(Acts::eBoundPhi, Acts::eBoundPhi) /
0382                                          Acts::UnitConstants::rad / Acts::UnitConstants::rad));
0383   trace("    err th  = {:.4f} rad", sqrt(covariance(Acts::eBoundTheta, Acts::eBoundTheta) /
0384                                          Acts::UnitConstants::rad / Acts::UnitConstants::rad));
0385   trace("    err q/p = {:.4f} / GeV", sqrt(covariance(Acts::eBoundQOverP, Acts::eBoundQOverP) *
0386                                            Acts::UnitConstants::GeV * Acts::UnitConstants::GeV));
0387   trace("    chi2    = {:.4f}", trajState.chi2Sum);
0388   trace("    loc err = {:.4f} mm^2",
0389         static_cast<float>(covariance(Acts::eBoundLoc0, Acts::eBoundLoc0) /
0390                            Acts::UnitConstants::mm / Acts::UnitConstants::mm));
0391   trace("    loc err = {:.4f} mm^2",
0392         static_cast<float>(covariance(Acts::eBoundLoc1, Acts::eBoundLoc1) /
0393                            Acts::UnitConstants::mm / Acts::UnitConstants::mm));
0394   trace("    loc err = {:.4f} mm^2",
0395         static_cast<float>(covariance(Acts::eBoundLoc0, Acts::eBoundLoc1) /
0396                            Acts::UnitConstants::mm / Acts::UnitConstants::mm));
0397 
0398   uint64_t surface = targetSurf->geometryId().value();
0399   uint32_t system  = 0; // default value...will be set in TrackPropagation factory
0400 
0401   return std::make_unique<edm4eic::TrackPoint>(
0402       edm4eic::TrackPoint{.surface         = surface,
0403                           .system          = system,
0404                           .position        = position,
0405                           .positionError   = positionError,
0406                           .momentum        = momentum,
0407                           .momentumError   = momentumError,
0408                           .time            = time,
0409                           .timeError       = timeError,
0410                           .theta           = theta,
0411                           .phi             = phi,
0412                           .directionError  = directionError,
0413                           .pathlength      = pathLength,
0414                           .pathlengthError = pathLengthError});
0415 }
0416 
0417 } // namespace eicrecon