Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-11-26 09:25:00

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/EventData/AnyTrackStateProxy.hpp"
0010 #include "Acts/EventData/TrackStatePropMask.hpp"
0011 #include "Acts/Utilities/HashedString.hpp"
0012 #include "ActsExamples/EventData/Track.hpp"
0013 
0014 #include <vector>
0015 
0016 #include <pybind11/pybind11.h>
0017 #include <pybind11/stl.h>
0018 
0019 #include "EventDataHelpers.hpp"
0020 
0021 namespace py = pybind11;
0022 
0023 using namespace ActsExamples;
0024 using namespace ActsPython::EventDataHelpers;
0025 
0026 namespace {
0027 
0028 /// Setters only exist when `!Map::IsReadOnly`. isMeasurement is computed and
0029 /// only gets a plain setIsMeasurement(), no getter/setter pair.
0030 template <typename Map>
0031 void addTrackStateTypeFlags(py::class_<Map>& cls) {
0032   cls.def_property_readonly("hasMaterial", &Map::hasMaterial)
0033       .def_property_readonly("hasParameters", &Map::hasParameters)
0034       .def_property_readonly("hasMeasurement", &Map::hasMeasurement)
0035       .def_property_readonly("isMeasurement", &Map::isMeasurement)
0036       .def_property_readonly("isOutlier", &Map::isOutlier)
0037       .def_property_readonly("isHole", &Map::isHole)
0038       .def_property_readonly("isSharedHit", &Map::isSharedHit)
0039       .def_property_readonly("isSplitHit", &Map::isSplitHit);
0040 
0041   if constexpr (!Map::IsReadOnly) {
0042     cls.def_property("hasMeasurement", &Map::hasMeasurement,
0043                      &Map::setHasMeasurement)
0044         .def("setIsMeasurement", &Map::setIsMeasurement)
0045         .def_property("isOutlier", &Map::isOutlier, &Map::setIsOutlier)
0046         .def_property("isHole", &Map::isHole, &Map::setIsHole)
0047         .def_property("isSharedHit", &Map::isSharedHit, &Map::setIsSharedHit)
0048         .def_property("isSplitHit", &Map::isSplitHit, &Map::setIsSplitHit);
0049   }
0050 }
0051 
0052 /// Copy a dynamic-size Eigen vector/matrix map into std::vector(s).
0053 template <typename Map>
0054 std::vector<double> toVector(const Map& map) {
0055   return std::vector<double>(map.data(), map.data() + map.size());
0056 }
0057 template <typename Map>
0058 std::vector<std::vector<double>> toNestedVector(const Map& map) {
0059   std::vector<std::vector<double>> out(static_cast<std::size_t>(map.rows()));
0060   for (Eigen::Index i = 0; i < map.rows(); ++i) {
0061     out[static_cast<std::size_t>(i)].assign(map.row(i).begin(),
0062                                             map.row(i).end());
0063   }
0064   return out;
0065 }
0066 
0067 /// Assign a std::vector/nested std::vector into a dynamic-size Eigen map,
0068 /// raising ValueError on a size mismatch.
0069 template <typename Map>
0070 void assignVector(Map map, const std::vector<double>& values) {
0071   if (static_cast<Eigen::Index>(values.size()) != map.size()) {
0072     throw std::invalid_argument("size mismatch");
0073   }
0074   std::copy(values.begin(), values.end(), map.begin());
0075 }
0076 template <typename Map>
0077 void assignNestedVector(Map map,
0078                         const std::vector<std::vector<double>>& values) {
0079   if (static_cast<Eigen::Index>(values.size()) != map.rows()) {
0080     throw std::invalid_argument("size mismatch");
0081   }
0082   for (Eigen::Index i = 0; i < map.rows(); ++i) {
0083     const auto& row = values[static_cast<std::size_t>(i)];
0084     if (static_cast<Eigen::Index>(row.size()) != map.cols()) {
0085       throw std::invalid_argument("size mismatch");
0086     }
0087     std::copy(row.begin(), row.end(), map.row(i).begin());
0088   }
0089 }
0090 
0091 /// Bind the surface shared by the concrete and Any track state proxies (same
0092 /// rationale as @ref bindTrackProxyCommon); `effectiveCalibrated`/
0093 /// `effectiveCalibratedCovariance` stay read-only here, see below.
0094 template <typename Cls>
0095 void bindTrackStateProxyCommon(Cls& cls) {
0096   using Proxy = typename Cls::type;
0097   cls.def_property_readonly("index", &Proxy::index)
0098       .def_property_readonly("hasPrevious", &Proxy::hasPrevious)
0099       .def_property_readonly("referenceSurface", &Proxy::referenceSurface)
0100       .def_property_readonly("hasReferenceSurface", &Proxy::hasReferenceSurface)
0101       .def_property_readonly("mask", &Proxy::getMask)
0102       .def_property_readonly("hasPredicted", &Proxy::hasPredicted)
0103       .def_property_readonly("hasFiltered", &Proxy::hasFiltered)
0104       .def_property_readonly("hasSmoothed", &Proxy::hasSmoothed)
0105       .def_property_readonly("hasJacobian", &Proxy::hasJacobian)
0106       .def_property_readonly("hasProjector", &Proxy::hasProjector)
0107       .def_property_readonly("hasUncalibratedSourceLink",
0108                              &Proxy::hasUncalibratedSourceLink)
0109       .def_property_readonly("hasCalibrated", &Proxy::hasCalibrated)
0110       .def_property_readonly("uncalibratedSourceLink",
0111                              &Proxy::getUncalibratedSourceLink)
0112       .def_property_readonly("calibratedSize", &Proxy::calibratedSize)
0113       .def_property_readonly("projectorSubspaceIndices",
0114                              [](const Proxy& self) {
0115                                auto indices = self.projectorSubspaceIndices();
0116                                return std::vector<int>(
0117                                    indices.begin(),
0118                                    indices.begin() + self.calibratedSize());
0119                              })
0120       .def(
0121           "hasColumn",
0122           [](const Proxy& self, const std::string& key) {
0123             return self.hasColumn(Acts::hashStringDynamic(key));
0124           },
0125           py::arg("key"))
0126       // effectiveCalibrated(+Covariance) write access is Vector-only; see
0127       // bindTrackStateProxyVector.
0128       .def_property_readonly("effectiveCalibrated",
0129                              [](const Proxy& self) {
0130                                return toVector(self.effectiveCalibrated());
0131                              })
0132       .def_property_readonly(
0133           "effectiveCalibratedCovariance", [](const Proxy& self) {
0134             return toNestedVector(self.effectiveCalibratedCovariance());
0135           });
0136 
0137   // typeFlags returns genuinely different types depending on constness
0138   // (ConstTrackStateTypeMap vs. MutableTrackStateTypeMap), so it can't share
0139   // a getter+setter pair with the generic accessors below.
0140   cls.def_property_readonly(
0141       "typeFlags",
0142       py::cpp_function([](const Proxy& self) { return self.typeFlags(); },
0143                        py::keep_alive<0, 1>()));
0144 
0145   bindScalar(cls, "previous",
0146              [](auto& self) -> decltype(auto) { return self.previous(); });
0147   bindScalar(cls, "chi2",
0148              [](auto& self) -> decltype(auto) { return self.chi2(); });
0149   bindScalar(cls, "pathLength",
0150              [](auto& self) -> decltype(auto) { return self.pathLength(); });
0151   bindEigen(cls, "predicted",
0152             [](auto& self) -> decltype(auto) { return self.predicted(); });
0153   bindEigen(cls, "filtered",
0154             [](auto& self) -> decltype(auto) { return self.filtered(); });
0155   bindEigen(cls, "smoothed",
0156             [](auto& self) -> decltype(auto) { return self.smoothed(); });
0157   bindEigen(cls, "predictedCovariance", [](auto& self) -> decltype(auto) {
0158     return self.predictedCovariance();
0159   });
0160   bindEigen(cls, "filteredCovariance", [](auto& self) -> decltype(auto) {
0161     return self.filteredCovariance();
0162   });
0163   bindEigen(cls, "smoothedCovariance", [](auto& self) -> decltype(auto) {
0164     return self.smoothedCovariance();
0165   });
0166   bindEigen(cls, "jacobian",
0167             [](auto& self) -> decltype(auto) { return self.jacobian(); });
0168   // "best available" of predicted/filtered/smoothed; no mutable overload
0169   // exists at all, so always read-only regardless of Proxy.
0170   bindEigenReadonly(cls, "parameters",
0171                     [](const Proxy& self) { return self.parameters(); });
0172   bindEigenReadonly(cls, "covariance",
0173                     [](const Proxy& self) { return self.covariance(); });
0174 
0175   if constexpr (!Proxy::ReadOnly) {
0176     cls.def_property("referenceSurface", &Proxy::referenceSurface,
0177                      &Proxy::setReferenceSurface)
0178         // overrides the read-only common binding above: the mutable overload
0179         // returns MutableTrackStateTypeMap, not ConstTrackStateTypeMap.
0180         .def_property_readonly(
0181             "typeFlags",
0182             py::cpp_function([](Proxy& self) { return self.typeFlags(); },
0183                              py::keep_alive<0, 1>()))
0184         .def_property(
0185             "uncalibratedSourceLink", &Proxy::getUncalibratedSourceLink,
0186             [](Proxy& self, const Acts::SourceLink& sourceLink) {
0187               // Some concrete setUncalibratedSourceLink overloads take
0188               // SourceLink&&; pybind's argument caster only ever produces an
0189               // lvalue, so a direct member-pointer binding doesn't compile.
0190               self.setUncalibratedSourceLink(Acts::SourceLink{sourceLink});
0191             })
0192         .def(
0193             "setProjectorSubspaceIndices",
0194             [](Proxy& self, const std::vector<int>& indices) {
0195               self.setProjectorSubspaceIndices(indices);
0196             },
0197             py::arg("indices"))
0198         .def(
0199             "allocateCalibrated",
0200             [](Proxy& self, std::size_t measdim) {
0201               self.allocateCalibrated(measdim);
0202             },
0203             py::arg("measdim"))
0204         .def("unset", &Proxy::unset, py::arg("mask"))
0205         .def("addComponents", &Proxy::addComponents, py::arg("mask"));
0206   }
0207 }
0208 
0209 /// Bind what only concrete Vector-backed proxies have: `copyFrom`, and write
0210 /// access to `effectiveCalibrated`/`effectiveCalibratedCovariance` (needs a
0211 /// contiguous `Eigen::Map`, not guaranteed by `AnyTrackStateProxy`).
0212 template <typename Cls>
0213 void bindTrackStateProxyVector(Cls& cls) {
0214   using Proxy = typename Cls::type;
0215   if constexpr (!Proxy::ReadOnly) {
0216     cls.def("copyFrom", &Proxy::template copyFrom<ConstTrackStateProxy>,
0217             py::arg("other"), py::arg("mask") = Acts::TrackStatePropMask::All,
0218             py::arg("onlyAllocated") = true)
0219         .def("copyFrom", &Proxy::template copyFrom<TrackStateProxy>,
0220              py::arg("other"), py::arg("mask") = Acts::TrackStatePropMask::All,
0221              py::arg("onlyAllocated") = true)
0222         .def_property(
0223             "effectiveCalibrated",
0224             [](const Proxy& self) {
0225               return toVector(self.effectiveCalibrated());
0226             },
0227             [](Proxy& self, const std::vector<double>& v) {
0228               assignVector(self.effectiveCalibrated(), v);
0229             })
0230         .def_property(
0231             "effectiveCalibratedCovariance",
0232             [](const Proxy& self) {
0233               return toNestedVector(self.effectiveCalibratedCovariance());
0234             },
0235             [](Proxy& self, const std::vector<std::vector<double>>& v) {
0236               assignNestedVector(self.effectiveCalibratedCovariance(), v);
0237             });
0238   }
0239 }
0240 
0241 }  // namespace
0242 
0243 namespace ActsPython {
0244 
0245 void addEventDataTrackStates(py::module& mex) {
0246   py::class_<Acts::TrackStateType> trackStateTypeFlags(mex,
0247                                                        "TrackStateTypeFlags");
0248   addTrackStateTypeFlags(trackStateTypeFlags);
0249 
0250   py::class_<Acts::ConstTrackStateTypeMap> constTrackStateTypeFlags(
0251       mex, "ConstTrackStateTypeFlags");
0252   addTrackStateTypeFlags(constTrackStateTypeFlags);
0253 
0254   py::class_<Acts::MutableTrackStateTypeMap> mutableTrackStateTypeFlags(
0255       mex, "MutableTrackStateTypeFlags");
0256   addTrackStateTypeFlags(mutableTrackStateTypeFlags);
0257 
0258   py::class_<ConstTrackStateProxy> constTrackState(mex, "ConstTrackStateProxy");
0259   bindTrackStateProxyCommon(constTrackState);
0260   bindTrackStateProxyVector(constTrackState);
0261 
0262   py::class_<TrackStateProxy> trackState(mex, "TrackStateProxy");
0263   bindTrackStateProxyCommon(trackState);
0264   bindTrackStateProxyVector(trackState);
0265 
0266   py::classh<Acts::AnyConstTrackStateProxy> anyConstTrackState(
0267       mex, "AnyConstTrackStateProxy");
0268   bindTrackStateProxyCommon(anyConstTrackState);
0269   anyConstTrackState.def(py::init<ConstTrackStateProxy&>());
0270   py::implicitly_convertible<ConstTrackStateProxy,
0271                              Acts::AnyConstTrackStateProxy>();
0272   // Kept for backwards compatibility with the previous (misspelled) name.
0273   mex.attr("AnyConstTrackState") = mex.attr("AnyConstTrackStateProxy");
0274 
0275   py::classh<Acts::AnyMutableTrackStateProxy> anyMutableTrackState(
0276       mex, "AnyMutableTrackStateProxy");
0277   bindTrackStateProxyCommon(anyMutableTrackState);
0278   anyMutableTrackState.def(py::init<TrackStateProxy&>());
0279   py::implicitly_convertible<TrackStateProxy,
0280                              Acts::AnyMutableTrackStateProxy>();
0281 }
0282 
0283 }  // namespace ActsPython