File indexing completed on 2026-11-20 09:27:57
0001
0002
0003
0004
0005
0006
0007
0008
0009 #include "Acts/Definitions/Units.hpp"
0010 #include "Acts/Geometry/CylinderVolumeBounds.hpp"
0011 #include "Acts/Geometry/Polyhedron.hpp"
0012 #include "Acts/Geometry/TrackingVolume.hpp"
0013 #include "Acts/Navigation/SurfaceArrayNavigationPolicy.hpp"
0014 #include "Acts/Surfaces/Surface.hpp"
0015 #include "Acts/Surfaces/SurfaceArray.hpp"
0016 #include "Acts/Utilities/Logger.hpp"
0017 #include "ActsPlugins/Detray/DetrayPayloadConverter.hpp"
0018
0019 #include <algorithm>
0020 #include <cmath>
0021 #include <limits>
0022 #include <map>
0023 #include <numbers>
0024 #include <optional>
0025 #include <set>
0026 #include <stdexcept>
0027 #include <utility>
0028 #include <vector>
0029
0030 #include <detray/definitions/grid_axis.hpp>
0031 #include <detray/io/frontend/payloads.hpp>
0032
0033 namespace ActsPlugins {
0034
0035 namespace {
0036
0037 using Acts::Vector3;
0038
0039
0040 struct DetrayAxis {
0041 double min = 0.;
0042 double width = 1.;
0043 int nBins = 0;
0044 bool circular = false;
0045
0046
0047 int rawBin(double v) const {
0048 return static_cast<int>((v - min) / width + 1.) - 1;
0049 }
0050
0051
0052 int bin(int raw) const {
0053 if (circular) {
0054 return (nBins + (raw % nBins)) % nBins;
0055 }
0056 return std::clamp(raw, 0, nBins - 1);
0057 }
0058 };
0059
0060
0061
0062 struct Helix {
0063 double z0 = 0.;
0064 double kappa = 0.;
0065 double psi0 = 0.;
0066 double cotTheta = 0.;
0067
0068 Vector3 position(double s) const {
0069 const double half = 0.5 * kappa * s;
0070 const double chord =
0071 std::abs(half) < 1e-9 ? s : 2. * std::sin(half) / kappa;
0072 return {chord * std::cos(psi0 + half), chord * std::sin(psi0 + half),
0073 z0 + cotTheta * s};
0074 }
0075
0076 Vector3 direction(double s) const {
0077 const double psi = psi0 + kappa * s;
0078 return Vector3{std::cos(psi), std::sin(psi), cotTheta}.normalized();
0079 }
0080
0081
0082 std::optional<double> arcAtRadius(double r) const {
0083 if (std::abs(kappa) < 1e-12) {
0084 return r;
0085 }
0086 const double arg = 0.5 * std::abs(kappa) * r;
0087 if (arg > 1.) {
0088 return std::nullopt;
0089 }
0090 return 2. * std::asin(arg) / std::abs(kappa);
0091 }
0092
0093
0094 static std::optional<std::pair<Helix, double>> through(const Vector3& point,
0095 double z0, double k) {
0096 Helix h;
0097 h.z0 = z0;
0098 h.kappa = k;
0099 const double rho = std::hypot(point.x(), point.y());
0100 const auto sPoint = h.arcAtRadius(rho);
0101 if (!sPoint.has_value() || *sPoint <= 0.) {
0102 return std::nullopt;
0103 }
0104 h.cotTheta = (point.z() - z0) / *sPoint;
0105 h.psi0 = std::atan2(point.y(), point.x()) - 0.5 * k * *sPoint;
0106 return std::pair{h, *sPoint};
0107 }
0108 };
0109
0110 }
0111
0112 std::optional<DetrayPayloadConverter::DetraySurfaceGrid>
0113 DetrayPayloadConverter::convertDetraySurfaceGridPolicy(
0114 const DetraySurfaceGridPolicy& policy, const Acts::GeometryContext& gctx,
0115 const SurfaceLookupFunction& surfaceLookup, const Acts::Logger& logger) {
0116 using Acts::SurfaceArrayNavigationPolicy;
0117
0118
0119
0120 const Acts::TrackingVolume& volume = policy.volume();
0121 const SurfaceArrayNavigationPolicy* surfaceArray = nullptr;
0122 if (const Acts::INavigationPolicy* root = volume.navigationPolicy();
0123 root != nullptr) {
0124 root->visit([&](const Acts::INavigationPolicy& p) {
0125 if (const auto* sa =
0126 dynamic_cast<const SurfaceArrayNavigationPolicy*>(&p);
0127 sa != nullptr) {
0128 if (surfaceArray != nullptr) {
0129 throw std::runtime_error{
0130 "DetraySurfaceGridPolicy: volume " + volume.volumeName() +
0131 " has more than one SurfaceArrayNavigationPolicy"};
0132 }
0133 surfaceArray = sa;
0134 }
0135 });
0136 }
0137 if (surfaceArray == nullptr) {
0138 throw std::runtime_error{"DetraySurfaceGridPolicy: volume " +
0139 volume.volumeName() +
0140 " has no SurfaceArrayNavigationPolicy"};
0141 }
0142 return convertSurfaceGridForDetray(*surfaceArray, volume, gctx, surfaceLookup,
0143 policy.config(), logger);
0144 }
0145
0146 std::optional<DetrayPayloadConverter::DetraySurfaceGrid>
0147 DetrayPayloadConverter::convertSurfaceGridForDetray(
0148 const Acts::SurfaceArrayNavigationPolicy& policy,
0149 const Acts::TrackingVolume& volume, const Acts::GeometryContext& gctx,
0150 const SurfaceLookupFunction& surfaceLookup,
0151 const DetraySurfaceGridConfig& fill, const Acts::Logger& logger) {
0152 using Acts::SurfaceArrayNavigationPolicy;
0153
0154
0155
0156 const SurfaceArrayNavigationPolicy::Config& actsConfig = policy.config();
0157 std::optional<SurfaceArrayNavigationPolicy> rebinned;
0158 if (fill.numberOfBinsFactor.has_value() &&
0159 *fill.numberOfBinsFactor != actsConfig.numberOfBinsFactor &&
0160 (actsConfig.bins.first == 0 || actsConfig.bins.second == 0)) {
0161 SurfaceArrayNavigationPolicy::Config config = actsConfig;
0162 config.numberOfBinsFactor = *fill.numberOfBinsFactor;
0163 rebinned.emplace(gctx, volume, logger, config);
0164 }
0165 const SurfaceArrayNavigationPolicy& binning =
0166 rebinned.has_value() ? *rebinned : policy;
0167
0168 std::optional<DetraySurfaceGrid> grid =
0169 convertSurfaceArray(binning, gctx, surfaceLookup, logger);
0170 if (grid.has_value()) {
0171 fillSurfaceGridDetrayNative(*grid, binning.surfaceArray(), volume, gctx,
0172 surfaceLookup, fill, logger);
0173 }
0174 return grid;
0175 }
0176
0177 void DetrayPayloadConverter::fillSurfaceGridDetrayNative(
0178 DetraySurfaceGrid& grid, const Acts::SurfaceArray& surfaceArray,
0179 const Acts::TrackingVolume& volume, const Acts::GeometryContext& gctx,
0180 const SurfaceLookupFunction& surfaceLookup,
0181 const DetraySurfaceGridConfig& fill, const Acts::Logger& logger) {
0182 using namespace Acts;
0183
0184 const Surface* representative = surfaceArray.surfaceRepresentation();
0185 const bool isCylinder =
0186 representative != nullptr && representative->type() == Surface::Cylinder;
0187 const bool isDisc =
0188 representative != nullptr && representative->type() == Surface::Disc;
0189 const auto* bounds =
0190 dynamic_cast<const CylinderVolumeBounds*>(&volume.volumeBounds());
0191 if ((!isCylinder && !isDisc) || bounds == nullptr || grid.axes.size() != 2) {
0192 ACTS_WARNING(volume.volumeName()
0193 << ": no detray-native fill for this grid, keeping it");
0194 return;
0195 }
0196
0197 const Transform3& volumeTransform = volume.localToGlobalTransform(gctx);
0198 const Vector3 volumeCenter = volumeTransform.translation();
0199 if ((volumeTransform.rotation().matrix() - RotationMatrix3::Identity())
0200 .norm() > 1e-9 ||
0201 std::hypot(volumeCenter.x(), volumeCenter.y()) > 1e-6) {
0202 ACTS_WARNING(volume.volumeName()
0203 << ": volume is rotated or off the beam axis, keeping the "
0204 "plain grid");
0205 return;
0206 }
0207
0208 const double rMin = bounds->get(CylinderVolumeBounds::eMinR);
0209 const double rMax = bounds->get(CylinderVolumeBounds::eMaxR);
0210 const double halfZ = bounds->get(CylinderVolumeBounds::eHalfLengthZ);
0211 const double zLow = volumeCenter.z() - halfZ;
0212 const double zHigh = volumeCenter.z() + halfZ;
0213
0214
0215 const double refRadius = rMin > 0. ? 0.5 * (rMin + rMax) : rMax;
0216
0217 std::array<DetrayAxis, 2> axes{};
0218 for (std::size_t i = 0; i < 2; ++i) {
0219 const auto& ax = grid.axes[i];
0220 if (ax.binning != detray::axis::binning::e_regular ||
0221 ax.edges.size() != 2 || ax.bins == 0) {
0222 ACTS_WARNING(volume.volumeName()
0223 << ": irregular grid axis, keeping the plain grid");
0224 return;
0225 }
0226 axes[i].min = ax.edges[0];
0227 axes[i].nBins = static_cast<int>(ax.bins);
0228 axes[i].width = (ax.edges[1] - ax.edges[0]) / static_cast<double>(ax.bins);
0229 axes[i].circular = ax.bounds == detray::axis::bounds::e_circular;
0230 }
0231
0232 const std::size_t phiAxis = isCylinder ? 0 : 1;
0233 const std::size_t spanAxis = 1 - phiAxis;
0234
0235
0236
0237
0238 auto lookupPoint = [&](const Vector3& pos,
0239 const Vector3& dir) -> std::array<double, 2> {
0240 if (isCylinder) {
0241 const double dPerp2 = dir.x() * dir.x() + dir.y() * dir.y();
0242 const double pPerp2 = pos.x() * pos.x() + pos.y() * pos.y();
0243 const double radDiff = refRadius * refRadius - pPerp2;
0244 double path = 0.;
0245 if (dPerp2 < std::numeric_limits<double>::epsilon()) {
0246 return {std::atan2(pos.y(), pos.x()), pos.z()};
0247 }
0248 if (std::abs(radDiff) > 1. * UnitConstants::um) {
0249 const double k = -(pos.x() * dir.x() + pos.y() * dir.y()) / dPerp2;
0250 const double discr = radDiff / dPerp2 + k * k;
0251 if (discr < 0.) {
0252 return {std::atan2(pos.y(), pos.x()), pos.z()};
0253 }
0254 const double s1 = k + std::sqrt(discr);
0255 const double s2 = k - std::sqrt(discr);
0256 path = std::abs(s1) < std::abs(s2) ? s1 : s2;
0257 }
0258 const Vector3 x = pos + path * dir;
0259 return {std::atan2(x.y(), x.x()), x.z()};
0260 }
0261
0262 Vector3 x = pos;
0263 if (std::abs(dir.z()) > std::numeric_limits<double>::epsilon()) {
0264 x = pos + ((volumeCenter.z() - pos.z()) / dir.z()) * dir;
0265 }
0266 return {std::hypot(x.x(), x.y()), std::atan2(x.y(), x.x())};
0267 };
0268
0269
0270 std::vector<double> vertexZs;
0271 const std::size_t nZ = std::max<std::size_t>(fill.nVertexZ, 1);
0272 for (std::size_t i = 0; i < nZ; ++i) {
0273 vertexZs.push_back(nZ == 1 ? 0.
0274 : fill.vertexZHalfRange *
0275 (-1. + 2. * static_cast<double>(i) /
0276 static_cast<double>(nZ - 1)));
0277 }
0278 std::vector<double> curvatures{0.};
0279 if (fill.minPt > 0. && fill.bField > 0. && fill.nCurvature > 1) {
0280
0281 const double radius = (fill.minPt / UnitConstants::GeV) /
0282 (0.299792458 * fill.bField / UnitConstants::T) *
0283 UnitConstants::m;
0284 const double kMax = 1. / radius;
0285 curvatures.clear();
0286 const std::size_t nK = fill.nCurvature;
0287 for (std::size_t i = 0; i < nK; ++i) {
0288 curvatures.push_back(kMax * (-1. + 2. * static_cast<double>(i) /
0289 static_cast<double>(nK - 1)));
0290 }
0291 }
0292
0293
0294 auto entry =
0295 [&](const Helix& h,
0296 double sPoint) -> std::optional<std::pair<Vector3, Vector3>> {
0297 double sEnter = 0.;
0298 if (rMin > 0.) {
0299 const auto s = h.arcAtRadius(rMin);
0300 if (!s.has_value()) {
0301 return std::nullopt;
0302 }
0303 sEnter = std::max(sEnter, *s);
0304 }
0305 if (h.z0 < zLow || h.z0 > zHigh) {
0306 if (std::abs(h.cotTheta) < 1e-12) {
0307 return std::nullopt;
0308 }
0309 const double zFace = h.z0 < zLow ? zLow : zHigh;
0310 const double s = (zFace - h.z0) / h.cotTheta;
0311 if (s < 0.) {
0312 return std::nullopt;
0313 }
0314 sEnter = std::max(sEnter, s);
0315 }
0316 if (sEnter > sPoint * (1. + 1e-9) + 1e-6) {
0317 return std::nullopt;
0318 }
0319 return std::pair{h.position(sEnter), h.direction(sEnter)};
0320 };
0321
0322
0323 std::map<std::pair<int, int>, std::set<std::size_t>> contents;
0324 std::size_t nUnreached = 0;
0325
0326 const std::vector<const Surface*> surfaces = surfaceArray.surfaces();
0327 for (const Surface* surface : surfaces) {
0328 const std::size_t index = surfaceLookup(surface);
0329
0330 const Polyhedron polyhedron = surface->polyhedronRepresentation(gctx, 16);
0331
0332
0333
0334 Vector3 centroid = Vector3::Zero();
0335 for (const Vector3& v : polyhedron.vertices) {
0336 centroid += v;
0337 }
0338 const double centerPhi = std::atan2(centroid.y(), centroid.x());
0339
0340 bool reached = false;
0341 for (const double z0 : vertexZs) {
0342 for (const double kappa : curvatures) {
0343
0344
0345 std::map<int, std::pair<double, double>> columns;
0346 auto addSample = [&](const Vector3& point) {
0347 const auto helix = Helix::through(point, z0, kappa);
0348 if (!helix.has_value()) {
0349 return std::optional<std::array<double, 2>>{};
0350 }
0351 const auto query = entry(helix->first, helix->second);
0352 if (!query.has_value()) {
0353 return std::optional<std::array<double, 2>>{};
0354 }
0355 std::array<double, 2> g = lookupPoint(query->first, query->second);
0356 double dphi = g[phiAxis] - centerPhi;
0357 dphi = std::remainder(dphi, 2. * std::numbers::pi);
0358 g[phiAxis] = centerPhi + dphi;
0359 const int col =
0360 axes[spanAxis].bin(axes[spanAxis].rawBin(g[spanAxis]));
0361 const double phi = g[phiAxis];
0362 auto [it, inserted] = columns.try_emplace(col, phi, phi);
0363 if (!inserted) {
0364 it->second.first = std::min(it->second.first, phi);
0365 it->second.second = std::max(it->second.second, phi);
0366 }
0367 return std::optional<std::array<double, 2>>{g};
0368 };
0369
0370 for (const auto& face : polyhedron.faces) {
0371 for (std::size_t i = 0; i < face.size(); ++i) {
0372 const Vector3& from = polyhedron.vertices.at(face.at(i));
0373 const Vector3& to =
0374 polyhedron.vertices.at(face.at((i + 1) % face.size()));
0375
0376 const auto a = addSample(from);
0377 const auto b = addSample(to);
0378 if (!a.has_value() || !b.has_value()) {
0379 continue;
0380 }
0381 const double spanBins =
0382 std::max(std::abs((*b)[0] - (*a)[0]) / axes[0].width,
0383 std::abs((*b)[1] - (*a)[1]) / axes[1].width);
0384 const auto nSub = static_cast<std::size_t>(
0385 std::ceil(spanBins / fill.maxSampleSpacing));
0386 for (std::size_t k = 1; k < nSub; ++k) {
0387 const double t =
0388 static_cast<double>(k) / static_cast<double>(nSub);
0389 addSample(from + t * (to - from));
0390 }
0391 }
0392 }
0393
0394
0395
0396
0397 constexpr double pi = std::numbers::pi;
0398 auto fillRows = [&](int col, double lo, double hi) {
0399 if (lo > hi) {
0400 return;
0401 }
0402 for (int row = axes[phiAxis].rawBin(lo);
0403 row <= axes[phiAxis].rawBin(hi); ++row) {
0404 const int rowBin = axes[phiAxis].bin(row);
0405 const std::pair<int, int> key =
0406 phiAxis == 0 ? std::pair{rowBin, col} : std::pair{col, rowBin};
0407 contents[key].insert(index);
0408 reached = true;
0409 }
0410 };
0411 for (const auto& [col, range] : columns) {
0412 const auto [lo, hi] = range;
0413 fillRows(col, std::max(lo, -pi), std::min(hi, pi));
0414 if (hi > pi) {
0415 fillRows(col, -pi, hi - 2. * pi);
0416 }
0417 if (lo < -pi) {
0418 fillRows(col, lo + 2. * pi, pi);
0419 }
0420 }
0421 }
0422 }
0423 if (!reached) {
0424 ++nUnreached;
0425 }
0426 }
0427
0428 std::size_t entriesBefore = 0;
0429 std::size_t entriesAfter = 0;
0430 std::size_t maxContent = 0;
0431 for (auto& bin : grid.bins) {
0432 entriesBefore += bin.content.size();
0433 const auto it = contents.find({static_cast<int>(bin.loc_index.at(0)),
0434 static_cast<int>(bin.loc_index.at(1))});
0435
0436 if (it != contents.end()) {
0437 bin.content.assign(it->second.begin(), it->second.end());
0438 }
0439 entriesAfter += bin.content.size();
0440 maxContent = std::max(maxContent, bin.content.size());
0441 }
0442
0443 if (nUnreached > 0) {
0444 ACTS_WARNING(volume.volumeName()
0445 << ": " << nUnreached
0446 << " surfaces are not reached by the track family");
0447 }
0448 ACTS_DEBUG(volume.volumeName()
0449 << ": detray-native fill, reference r = " << refRadius << " mm, "
0450 << grid.bins.size() << " bins, entries " << entriesBefore << " -> "
0451 << entriesAfter << ", max per bin " << maxContent);
0452 }
0453
0454 }