Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-12-04 09:44:46

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 #pragma once
0010 
0011 // for definitions of Calibrator, MeasurementSelector
0012 #include "Acts/TrackFinding/CombinatorialKalmanFilterExtensions.hpp"
0013 #include "Acts/TrackFitting/KalmanFitter.hpp"
0014 
0015 namespace Acts {
0016 
0017 /// @brief Create track states for selected measurements associated to a surface.
0018 ///
0019 /// - First get a source link range covering relevant measurements associated to
0020 ///   the given surface. This task is delegated to a SourceLinkAccessor.
0021 /// - Then create temporary track states for all measurements defined
0022 ///   by a source link range, calibrate the measurements and fill the
0023 ///   the calibrated data of these track states using a dedicated calibrator
0024 /// - The measurement selection is delegated to a dedicated measurement
0025 ///   selector.
0026 /// - Finally add branches to the given trajectory for the selected, temporary
0027 ///   track states. The track states of these branches still lack the filtered
0028 ///    data which is to be filled by the next stage e.g. the
0029 ///    CombinatorialKalmanFilter.
0030 /// All track states, the temporary track states and track states for selected
0031 /// measurements, are created in the given trajectory. The resulting container
0032 /// may become big. Thus, it is advisable to copy selected tracks and their
0033 /// track states to a separate container after each track finding step.
0034 ///
0035 template <typename source_link_iterator_t, typename track_container_t>
0036 struct TrackStateCreator {
0037   /// Type alias for result of track states creation operation
0038   using TrackStatesResult =
0039       Acts::Result<CkfTypes::BranchVector<TrackIndexType>>;
0040   /// Type alias for track state container backend from track container
0041   using TrackStateContainerBackend =
0042       typename track_container_t::TrackStateContainerBackend;
0043   /// Type alias for track proxy from track container
0044   using TrackProxy = typename track_container_t::TrackProxy;
0045   /// Type alias for track state proxy from track container
0046   using TrackStateProxy = typename track_container_t::TrackStateProxy;
0047   /// Type alias for the predicted state on a surface
0048   using BoundState = CkfTypes::BoundState;
0049   /// Type alias for the arguments from the CKF
0050   using Arguments =
0051       CkfTypes::TrackStateCreatorArguments<TrackStateContainerBackend>;
0052   /// Type alias for container of candidate track state proxies
0053   using candidate_container_t =
0054       typename std::vector<typename track_container_t::TrackStateProxy>;
0055 
0056   // delegate definition to get source link ranges for a surface
0057   /// Type alias for delegate to access source link ranges for a surface
0058   using SourceLinkAccessor =
0059       Delegate<std::pair<source_link_iterator_t, source_link_iterator_t>(
0060           const Surface&)>;
0061 
0062   // delegate to get calibrted measurements from a source link iterator
0063   /// Type alias for calibrator delegate to process measurements from source
0064   /// links
0065   using Calibrator =
0066       typename KalmanFitterExtensions<TrackStateContainerBackend>::Calibrator;
0067 
0068   // delegate to select measurements from a track state range
0069   /// Type alias for delegate to select measurements from track state candidates
0070   using MeasurementSelector =
0071       Delegate<Result<std::pair<typename candidate_container_t::iterator,
0072                                 typename candidate_container_t::iterator>>(
0073           candidate_container_t& trackStates, bool&, const Logger&)>;
0074 
0075   /// The source link accessor will return an source link range for a surface
0076   /// which link to the associated measurements.
0077   SourceLinkAccessor sourceLinkAccessor;
0078 
0079   /// The Calibrator is a dedicated calibration algorithm that allows to
0080   /// calibrate measurements using track information, this could be e.g. sagging
0081   /// for wires, module deformations, etc.
0082   Calibrator calibrator{DelegateFuncTag<
0083       detail::voidFitterCalibrator<TrackStateContainerBackend>>{}};
0084 
0085   /// Delegate for measurement selection on surfaces
0086   MeasurementSelector measurementSelector{
0087       DelegateFuncTag<voidMeasurementSelector>{}};
0088 
0089  public:
0090   /// @brief extend the trajectory onto the surface of the predicted state.
0091   ///
0092   /// @param args the predicted state, the trajectory to extend, and the
0093   ///        contexts
0094   /// @param logger a logger for messages
0095   ///
0096   /// @return a list of indices of newly created track states which extend the
0097   ///    trajectory onto the given surface and match the bound state, or an
0098   ///    error.
0099   ///
0100   /// Extend or branch the trajectory onto the given surface. This may create
0101   /// new track states using measurements which match the predicted bound state.
0102   /// This may create multiple branches. The new track states still miss the
0103   /// "filtered" data.
0104   Result<CkfTypes::BranchVector<TrackIndexType>> createTrackStates(
0105       const Arguments& args, const Logger& logger) const {
0106     const BoundState& boundState = args.boundState;
0107     const Surface& surface = boundState.parameters.referenceSurface();
0108     TrackStatesResult tsRes = TrackStatesResult::success({});
0109     using SourceLinkRange = decltype(sourceLinkAccessor(surface));
0110     SourceLinkRange slRange = sourceLinkAccessor(surface);
0111     if (slRange.first != slRange.second) {
0112       auto [slBegin, slEnd] = slRange;
0113       std::vector<TrackStateProxy> trackStateCandidates;
0114       tsRes = createSourceLinkTrackStates(
0115           args.geoContext, args.calibrationContext, surface, boundState,
0116           slBegin, slEnd, args.prevTip, trackStateCandidates,
0117           args.trajectory.get(), logger);
0118     }
0119     return tsRes;
0120   }
0121 
0122   /// Create track states for selected measurements given by the source links
0123   ///
0124   /// @param gctx The current geometry context
0125   /// @param calibrationContext pointer to the current calibration context
0126   /// @param surface the surface the sourceLinks are associated to
0127   /// @param boundState Bound state from the propagation on this surface
0128   /// @param slBegin Begin iterator for sourceLinks
0129   /// @param slEnd End iterator for sourceLinks
0130   /// @param prevTip Index pointing at previous trajectory state (i.e. tip)
0131   /// @param trackStateCandidates a temporary buffer which can be used to
0132   ///        to keep track of newly created temporary track states.
0133   /// @param trajectory the trajectory to which new track states for selected measurements will be added
0134   /// @param logger the logger for messages.
0135   /// @return Result containing vector of track state indices or error
0136   Result<CkfTypes::BranchVector<TrackIndexType>> createSourceLinkTrackStates(
0137       const GeometryContext& gctx, const CalibrationContext& calibrationContext,
0138       [[maybe_unused]] const Surface& surface, const BoundState& boundState,
0139       const source_link_iterator_t& slBegin,
0140       const source_link_iterator_t& slEnd, TrackIndexType prevTip,
0141       std::vector<TrackStateProxy>& trackStateCandidates,
0142       TrackStateContainerBackend& trajectory, const Logger& logger) const {
0143     using PM = TrackStatePropMask;
0144 
0145     using ResultTrackStateList =
0146         Acts::Result<CkfTypes::BranchVector<TrackIndexType>>;
0147     ResultTrackStateList resultTrackStateList{
0148         CkfTypes::BranchVector<TrackIndexType>()};
0149     const auto& [boundParams, jacobian, pathLength] = boundState;
0150 
0151     trackStateCandidates.clear();
0152     if constexpr (std::ranges::random_access_range<source_link_iterator_t>) {
0153       trackStateCandidates.reserve(std::distance(slBegin, slEnd));
0154     }
0155 
0156     // Calibrate all the source links on the surface since the selection has
0157     // to be done based on calibrated measurement
0158     for (auto it = slBegin; it != slEnd; ++it) {
0159       // get the source link
0160       const auto sourceLink = *it;
0161 
0162       // prepare the track state
0163       PM mask = PM::Predicted | PM::Jacobian | PM::Calibrated;
0164       if (it != slBegin) {
0165         // not the first TrackState, only need uncalibrated and calibrated
0166         mask = PM::Calibrated;
0167       }
0168 
0169       ACTS_VERBOSE("Create temp track state with mask: " << mask);
0170       // Temporary and final track states are created in the same
0171       // trajectory, which could lead to very large containers.
0172 
0173       // CAREFUL! This trackstate has a previous index that is not in this
0174       // MultiTrajectory Visiting backwards from this track state will
0175       // fail!
0176       auto ts = trajectory.makeTrackState(mask, prevTip);
0177 
0178       if (it == slBegin) {
0179         // only set these for first
0180         ts.predicted() = boundParams.parameters();
0181         if (boundParams.covariance()) {
0182           ts.predictedCovariance() = *boundParams.covariance();
0183         }
0184         ts.jacobian() = jacobian;
0185       } else {
0186         // subsequent track states can reuse
0187         auto& first = trackStateCandidates.front();
0188         ts.shareFrom(first, PM::Predicted);
0189         ts.shareFrom(first, PM::Jacobian);
0190       }
0191 
0192       ts.pathLength() = pathLength;
0193       ts.setReferenceSurface(boundParams.referenceSurface().getSharedPtr());
0194 
0195       // now calibrate the track state
0196       calibrator(gctx, calibrationContext, sourceLink, ts);
0197 
0198       trackStateCandidates.push_back(ts);
0199     }
0200 
0201     bool isOutlier = false;
0202     Result<std::pair<typename std::vector<TrackStateProxy>::iterator,
0203                      typename std::vector<TrackStateProxy>::iterator>>
0204         selectorResult =
0205             measurementSelector(trackStateCandidates, isOutlier, logger);
0206     if (!selectorResult.ok()) {
0207       ACTS_DEBUG("Selection of calibrated measurements failed: "
0208                  << selectorResult.error().message());
0209       resultTrackStateList =
0210           ResultTrackStateList::failure(selectorResult.error());
0211     } else {
0212       auto selectedTrackStateRange = *selectorResult;
0213       resultTrackStateList = processSelectedTrackStates(
0214           selectedTrackStateRange.first, selectedTrackStateRange.second,
0215           trajectory, isOutlier, logger);
0216     }
0217 
0218     return resultTrackStateList;
0219   }
0220 
0221   /// Create track states for the given trajectory from candidate track states
0222   ///
0223   /// @param begin begin iterator of the list of candidate track states
0224   /// @param end end iterator of the list of candidate track states
0225   /// @param trackStates the trajectory to which the new track states are added
0226   /// @param isOutlier true if the candidate(s) is(are) an outlier(s).
0227   /// @param logger the logger for messages
0228   /// @return Result containing vector of track state indices or error
0229   Result<CkfTypes::BranchVector<TrackIndexType>> processSelectedTrackStates(
0230       typename std::vector<TrackStateProxy>::const_iterator begin,
0231       typename std::vector<TrackStateProxy>::const_iterator end,
0232       TrackStateContainerBackend& trackStates, bool isOutlier,
0233       const Logger& logger) const {
0234     using PM = TrackStatePropMask;
0235 
0236     using ResultTrackStateList =
0237         Acts::Result<CkfTypes::BranchVector<TrackIndexType>>;
0238     ResultTrackStateList resultTrackStateList{
0239         CkfTypes::BranchVector<TrackIndexType>()};
0240     CkfTypes::BranchVector<TrackIndexType>& trackStateList =
0241         *resultTrackStateList;
0242     trackStateList.reserve(end - begin);
0243 
0244     std::optional<TrackStateProxy> firstTrackState{std::nullopt};
0245     for (auto it = begin; it != end; ++it) {
0246       auto& candidateTrackState = *it;
0247 
0248       // The filtered parameters are deliberately not allocated here. Outliers
0249       // never get separate filtered parameters, and for measurements the
0250       // caller allocates them right before the Kalman update writes them, so
0251       // that nobody can observe allocated but uninitialized filtered
0252       // parameters via `parameters()`.
0253       PM mask = PM::Predicted | PM::Jacobian | PM::Calibrated;
0254       if (it != begin) {
0255         // subsequent track states don't need storage for these as they will
0256         // be shared
0257         mask &= ~PM::Predicted & ~PM::Jacobian;
0258       }
0259 
0260       // copy this trackstate into fitted states MultiTrajectory
0261       auto trackState =
0262           trackStates.makeTrackState(mask, candidateTrackState.previous());
0263       ACTS_VERBOSE("Create SourceLink output track state #"
0264                    << trackState.index() << " with mask: " << mask);
0265 
0266       if (it != begin) {
0267         // assign indices pointing to first track state
0268         trackState.shareFrom(*firstTrackState, PM::Predicted);
0269         trackState.shareFrom(*firstTrackState, PM::Jacobian);
0270       } else {
0271         firstTrackState = trackState;
0272       }
0273 
0274       // either copy ALL or everything except for predicted and jacobian
0275       trackState.copyFrom(candidateTrackState, mask, false);
0276 
0277       auto typeFlags = trackState.typeFlags();
0278       typeFlags.setHasParameters();
0279       typeFlags.setHasMeasurement();
0280       if (trackState.referenceSurface().hasMaterial()) {
0281         typeFlags.setHasMaterial();
0282       }
0283       if (isOutlier) {
0284         // propagate information that this is an outlier state
0285         ACTS_VERBOSE(
0286             "Creating outlier track state with tip = " << trackState.index());
0287         typeFlags.setIsOutlier();
0288       }
0289 
0290       trackStateList.push_back(trackState.index());
0291     }
0292     return resultTrackStateList;
0293   }
0294 
0295   /// Default measurement selector which will return all measurements
0296   /// @param candidates Measurement track state candidates
0297   /// @return Iterator pair representing the range of all candidates
0298   static Result<std::pair<typename std::vector<TrackStateProxy>::iterator,
0299                           typename std::vector<TrackStateProxy>::iterator>>
0300   voidMeasurementSelector(typename std::vector<TrackStateProxy>& candidates,
0301                           bool& /*isOutlier*/, const Logger& /*logger*/) {
0302     return std::pair{candidates.begin(), candidates.end()};
0303   };
0304 };
0305 
0306 }  // namespace Acts