Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2025-10-23 08:23:18

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