Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2025-07-01 08:07:58

0001 // This file is part of the Acts project.
0002 //
0003 // Copyright (C) 2022 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 http://mozilla.org/MPL/2.0/.
0008 
0009 /// This file implements the tools for a hough transform.
0010 
0011 #pragma once
0012 #include "Acts/Utilities/Delegate.hpp"
0013 #include "Acts/Utilities/Grid.hpp"
0014 #include "Acts/Utilities/Logger.hpp"
0015 #include "Acts/Utilities/Result.hpp"
0016 
0017 #include <array>
0018 #include <map>
0019 #include <optional>
0020 #include <set>
0021 #include <span>
0022 #include <unordered_set>
0023 
0024 namespace Acts::HoughTransformUtils {
0025 
0026 /// this type is responsible for encoding the parameters of our hough space
0027 using CoordType = double;
0028 
0029 // this type is used to encode hit counts.
0030 // Floating point to allow hit weights to be applied
0031 using YieldType = float;
0032 
0033 /// @brief this function represents a mapping of a coordinate point in detector space to a line in
0034 /// hough space. Given the value of the first hough coordinate, it shall return
0035 /// the corresponding second coordinate according to the line parametrisation.
0036 /// Should be implemented by the user.
0037 /// @tparam PointType: The class representing a point in detector space (can differ between implementations)
0038 template <class PointType>
0039 using LineParametrisation =
0040     std::function<CoordType(CoordType, const PointType&)>;
0041 
0042 /// @brief struct to define the ranges of the hough histogram.
0043 /// Used to move between parameter and bin index coordinates.
0044 /// Disconnected from the hough plane binning to be able to re-use
0045 /// a plane with a given binning for several parameter ranges
0046 struct HoughAxisRanges {
0047   CoordType xMin = 0.0f;  // minimum value of the first coordinate
0048   CoordType xMax = 0.0f;  // maximum value of the first coordinate
0049   CoordType yMin = 0.0f;  // minimum value of the second coordinate
0050   CoordType yMax = 0.0f;  // maximum value of the second coordinate
0051 };
0052 
0053 /// convenience functions to link bin indices to axis coordinates
0054 
0055 /// @brief find the bin index corresponding to a certain abscissa
0056 /// of the coordinate axis, based on the axis limits and binning.
0057 /// @param min: Start of axis range
0058 /// @param max: End of axis range
0059 /// @param nSteps: Number of bins in axis
0060 /// @param val: value to find the corresponding bin for
0061 /// @return the bin number.
0062 /// No special logic to prevent over-/underflow, checking these is
0063 /// left to the caller
0064 inline int binIndex(double min, double max, unsigned nSteps, double val) {
0065   return static_cast<int>((val - min) / (max - min) * nSteps);
0066 }
0067 // Returns the lower bound of the bin specified by step
0068 /// @param min: Start of axis range
0069 /// @param max: End of axis range
0070 /// @param nSteps: Number of bins in axis
0071 /// @param binIndex: The index of the bin
0072 /// @return the parameter value at the lower bin edge.
0073 /// No special logic to prevent over-/underflow, checking these is
0074 /// left to the caller
0075 inline double lowerBinEdge(double min, double max, unsigned nSteps,
0076                            std::size_t binIndex) {
0077   return min + (max - min) * binIndex / nSteps;
0078 }
0079 // Returns the lower bound of the bin specified by step
0080 /// @param min: Start of axis range
0081 /// @param max: End of axis range
0082 /// @param nSteps: Number of bins in axis
0083 /// @param binIndex: The index of the bin
0084 /// @return the parameter value at the bin center.
0085 /// No special logic to prevent over-/underflow, checking these is
0086 /// left to the caller
0087 inline double binCenter(double min, double max, unsigned nSteps,
0088                         std::size_t binIndex) {
0089   return min + (max - min) * 0.5 * (2 * binIndex + 1) / nSteps;
0090 }
0091 
0092 /// @brief data class for the information to store for each
0093 /// cell of the hough histogram.
0094 /// @tparam identifier_t: Type of the identifier to associate to the hits
0095 ///                       Should be sortable. Used to uniquely identify each
0096 ///                       hit and to eventually return the list of hits per cell
0097 template <class identifier_t>
0098 class HoughCell {
0099  public:
0100   /// @brief construct the cell as empty
0101   HoughCell() = default;
0102   /// @brief add an entry to this cell
0103   /// @param identifier: Identifier of the hit (used to distinguish hits from another)
0104   /// @param layer: Layer of the hit (used when counting layers)
0105   /// @param weight: Optional weight to assign to the hit
0106   void fill(const identifier_t& identifier, unsigned int layer,
0107             YieldType weight = 1.);
0108   /// @brief access the number of layers with hits compatible with this cell
0109   YieldType nLayers() const { return m_nLayers; }
0110   /// @brief access the number of unique hits compatible with this cell
0111   YieldType nHits() const { return m_nHits; }
0112   /// @brief access the span of layers compatible with this cell
0113   std::span<const unsigned, std::dynamic_extent> getLayers() const;
0114   // /// @brief access the pan of unique hits compatible with this cell
0115   std::span<const identifier_t, std::dynamic_extent> getHits() const;
0116 
0117   /// @brief reset this cell, removing any existing content.
0118   void reset();
0119 
0120  private:
0121   /// (weighted) number of layers with hits on this cell
0122   YieldType m_nLayers{0};
0123   /// (weighted) number of unique hits on this cell
0124   YieldType m_nHits{0};
0125 
0126   /// index for the hits -- keeps track of vector's size
0127   std::size_t m_iHit{0};
0128   /// index for the layers -- keeps track of vector's size
0129   std::size_t m_iLayer{0};
0130 
0131   /// a batch to resize the vector of the hits or the layers
0132   std::size_t m_assignBatch{20};
0133 
0134   /// vector of layers with hits on this cell
0135   std::vector<unsigned> m_layers{std::vector<unsigned>(m_assignBatch)};
0136 
0137   /// vector of hits on this cell
0138   std::vector<identifier_t> m_hits{std::vector<identifier_t>(m_assignBatch)};
0139 };
0140 
0141 /// @brief Configuration - number of bins in each axis.
0142 /// The Hough plane is agnostic of how the bins map to
0143 /// coordinates, allowing to re-use a plane for several
0144 /// (sub) detectors of different dimensions if the bin number
0145 /// remains applicable
0146 struct HoughPlaneConfig {
0147   std::size_t nBinsX = 0;  // number of bins in the first coordinate
0148   std::size_t nBinsY = 0;  // number of bins in the second coordinate
0149 };
0150 
0151 /// @brief Representation of the hough plane - the histogram used
0152 /// for the hough transform with methods to fill and evaluate
0153 /// the histogram. Templated to a class used as identifier for the hits
0154 template <class identifier_t>
0155 class HoughPlane {
0156  public:
0157   /// @brief hough histogram representation as a 2D-indexable vector of hough cells
0158   using Axis =
0159       Acts::Axis<Acts::AxisType::Equidistant, Acts::AxisBoundaryType::Bound>;
0160   using HoughHist = Grid<HoughCell<identifier_t>, Axis, Axis>;
0161   using Index = typename HoughHist::index_t;
0162 
0163   /// @brief instantiate the (empty) hough plane
0164   /// @param cfg: configuration
0165   HoughPlane(const HoughPlaneConfig& cfg);
0166 
0167   /// fill and reset methods to modify the grid content
0168 
0169   /// @brief add one measurement to the hough plane
0170   /// @tparam PointType: Type of the objects to use when adding measurements (e.g. experiment EDM object)
0171   /// @param measurement: The measurement to add
0172   /// @param axisRanges: Ranges of the hough axes, used to map the bin numbers to parameter values
0173   /// @param linePar: The function y(x) parametrising the hough space line for a given measurement
0174   /// @param widthPar: The function dy(x) parametrising the width of the y(x) curve
0175   ///                   for a given measurement
0176   /// @param identifier: The unique identifier for the given hit
0177   /// @param layer: A layer index for this hit
0178   /// @param weight: An optional weight to assign to this hit
0179   template <class PointType>
0180   void fill(const PointType& measurement, const HoughAxisRanges& axisRanges,
0181             LineParametrisation<PointType> linePar,
0182             LineParametrisation<PointType> widthPar,
0183             const identifier_t& identifier, unsigned layer = 0,
0184             YieldType weight = 1.0f);
0185   /// @brief resets the contents of the grid. Can be used to avoid reallocating the histogram
0186   /// when switching regions / (sub)detectors
0187   void reset();
0188 
0189   //// user-facing accessors
0190 
0191   /// @brief get the layers with hits in one cell of the histogram
0192   /// @param xBin: bin index in the first coordinate
0193   /// @param yBin: bin index in the second coordinate
0194   /// @return the set of layer indices that have hits for this cell
0195   std::unordered_set<unsigned> layers(std::size_t xBin,
0196                                       std::size_t yBin) const {
0197     return m_houghHist.atLocalBins({xBin, yBin}).layers();
0198   }
0199 
0200   /// @brief get the (weighted) number of layers  with hits in one cell of the histogram
0201   /// @param xBin: bin index in the first coordinate
0202   /// @param yBin: bin index in the second coordinate
0203   /// @return the (weighed) number of layers that have hits for this cell
0204   YieldType nLayers(std::size_t xBin, std::size_t yBin) const {
0205     return m_houghHist.atLocalBins({xBin, yBin}).nLayers();
0206   }
0207 
0208   /// @brief get the identifiers of all hits in one cell of the histogram
0209   /// @param xBin: bin index in the first coordinate
0210   /// @param yBin: bin index in the second coordinate
0211   /// @return the set of identifiers of the hits for this cell
0212   std::unordered_set<identifier_t> hitIds(std::size_t xBin,
0213                                           std::size_t yBin) const {
0214     const auto hits_span = m_houghHist.atLocalBins({xBin, yBin}).getHits();
0215 
0216     return std::unordered_set<identifier_t>(hits_span.begin(), hits_span.end());
0217   }
0218   /// @brief access the (weighted) number of hits in one cell of the histogram from bin's coordinates
0219   /// @param xBin: bin index in the first coordinate
0220   /// @param yBin: bin index in the second coordinate
0221   /// @return the (weighted) number of hits for this cell
0222   YieldType nHits(std::size_t xBin, std::size_t yBin) const {
0223     return m_houghHist.atLocalBins({xBin, yBin}).nHits();
0224   }
0225 
0226   /// @brief access the (weighted) number of hits in one cell of the histogram from globalBin index
0227   /// @param globalBin: global bin index
0228   /// @return the (weighted) number of hits for this cell
0229   YieldType nHits(std::size_t globalBin) const {
0230     return m_houghHist.at(globalBin).nHits();
0231   }
0232 
0233   /// @brief get the number of bins on the first coordinate
0234   std::size_t nBinsX() const { return m_cfg.nBinsX; }
0235   /// @brief get the number of bins on the second coordinate
0236   std::size_t nBinsY() const { return m_cfg.nBinsY; }
0237 
0238   /// @brief get the maximum number of (weighted) hits seen in a single
0239   /// cell across the entire histrogram.
0240   YieldType maxHits() const { return m_maxHits; }
0241 
0242   /// @brief get the list of cells with non-zero content.
0243   /// Useful for peak-finders in sparse data
0244   /// to avoid looping over all cells
0245   const std::unordered_set<std::size_t>& getNonEmptyBins() const {
0246     return m_touchedBins;
0247   }
0248 
0249   /// @brief get the coordinates of the bin given the global bin index
0250   Index axisBins(std::size_t globalBin) const {
0251     return m_houghHist.localBinsFromGlobalBin(globalBin);
0252   }
0253 
0254   /// @brief get the globalBin index given the coordinates of the bin
0255   std::size_t globalBin(Index indexBin) const {
0256     return m_houghHist.globalBinFromLocalBins(indexBin);
0257   }
0258 
0259   /// @brief get the bin indices of the cell containing the largest number
0260   /// of (weighted) hits across the entire histogram
0261   std::pair<std::size_t, std::size_t> locMaxHits() const {
0262     return m_maxLocHits;
0263   }
0264 
0265   /// @brief get the maximum number of (weighted) layers with hits  seen
0266   /// in a single cell across the entire histrogram.
0267   YieldType maxLayers() const { return m_maxLayers; }
0268 
0269   /// @brief get the bin indices of the cell containing the largest number
0270   /// of (weighted) layers with hits across the entire histogram
0271   std::pair<std::size_t, std::size_t> locMaxLayers() const {
0272     return m_maxLocLayers;
0273   }
0274 
0275  private:
0276   /// @brief Helper method to fill a bin of the hough histogram.
0277   /// Updates the internal helper data structures (maximum tracker etc).
0278   /// @param binX: bin number along x
0279   /// @param binY: bin number along y
0280   /// @param identifier: hit identifier
0281   /// @param layer: layer index
0282   /// @param w: optional hit weight
0283   void fillBin(std::size_t binX, std::size_t binY,
0284                const identifier_t& identifier, unsigned layer, double w = 1.0f);
0285 
0286   YieldType m_maxHits = 0.0f;    // track the maximum number of hits seen
0287   YieldType m_maxLayers = 0.0f;  // track the maximum number of layers seen
0288 
0289   /// track the location of the maximum in hits
0290   std::pair<std::size_t, std::size_t> m_maxLocHits = {0, 0};
0291   /// track the location of the maximum in layers
0292   std::pair<std::size_t, std::size_t> m_maxLocLayers = {0, 0};
0293 
0294   std::size_t m_assignBatch{20};
0295 
0296   /// track the bins with non-trivial content
0297   std::unordered_set<std::size_t> m_touchedBins{};
0298 
0299   std::size_t m_iBin = 0;
0300 
0301   HoughPlaneConfig m_cfg;  // the configuration object
0302   HoughHist m_houghHist;   // the histogram data object
0303 };
0304 
0305 /// example peak finders.
0306 namespace PeakFinders {
0307 /// configuration for the LayerGuidedCombinatoric peak finder
0308 struct LayerGuidedCombinatoricConfig {
0309   YieldType threshold = 3.0f;  // min number of layers to obtain a maximum
0310   int localMaxWindowSize = 0;  // Only create candidates from a local maximum
0311 };
0312 
0313 /// @brief Peak finder inspired by ATLAS ITk event filter developments.
0314 /// Builds peaks based on layer counts and allows for subsequent resolution
0315 /// of the combinatorics by building multiple candidates per peak if needed.
0316 /// In flat regions, peak positions are moved towards smaller values of the
0317 /// second and first coordinate.
0318 /// @tparam identifier_t: The identifier type to use. Should match the one used in the hough plane.
0319 template <class identifier_t>
0320 class LayerGuidedCombinatoric {
0321  public:
0322   /// @brief data class representing the found maxima.
0323   /// Here, we just have a list of cluster identifiers
0324   struct Maximum {
0325     std::unordered_set<identifier_t> hitIdentifiers =
0326         {};  // identifiers of contributing hits
0327   };
0328   /// @brief constructor
0329   /// @param cfg: Configuration object
0330   LayerGuidedCombinatoric(const LayerGuidedCombinatoricConfig& cfg);
0331 
0332   /// @brief main peak finder method.
0333   /// @param plane: Filled hough plane to search
0334   /// @return vector of found maxima
0335   std::vector<Maximum> findPeaks(const HoughPlane<identifier_t>& plane) const;
0336 
0337  private:
0338   /// @brief check if a given bin is a local maximum.
0339   /// @param plane: The filled hough plane
0340   /// @param xBin: x bin index
0341   /// @param yBin: y bin index
0342   /// @return true if a maximum, false otherwise
0343   bool passThreshold(const HoughPlane<identifier_t>& plane, std::size_t xBin,
0344                      std::size_t yBin) const;  // did we pass extensions?
0345 
0346   LayerGuidedCombinatoricConfig m_cfg;  // configuration data object
0347 };
0348 /// @brief Configuration for the IslandsAroundMax peak finder
0349 struct IslandsAroundMaxConfig {
0350   YieldType threshold =
0351       3.0f;  // min number of weigted hits required in a maximum
0352   YieldType fractionCutoff =
0353       0;  // Fraction of the global maximum at which to cut off maxima
0354   std::pair<CoordType, CoordType> minSpacingBetweenPeaks = {
0355       0.0f, 0.0f};  // minimum distance of a new peak from existing peaks in
0356                     // parameter space
0357 };
0358 /// @brief Peak finder inspired by ATLAS muon reconstruction.
0359 /// Looks for regions above a given fraction of the global maximum
0360 /// hit count and connects them into islands comprising adjacent bins
0361 /// above the threshold. Peak positions are averaged across cells in the island,
0362 /// weighted by hit counts
0363 /// @tparam identifier_t: The identifier type to use. Should match the one used in the hough plane.
0364 template <class identifier_t>
0365 class IslandsAroundMax {
0366  public:
0367   /// @brief data struct representing a local maximum.
0368   /// Comes with a position estimate and a list of hits within the island
0369   struct Maximum {
0370     CoordType x = 0;   // x value of the maximum
0371     CoordType y = 0;   // y value of the maximum
0372     CoordType wx = 0;  // x width of the maximum
0373     CoordType wy = 0;  // y width of the maximum
0374     std::unordered_set<identifier_t> hitIdentifiers =
0375         {};  // identifiers of contributing hits
0376   };
0377   /// @brief constructor.
0378   /// @param cfg: configuration object
0379   IslandsAroundMax(const IslandsAroundMaxConfig& cfg);
0380 
0381   /// @brief main peak finder method.
0382   /// @param plane: The filled hough plane to search
0383   /// @param ranges: The axis ranges used for mapping between parameter space and bins.
0384   /// @return List of the found maxima
0385   std::vector<Maximum> findPeaks(const HoughPlane<identifier_t>& plane,
0386                                  const HoughAxisRanges& ranges);
0387 
0388  private:
0389   /// @brief method to incrementally grow an island by adding adjacent cells
0390   /// Performs a breadth-first search for neighbours above threshold and adds
0391   /// them to candidate. Stops when no suitable neighbours are left.
0392   /// @param houghPlane: The current hough Plane we are looking for maxima
0393   /// @param inMaximum: List of cells found in the island. Incrementally populated by calls to the method
0394   /// @param toExplore: List of the global Bin indices of neighbour cell candidates left to explore. Method will not do anything once this is empty
0395   /// @param threshold: the threshold to apply to check if a cell should be added to an island
0396   /// @param yieldMap: A map of the hit content of above-threshold cells. Used cells will be set to empty content to avoid re-use by subsequent calls
0397   void extendMaximum(const HoughPlane<identifier_t>& houghPlane,
0398                      std::vector<std::array<std::size_t, 2>>& inMaximum,
0399                      std::vector<std::size_t>& toExplore, YieldType threshold,
0400                      std::unordered_map<std::size_t, YieldType>& yieldMap);
0401 
0402   IslandsAroundMaxConfig m_cfg;  // configuration data object
0403 
0404   /// @brief array of steps to consider when exploring neighbouring cells.
0405   const std::array<std::pair<int, int>, 8> m_stepDirections{
0406       std::make_pair(-1, -1), std::make_pair(0, -1), std::make_pair(1, -1),
0407       std::make_pair(-1, 0),  std::make_pair(1, 0),  std::make_pair(-1, 1),
0408       std::make_pair(0, 1),   std::make_pair(1, 1)};
0409 };
0410 }  // namespace PeakFinders
0411 }  // namespace Acts::HoughTransformUtils
0412 
0413 #include "HoughTransformUtils.ipp"