Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2025-12-17 09:21: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 "ActsExamples/EventData/NeuralCalibrator.hpp"
0010 
0011 #include "Acts/Definitions/TrackParametrization.hpp"
0012 #include "Acts/EventData/MeasurementHelpers.hpp"
0013 #include "Acts/EventData/SourceLink.hpp"
0014 #include "Acts/Utilities/CalibrationContext.hpp"
0015 #include "Acts/Utilities/Helpers.hpp"
0016 #include "Acts/Utilities/UnitVectors.hpp"
0017 #include "Acts/Utilities/detail/EigenCompat.hpp"
0018 #include "ActsExamples/EventData/IndexSourceLink.hpp"
0019 #include "ActsExamples/EventData/Measurement.hpp"
0020 
0021 #include <TFile.h>
0022 
0023 using namespace Acts;
0024 using namespace ActsPlugins;
0025 
0026 namespace detail {
0027 
0028 template <typename Array>
0029 std::size_t fillChargeMatrix(Array& arr, const ActsExamples::Cluster& cluster,
0030                              std::size_t size0 = 7u, std::size_t size1 = 7u) {
0031   // First, rescale the activations to sum to unity. This promotes
0032   // numerical stability in the index computation
0033   double totalAct = 0;
0034   for (const ActsExamples::Cluster::Cell& cell : cluster.channels) {
0035     totalAct += cell.activation;
0036   }
0037   std::vector<double> weights;
0038   for (const ActsExamples::Cluster::Cell& cell : cluster.channels) {
0039     weights.push_back(cell.activation / totalAct);
0040   }
0041 
0042   double acc0 = 0;
0043   double acc1 = 0;
0044   for (std::size_t i = 0; i < cluster.channels.size(); i++) {
0045     acc0 += cluster.channels.at(i).bin[0] * weights.at(i);
0046     acc1 += cluster.channels.at(i).bin[1] * weights.at(i);
0047   }
0048 
0049   // By convention, put the center pixel in the middle cell.
0050   // Achieved by translating the cluster --> compute the offsets
0051   int offset0 = static_cast<int>(acc0) - size0 / 2;
0052   int offset1 = static_cast<int>(acc1) - size1 / 2;
0053 
0054   // Zero the charge matrix first, to guard against leftovers
0055   arr = Eigen::ArrayXXf::Zero(1, size0 * size1);
0056   // Fill the matrix
0057   for (const ActsExamples::Cluster::Cell& cell : cluster.channels) {
0058     // Translate each pixel
0059     int iMat = cell.bin[0] - offset0;
0060     int jMat = cell.bin[1] - offset1;
0061     if (iMat >= 0 && iMat < static_cast<int>(size0) && jMat >= 0 &&
0062         jMat < static_cast<int>(size1)) {
0063       typename Array::Index index = iMat * size0 + jMat;
0064       if (index < arr.size()) {
0065         arr(index) = cell.activation;
0066       }
0067     }
0068   }
0069   return size0 * size1;
0070 }
0071 
0072 }  // namespace detail
0073 
0074 ActsExamples::NeuralCalibrator::NeuralCalibrator(
0075     const std::filesystem::path& modelPath, std::size_t nComponents,
0076     std::vector<std::size_t> volumeIds)
0077     : m_env(ORT_LOGGING_LEVEL_WARNING, "NeuralCalibrator"),
0078       m_model(m_env, modelPath.c_str()),
0079       m_nComponents{nComponents},
0080       m_volumeIds{std::move(volumeIds)} {}
0081 
0082 void ActsExamples::NeuralCalibrator::calibrate(
0083     const MeasurementContainer& measurements, const ClusterContainer* clusters,
0084     const GeometryContext& gctx, const CalibrationContext& cctx,
0085     const SourceLink& sourceLink,
0086     MultiTrajectory<VectorMultiTrajectory>::TrackStateProxy& trackState) const {
0087   trackState.setUncalibratedSourceLink(SourceLink{sourceLink});
0088   const IndexSourceLink& idxSourceLink = sourceLink.get<IndexSourceLink>();
0089   assert((idxSourceLink.index() < measurements.size()) and
0090          "Source link index is outside the container bounds");
0091 
0092   if (!rangeContainsValue(m_volumeIds, idxSourceLink.geometryId().volume())) {
0093     m_fallback.calibrate(measurements, clusters, gctx, cctx, sourceLink,
0094                          trackState);
0095     return;
0096   }
0097 
0098   NetworkBatchInput inputBatch(1, m_nInputs);
0099   auto input = inputBatch(0, Acts::detail::EigenCompat::all);
0100 
0101   // TODO: Matrix size should be configurable perhaps?
0102   std::size_t matSize0 = 7u;
0103   std::size_t matSize1 = 7u;
0104   std::size_t iInput = ::detail::fillChargeMatrix(
0105       input, (*clusters)[idxSourceLink.index()], matSize0, matSize1);
0106 
0107   input[iInput++] = idxSourceLink.geometryId().volume();
0108   input[iInput++] = idxSourceLink.geometryId().layer();
0109 
0110   const Surface& referenceSurface = trackState.referenceSurface();
0111   auto trackParameters = trackState.parameters();
0112 
0113   const ConstVariableBoundMeasurementProxy measurement =
0114       measurements.getMeasurement(idxSourceLink.index());
0115 
0116   assert(measurement.contains(eBoundLoc0) &&
0117          "Measurement does not contain the required bound loc0");
0118   assert(measurement.contains(eBoundLoc1) &&
0119          "Measurement does not contain the required bound loc1");
0120 
0121   auto boundLoc0 = measurement.indexOf(eBoundLoc0);
0122   auto boundLoc1 = measurement.indexOf(eBoundLoc1);
0123 
0124   Vector2 localPosition{measurement.parameters()[boundLoc0],
0125                         measurement.parameters()[boundLoc1]};
0126   Vector2 localCovariance{measurement.covariance()(boundLoc0, boundLoc0),
0127                           measurement.covariance()(boundLoc1, boundLoc1)};
0128 
0129   Vector3 dir = makeDirectionFromPhiTheta(trackParameters[eBoundPhi],
0130                                           trackParameters[eBoundTheta]);
0131   Vector3 globalPosition =
0132       referenceSurface.localToGlobal(gctx, localPosition, dir);
0133 
0134   // Rotation matrix. When applied to global coordinates, they
0135   // are rotated into the local reference frame of the
0136   // surface. Note that this such a rotation can be found by
0137   // inverting a matrix whose columns correspond to the
0138   // coordinate axes of the local coordinate system.
0139   RotationMatrix3 rot =
0140       referenceSurface.referenceFrame(gctx, globalPosition, dir).inverse();
0141   std::pair<double, double> angles = VectorHelpers::incidentAngles(dir, rot);
0142 
0143   input[iInput++] = angles.first;
0144   input[iInput++] = angles.second;
0145   input[iInput++] = localPosition[0];
0146   input[iInput++] = localPosition[1];
0147   input[iInput++] = localCovariance[0];
0148   input[iInput++] = localCovariance[1];
0149   if (iInput != m_nInputs) {
0150     throw std::runtime_error("Expected input size of " +
0151                              std::to_string(m_nInputs) +
0152                              ", got: " + std::to_string(iInput));
0153   }
0154 
0155   // Input is a single row, hence .front()
0156   std::vector<float> output = m_model.runONNXInference(inputBatch).front();
0157   // Assuming 2-D measurements, the expected params structure is:
0158   // [           0,    nComponent[ --> priors
0159   // [  nComponent,  3*nComponent[ --> means
0160   // [3*nComponent,  5*nComponent[ --> variances
0161   std::size_t nParams = 5 * m_nComponents;
0162   if (output.size() != nParams) {
0163     throw std::runtime_error("Got output vector of size " +
0164                              std::to_string(output.size()) +
0165                              ", expected size " + std::to_string(nParams));
0166   }
0167 
0168   // Most probable value computation of mixture density
0169   std::size_t iMax = 0;
0170   if (m_nComponents > 1) {
0171     iMax = std::distance(
0172         output.begin(),
0173         std::max_element(output.begin(), output.begin() + m_nComponents));
0174   }
0175   std::size_t iLoc0 = m_nComponents + iMax * 2;
0176   std::size_t iVar0 = 3 * m_nComponents + iMax * 2;
0177 
0178   visit_measurement(measurement.size(), [&](auto N) -> void {
0179     constexpr std::size_t kMeasurementSize = decltype(N)::value;
0180     const ConstFixedBoundMeasurementProxy<kMeasurementSize> fixedMeasurement =
0181         static_cast<ConstFixedBoundMeasurementProxy<kMeasurementSize>>(
0182             measurement);
0183 
0184     ActsVector<kMeasurementSize> calibratedParameters =
0185         fixedMeasurement.parameters();
0186     ActsSquareMatrix<kMeasurementSize> calibratedCovariance =
0187         fixedMeasurement.covariance();
0188 
0189     calibratedParameters[boundLoc0] = output[iLoc0];
0190     calibratedParameters[boundLoc1] = output[iLoc0 + 1];
0191     calibratedCovariance(boundLoc0, boundLoc0) = output[iVar0];
0192     calibratedCovariance(boundLoc1, boundLoc1) = output[iVar0 + 1];
0193 
0194     trackState.allocateCalibrated(calibratedParameters, calibratedCovariance);
0195     trackState.setProjectorSubspaceIndices(fixedMeasurement.subspaceIndices());
0196   });
0197 }