Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-11-21 09:22:59

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 #include "Acts/Vertexing/ImpactPointEstimator.hpp"
0010 
0011 #include "Acts/Definitions/Algebra.hpp"
0012 #include "Acts/Propagator/PropagatorOptions.hpp"
0013 #include "Acts/Propagator/detail/DirectionToSurface.hpp"
0014 #include "Acts/Surfaces/PerigeeSurface.hpp"
0015 #include "Acts/Surfaces/PointSurface.hpp"
0016 #include "Acts/Utilities/AngleHelpers.hpp"
0017 #include "Acts/Utilities/MathHelpers.hpp"
0018 #include "Acts/Vertexing/VertexingError.hpp"
0019 
0020 namespace Acts {
0021 
0022 namespace {
0023 
0024 template <typename vector_t>
0025 Result<double> getVertexCompatibilityImpl(const GeometryContext& gctx,
0026                                           const BoundTrackParameters* trkParams,
0027                                           const vector_t& vertexPos) {
0028   static constexpr int nDim = vector_t::RowsAtCompileTime;
0029   static_assert(nDim == 3 || nDim == 4,
0030                 "The number of dimensions nDim must be either 3 or 4.");
0031 
0032   static_assert(vector_t::RowsAtCompileTime == nDim,
0033                 "The dimension of the vertex position vector must match nDim.");
0034 
0035   if (trkParams == nullptr) {
0036     return VertexingError::EmptyInput;
0037   }
0038 
0039   // Retrieve weight matrix of the track's local x-, y-, and time-coordinate
0040   // (the latter only if nDim = 4). For this, the covariance needs to be set.
0041   if (!trkParams->covariance().has_value()) {
0042     return VertexingError::NoCovariance;
0043   }
0044   SquareMatrix<nDim - 1> subCovMat;
0045   if constexpr (nDim == 3) {
0046     subCovMat = trkParams->spatialImpactParameterCovariance().value();
0047   } else {
0048     subCovMat = trkParams->impactParameterCovariance().value();
0049   }
0050   SquareMatrix<nDim - 1> weight = subCovMat.inverse();
0051 
0052   // Orientation of the surface (i.e., axes of the measurement frame in which
0053   // the track's local coordinates are expressed). We use referenceFrame rather
0054   // than the transform rotation because the PointSurface (used by
0055   // estimate3DImpactParameters) has a direction-dependent measurement frame
0056   // that is not stored in its transform. For direction-independent surfaces
0057   // (e.g. PlaneSurface) referenceFrame returns the transform rotation, so this
0058   // is behavior-preserving there.
0059   RotationMatrix3 surfaceAxes = trkParams->referenceSurface().referenceFrame(
0060       gctx, trkParams->position(gctx), trkParams->direction());
0061   // Origin of the surface coordinate system
0062   Vector3 surfaceOrigin = trkParams->referenceSurface().center(gctx);
0063 
0064   // x- and y-axis of the surface coordinate system
0065   Vector3 xAxis = surfaceAxes.col(0);
0066   Vector3 yAxis = surfaceAxes.col(1);
0067 
0068   // Vector pointing from the surface origin to the vertex position
0069   // TODO: The vertex should always be at the surfaceOrigin since the
0070   // track parameters should be obtained by estimate3DImpactParameters.
0071   // Therefore, originToVertex should always be 0, which is currently not the
0072   // case.
0073   Vector3 originToVertex = vertexPos.template head<3>() - surfaceOrigin;
0074 
0075   // x-, y-, and possibly time-coordinate of the vertex and the track in the
0076   // surface coordinate system
0077   Vector<nDim - 1> localVertexCoords;
0078   localVertexCoords.template head<2>() =
0079       Vector2(originToVertex.dot(xAxis), originToVertex.dot(yAxis));
0080 
0081   Vector<nDim - 1> localTrackCoords;
0082   localTrackCoords.template head<2>() =
0083       Vector2(trkParams->parameters()[eX], trkParams->parameters()[eY]);
0084 
0085   // Fill time coordinates if we check the 4D vertex compatibility
0086   if constexpr (nDim == 4) {
0087     localVertexCoords(2) = vertexPos(3);
0088     localTrackCoords(2) = trkParams->parameters()[eBoundTime];
0089   }
0090 
0091   // residual
0092   Vector<nDim - 1> residual = localTrackCoords - localVertexCoords;
0093 
0094   // return chi2
0095   return residual.dot(weight * residual);
0096 }
0097 
0098 /// @brief Performs a Newton approximation to retrieve a point
0099 /// of closest approach in 3D to a reference position
0100 ///
0101 /// @param helixCenter Position of the helix center
0102 /// @param vtxPos Vertex position
0103 /// @param phi Azimuthal momentum angle
0104 /// @note Modifying phi corresponds to moving along the track. This function
0105 /// optimizes phi until we reach a 3D PCA.
0106 /// @param theta Polar momentum angle (constant along the track)
0107 /// @param rho Signed helix radius
0108 ///
0109 /// @return Phi value at 3D PCA
0110 Result<double> performNewtonOptimization(
0111     const Vector3& helixCenter, const Vector3& vtxPos, double phi, double theta,
0112     double rho, const ImpactPointEstimator::Config& cfg, const Logger& logger) {
0113   double sinPhi = std::sin(phi);
0114   double cosPhi = std::cos(phi);
0115 
0116   int nIter = 0;
0117   bool hasConverged = false;
0118 
0119   double cotTheta = 1. / std::tan(theta);
0120 
0121   double xO = helixCenter.x();
0122   double yO = helixCenter.y();
0123   double zO = helixCenter.z();
0124 
0125   double xVtx = vtxPos.x();
0126   double yVtx = vtxPos.y();
0127   double zVtx = vtxPos.z();
0128 
0129   // Iterate until convergence is reached or the maximum amount of iterations
0130   // is exceeded
0131   while (!hasConverged && nIter < cfg.maxIterations) {
0132     double derivative = rho * ((xVtx - xO) * cosPhi + (yVtx - yO) * sinPhi +
0133                                (zVtx - zO + rho * phi * cotTheta) * cotTheta);
0134     double secDerivative = rho * (-(xVtx - xO) * sinPhi + (yVtx - yO) * cosPhi +
0135                                   rho * cotTheta * cotTheta);
0136 
0137     if (secDerivative < 0.) {
0138       ACTS_ERROR(
0139           "Encountered negative second derivative during Newton "
0140           "optimization.");
0141       return VertexingError::NumericFailure;
0142     }
0143 
0144     double deltaPhi = -derivative / secDerivative;
0145 
0146     phi += deltaPhi;
0147     sinPhi = std::sin(phi);
0148     cosPhi = std::cos(phi);
0149 
0150     nIter += 1;
0151 
0152     if (std::abs(deltaPhi) < cfg.precision) {
0153       hasConverged = true;
0154     }
0155   }  // end while loop
0156 
0157   if (!hasConverged) {
0158     ACTS_ERROR("Newton optimization did not converge.");
0159     return VertexingError::NotConverged;
0160   }
0161   return phi;
0162 }
0163 
0164 // Note: always return Vector4, we'll chop off the last component if needed
0165 template <typename vector_t>
0166 Result<std::pair<Vector4, Vector3>> getDistanceAndMomentumImpl(
0167     const GeometryContext& gctx, const BoundTrackParameters& trkParams,
0168     const vector_t& vtxPos, const ImpactPointEstimator::Config& cfg,
0169     ImpactPointEstimator::State& state, const Logger& logger) {
0170   static constexpr int nDim = vector_t::RowsAtCompileTime;
0171   static_assert(nDim == 3 || nDim == 4,
0172                 "The number of dimensions nDim must be either 3 or 4.");
0173 
0174   // Reference point R
0175   Vector3 refPoint = trkParams.referenceSurface().center(gctx);
0176 
0177   // Extract charge-related particle parameters
0178   double absoluteCharge = trkParams.particleHypothesis().absoluteCharge();
0179   double qOvP = trkParams.parameters()[BoundIndices::eBoundQOverP];
0180 
0181   // Z-component of the B field at the reference position.
0182   // Note that we assume a constant B field here!
0183   auto fieldRes = cfg.bField->getField(refPoint, state.fieldCache);
0184   if (!fieldRes.ok()) {
0185     ACTS_ERROR("In getDistanceAndMomentum, the B field at\n"
0186                << refPoint << "\ncould not be retrieved.");
0187     return fieldRes.error();
0188   }
0189   double bZ = (*fieldRes)[eZ];
0190 
0191   // The particle moves on a straight trajectory if its charge is 0 or if there
0192   // is no B field. In that case, the 3D PCA can be calculated analytically, see
0193   // Sec 3.2 of the reference.
0194   if (absoluteCharge == 0. || bZ == 0.) {
0195     // Momentum direction (constant for straight tracks)
0196     Vector3 momDirStraightTrack = trkParams.direction();
0197 
0198     // Current position on the track
0199     Vector3 positionOnTrack = trkParams.position(gctx);
0200 
0201     // Distance between positionOnTrack and the 3D PCA
0202     double distanceToPca =
0203         (vtxPos.template head<3>() - positionOnTrack).dot(momDirStraightTrack);
0204 
0205     // 3D PCA
0206     Vector<nDim> pcaStraightTrack;
0207     pcaStraightTrack.template head<3>() =
0208         positionOnTrack + distanceToPca * momDirStraightTrack;
0209     if constexpr (nDim == 4) {
0210       // Track time at positionOnTrack
0211       double timeOnTrack = trkParams.parameters()[BoundIndices::eBoundTime];
0212 
0213       double m0 = trkParams.particleHypothesis().mass();
0214       double p = trkParams.particleHypothesis().extractMomentum(qOvP);
0215 
0216       // Speed in units of c
0217       double beta = p / fastHypot(p, m0);
0218 
0219       pcaStraightTrack[3] = timeOnTrack + distanceToPca / beta;
0220     }
0221 
0222     // Vector pointing from the vertex position to the 3D PCA
0223     Vector4 deltaRStraightTrack{Vector4::Zero()};
0224     deltaRStraightTrack.head<nDim>() = pcaStraightTrack - vtxPos;
0225 
0226     return std::pair(deltaRStraightTrack, momDirStraightTrack);
0227   }
0228 
0229   // Charged particles in a constant B field follow a helical trajectory. In
0230   // that case, we calculate the 3D PCA using the Newton method, see Sec 4.2 in
0231   // the reference.
0232 
0233   // Spatial Perigee parameters (i.e., spatial parameters of 2D PCA)
0234   double d0 = trkParams.parameters()[BoundIndices::eBoundLoc0];
0235   double z0 = trkParams.parameters()[BoundIndices::eBoundLoc1];
0236   // Momentum angles at 2D PCA
0237   double phiP = trkParams.parameters()[BoundIndices::eBoundPhi];
0238   double theta = trkParams.parameters()[BoundIndices::eBoundTheta];
0239   // Functions of the polar angle theta for later use
0240   double sinTheta = std::sin(theta);
0241   double cotTheta = 1. / std::tan(theta);
0242 
0243   // Set optimization variable phi to the angle at the 2D PCA as a first guess.
0244   // Note that phi corresponds to phiV in the reference.
0245   double phi = phiP;
0246 
0247   // Signed radius of the helix on which the particle moves
0248   double rho = sinTheta * (1. / qOvP) / bZ;
0249 
0250   // Position of the helix center.
0251   // We can set the z-position to a convenient value since it is not fixed by
0252   // the Perigee parameters. Note that phi = phiP because we did not start the
0253   // optimization yet.
0254   Vector3 helixCenter =
0255       refPoint + Vector3(-(d0 - rho) * std::sin(phi),
0256                          (d0 - rho) * std::cos(phi), z0 + rho * phi * cotTheta);
0257 
0258   // Use Newton optimization method to iteratively change phi until we arrive at
0259   // the 3D PCA
0260   auto res = performNewtonOptimization(helixCenter, vtxPos.template head<3>(),
0261                                        phi, theta, rho, cfg, logger);
0262   if (!res.ok()) {
0263     return res.error();
0264   }
0265   // Set new phi value
0266   phi = *res;
0267 
0268   double cosPhi = std::cos(phi);
0269   double sinPhi = std::sin(phi);
0270 
0271   // Momentum direction at the 3D PCA.
0272   // Note that we have thetaV = thetaP = theta since the polar angle does not
0273   // change in a constant B field.
0274   Vector3 momDir =
0275       Vector3(cosPhi * sinTheta, sinPhi * sinTheta, std::cos(theta));
0276 
0277   // 3D PCA (point P' in the reference). Note that the prefix "3D" does not
0278   // refer to the dimension of the pca variable. Rather, it indicates that we
0279   // minimized the 3D distance between the track and the reference point.
0280   Vector<nDim> pca;
0281   pca.template head<3>() =
0282       helixCenter + rho * Vector3(-sinPhi, cosPhi, -cotTheta * phi);
0283 
0284   if constexpr (nDim == 4) {
0285     // Time at the 2D PCA P
0286     double tP = trkParams.parameters()[BoundIndices::eBoundTime];
0287 
0288     double m0 = trkParams.particleHypothesis().mass();
0289     double p = trkParams.particleHypothesis().extractMomentum(qOvP);
0290 
0291     // Speed in units of c
0292     double beta = p / fastHypot(p, m0);
0293 
0294     pca[3] = tP - rho / (beta * sinTheta) * (phi - phiP);
0295   }
0296   // Vector pointing from the vertex position to the 3D PCA
0297   Vector4 deltaR{Vector4::Zero()};
0298   deltaR.head<nDim>() = pca - vtxPos;
0299 
0300   return std::pair(deltaR, momDir);
0301 }
0302 
0303 }  // namespace
0304 
0305 Result<double> ImpactPointEstimator::calculateDistance(
0306     const GeometryContext& gctx, const BoundTrackParameters& trkParams,
0307     const Vector3& vtxPos, State& state) const {
0308   auto res = getDistanceAndMomentumImpl(gctx, trkParams, vtxPos, m_cfg, state,
0309                                         *m_logger);
0310 
0311   if (!res.ok()) {
0312     return res.error();
0313   }
0314 
0315   // Return distance (we get a 4D vector in all cases, but we only need the
0316   // position norm)
0317   return res.value().first.template head<3>().norm();
0318 }
0319 
0320 Result<BoundTrackParameters> ImpactPointEstimator::estimate3DImpactParameters(
0321     const GeometryContext& gctx, const MagneticFieldContext& mctx,
0322     const BoundTrackParameters& trkParams, const Vector3& vtxPos,
0323     State& /*state*/) const {
0324   // A PointSurface at the vertex represents the point of closest approach to
0325   // the vertex: its measurement-plane normal always equals the local track
0326   // momentum direction, so propagating the track onto it converges exactly to
0327   // the 3D PCA (the point where the momentum is perpendicular to the
0328   // vertex-to-track residual).
0329   //
0330   // This replaces the previous two-step approach, which estimated the 3D PCA
0331   // analytically (Newton method for helical tracks) and then propagated to an
0332   // approximate plane surface oriented along that estimate. That plane was a
0333   // hand-built point surface with a fixed normal, and was only exact when the
0334   // vertex-to-PCA vector happened to be orthogonal to the momentum. Propagating
0335   // directly to a PointSurface removes that approximation.
0336   std::shared_ptr<PointSurface> pointSurface =
0337       Surface::makeShared<PointSurface>(vtxPos);
0338 
0339   // Create propagator options
0340   PropagatorPlainOptions pOptions(gctx, mctx);
0341   pOptions.direction = detail::directionToSurface(
0342       gctx, *pointSurface, trkParams.position(gctx), trkParams.direction());
0343 
0344   // Propagate to the point surface; the resulting parameters are at the 3D PCA
0345   auto result =
0346       m_cfg.propagator->propagateToSurface(trkParams, *pointSurface, pOptions);
0347   if (result.ok()) {
0348     return *result;
0349   } else {
0350     ACTS_ERROR("Error during propagation in estimate3DImpactParameters.");
0351     ACTS_DEBUG(
0352         "The point surface to which we tried to propagate has its origin at\n"
0353         << vtxPos);
0354     return result.error();
0355   }
0356 }
0357 
0358 Result<double> ImpactPointEstimator::getVertexCompatibility(
0359     const GeometryContext& gctx, const BoundTrackParameters* trkParams,
0360     Eigen::Map<const DynamicVector> vertexPos) const {
0361   if (vertexPos.size() == 3) {
0362     return getVertexCompatibilityImpl(gctx, trkParams,
0363                                       vertexPos.template head<3>());
0364   } else if (vertexPos.size() == 4) {
0365     return getVertexCompatibilityImpl(gctx, trkParams,
0366                                       vertexPos.template head<4>());
0367   } else {
0368     return VertexingError::InvalidInput;
0369   }
0370 }
0371 
0372 Result<std::pair<Acts::Vector4, Acts::Vector3>>
0373 ImpactPointEstimator::getDistanceAndMomentum(
0374     const GeometryContext& gctx, const BoundTrackParameters& trkParams,
0375     Eigen::Map<const DynamicVector> vtxPos, State& state) const {
0376   if (vtxPos.size() == 3) {
0377     return getDistanceAndMomentumImpl(
0378         gctx, trkParams, vtxPos.template head<3>(), m_cfg, state, *m_logger);
0379   } else if (vtxPos.size() == 4) {
0380     return getDistanceAndMomentumImpl(
0381         gctx, trkParams, vtxPos.template head<4>(), m_cfg, state, *m_logger);
0382   } else {
0383     return VertexingError::InvalidInput;
0384   }
0385 }
0386 
0387 Result<ImpactParametersAndSigma> ImpactPointEstimator::getImpactParameters(
0388     const BoundTrackParameters& track, const Vertex& vtx,
0389     const GeometryContext& gctx, const MagneticFieldContext& mctx,
0390     bool calculateTimeIP) const {
0391   const std::shared_ptr<PerigeeSurface> perigeeSurface =
0392       Surface::makeShared<PerigeeSurface>(vtx.position());
0393 
0394   // Create propagator options
0395   PropagatorPlainOptions pOptions(gctx, mctx);
0396   pOptions.direction = detail::directionToSurface(
0397       gctx, *perigeeSurface, track.position(gctx), track.direction());
0398 
0399   // Do the propagation to linPoint
0400   auto result =
0401       m_cfg.propagator->propagateToSurface(track, *perigeeSurface, pOptions);
0402 
0403   if (!result.ok()) {
0404     ACTS_ERROR("Error during propagation in getImpactParameters.");
0405     ACTS_DEBUG(
0406         "The Perigee surface to which we tried to propagate has its origin "
0407         "at\n"
0408         << vtx.position());
0409     return result.error();
0410   }
0411 
0412   const auto& params = *result;
0413 
0414   // Check if the covariance matrix of the Perigee parameters exists
0415   if (!params.covariance().has_value()) {
0416     return VertexingError::NoCovariance;
0417   }
0418 
0419   // Extract Perigee parameters and corresponding covariance matrix
0420   auto impactParams = params.impactParameters();
0421   auto impactParamCovariance = params.impactParameterCovariance().value();
0422 
0423   // Vertex variances
0424   // TODO: By looking at sigmaD0 and sigmaZ0 we neglect the offdiagonal terms
0425   // (i.e., we approximate the vertex as a sphere rather than an ellipsoid).
0426   // Using the full covariance matrix might furnish better results.
0427   double vtxVarX = vtx.covariance()(eX, eX);
0428   double vtxVarY = vtx.covariance()(eY, eY);
0429   double vtxVarZ = vtx.covariance()(eZ, eZ);
0430 
0431   ImpactParametersAndSigma ipAndSigma;
0432 
0433   ipAndSigma.d0 = impactParams[0];
0434   // Variance of the vertex extent in the x-y-plane
0435   double vtxVar2DExtent = std::max(vtxVarX, vtxVarY);
0436   // TODO: vtxVar2DExtent, vtxVarZ, and vtxVarT should always be >= 0. We need
0437   // to throw an error here once
0438   // https://github.com/acts-project/acts/issues/2231 is resolved.
0439   if (vtxVar2DExtent > 0) {
0440     ipAndSigma.sigmaD0 =
0441         std::sqrt(vtxVar2DExtent + impactParamCovariance(0, 0));
0442   } else {
0443     ipAndSigma.sigmaD0 = std::sqrt(impactParamCovariance(0, 0));
0444   }
0445 
0446   ipAndSigma.z0 = impactParams[1];
0447   if (vtxVarZ > 0) {
0448     ipAndSigma.sigmaZ0 = std::sqrt(vtxVarZ + impactParamCovariance(1, 1));
0449   } else {
0450     ipAndSigma.sigmaZ0 = std::sqrt(impactParamCovariance(1, 1));
0451   }
0452 
0453   if (calculateTimeIP) {
0454     ipAndSigma.deltaT = std::abs(vtx.time() - impactParams[2]);
0455     double vtxVarT = vtx.fullCovariance()(eTime, eTime);
0456     if (vtxVarT > 0) {
0457       ipAndSigma.sigmaDeltaT = std::sqrt(vtxVarT + impactParamCovariance(2, 2));
0458     } else {
0459       ipAndSigma.sigmaDeltaT = std::sqrt(impactParamCovariance(2, 2));
0460     }
0461   }
0462 
0463   return ipAndSigma;
0464 }
0465 
0466 Result<std::pair<double, double>> ImpactPointEstimator::getLifetimeSignOfTrack(
0467     const BoundTrackParameters& track, const Vertex& vtx,
0468     const Vector3& direction, const GeometryContext& gctx,
0469     const MagneticFieldContext& mctx) const {
0470   const std::shared_ptr<PerigeeSurface> perigeeSurface =
0471       Surface::makeShared<PerigeeSurface>(vtx.position());
0472 
0473   // Create propagator options
0474   PropagatorPlainOptions pOptions(gctx, mctx);
0475   pOptions.direction = detail::directionToSurface(
0476       gctx, *perigeeSurface, track.position(gctx), track.direction());
0477 
0478   // Do the propagation to the perigeee
0479   auto result =
0480       m_cfg.propagator->propagateToSurface(track, *perigeeSurface, pOptions);
0481 
0482   if (!result.ok()) {
0483     return result.error();
0484   }
0485 
0486   const auto& params = (*result).parameters();
0487   const double d0 = params[BoundIndices::eBoundLoc0];
0488   const double z0 = params[BoundIndices::eBoundLoc1];
0489   const double phi = params[BoundIndices::eBoundPhi];
0490   const double theta = params[BoundIndices::eBoundTheta];
0491 
0492   double vs = std::sin(std::atan2(direction[1], direction[0]) - phi) * d0;
0493   double eta = AngleHelpers::etaFromTheta(theta);
0494   double dir_eta = VectorHelpers::eta(direction);
0495 
0496   double zs = (dir_eta - eta) * z0;
0497 
0498   std::pair<double, double> vszs;
0499 
0500   vszs.first = vs >= 0. ? 1. : -1.;
0501   vszs.second = zs >= 0. ? 1. : -1.;
0502 
0503   return vszs;
0504 }
0505 
0506 Result<double> ImpactPointEstimator::get3DLifetimeSignOfTrack(
0507     const BoundTrackParameters& track, const Vertex& vtx,
0508     const Vector3& direction, const GeometryContext& gctx,
0509     const MagneticFieldContext& mctx) const {
0510   const std::shared_ptr<PerigeeSurface> perigeeSurface =
0511       Surface::makeShared<PerigeeSurface>(vtx.position());
0512 
0513   // Create propagator options
0514   PropagatorPlainOptions pOptions(gctx, mctx);
0515   pOptions.direction = detail::directionToSurface(
0516       gctx, *perigeeSurface, track.position(gctx), track.direction());
0517 
0518   // Do the propagation to the perigeee
0519   auto result =
0520       m_cfg.propagator->propagateToSurface(track, *perigeeSurface, pOptions);
0521 
0522   if (!result.ok()) {
0523     return result.error();
0524   }
0525 
0526   const auto& params = *result;
0527   const Vector3 trkpos = params.position(gctx);
0528   const Vector3 trkmom = params.momentum();
0529 
0530   double sign =
0531       (direction.cross(trkmom)).dot(trkmom.cross(vtx.position() - trkpos));
0532 
0533   return sign >= 0. ? 1. : -1.;
0534 }
0535 
0536 }  // namespace Acts