Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2025-12-30 09:22:25

0001 // SPDX-License-Identifier: LGPL-3.0-or-later
0002 // Copyright (C) 2023  - 2025 Joe Osborn, Dmitry Romanov, Wouter Deconinck
0003 
0004 #include "TrackSeeding.h"
0005 
0006 #include <Acts/Definitions/Algebra.hpp>
0007 #include <Acts/Definitions/Units.hpp>
0008 #if Acts_VERSION_MAJOR >= 37
0009 #include <Acts/EventData/SpacePointProxy.hpp>
0010 #endif
0011 #include <Acts/Seeding/SeedFinderUtils.hpp>
0012 #if Acts_VERSION_MAJOR >= 37
0013 #include <Acts/EventData/Seed.hpp>
0014 #else
0015 #include <Acts/Seeding/Seed.hpp>
0016 #endif
0017 #include <Acts/Seeding/SeedConfirmationRangeConfig.hpp>
0018 #include <Acts/Seeding/SeedFilter.hpp>
0019 #include <Acts/Seeding/SeedFilterConfig.hpp>
0020 #include <Acts/Seeding/SeedFinderConfig.hpp>
0021 #include <Acts/Seeding/SeedFinderOrthogonal.hpp>
0022 #include <Acts/Seeding/SeedFinderOrthogonalConfig.hpp>
0023 #include <Acts/Surfaces/PerigeeSurface.hpp>
0024 #include <Acts/Surfaces/Surface.hpp>
0025 #include <Acts/Utilities/KDTree.hpp> // IWYU pragma: keep FIXME KDTree missing in SeedFinderOrthogonal.hpp until Acts v23.0.0
0026 #include <Acts/Utilities/Result.hpp>
0027 #include <edm4eic/Cov6f.h>
0028 #include <edm4hep/Vector2f.h>
0029 #include <Eigen/Core>
0030 #include <Eigen/Geometry>
0031 #include <array>
0032 #include <cmath>
0033 #include <gsl/pointers>
0034 #include <limits>
0035 #include <tuple>
0036 
0037 namespace eicrecon {
0038 
0039 void TrackSeeding::init() {
0040 
0041   // Filter parameters
0042   m_seedFilterConfig.maxSeedsPerSpM        = m_cfg.maxSeedsPerSpM_filter;
0043   m_seedFilterConfig.deltaRMin             = m_cfg.deltaRMin;
0044   m_seedFilterConfig.seedConfirmation      = m_cfg.seedConfirmation;
0045   m_seedFilterConfig.deltaInvHelixDiameter = m_cfg.deltaInvHelixDiameter;
0046   m_seedFilterConfig.impactWeightFactor    = m_cfg.impactWeightFactor;
0047   m_seedFilterConfig.zOriginWeightFactor   = m_cfg.zOriginWeightFactor;
0048   m_seedFilterConfig.compatSeedWeight      = m_cfg.compatSeedWeight;
0049   m_seedFilterConfig.compatSeedLimit       = m_cfg.compatSeedLimit;
0050   m_seedFilterConfig.seedWeightIncrement   = m_cfg.seedWeightIncrement;
0051 
0052   m_seedFilterConfig.centralSeedConfirmationRange = Acts::SeedConfirmationRangeConfig{
0053       .zMinSeedConf            = m_cfg.zMinSeedConfCentral,
0054       .zMaxSeedConf            = m_cfg.zMaxSeedConfCentral,
0055       .rMaxSeedConf            = m_cfg.rMaxSeedConfCentral,
0056       .nTopForLargeR           = m_cfg.nTopForLargeRCentral,
0057       .nTopForSmallR           = m_cfg.nTopForSmallRCentral,
0058       .seedConfMinBottomRadius = m_cfg.seedConfMinBottomRadiusCentral,
0059       .seedConfMaxZOrigin      = m_cfg.seedConfMaxZOriginCentral,
0060       .minImpactSeedConf       = m_cfg.minImpactSeedConfCentral};
0061 
0062   m_seedFilterConfig.forwardSeedConfirmationRange = Acts::SeedConfirmationRangeConfig{
0063       .zMinSeedConf            = m_cfg.zMinSeedConfForward,
0064       .zMaxSeedConf            = m_cfg.zMaxSeedConfForward,
0065       .rMaxSeedConf            = m_cfg.rMaxSeedConfForward,
0066       .nTopForLargeR           = m_cfg.nTopForLargeRForward,
0067       .nTopForSmallR           = m_cfg.nTopForSmallRForward,
0068       .seedConfMinBottomRadius = m_cfg.seedConfMinBottomRadiusForward,
0069       .seedConfMaxZOrigin      = m_cfg.seedConfMaxZOriginForward,
0070       .minImpactSeedConf       = m_cfg.minImpactSeedConfForward};
0071 
0072 #if Acts_VERSION_MAJOR < 42
0073   m_seedFilterConfig = m_seedFilterConfig.toInternalUnits();
0074 #endif
0075 
0076   // Finder parameters
0077 #if Acts_VERSION_MAJOR >= 37
0078   m_seedFinderConfig.seedFilter =
0079       std::make_unique<Acts::SeedFilter<proxy_type>>(m_seedFilterConfig);
0080 #else
0081   m_seedFinderConfig.seedFilter = std::make_unique<Acts::SeedFilter<eicrecon::SpacePoint>>(
0082       Acts::SeedFilter<eicrecon::SpacePoint>(m_seedFilterConfig));
0083 #endif
0084   m_seedFinderConfig.rMax               = m_cfg.rMax;
0085   m_seedFinderConfig.rMin               = m_cfg.rMin;
0086   m_seedFinderConfig.deltaRMinTopSP     = m_cfg.deltaRMinTopSP;
0087   m_seedFinderConfig.deltaRMaxTopSP     = m_cfg.deltaRMaxTopSP;
0088   m_seedFinderConfig.deltaRMinBottomSP  = m_cfg.deltaRMinBottomSP;
0089   m_seedFinderConfig.deltaRMaxBottomSP  = m_cfg.deltaRMaxBottomSP;
0090   m_seedFinderConfig.collisionRegionMin = m_cfg.collisionRegionMin;
0091   m_seedFinderConfig.collisionRegionMax = m_cfg.collisionRegionMax;
0092   m_seedFinderConfig.zMin               = m_cfg.zMin;
0093   m_seedFinderConfig.zMax               = m_cfg.zMax;
0094   m_seedFinderConfig.maxSeedsPerSpM     = m_cfg.maxSeedsPerSpM;
0095   m_seedFinderConfig.cotThetaMax        = m_cfg.cotThetaMax;
0096   m_seedFinderConfig.sigmaScattering    = m_cfg.sigmaScattering;
0097   m_seedFinderConfig.radLengthPerSeed   = m_cfg.radLengthPerSeed;
0098   m_seedFinderConfig.minPt              = m_cfg.minPt;
0099   m_seedFinderConfig.impactMax          = m_cfg.impactMax;
0100   m_seedFinderConfig.rMinMiddle         = m_cfg.rMinMiddle;
0101   m_seedFinderConfig.rMaxMiddle         = m_cfg.rMaxMiddle;
0102   m_seedFinderConfig.deltaPhiMax        = m_cfg.deltaPhiMax;
0103 
0104   m_seedFinderOptions.beamPos   = Acts::Vector2(m_cfg.beamPosX, m_cfg.beamPosY);
0105   m_seedFinderOptions.bFieldInZ = m_cfg.bFieldInZ;
0106 
0107   m_seedFinderConfig = m_seedFinderConfig
0108 #if Acts_VERSION_MAJOR < 42
0109                            .toInternalUnits()
0110 #endif
0111                            .calculateDerivedQuantities();
0112   m_seedFinderOptions = m_seedFinderOptions
0113 #if Acts_VERSION_MAJOR < 42
0114                             .toInternalUnits()
0115 #endif
0116                             .calculateDerivedQuantities(m_seedFinderConfig);
0117 }
0118 
0119 void TrackSeeding::process(const Input& input, const Output& output) const {
0120 
0121   const auto [trk_hits] = input;
0122   auto [trackparams]    = output;
0123 
0124   std::vector<const eicrecon::SpacePoint*> spacePoints = getSpacePoints(*trk_hits);
0125 
0126 #if Acts_VERSION_MAJOR >= 37
0127   Acts::SeedFinderOrthogonal<proxy_type> finder(m_seedFinderConfig); // FIXME move into class scope
0128 #else
0129   Acts::SeedFinderOrthogonal<eicrecon::SpacePoint> finder(
0130       m_seedFinderConfig); // FIXME move into class scope
0131 #endif
0132 
0133 #if Acts_VERSION_MAJOR >= 37
0134   // Config
0135   Acts::SpacePointContainerConfig spConfig;
0136 
0137   // Options
0138   Acts::SpacePointContainerOptions spOptions;
0139   spOptions.beamPos = {0., 0.};
0140 
0141   ActsExamples::SpacePointContainer container(spacePoints);
0142   Acts::SpacePointContainer<decltype(container), Acts::detail::RefHolder> spContainer(
0143       spConfig, spOptions, container);
0144 
0145   std::vector<Acts::Seed<proxy_type>> seeds = finder.createSeeds(m_seedFinderOptions, spContainer);
0146 
0147   // need to convert here from seed of proxies to seed of sps
0148   eicrecon::SeedContainer seedsToAdd;
0149   seedsToAdd.reserve(seeds.size());
0150   for (const auto& seed : seeds) {
0151     const auto& sps = seed.sp();
0152     seedsToAdd.emplace_back(*sps[0]->externalSpacePoint(), *sps[1]->externalSpacePoint(),
0153                             *sps[2]->externalSpacePoint());
0154     seedsToAdd.back().setVertexZ(seed.z());
0155     seedsToAdd.back().setQuality(seed.seedQuality());
0156   }
0157 
0158   addToTrackParams(*trackparams, seedsToAdd);
0159 
0160 #else
0161 
0162   std::function<std::tuple<Acts::Vector3, Acts::Vector2, std::optional<Acts::ActsScalar>>(
0163       const eicrecon::SpacePoint* sp)>
0164       create_coordinates = [](const eicrecon::SpacePoint* sp) {
0165         Acts::Vector3 position(sp->x(), sp->y(), sp->z());
0166         Acts::Vector2 variance(sp->varianceR(), sp->varianceZ());
0167         return std::make_tuple(position, variance, sp->t());
0168       };
0169 
0170   eicrecon::SeedContainer seeds =
0171       finder.createSeeds(m_seedFinderOptions, spacePoints, create_coordinates);
0172 
0173   addToTrackParams(*trackparams, seeds);
0174 
0175 #endif
0176 
0177   for (auto& sp : spacePoints) {
0178     delete sp;
0179   }
0180 }
0181 
0182 std::vector<const eicrecon::SpacePoint*>
0183 TrackSeeding::getSpacePoints(const edm4eic::TrackerHitCollection& trk_hits) {
0184   std::vector<const eicrecon::SpacePoint*> spacepoints;
0185 
0186   for (const auto hit : trk_hits) {
0187     const eicrecon::SpacePoint* sp = new SpacePoint(hit);
0188     spacepoints.push_back(sp);
0189   }
0190 
0191   return spacepoints;
0192 }
0193 
0194 void TrackSeeding::addToTrackParams(edm4eic::TrackParametersCollection& trackparams,
0195                                     SeedContainer& seeds) const {
0196 
0197   for (auto& seed : seeds) {
0198     std::vector<std::pair<float, float>> xyHitPositions;
0199     std::vector<std::pair<float, float>> rzHitPositions;
0200     for (const auto& spptr : seed.sp()) {
0201       xyHitPositions.emplace_back(spptr->x(), spptr->y());
0202       rzHitPositions.emplace_back(spptr->r(), spptr->z());
0203     }
0204 
0205     auto RX0Y0 = circleFit(xyHitPositions);
0206     float R    = std::get<0>(RX0Y0);
0207     float X0   = std::get<1>(RX0Y0);
0208     float Y0   = std::get<2>(RX0Y0);
0209     if (!(std::isfinite(R) && std::isfinite(std::abs(X0)) && std::isfinite(std::abs(Y0)))) {
0210       // avoid float overflow for hits on a line
0211       continue;
0212     }
0213     if (std::hypot(X0, Y0) < std::numeric_limits<decltype(std::hypot(X0, Y0))>::epsilon() ||
0214         !std::isfinite(std::hypot(X0, Y0))) {
0215       //Avoid center of circle at origin, where there is no point-of-closest approach
0216       //Also, avoid float overfloat on circle center
0217       continue;
0218     }
0219 
0220     auto slopeZ0     = lineFit(rzHitPositions);
0221     const auto xypos = findPCA(RX0Y0);
0222 
0223     //Determine charge
0224     int charge = determineCharge(xyHitPositions, xypos, RX0Y0);
0225 
0226     float theta = atan(1. / std::get<0>(slopeZ0));
0227     // normalize to 0<theta<pi
0228     if (theta < 0) {
0229       theta += M_PI;
0230     }
0231     float eta    = -log(tan(theta / 2.));
0232     float pt     = R * m_cfg.bFieldInZ; // pt[GeV] = R[mm] * B[GeV/mm]
0233     float p      = pt * cosh(eta);
0234     float qOverP = charge / p;
0235 
0236     //Calculate phi at xypos
0237     auto xpos = xypos.first;
0238     auto ypos = xypos.second;
0239 
0240     auto vxpos = -1. * charge * (ypos - Y0);
0241     auto vypos = charge * (xpos - X0);
0242 
0243     auto phi = atan2(vypos, vxpos);
0244 
0245     const float z0 = seed.z();
0246     auto perigee   = Acts::Surface::makeShared<Acts::PerigeeSurface>(Acts::Vector3(0, 0, 0));
0247     Acts::Vector3 global(xypos.first, xypos.second, z0);
0248 
0249     //Compute local position at PCA
0250     Acts::Vector2 localpos;
0251     Acts::Vector3 direction(sin(theta) * cos(phi), sin(theta) * sin(phi), cos(theta));
0252 
0253     auto local = perigee->globalToLocal(m_geoSvc->getActsGeometryContext(), global, direction);
0254 
0255     if (!local.ok()) {
0256       continue;
0257     }
0258 
0259     localpos = local.value();
0260 
0261     auto trackparam = trackparams.create();
0262     trackparam.setType(-1); // type --> seed(-1)
0263     trackparam.setLoc({static_cast<float>(localpos(0)),
0264                        static_cast<float>(localpos(1))}); // 2d location on surface
0265     trackparam.setPhi(static_cast<float>(phi));           // phi [rad]
0266     trackparam.setTheta(theta);                           //theta [rad]
0267     trackparam.setQOverP(qOverP);                         // Q/p [e/GeV]
0268     trackparam.setTime(10);                               // time in ns
0269     edm4eic::Cov6f cov;
0270     cov(0, 0) = m_cfg.locaError / Acts::UnitConstants::mm;    // loc0
0271     cov(1, 1) = m_cfg.locbError / Acts::UnitConstants::mm;    // loc1
0272     cov(2, 2) = m_cfg.phiError / Acts::UnitConstants::rad;    // phi
0273     cov(3, 3) = m_cfg.thetaError / Acts::UnitConstants::rad;  // theta
0274     cov(4, 4) = m_cfg.qOverPError * Acts::UnitConstants::GeV; // qOverP
0275     cov(5, 5) = m_cfg.timeError / Acts::UnitConstants::ns;    // time
0276     trackparam.setCovariance(cov);
0277   }
0278 }
0279 
0280 std::pair<float, float> TrackSeeding::findPCA(std::tuple<float, float, float>& circleParams) {
0281   const float R  = std::get<0>(circleParams);
0282   const float X0 = std::get<1>(circleParams);
0283   const float Y0 = std::get<2>(circleParams);
0284 
0285   const double R0 = std::hypot(X0, Y0);
0286 
0287   //Calculate point on circle closest to origin
0288   const double xmin = X0 * (1. - R / R0);
0289   const double ymin = Y0 * (1. - R / R0);
0290 
0291   return std::make_pair(xmin, ymin);
0292 }
0293 
0294 int TrackSeeding::determineCharge(std::vector<std::pair<float, float>>& positions,
0295                                   const std::pair<float, float>& PCA,
0296                                   std::tuple<float, float, float>& RX0Y0) {
0297 
0298   const auto& firstpos = positions.at(0);
0299   auto hit_x           = firstpos.first;
0300   auto hit_y           = firstpos.second;
0301 
0302   auto xpos = PCA.first;
0303   auto ypos = PCA.second;
0304 
0305   float X0 = std::get<1>(RX0Y0);
0306   float Y0 = std::get<2>(RX0Y0);
0307 
0308   Acts::Vector3 B_z(0, 0, 1);
0309   Acts::Vector3 radial(X0 - xpos, Y0 - ypos, 0);
0310   Acts::Vector3 hit(hit_x - xpos, hit_y - ypos, 0);
0311 
0312   auto cross = radial.cross(hit);
0313 
0314   float dot = cross.dot(B_z);
0315 
0316   return copysign(1., -dot);
0317 }
0318 
0319 /**
0320    * Circle fit to a given set of data points (in 2D)
0321    * This is an algebraic fit, due to Taubin, based on the journal article
0322    * G. Taubin, "Estimation Of Planar Curves, Surfaces And Nonplanar
0323    * Space Curves Defined By Implicit Equations, With
0324    * Applications To Edge And Range Image Segmentation",
0325    * IEEE Trans. PAMI, Vol. 13, pages 1115-1138, (1991)
0326    * It works well whether data points are sampled along an entire circle or along a small arc.
0327    * It still has a small bias and its statistical accuracy is slightly lower than that of the geometric fit (minimizing geometric distances),
0328    * It provides a very good initial guess for a subsequent geometric fit.
0329    * Nikolai Chernov  (September 2012)
0330    */
0331 std::tuple<float, float, float>
0332 TrackSeeding::circleFit(std::vector<std::pair<float, float>>& positions) {
0333   // Compute x- and y- sample means
0334   double meanX  = 0;
0335   double meanY  = 0;
0336   double weight = 0;
0337 
0338   for (const auto& [x, y] : positions) {
0339     meanX += x;
0340     meanY += y;
0341     ++weight;
0342   }
0343   meanX /= weight;
0344   meanY /= weight;
0345 
0346   //     computing moments
0347 
0348   double Mxx = 0;
0349   double Myy = 0;
0350   double Mxy = 0;
0351   double Mxz = 0;
0352   double Myz = 0;
0353   double Mzz = 0;
0354 
0355   for (auto& [x, y] : positions) {
0356     double Xi = x - meanX; //  centered x-coordinates
0357     double Yi = y - meanY; //  centered y-coordinates
0358     double Zi = std::pow(Xi, 2) + std::pow(Yi, 2);
0359 
0360     Mxy += Xi * Yi;
0361     Mxx += Xi * Xi;
0362     Myy += Yi * Yi;
0363     Mxz += Xi * Zi;
0364     Myz += Yi * Zi;
0365     Mzz += Zi * Zi;
0366   }
0367   Mxx /= weight;
0368   Myy /= weight;
0369   Mxy /= weight;
0370   Mxz /= weight;
0371   Myz /= weight;
0372   Mzz /= weight;
0373 
0374   //  computing coefficients of the characteristic polynomial
0375 
0376   const double Mz     = Mxx + Myy;
0377   const double Cov_xy = Mxx * Myy - Mxy * Mxy;
0378   const double Var_z  = Mzz - Mz * Mz;
0379   const double A3     = 4 * Mz;
0380   const double A2     = -3 * Mz * Mz - Mzz;
0381   const double A1     = Var_z * Mz + 4 * Cov_xy * Mz - Mxz * Mxz - Myz * Myz;
0382   const double A0  = Mxz * (Mxz * Myy - Myz * Mxy) + Myz * (Myz * Mxx - Mxz * Mxy) - Var_z * Cov_xy;
0383   const double A22 = A2 + A2;
0384   const double A33 = A3 + A3 + A3;
0385 
0386   //    finding the root of the characteristic polynomial
0387   //    using Newton's method starting at x=0
0388   //    (it is guaranteed to converge to the right root)
0389   static constexpr int iter_max = 99;
0390   double x                      = 0;
0391   double y                      = A0;
0392 
0393   // usually, 4-6 iterations are enough
0394   for (int iter = 0; iter < iter_max; ++iter) {
0395     const double Dy   = A1 + x * (A22 + A33 * x);
0396     const double xnew = x - y / Dy;
0397     if ((xnew == x) || (!std::isfinite(xnew))) {
0398       break;
0399     }
0400 
0401     const double ynew = A0 + xnew * (A1 + xnew * (A2 + xnew * A3));
0402     if (std::abs(ynew) >= std::abs(y)) {
0403       break;
0404     }
0405 
0406     x = xnew;
0407     y = ynew;
0408   }
0409 
0410   //  computing parameters of the fitting circle
0411   const double DET     = std::pow(x, 2) - x * Mz + Cov_xy;
0412   const double Xcenter = (Mxz * (Myy - x) - Myz * Mxy) / DET / 2;
0413   const double Ycenter = (Myz * (Mxx - x) - Mxz * Mxy) / DET / 2;
0414 
0415   //  assembling the output
0416   float X0 = Xcenter + meanX;
0417   float Y0 = Ycenter + meanY;
0418   float R  = std::sqrt(std::pow(Xcenter, 2) + std::pow(Ycenter, 2) + Mz);
0419   return std::make_tuple(R, X0, Y0);
0420 }
0421 
0422 std::tuple<float, float> TrackSeeding::lineFit(std::vector<std::pair<float, float>>& positions) {
0423   double xsum  = 0;
0424   double x2sum = 0;
0425   double ysum  = 0;
0426   double xysum = 0;
0427   for (const auto& [r, z] : positions) {
0428     xsum  = xsum + r;               //calculate sigma(xi)
0429     ysum  = ysum + z;               //calculate sigma(yi)
0430     x2sum = x2sum + std::pow(r, 2); //calculate sigma(x^2i)
0431     xysum = xysum + r * z;          //calculate sigma(xi*yi)
0432   }
0433 
0434   const auto npts          = positions.size();
0435   const double denominator = (x2sum * npts - std::pow(xsum, 2));
0436   const float a            = (xysum * npts - xsum * ysum) / denominator;  //calculate slope
0437   const float b            = (x2sum * ysum - xsum * xysum) / denominator; //calculate intercept
0438   return std::make_tuple(a, b);
0439 }
0440 
0441 } // namespace eicrecon