Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-11-26 09:22: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 #include "Acts/Surfaces/CylinderSurface.hpp"
0010 
0011 #include "Acts/Definitions/Algebra.hpp"
0012 #include "Acts/Definitions/Tolerance.hpp"
0013 #include "Acts/Definitions/Units.hpp"
0014 #include "Acts/Geometry/GeometryObject.hpp"
0015 #include "Acts/Surfaces/CylinderBounds.hpp"
0016 #include "Acts/Surfaces/SurfaceError.hpp"
0017 #include "Acts/Surfaces/SurfaceMergingException.hpp"
0018 #include "Acts/Surfaces/detail/AlignmentHelper.hpp"
0019 #include "Acts/Surfaces/detail/CylinderHelper.hpp"
0020 #include "Acts/Surfaces/detail/FacesHelper.hpp"
0021 #include "Acts/Surfaces/detail/MergeHelper.hpp"
0022 #include "Acts/Utilities/AlgebraHelpers.hpp"
0023 #include "Acts/Utilities/Diagnostics.hpp"
0024 #include "Acts/Utilities/Intersection.hpp"
0025 #include "Acts/Utilities/ThrowAssert.hpp"
0026 #include "Acts/Utilities/detail/periodic.hpp"
0027 
0028 #include <algorithm>
0029 #include <cassert>
0030 #include <cmath>
0031 #include <iostream>
0032 #include <memory>
0033 #include <set>
0034 #include <stdexcept>
0035 #include <utility>
0036 #include <vector>
0037 
0038 namespace Acts {
0039 
0040 using VectorHelpers::perp;
0041 using VectorHelpers::phi;
0042 
0043 CylinderSurface::CylinderSurface(const CylinderSurface& other)
0044     : GeometryObject{}, RegularSurface(other), m_bounds(other.m_bounds) {}
0045 
0046 CylinderSurface::CylinderSurface(const GeometryContext& gctx,
0047                                  const CylinderSurface& other,
0048                                  const Transform3& shift)
0049     : RegularSurface(gctx, other, shift), m_bounds(other.m_bounds) {}
0050 
0051 CylinderSurface::CylinderSurface(const Transform3& transform, double radius,
0052                                  double halfz, double halfphi, double avphi)
0053     : RegularSurface(transform),
0054       m_bounds(std::make_shared<const CylinderBounds>(radius, halfz, halfphi,
0055                                                       avphi)) {}
0056 
0057 CylinderSurface::CylinderSurface(std::shared_ptr<const CylinderBounds> cbounds,
0058                                  const SurfacePlacementBase& placement)
0059     : RegularSurface{placement}, m_bounds(std::move(cbounds)) {
0060   // surfaces representing a detector element must have bounds
0061   throw_assert(m_bounds, "CylinderBounds must not be nullptr");
0062 }
0063 
0064 CylinderSurface::CylinderSurface(const Transform3& transform,
0065                                  std::shared_ptr<const CylinderBounds> cbounds)
0066     : RegularSurface(transform), m_bounds(std::move(cbounds)) {
0067   throw_assert(m_bounds, "CylinderBounds must not be nullptr");
0068 }
0069 
0070 CylinderSurface& CylinderSurface::operator=(const CylinderSurface& other) {
0071   if (this != &other) {
0072     ACTS_PUSH_IGNORE_DEPRECATED()
0073     Surface::operator=(other);
0074     ACTS_POP_IGNORE_DEPRECATED()
0075     m_bounds = other.m_bounds;
0076   }
0077   return *this;
0078 }
0079 
0080 // return the binning position for ordering in the BinnedArray
0081 Vector3 CylinderSurface::referencePosition(const GeometryContext& gctx,
0082                                            AxisDirection aDir) const {
0083   // special binning type for R-type methods
0084   if (aDir == AxisDirection::AxisR || aDir == AxisDirection::AxisRPhi) {
0085     double R = bounds().get(CylinderBounds::eR);
0086     double phi = bounds().get(CylinderBounds::eAveragePhi);
0087     return localToGlobal(gctx, Vector2{phi * R, 0});
0088   }
0089   // give the center as default for all of these binning types
0090   // AxisDirection::AxisX, AxisDirection::AxisY, AxisDirection::AxisZ,
0091   // AxisDirection::AxisR, AxisDirection::AxisPhi, AxisDirection::AxisRPhi,
0092   // AxisDirection::AxisTheta, AxisDirection::AxisEta
0093   return center(gctx);
0094 }
0095 
0096 // return the measurement frame: it's the tangential plane
0097 RotationMatrix3 CylinderSurface::referenceFrame(
0098     const GeometryContext& gctx, const Vector3& position,
0099     const Vector3& /*direction*/) const {
0100   RotationMatrix3 mFrame;
0101   // construct the measurement frame
0102   // measured Y is the z axis
0103   Vector3 measY = rotSymmetryAxis(gctx);
0104   // measured z is the position normalized transverse (in local)
0105   Vector3 measDepth = normal(gctx, position);
0106   // measured X is what comoes out of it
0107   Vector3 measX(measY.cross(measDepth).normalized());
0108   // assign the columnes
0109   mFrame.col(0) = measX;
0110   mFrame.col(1) = measY;
0111   mFrame.col(2) = measDepth;
0112   // return the rotation matrix
0113   return mFrame;
0114 }
0115 
0116 Surface::SurfaceType CylinderSurface::type() const {
0117   return Surface::Cylinder;
0118 }
0119 
0120 Vector3 CylinderSurface::localToGlobal(const GeometryContext& gctx,
0121                                        const Vector2& lposition) const {
0122   // create the position in the local 3d frame
0123   double r = bounds().get(CylinderBounds::eR);
0124   double phi = lposition[0] / r;
0125   Vector3 position(r * std::cos(phi), r * std::sin(phi), lposition[1]);
0126   return localToGlobalTransform(gctx) * position;
0127 }
0128 
0129 Result<Vector2> CylinderSurface::globalToLocal(const GeometryContext& gctx,
0130                                                const Vector3& position,
0131                                                double tolerance) const {
0132   double inttol = tolerance;
0133   if (tolerance == s_onSurfaceTolerance) {
0134     // transform default value!
0135     // @TODO: check if s_onSurfaceTolerance would do here
0136     inttol = bounds().get(CylinderBounds::eR) * 0.0001;
0137   }
0138   if (inttol < 0.01) {
0139     inttol = 0.01;
0140   }
0141   const Transform3& sfTransform = localToGlobalTransform(gctx);
0142   Transform3 inverseTrans(sfTransform.inverse());
0143   Vector3 loc3Dframe(inverseTrans * position);
0144   if (std::abs(perp(loc3Dframe) - bounds().get(CylinderBounds::eR)) > inttol) {
0145     return Result<Vector2>::failure(SurfaceError::GlobalPositionNotOnSurface);
0146   }
0147   return Result<Vector2>::success(
0148       {bounds().get(CylinderBounds::eR) * phi(loc3Dframe), loc3Dframe.z()});
0149 }
0150 
0151 std::string CylinderSurface::name() const {
0152   return "Acts::CylinderSurface";
0153 }
0154 
0155 Vector3 CylinderSurface::normal(const GeometryContext& gctx,
0156                                 const Vector2& lposition) const {
0157   double phi = lposition[0] / m_bounds->get(CylinderBounds::eR);
0158   Vector3 localNormal(std::cos(phi), std::sin(phi), 0.);
0159   return localToGlobalTransform(gctx).linear() * localNormal;
0160 }
0161 
0162 Vector3 CylinderSurface::normal(const GeometryContext& gctx,
0163                                 const Vector3& position) const {
0164   const Transform3& sfTransform = localToGlobalTransform(gctx);
0165   // get it into the cylinder frame
0166   Vector3 pos3D = sfTransform.inverse() * position;
0167   // set the z coordinate to 0
0168   pos3D.z() = 0.;
0169   // normalize and rotate back into global
0170   return sfTransform.linear() * pos3D.normalized();
0171 }
0172 
0173 double CylinderSurface::pathCorrection(const GeometryContext& gctx,
0174                                        const Vector3& position,
0175                                        const Vector3& direction) const {
0176   Vector3 normalT = normal(gctx, position);
0177   double cosAlpha = normalT.dot(direction);
0178   return std::abs(1. / cosAlpha);
0179 }
0180 
0181 const CylinderBounds& CylinderSurface::bounds() const {
0182   return *m_bounds;
0183 }
0184 
0185 Polyhedron CylinderSurface::polyhedronRepresentation(
0186     const GeometryContext& gctx, unsigned int quarterSegments) const {
0187   auto ctrans = localToGlobalTransform(gctx);
0188 
0189   // Prepare vertices and faces
0190   std::vector<Vector3> vertices =
0191       bounds().circleVertices(ctrans, quarterSegments);
0192   auto [faces, triangularMesh] =
0193       detail::FacesHelper::cylindricalFaceMesh(vertices);
0194   return Polyhedron(vertices, faces, triangularMesh, false);
0195 }
0196 
0197 Vector3 CylinderSurface::rotSymmetryAxis(const GeometryContext& gctx) const {
0198   // fast access via transform matrix (and not rotation())
0199   return localToGlobalTransform(gctx).matrix().block<3, 1>(0, 2);
0200 }
0201 
0202 detail::RealQuadraticEquation CylinderSurface::intersectionSolver(
0203     const Transform3& transform, const Vector3& position,
0204     const Vector3& direction) const {
0205   // Solve for radius R
0206   double R = bounds().get(CylinderBounds::eR);
0207 
0208   // Get the transformation matrix
0209   const auto& tMatrix = transform.matrix();
0210   Vector3 caxis = tMatrix.block<3, 1>(0, 2).transpose();
0211   Vector3 ccenter = tMatrix.block<3, 1>(0, 3).transpose();
0212 
0213   Vector3 pc = position - ccenter;
0214   // Cylindrical portals are commonly aligned with the global z-axis. In
0215   // that case the quadratic only needs the transverse coordinates, also
0216   // for translated cylinders and rotations about their axis. Use an exact
0217   // check so that even small tilts retain the general intersection below.
0218   if (caxis.x() == 0. && caxis.y() == 0. && std::abs(caxis.z()) == 1.) {
0219     double a = direction.head<2>().squaredNorm();
0220     double b = 2. * direction.head<2>().dot(pc.head<2>());
0221     double c = pc.head<2>().squaredNorm() - R * R;
0222     return detail::RealQuadraticEquation(a, b, c);
0223   }
0224 
0225   // Check documentation for explanation
0226   Vector3 pcXcd = pc.cross(caxis);
0227   Vector3 ldXcd = direction.cross(caxis);
0228   return detail::CylinderHelper::intersectionSolver(pcXcd, ldXcd, R);
0229 }
0230 
0231 MultiIntersection3D CylinderSurface::intersect(
0232     const GeometryContext& gctx, const Vector3& position,
0233     const Vector3& direction, const BoundaryTolerance& boundaryTolerance,
0234     double tolerance) const {
0235   const auto& gctxTransform = localToGlobalTransform(gctx);
0236 
0237   // Solve the quadratic equation
0238   auto qe = intersectionSolver(gctxTransform, position, direction);
0239 
0240   // If no valid solution return a non-valid surfaceIntersection
0241   if (qe.solutions == 0) {
0242     return MultiIntersection3D(Intersection3D::Invalid(),
0243                                Intersection3D::Invalid());
0244   }
0245 
0246   // Check the validity of the first solution
0247   Vector3 solution1 = position + qe.first * direction;
0248   IntersectionStatus status1 = std::abs(qe.first) < std::abs(tolerance)
0249                                    ? IntersectionStatus::onSurface
0250                                    : IntersectionStatus::reachable;
0251 
0252   // Helper method for boundary check
0253   auto boundaryCheck = [&](const Vector3& solution,
0254                            IntersectionStatus status) -> IntersectionStatus {
0255     // No check to be done, return current status
0256     if (boundaryTolerance.isInfinite()) {
0257       return status;
0258     }
0259     if (boundaryTolerance.isNone() && bounds().coversFullAzimuth()) {
0260       // Project out the current Z value via local z axis
0261       // Built-in local to global for speed reasons
0262       const auto& tMatrix = gctxTransform.matrix();
0263       // Create the reference vector in local
0264       double cZ = 0.;
0265       if (tMatrix(0, 2) == 0. && tMatrix(1, 2) == 0.) {
0266         cZ = (solution.z() - tMatrix(2, 3)) * tMatrix(2, 2);
0267       } else {
0268         const Vector3 vecLocal(solution - tMatrix.block<3, 1>(0, 3));
0269         cZ = vecLocal.dot(tMatrix.block<3, 1>(0, 2));
0270       }
0271       double hZ = bounds().get(CylinderBounds::eHalfLengthZ) + tolerance;
0272       return std::abs(cZ) < std::abs(hZ) ? status
0273                                          : IntersectionStatus::unreachable;
0274     }
0275     return isOnSurface(gctx, solution, direction, boundaryTolerance)
0276                ? status
0277                : IntersectionStatus::unreachable;
0278   };
0279   // Check first solution for boundary compatibility
0280   status1 = boundaryCheck(solution1, status1);
0281   // Set the intersection
0282   Intersection3D first(solution1, qe.first, status1);
0283   if (qe.solutions == 1) {
0284     return MultiIntersection3D(first, first);
0285   }
0286   // Check the validity of the second solution
0287   Vector3 solution2 = position + qe.second * direction;
0288   IntersectionStatus status2 = std::abs(qe.second) < std::abs(tolerance)
0289                                    ? IntersectionStatus::onSurface
0290                                    : IntersectionStatus::reachable;
0291   // Check first solution for boundary compatibility
0292   status2 = boundaryCheck(solution2, status2);
0293   Intersection3D second(solution2, qe.second, status2);
0294   // Order based on path length
0295   if (first.pathLength() <= second.pathLength()) {
0296     return MultiIntersection3D(first, second);
0297   }
0298   return MultiIntersection3D(second, first);
0299 }
0300 
0301 MultiIntersection3D CylinderSurface::intersect(
0302     const GeometryContext& gctx, const Vector3& position,
0303     const Vector3& direction, const Vector3& curvature,
0304     const BoundaryTolerance& boundaryTolerance, double tolerance) const {
0305   if (curvature.isZero(0.) || !curvature.allFinite()) {
0306     return intersect(gctx, position, direction, boundaryTolerance, tolerance);
0307   }
0308   const auto& transform = localToGlobalTransform(gctx);
0309   const double radius = bounds().get(CylinderBounds::eR);
0310   const double halfLength = bounds().get(CylinderBounds::eHalfLengthZ);
0311   const Vector3 localPosition =
0312       transform.linear().transpose() * (position - transform.translation());
0313   const Vector3 localDirection = transform.linear().transpose() * direction;
0314   const Vector3 localCurvature = transform.linear().transpose() * curvature;
0315   const auto roots = detail::CylinderHelper::intersectionSolver(
0316       localPosition.head<2>(), localDirection.head<2>(), radius);
0317   if (roots.solutions == 0) {
0318     return MultiIntersection3D(Intersection3D::Invalid(),
0319                                Intersection3D::Invalid());
0320   }
0321   double s1 = roots.first;
0322   double s2 = roots.solutions == 1 ? roots.first : roots.second;
0323   if (s1 > s2) {
0324     std::swap(s1, s2);
0325   }
0326   // Keep the ray branch order even when corrections change the path ordering:
0327   // navigation stores indices and re-intersects those same branches.
0328   const Vector3 seed1 = localPosition + s1 * localDirection;
0329   const Vector3 seed2 = localPosition + s2 * localDirection;
0330   const double curvatureNorm = curvature.norm();
0331   const auto status = [tolerance](double s) {
0332     return std::abs(s) < std::abs(tolerance) ? IntersectionStatus::onSurface
0333                                              : IntersectionStatus::reachable;
0334   };
0335   auto first = detail::CylinderHelper::correctIntersection(
0336       s1, seed1, localDirection, localCurvature, curvatureNorm, radius,
0337       tolerance);
0338   auto second = detail::CylinderHelper::correctIntersection(
0339       s2, seed2, localDirection, localCurvature, curvatureNorm, radius,
0340       tolerance);
0341   const auto scales =
0342       detail::CylinderHelper::cylinderProjectionScales(first, second, radius);
0343   const auto inside = [&](const Vector3& local, bool fallback) {
0344     if (boundaryTolerance.isInfinite()) {
0345       return true;
0346     }
0347     if (boundaryTolerance.isNone() && bounds().coversFullAzimuth()) {
0348       // Preserve the ray's tolerance-expanded length check on fallback, but
0349       // check a corrected prediction against the requested physical bounds.
0350       return fallback ? std::abs(local.z()) < std::abs(halfLength + tolerance)
0351                       : std::abs(local.z()) <= halfLength;
0352     }
0353     if (fallback) {
0354       // The general ray path checks membership before bounds. Retain that
0355       // check for sector/toleranced bounds, especially for distant seeds.
0356       const double radialTolerance = std::max(
0357           tolerance == s_onSurfaceTolerance ? radius * 0.0001 : tolerance,
0358           0.01);
0359       if (std::abs(local.head<2>().norm() - radius) > radialTolerance) {
0360         return false;
0361       }
0362     }
0363     return insideBounds(
0364         Vector2(radius * std::atan2(local.y(), local.x()), local.z()),
0365         boundaryTolerance);
0366   };
0367   const auto finish = [&](double s, const Vector3& seed,
0368                           std::optional<detail::CurvatureCorrection>& corrected,
0369                           double scale) {
0370     if (corrected && scale > 0. && std::isfinite(scale)) {
0371       corrected->position.head<2>() *= scale;
0372       const Vector3 global = transform * corrected->position;
0373       if (global.allFinite()) {
0374         return Intersection3D(global, corrected->pathLength,
0375                               inside(corrected->position, false)
0376                                   ? IntersectionStatus::reachable
0377                                   : IntersectionStatus::unreachable);
0378       }
0379     }
0380     // Fallback reuses the ray seed; do not solve the intersection again.
0381     return Intersection3D(
0382         position + s * direction, s,
0383         inside(seed, true) ? status(s) : IntersectionStatus::unreachable);
0384   };
0385   return MultiIntersection3D(finish(s1, seed1, first, scales.first),
0386                              finish(s2, seed2, second, scales.second));
0387 }
0388 
0389 AlignmentToPathMatrix CylinderSurface::alignmentToPathDerivative(
0390     const GeometryContext& gctx, const Vector3& position,
0391     const Vector3& direction) const {
0392   assert(isOnSurface(gctx, position, direction, BoundaryTolerance::Infinite()));
0393 
0394   // Local-frame constraint F(x, y, z) = x^2 + y^2 - R^2 = 0.
0395   // Implicit differentiation at the current position gives the
0396   // alignment-to-path derivative.
0397   const auto& rotation = localToGlobalTransform(gctx).rotation();
0398   const Vector3 localPos = rotation.transpose() * (position - center(gctx));
0399   const Vector3 localDir = rotation.transpose() * direction;
0400   // Vanishes when the track is tangent to the cylinder.
0401   const double denom =
0402       localPos.x() * localDir.x() + localPos.y() * localDir.y();
0403 
0404   AlignmentToPathMatrix alignToPath = AlignmentToPathMatrix::Zero();
0405   const Vector3 globalCenterDerivative =
0406       (localPos.x() * rotation.col(0) + localPos.y() * rotation.col(1)) / denom;
0407   detail::setAlignToPathLocalCenterDerivative(alignToPath,
0408                                               globalCenterDerivative, rotation);
0409   // A rotation w about the local axes moves the surface point at localPos by
0410   // cross(w, localPos), so ds/dw = cross(localPos, grad(F) / 2) / denom
0411   // = z (-y, x, 0) / denom.
0412   alignToPath.segment<3>(eAlignmentRotation0) =
0413       Vector3(-localPos.z() * localPos.y() / denom,
0414               localPos.z() * localPos.x() / denom, 0.)
0415           .transpose();
0416 
0417   return alignToPath;
0418 }
0419 
0420 Matrix<2, 3> CylinderSurface::localCartesianToBoundLocalDerivative(
0421     const GeometryContext& gctx, const Vector3& position,
0422     const Vector3& /*direction*/) const {
0423   using VectorHelpers::perp;
0424   // The local frame transform
0425   const auto& sTransform = localToGlobalTransform(gctx);
0426   // calculate the transformation to local coordinates
0427   const Vector3 localPos = sTransform.inverse() * position;
0428   const double lr = perp(localPos);
0429   // the normalised coordinates are already cos and sin of the local azimuth
0430   const double lcphi = localPos.x() / lr;
0431   const double lsphi = localPos.y() / lr;
0432   // Solve for radius R
0433   double R = bounds().get(CylinderBounds::eR);
0434   Matrix<2, 3> loc3DToLocBound = Matrix<2, 3>::Zero();
0435   loc3DToLocBound << -R * lsphi / lr, R * lcphi / lr, 0, 0, 0, 1;
0436 
0437   return loc3DToLocBound;
0438 }
0439 
0440 bool CylinderSurface::contains(const GeometryContext& gctx,
0441                                const Surface& other, double tolerance) const {
0442   const auto* cylinder = dynamic_cast<const CylinderSurface*>(&other);
0443   if (cylinder == nullptr) {
0444     return false;
0445   }
0446 
0447   // The other surface in the frame of this one, which has to be coaxial
0448   const Transform3 otherLocal = localToGlobalTransform(gctx).inverse() *
0449                                 cylinder->localToGlobalTransform(gctx);
0450   if (otherLocal.linear().col(2).head<2>().norm() > tolerance ||
0451       otherLocal.translation().head<2>().norm() > tolerance) {
0452     return false;
0453   }
0454 
0455   const CylinderBounds& otherBounds = cylinder->bounds();
0456   const double r = bounds().get(CylinderBounds::eR);
0457   if (std::abs(otherBounds.get(CylinderBounds::eR) - r) > tolerance ||
0458       std::abs(otherLocal.translation().z()) +
0459               otherBounds.get(CylinderBounds::eHalfLengthZ) >
0460           bounds().get(CylinderBounds::eHalfLengthZ) + tolerance) {
0461     return false;
0462   }
0463 
0464   const double otherAvgPhi = otherBounds.get(CylinderBounds::eAveragePhi);
0465   const Vector3 otherAvgDir =
0466       otherLocal.linear() *
0467       Vector3{std::cos(otherAvgPhi), std::sin(otherAvgPhi), 0};
0468   return detail::phiSectorContains(
0469       bounds().get(CylinderBounds::eHalfPhiSector),
0470       bounds().get(CylinderBounds::eAveragePhi),
0471       otherBounds.get(CylinderBounds::eHalfPhiSector),
0472       std::atan2(otherAvgDir.y(), otherAvgDir.x()), tolerance / r);
0473 }
0474 
0475 std::pair<std::shared_ptr<CylinderSurface>, bool> CylinderSurface::mergedWith(
0476     const CylinderSurface& other, AxisDirection direction,
0477     bool externalRotation, const Logger& logger) const {
0478   using namespace UnitLiterals;
0479 
0480   ACTS_VERBOSE("Merging cylinder surfaces in " << axisDirectionName(direction)
0481                                                << " direction");
0482 
0483   if (isAlignable() || other.isAlignable()) {
0484     throw SurfaceMergingException(getSharedPtr(), other.getSharedPtr(),
0485                                   "CylinderSurface::merge: surfaces are "
0486                                   "associated with a detector element");
0487   }
0488 
0489   assert(m_transform != nullptr && other.m_transform != nullptr);
0490 
0491   Transform3 otherLocal = m_transform->inverse() * *other.m_transform;
0492 
0493   constexpr auto tolerance = s_onSurfaceTolerance;
0494 
0495   // surface cannot have any relative rotation
0496 
0497   if (std::abs(otherLocal.linear().col(eX)[eZ]) >= tolerance ||
0498       std::abs(otherLocal.linear().col(eY)[eZ]) >= tolerance) {
0499     ACTS_ERROR("CylinderSurface::merge: surfaces have relative rotation");
0500     throw SurfaceMergingException(
0501         getSharedPtr(), other.getSharedPtr(),
0502         "CylinderSurface::merge: surfaces have relative rotation");
0503   }
0504 
0505   // radii need to be identical
0506   if (std::abs(bounds().get(CylinderBounds::eR) -
0507                other.bounds().get(CylinderBounds::eR)) > tolerance) {
0508     ACTS_ERROR("CylinderSurface::merge: surfaces have different radii");
0509     throw SurfaceMergingException(
0510         getSharedPtr(), other.getSharedPtr(),
0511         "CylinderSurface::merge: surfaces have different radii");
0512   }
0513 
0514   double r = bounds().get(CylinderBounds::eR);
0515 
0516   // no translation in x/z is allowed
0517   Vector3 translation = otherLocal.translation();
0518 
0519   if (std::abs(translation[0]) > tolerance ||
0520       std::abs(translation[1]) > tolerance) {
0521     ACTS_ERROR(
0522         "CylinderSurface::merge: surfaces have relative translation in x/y");
0523     throw SurfaceMergingException(
0524         getSharedPtr(), other.getSharedPtr(),
0525         "CylinderSurface::merge: surfaces have relative translation in x/y");
0526   }
0527 
0528   double hlZ = bounds().get(CylinderBounds::eHalfLengthZ);
0529   double minZ = -hlZ;
0530   double maxZ = hlZ;
0531 
0532   double zShift = translation[2];
0533   double otherHlZ = other.bounds().get(CylinderBounds::eHalfLengthZ);
0534   double otherMinZ = -otherHlZ + zShift;
0535   double otherMaxZ = otherHlZ + zShift;
0536 
0537   double hlPhi = bounds().get(CylinderBounds::eHalfPhiSector);
0538   double avgPhi = bounds().get(CylinderBounds::eAveragePhi);
0539 
0540   double otherHlPhi = other.bounds().get(CylinderBounds::eHalfPhiSector);
0541   double otherAvgPhi = other.bounds().get(CylinderBounds::eAveragePhi);
0542 
0543   if (direction == AxisDirection::AxisZ) {
0544     // z shift must match the bounds
0545 
0546     if (std::abs(otherLocal.linear().col(eY)[eX]) >= tolerance &&
0547         (!bounds().coversFullAzimuth() ||
0548          !other.bounds().coversFullAzimuth())) {
0549       throw SurfaceMergingException(getSharedPtr(), other.getSharedPtr(),
0550                                     "CylinderSurface::merge: surfaces have "
0551                                     "relative rotation in z and phi sector");
0552     }
0553 
0554     ACTS_VERBOSE("this: [" << minZ << ", " << maxZ << "] ~> "
0555                            << (minZ + maxZ) / 2.0 << " +- " << hlZ);
0556     ACTS_VERBOSE("zShift: " << zShift);
0557 
0558     ACTS_VERBOSE("other: [" << otherMinZ << ", " << otherMaxZ << "] ~> "
0559                             << (otherMinZ + otherMaxZ) / 2.0 << " +- "
0560                             << otherHlZ);
0561     if (std::abs(maxZ - otherMinZ) > tolerance &&
0562         std::abs(minZ - otherMaxZ) > tolerance) {
0563       ACTS_ERROR("CylinderSurface::merge: surfaces have incompatible z bounds");
0564       throw SurfaceMergingException(
0565           getSharedPtr(), other.getSharedPtr(),
0566           "CylinderSurface::merge: surfaces have incompatible z bounds");
0567     }
0568 
0569     if (hlPhi != otherHlPhi || avgPhi != otherAvgPhi) {
0570       throw SurfaceMergingException(getSharedPtr(), other.getSharedPtr(),
0571                                     "CylinderSurface::merge: surfaces have "
0572                                     "different phi sectors");
0573     }
0574 
0575     double newMaxZ = std::max(maxZ, otherMaxZ);
0576     double newMinZ = std::min(minZ, otherMinZ);
0577     double newHlZ = (newMaxZ - newMinZ) / 2.0;
0578     double newMidZ = (newMaxZ + newMinZ) / 2.0;
0579     ACTS_VERBOSE("merged: [" << newMinZ << ", " << newMaxZ << "] ~> " << newMidZ
0580                              << " +- " << newHlZ);
0581 
0582     auto newBounds = std::make_shared<CylinderBounds>(r, newHlZ, hlPhi, avgPhi);
0583 
0584     Transform3 newTransform =
0585         *m_transform * Translation3{Vector3::UnitZ() * newMidZ};
0586 
0587     return {Surface::makeShared<CylinderSurface>(newTransform, newBounds),
0588             zShift < 0};
0589 
0590   } else if (direction == AxisDirection::AxisRPhi) {
0591     // no z shift is allowed
0592     if (std::abs(translation[2]) > tolerance) {
0593       ACTS_ERROR(
0594           "CylinderSurface::merge: surfaces have relative translation in z for "
0595           "rPhi merging");
0596       throw SurfaceMergingException(
0597           getSharedPtr(), other.getSharedPtr(),
0598           "CylinderSurface::merge: surfaces have relative translation in z for "
0599           "rPhi merging");
0600     }
0601 
0602     if (hlZ != otherHlZ) {
0603       throw SurfaceMergingException(getSharedPtr(), other.getSharedPtr(),
0604                                     "CylinderSurface::merge: surfaces have "
0605                                     "different z bounds");
0606     }
0607 
0608     // Figure out signed relative rotation
0609     Vector2 rotatedX = otherLocal.linear().col(eX).head<2>();
0610     double zrotation = std::atan2(rotatedX[1], rotatedX[0]);
0611 
0612     ACTS_VERBOSE("this:  [" << avgPhi / 1_degree << " +- " << hlPhi / 1_degree
0613                             << "]");
0614     ACTS_VERBOSE("other: [" << otherAvgPhi / 1_degree << " +- "
0615                             << otherHlPhi / 1_degree << "]");
0616 
0617     ACTS_VERBOSE("Relative rotation around local z: " << zrotation / 1_degree);
0618 
0619     double prevOtherAvgPhi = otherAvgPhi;
0620     otherAvgPhi = detail::radian_sym(otherAvgPhi + zrotation);
0621     ACTS_VERBOSE("~> local other average phi: "
0622                  << otherAvgPhi / 1_degree
0623                  << " (was: " << prevOtherAvgPhi / 1_degree << ")");
0624 
0625     try {
0626       auto [newHlPhi, newAvgPhi, reversed] = detail::mergedPhiSector(
0627           hlPhi, avgPhi, otherHlPhi, otherAvgPhi, logger, tolerance);
0628 
0629       Transform3 newTransform = *m_transform;
0630 
0631       if (externalRotation) {
0632         ACTS_VERBOSE("Modifying transform for external rotation of "
0633                      << newAvgPhi / 1_degree);
0634         newTransform = newTransform * AngleAxis3(newAvgPhi, Vector3::UnitZ());
0635         newAvgPhi = 0.;
0636       }
0637 
0638       auto newBounds = std::make_shared<CylinderBounds>(
0639           r, bounds().get(CylinderBounds::eHalfLengthZ), newHlPhi, newAvgPhi);
0640 
0641       return {Surface::makeShared<CylinderSurface>(newTransform, newBounds),
0642               reversed};
0643     } catch (const std::invalid_argument& e) {
0644       throw SurfaceMergingException(getSharedPtr(), other.getSharedPtr(),
0645                                     e.what());
0646     }
0647   } else {
0648     throw SurfaceMergingException(getSharedPtr(), other.getSharedPtr(),
0649                                   "CylinderSurface::merge: invalid direction " +
0650                                       axisDirectionName(direction));
0651   }
0652 }
0653 
0654 const std::shared_ptr<const CylinderBounds>& CylinderSurface::boundsPtr()
0655     const {
0656   return m_bounds;
0657 }
0658 
0659 void CylinderSurface::assignSurfaceBounds(
0660     std::shared_ptr<const CylinderBounds> newBounds) {
0661   m_bounds = std::move(newBounds);
0662 }
0663 
0664 void CylinderSurface::assignSurfaceMaterial(
0665     std::shared_ptr<const ISurfaceMaterial> material) {
0666   if (material != nullptr) {
0667     const std::array<AxisDirection, 2> localSurfaceAxes = localAxes();
0668     const std::array<AxisDirection, 2> alternativeAxes = {
0669         AxisDirection::AxisPhi, AxisDirection::AxisZ};
0670     const std::vector<AxisDirection>& localMaterialAxes =
0671         material->localAxisDirections();
0672 
0673     if (!std::ranges::includes(
0674             std::set(localSurfaceAxes.begin(), localSurfaceAxes.end()),
0675             std::set(localMaterialAxes.begin(), localMaterialAxes.end())) &&
0676         !std::ranges::includes(
0677             std::set(alternativeAxes.begin(), alternativeAxes.end()),
0678             std::set(localMaterialAxes.begin(), localMaterialAxes.end()))) {
0679       std::string errorMsg =
0680           "CylinderSurface::checkSurfaceMaterial: material axis directions " +
0681           axesDirectionName(localMaterialAxes) +
0682           " are not supported by this surface. Supported axes are: " +
0683           axesDirectionName(std::vector<AxisDirection>{
0684               localSurfaceAxes.begin(), localSurfaceAxes.end()}) +
0685           " or " +
0686           axesDirectionName(std::vector<AxisDirection>{alternativeAxes.begin(),
0687                                                        alternativeAxes.end()});
0688       throw std::invalid_argument(errorMsg);
0689     }
0690 
0691     m_swapMaterialAxes = !localMaterialAxes.empty() &&
0692                          localMaterialAxes[0] != localSurfaceAxes[0] &&
0693                          localMaterialAxes[0] != alternativeAxes[0];
0694     m_scaleMaterialAxis =
0695         std::ranges::find(localMaterialAxes, AxisDirection::AxisPhi) !=
0696         localMaterialAxes.end();
0697   }
0698 
0699   m_surfaceMaterial = std::move(material);
0700 }
0701 
0702 Vector2 CylinderSurface::transformSurfaceLocalToMaterialLocal(
0703     const Vector2& surfaceLocal) const {
0704   Vector2 materialLocal = surfaceLocal;
0705   if (m_scaleMaterialAxis) {
0706     const double r = bounds().get(CylinderBounds::eR);
0707     materialLocal[0] = surfaceLocal[0] / r;
0708   }
0709   if (m_swapMaterialAxes) {
0710     std::swap(materialLocal[0], materialLocal[1]);
0711   }
0712   return materialLocal;
0713 }
0714 
0715 }  // namespace Acts