From 94c3839a32720c9418f8e9616bacaa0c9ae27c75 Mon Sep 17 00:00:00 2001 From: ssdetlab Date: Wed, 6 Nov 2024 23:06:43 +0200 Subject: [PATCH 01/23] add lookup generation examples --- .../Algorithms/TrackFinding/CMakeLists.txt | 2 + .../TrackFinding/ITrackParamsLookupReader.hpp | 27 ++++ .../TrackFinding/ITrackParamsLookupWriter.hpp | 28 +++++ .../TrackParamsLookupAccumulator.hpp | 65 ++++++++++ .../TrackParamsLookupEstimation.hpp | 76 ++++++++++++ .../TrackFinding/TrackParamsLookupTable.hpp | 61 ++++++++++ .../src/TrackParamsLookupAccumulator.cpp | 76 ++++++++++++ .../src/TrackParamsLookupEstimation.cpp | 115 ++++++++++++++++++ .../Io/Json/JsonTrackParamsLookupReader.hpp | 101 +++++++++++++++ .../Io/Json/JsonTrackParamsLookupWriter.hpp | 73 +++++++++++ Examples/Python/src/Json.cpp | 58 +++++++++ Examples/Python/src/Output.cpp | 12 ++ Examples/Python/src/TrackFinding.cpp | 6 + ...elescope_track_params_lookup_generation.py | 107 ++++++++++++++++ 14 files changed, 807 insertions(+) create mode 100644 Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/ITrackParamsLookupReader.hpp create mode 100644 Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/ITrackParamsLookupWriter.hpp create mode 100644 Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/TrackParamsLookupAccumulator.hpp create mode 100644 Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/TrackParamsLookupEstimation.hpp create mode 100644 Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/TrackParamsLookupTable.hpp create mode 100644 Examples/Algorithms/TrackFinding/src/TrackParamsLookupAccumulator.cpp create mode 100644 Examples/Algorithms/TrackFinding/src/TrackParamsLookupEstimation.cpp create mode 100644 Examples/Io/Json/include/ActsExamples/Io/Json/JsonTrackParamsLookupReader.hpp create mode 100644 Examples/Io/Json/include/ActsExamples/Io/Json/JsonTrackParamsLookupWriter.hpp create mode 100644 Examples/Scripts/Python/telescope_track_params_lookup_generation.py diff --git a/Examples/Algorithms/TrackFinding/CMakeLists.txt b/Examples/Algorithms/TrackFinding/CMakeLists.txt index 38781494068..733ed6d2d7b 100644 --- a/Examples/Algorithms/TrackFinding/CMakeLists.txt +++ b/Examples/Algorithms/TrackFinding/CMakeLists.txt @@ -10,6 +10,8 @@ add_library( src/TrackParamsEstimationAlgorithm.cpp src/MuonHoughSeeder.cpp src/GbtsSeedingAlgorithm.cpp + src/TrackParamsLookupAccumulator.cpp + src/TrackParamsLookupEstimation.cpp ) target_include_directories( diff --git a/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/ITrackParamsLookupReader.hpp b/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/ITrackParamsLookupReader.hpp new file mode 100644 index 00000000000..9d993fa8197 --- /dev/null +++ b/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/ITrackParamsLookupReader.hpp @@ -0,0 +1,27 @@ +// This file is part of the ACTS project. +// +// Copyright (C) 2016 CERN for the benefit of the ACTS project +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +#pragma once + +#include "ActsExamples/TrackFinding/TrackParamsLookupTable.hpp" + +namespace ActsExamples { + +/// @brief Interface for reading track parameter lookup tables +class ITrackParamsLookupReader { + public: + /// Virtual Destructor + virtual ~ITrackParamsLookupReader() = default; + + /// Reader method + /// + /// @param path the path to the file to read + virtual Lookup readLookup(const std::string& path) = 0; +}; + +} // namespace ActsExamples diff --git a/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/ITrackParamsLookupWriter.hpp b/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/ITrackParamsLookupWriter.hpp new file mode 100644 index 00000000000..40334704785 --- /dev/null +++ b/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/ITrackParamsLookupWriter.hpp @@ -0,0 +1,28 @@ +// This file is part of the ACTS project. +// +// Copyright (C) 2016 CERN for the benefit of the ACTS project +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +#pragma once + +#include "ActsExamples/TrackFinding/TrackParamsLookupTable.hpp" + +namespace ActsExamples { + +/// @brief Interface for writing track parameter lookup tables +class ITrackParamsLookupWriter { + public: + /// Virtual Destructor + virtual ~ITrackParamsLookupWriter() = default; + + /// Writer method + /// + /// @param lookup track lookup to write + virtual void writeLookup( + const Lookup& lookup) = 0; +}; + +} // namespace ActsExamples diff --git a/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/TrackParamsLookupAccumulator.hpp b/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/TrackParamsLookupAccumulator.hpp new file mode 100644 index 00000000000..55b2f29d130 --- /dev/null +++ b/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/TrackParamsLookupAccumulator.hpp @@ -0,0 +1,65 @@ +// This file is part of the ACTS project. +// +// Copyright (C) 2016 CERN for the benefit of the ACTS project +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +#pragma once + +#include "ActsExamples/TrackFinding/TrackParamsLookupTable.hpp" + +namespace ActsExamples { + +/// @brief Class to accumulate and average track lookup tables +/// +/// This class is used to accumulate track parameters in +/// reference layer grids and average them to create a lookup +/// table for track parameter estimation in seeding +class TrackParamsLookupAccumulator { + public: + /// @brief Nested configuration struct + struct Config { + /// Axis generator + LookupAxisGen axisGen; + }; + + /// @brief Constructor + TrackParamsLookupAccumulator(const Config& config) + : m_cfg(std::move(config)), + m_ipGrid(m_cfg.axisGen()), + m_refGrid(m_cfg.axisGen()) {} + + /// @brief Add track parameters to the accumulator + /// + /// @param ipTrackParameters the track parameters at the IP + /// @param refTrackParameters the track parameters at the reference layer + /// @param position local position of the track hit on the reference layer + void addTrack( + const Acts::CurvilinearTrackParameters& ipTrackParameters, + const Acts::CurvilinearTrackParameters& refTrackParameters, + const Acts::Vector2& position); + + /// @brief Finalize the lookup table + /// + /// Return the grid with the bin track parameters averaged + LookupGrid finalizeLookup(); + + /// Get readonly access to the config parameters + const Config& config() const { return m_cfg; } + + private: + /// Configuration + Config m_cfg; + + /// Mutex for modifying the grid + std::mutex m_writeMutex; + + /// Grids to accumulate IP and reference + /// layer track parameters + LookupAccumGrid m_ipGrid; + LookupAccumGrid m_refGrid; +}; + +} // namespace ActsExamples diff --git a/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/TrackParamsLookupEstimation.hpp b/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/TrackParamsLookupEstimation.hpp new file mode 100644 index 00000000000..d75146ddaf4 --- /dev/null +++ b/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/TrackParamsLookupEstimation.hpp @@ -0,0 +1,76 @@ +// This file is part of the ACTS project. +// +// Copyright (C) 2016 CERN for the benefit of the ACTS project +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +#pragma once + +#include "ActsExamples/EventData/SimHit.hpp" +#include "ActsExamples/EventData/SimParticle.hpp" +#include "ActsExamples/Framework/IAlgorithm.hpp" +#include "ActsExamples/Framework/DataHandle.hpp" +#include "ActsExamples/TrackFinding/ITrackParamsLookupWriter.hpp" +#include "ActsExamples/TrackFinding/TrackParamsLookupAccumulator.hpp" + +namespace ActsExamples { + +/// @brief Algorithm to estimate track parameters lookup tables +/// +/// This algorithm is used to estimate track parameters lookup tables +/// for track parameter estimation in seeding. The algorithm imposes +/// grids onto the reference tracking layers and accumulates track +/// parameters in the grid bins. The track parameters are then averaged +/// to create a lookup table for track parameter estimation in seeding. +class TrackParamsLookupEstimation : public IAlgorithm { + public: + /// @brief Nested configuration struct + struct Config { + /// Reference tracking layers + std::unordered_map< + Acts::GeometryIdentifier, + const Acts::Surface*> refLayers; + /// Binning of the grid to be emposed + /// onto the reference layers + std::pair bins; + /// Input SimHit container + std::string inputHits = "InputHits"; + /// Input SimParticle container + std::string inputParticles = "InputParticles"; + /// Track lookup writers + std::vector> + trackLookupGridWriters{}; + }; + + /// @brief Constructor + TrackParamsLookupEstimation( + const Config& config, Acts::Logging::Level level); + + /// @brief Destructor + ~TrackParamsLookupEstimation(); + + /// @brief The execute method + ProcessCode execute(const AlgorithmContext& ctx) const override; + + /// Get readonly access to the config parameters + const Config& config() const { return m_cfg; } + + private: + /// Configuration + Config m_cfg; + + /// Input data handles + ReadDataHandle m_inputParticles{ + this, + "InputSimParticles"}; + + ReadDataHandle m_inputSimHits{this, "InputSimHits"}; + + /// Accumulators for the track parameters + std::unordered_map> m_accumulators; +}; + +} // namespace ActsExamples diff --git a/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/TrackParamsLookupTable.hpp b/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/TrackParamsLookupTable.hpp new file mode 100644 index 00000000000..39548277424 --- /dev/null +++ b/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/TrackParamsLookupTable.hpp @@ -0,0 +1,61 @@ +// This file is part of the ACTS project. +// +// Copyright (C) 2016 CERN for the benefit of the ACTS project +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +#pragma once + +#include "Acts/EventData/TrackParameters.hpp" +#include "Acts/Utilities/Axis.hpp" +#include "Acts/Utilities/Grid.hpp" +#include "Acts/Utilities/GridAxisGenerators.hpp" + +namespace ActsExamples { + +/// @brief Track parameters lookup table axis used +/// in the track estimation algorithm +using LookupAxis = + Acts::Axis< + Acts::AxisType::Equidistant, + Acts::AxisBoundaryType::Open>; + +/// @brief Track parameters lookup table axis generator +/// used in the track estimation algorithm +using LookupAxisGen = + Acts::GridAxisGenerators::EqOpenEqOpen; + +/// @brief Grid used to accumulate IP track parameters and +/// reference layer track parameters for a given position +/// in the track estimation algorithm +using LookupAccumGrid = + Acts::Grid< + std::vector, + LookupAxis, + LookupAxis>; + +/// @brief Container for the lookup accumulation grids to +/// handle multiple reference layers in the track estimation +using LookupAccumGridContainer = + std::unordered_map< + Acts::GeometryIdentifier, LookupAccumGrid>; + +/// @brief IP-reference layer track parameters lookup pair +using LookupPair = std::pair< + std::shared_ptr, + std::shared_ptr>; + +/// @brief Lookup grid for track parameters estimation +/// in a given layer +using LookupGrid = + Acts::Grid; + +/// @brief Lookup table for track parameters estimation +/// in the track estimation algorithm +using Lookup = + std::unordered_map< + Acts::GeometryIdentifier, LookupGrid>; + +} // namespace ActsExamples diff --git a/Examples/Algorithms/TrackFinding/src/TrackParamsLookupAccumulator.cpp b/Examples/Algorithms/TrackFinding/src/TrackParamsLookupAccumulator.cpp new file mode 100644 index 00000000000..e1084e0f8cc --- /dev/null +++ b/Examples/Algorithms/TrackFinding/src/TrackParamsLookupAccumulator.cpp @@ -0,0 +1,76 @@ +// This file is part of the ACTS project. +// +// Copyright (C) 2016 CERN for the benefit of the ACTS project +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +#include "ActsExamples/TrackFinding/TrackParamsLookupAccumulator.hpp" + +#include "Acts/Utilities/Grid.hpp" +#include "Acts/Utilities/GridIterator.hpp" +#include "Acts/EventData/TrackParameters.hpp" + +void ActsExamples::TrackParamsLookupAccumulator::addTrack( + const Acts::CurvilinearTrackParameters& ipTrackParameters, + const Acts::CurvilinearTrackParameters& refTrackParameters, + const Acts::Vector2& position) { + // Lock the write mutex + std::lock_guard lock(m_writeMutex); + + // Get the local bins from the position + auto bin = m_ipGrid.localBinsFromPosition(position); + + // Add the track parameters to the grid + m_ipGrid.atLocalBins(bin).push_back(ipTrackParameters); + m_refGrid.atLocalBins(bin).push_back(refTrackParameters); +} + +ActsExamples::LookupGrid +ActsExamples::TrackParamsLookupAccumulator::finalizeLookup() { + // Average track parameters in a given bin + auto meanTrack = [](const std::vector& tracks) { + Acts::Vector4 fourPosition = Acts::Vector4::Zero(); + Acts::Vector3 direction = Acts::Vector3::Zero(); + Acts::ActsScalar qOverP = 0; + for (const auto& track : tracks) { + fourPosition += track.fourPosition(); + direction += track.direction(); + qOverP += track.qOverP(); + } + fourPosition /= tracks.size(); + direction /= tracks.size(); + qOverP /= tracks.size(); + + return Acts::CurvilinearTrackParameters( + fourPosition, + direction, + qOverP, + std::nullopt, + tracks.front().particleHypothesis()); + }; + + // Create a lookup grid with the same parameters as + // the accumulation grids + ActsExamples::LookupGrid lookupGrid(m_cfg.axisGen()); + + // Iterate over the bins and average the track parameters + for (auto it = m_ipGrid.begin(); it != m_ipGrid.end(); ++it) { + auto bin = it.localBinsIndices(); + if (m_ipGrid.atLocalBins(bin).empty() || + m_refGrid.atLocalBins(bin).empty()) { + continue; + } + + // Store the IP-reference-position correspondence + lookupGrid.atLocalBins(bin) = + std::make_pair( + std::make_shared( + meanTrack(m_ipGrid.atLocalBins(bin))), + std::make_shared( + meanTrack(m_refGrid.atLocalBins(bin)))); + } + + return lookupGrid; +} diff --git a/Examples/Algorithms/TrackFinding/src/TrackParamsLookupEstimation.cpp b/Examples/Algorithms/TrackFinding/src/TrackParamsLookupEstimation.cpp new file mode 100644 index 00000000000..b93821ee134 --- /dev/null +++ b/Examples/Algorithms/TrackFinding/src/TrackParamsLookupEstimation.cpp @@ -0,0 +1,115 @@ +// This file is part of the ACTS project. +// +// Copyright (C) 2016 CERN for the benefit of the ACTS project +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +#include "ActsExamples/TrackFinding/TrackParamsLookupEstimation.hpp" + +#include "Acts/EventData/SourceLink.hpp" +#include "Acts/Surfaces/RectangleBounds.hpp" + +ActsExamples::TrackParamsLookupEstimation::TrackParamsLookupEstimation( + const Config& config, Acts::Logging::Level level) + : IAlgorithm("TrackParamsLookupEstimation", level), + m_cfg(std::move(config)) { + // Iterate over the reference layers and create + // track parameter accumulators + for (const auto& [geoId, refSurface] : m_cfg.refLayers) { + // Get bounds to construct the accumulator grid + auto bounds = + dynamic_cast( + &refSurface->bounds()); + + if (bounds == nullptr) { + throw std::invalid_argument("Only rectangle bounds supported"); + } + + // Initialize the accumulator grid + auto halfX = bounds->halfLengthX(); + auto halfY = bounds->halfLengthY(); + + LookupAxisGen axisGen{ + {-halfX, halfX}, m_cfg.bins.first, + {-halfY, halfY}, m_cfg.bins.second}; + + TrackParamsLookupAccumulator::Config accConfig{ + axisGen}; + + // Each reference layer has its own accumulator + m_accumulators[geoId] = + std::make_unique(accConfig); + } + + m_inputParticles.initialize(m_cfg.inputParticles); + m_inputSimHits.initialize(m_cfg.inputHits); +} + +ActsExamples::TrackParamsLookupEstimation::~TrackParamsLookupEstimation() { + // Finiliaze the lookup tables and write them + ActsExamples::Lookup lookup; + for (auto& [id, acc] : m_accumulators) { + lookup.insert({id, acc->finalizeLookup()}); + } + for (auto& writer : m_cfg.trackLookupGridWriters) { + writer->writeLookup(lookup); + } +}; + +ActsExamples::ProcessCode +ActsExamples::TrackParamsLookupEstimation::execute( + const ActsExamples::AlgorithmContext& ctx) const { + // Get the particles and hits + const auto& particles = m_inputParticles(ctx); + const auto& hits = m_inputSimHits(ctx); + + // Iterate over the reference layer hits and + // accumulate the track parameters + for (const auto& [geoId, refSurface] : m_cfg.refLayers) { + // Get reference layer hits + auto refLayerHits = hits.equal_range( + geoId); + + for (auto hit = refLayerHits.first; hit != refLayerHits.second; ++hit) { + // Get the corresponding particle + const auto& id = hit->particleId(); + const auto& particle = particles.find(id); + + if (particle == particles.end()) { + throw std::invalid_argument("Particle not found"); + } + + // Hit stores the reference layer parameters + auto refLayerPars = Acts::CurvilinearTrackParameters( + hit->fourPosition(), + hit->direction(), + particle->qOverP(), + std::nullopt, + particle->hypothesis()); + + // Particle stores the IP parameters + auto ipPars = Acts::CurvilinearTrackParameters( + particle->fourPosition(), + particle->direction(), + particle->qOverP(), + std::nullopt, + particle->hypothesis()); + + // Get the local position of the hit + auto localPos = refSurface->globalToLocal( + ctx.geoContext, + hit->position(), + Acts::Vector3{0, 1, 0}).value(); + + // Add the track parameters to the accumulator grid + m_accumulators.at(geoId)->addTrack( + ipPars, + refLayerPars, + localPos); + } + } + + return ActsExamples::ProcessCode::SUCCESS; +} diff --git a/Examples/Io/Json/include/ActsExamples/Io/Json/JsonTrackParamsLookupReader.hpp b/Examples/Io/Json/include/ActsExamples/Io/Json/JsonTrackParamsLookupReader.hpp new file mode 100644 index 00000000000..c9665b3278a --- /dev/null +++ b/Examples/Io/Json/include/ActsExamples/Io/Json/JsonTrackParamsLookupReader.hpp @@ -0,0 +1,101 @@ +// This file is part of the ACTS project. +// +// Copyright (C) 2016 CERN for the benefit of the ACTS project +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +#pragma once + +#include "Acts/Definitions/Algebra.hpp" +#include "Acts/Plugins/Json/ActsJson.hpp" +#include "Acts/Plugins/Json/GridJsonConverter.hpp" +#include "Acts/Plugins/Json/TrackParametersJsonConverter.hpp" +#include "ActsExamples/TrackFinding/ITrackParamsLookupReader.hpp" +#include "Acts/Surfaces/RectangleBounds.hpp" +#include "Acts/Utilities/GridAxisGenerators.hpp" + +#include +#include + +#include + +namespace ActsExamples { + +/// @brief Json reader for track parameter lookup tables +/// +/// This reader is used to read track parameter lookup tables +/// from a json file to be later used in track parameter estimation +/// for seeding +class JsonTrackParamsLookupReader final : public ITrackParamsLookupReader { + public: + /// @brief Nested configuration struct + struct Config { + /// Reference tracking layers + std::unordered_map< + Acts::GeometryIdentifier, + const Acts::Surface*> refLayers; + /// Binning of the grid to be emposed + /// onto the reference layers + std::pair bins; + }; + + JsonTrackParamsLookupReader(const Config& config) : m_cfg(config) {}; + + ~JsonTrackParamsLookupReader() override = default; + + Lookup readLookup(const std::string& path) final { + // Read the json file + std::ifstream ifj(path); + nlohmann::json jLookup; + ifj >> jLookup; + + Lookup lookup; + // Iterate over the json and deserialize the grids + for (const auto& jGrid : jLookup) { + Acts::GeometryIdentifier id(jGrid["geo_id"]); + + if (m_cfg.refLayers.find(id) == m_cfg.refLayers.end()) { + throw std::invalid_argument("Geometry identifier not found"); + } + + const auto* refSurface = m_cfg.refLayers.at(id); + + // Get bounds to construct the lookup grid + auto bounds = + dynamic_cast(&refSurface->bounds()); + + if (bounds == nullptr) { + throw std::invalid_argument("Only rectangle bounds supported"); + } + + // Axis is not deserilizable, so we need to recreate it + auto halfX = bounds->halfLengthX(); + auto halfY = bounds->halfLengthY(); + + LookupAxisGen axisGen{ + {-halfX, halfX}, m_cfg.bins.first, + {-halfY, halfY}, m_cfg.bins.second}; + + // Deserialize the grid + LookupGrid grid = Acts::GridJsonConverter::fromJson< + LookupAxisGen, + LookupPair>( + jGrid["grid"], axisGen); + + lookup.insert({id, grid}); + } + + return lookup; + }; + + /// Readonly access to the config + const Config& config() const { return m_cfg; } + + private: + /// The config of the writer + Config m_cfg; +}; + +} // namespace ActsExamples diff --git a/Examples/Io/Json/include/ActsExamples/Io/Json/JsonTrackParamsLookupWriter.hpp b/Examples/Io/Json/include/ActsExamples/Io/Json/JsonTrackParamsLookupWriter.hpp new file mode 100644 index 00000000000..8f8ed02bb86 --- /dev/null +++ b/Examples/Io/Json/include/ActsExamples/Io/Json/JsonTrackParamsLookupWriter.hpp @@ -0,0 +1,73 @@ +// This file is part of the ACTS project. +// +// Copyright (C) 2016 CERN for the benefit of the ACTS project +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +#pragma once + +#include "Acts/Definitions/Algebra.hpp" +#include "Acts/Plugins/Json/ActsJson.hpp" +#include "Acts/Plugins/Json/GridJsonConverter.hpp" +#include "Acts/Plugins/Json/TrackParametersJsonConverter.hpp" +#include "ActsExamples/TrackFinding/ITrackParamsLookupWriter.hpp" + +#include +#include + +#include + +namespace ActsExamples { + +/// @brief Json writer for track parameter lookup tables +/// +/// This writer is used to write track parameter lookup tables +/// to a json file to be later used in track parameter estimation +/// for seeding +class JsonTrackParamsLookupWriter final : public ITrackParamsLookupWriter { + public: + /// @brief Nested configuration struct + struct Config { + /// Output file name + std::string path; + }; + + /// Constructor + /// + /// @param config The configuration struct of the writer + JsonTrackParamsLookupWriter(const Config& config) : m_cfg(config) {}; + + /// Virtual destructor + ~JsonTrackParamsLookupWriter() override = default; + + /// Write out the material map + /// + /// @param lookup The lookup to write + void writeLookup(const Lookup& lookup) final { + nlohmann::json jLookup; + + // Iterate over the lookup and serialize the grids + for (const auto& [id, grid] : lookup) { + nlohmann::json jGrid; + jGrid["geo_id"] = id.value(); + jGrid["grid"] = Acts::GridJsonConverter::toJson(grid); + + jLookup.push_back(jGrid); + } + + // Write the json file + std::ofstream ofj(m_cfg.path, std::ios::out); + ofj << std::setw(4) << jLookup << std::endl; + }; + + /// Readonly access to the config + const Config& config() const { return m_cfg; } + + private: + /// The config of the writer + Config m_cfg; +}; + +} // namespace ActsExamples diff --git a/Examples/Python/src/Json.cpp b/Examples/Python/src/Json.cpp index be367612ac2..bb03d67bd98 100644 --- a/Examples/Python/src/Json.cpp +++ b/Examples/Python/src/Json.cpp @@ -19,6 +19,8 @@ #include "ActsExamples/Io/Json/JsonMaterialWriter.hpp" #include "ActsExamples/Io/Json/JsonSurfacesReader.hpp" #include "ActsExamples/Io/Json/JsonSurfacesWriter.hpp" +#include "ActsExamples/Io/Json/JsonTrackParamsLookupWriter.hpp" +#include "ActsExamples/Io/Json/JsonTrackParamsLookupReader.hpp" #include #include @@ -37,8 +39,14 @@ class IMaterialDecorator; namespace ActsExamples { class IMaterialWriter; class IWriter; + +namespace Experimental { + class ITrackParamsLookupWriter; +} // namespace Experimental + } // namespace ActsExamples + namespace py = pybind11; using namespace pybind11::literals; @@ -111,6 +119,56 @@ void addJson(Context& ctx) { ACTS_PYTHON_STRUCT_END(); } + { + using IWriter = ActsExamples::ITrackParamsLookupWriter; + using Writer = ActsExamples::JsonTrackParamsLookupWriter; + using Config = Writer::Config; + + auto cls = + py::class_>( + mex, "JsonTrackParamsLookupWriter") + .def(py::init(), py::arg("config")) + .def("writeLookup", &Writer::writeLookup) + .def_property_readonly("config", &Writer::config); + + auto c = + py::class_(cls, "Config") + .def(py::init<>()) + .def(py::init(), py::arg("path")); + + ACTS_PYTHON_STRUCT_BEGIN(c, Config); + ACTS_PYTHON_MEMBER(path); + ACTS_PYTHON_STRUCT_END(); + } + + { + using IReader = ActsExamples::ITrackParamsLookupReader; + using Reader = ActsExamples::JsonTrackParamsLookupReader; + using Config = Reader::Config; + + auto cls = + py::class_>( + mex, "JsonTrackParamsLookupReader") + .def(py::init(), py::arg("config")) + .def("readLookup", &Reader::readLookup) + .def_property_readonly("config", &Reader::config); + + auto c = + py::class_(cls, "Config") + .def(py::init<>()) + .def(py::init< + std::unordered_map< + Acts::GeometryIdentifier, + const Acts::Surface*>, + std::pair>(), + py::arg("refLayers"), py::arg("bins")); + + ACTS_PYTHON_STRUCT_BEGIN(c, Config); + ACTS_PYTHON_MEMBER(refLayers); + ACTS_PYTHON_MEMBER(bins); + ACTS_PYTHON_STRUCT_END(); + } + { auto cls = py::class_ #include @@ -290,6 +292,16 @@ void addOutput(Context& ctx) { py::class_>( mex, "IMaterialWriter"); + py::class_< + ActsExamples::ITrackParamsLookupWriter, + std::shared_ptr>( + mex, "ITrackParamsLookupWriter"); + + py::class_< + ActsExamples::ITrackParamsLookupReader, + std::shared_ptr>( + mex, "ITrackParamsLookupReader"); + { using Writer = ActsExamples::RootMaterialWriter; auto w = py::class_>( diff --git a/Examples/Python/src/TrackFinding.cpp b/Examples/Python/src/TrackFinding.cpp index ad3ad364ce7..69a4ce899b3 100644 --- a/Examples/Python/src/TrackFinding.cpp +++ b/Examples/Python/src/TrackFinding.cpp @@ -28,6 +28,7 @@ #include "ActsExamples/TrackFinding/SpacePointMaker.hpp" #include "ActsExamples/TrackFinding/TrackFindingAlgorithm.hpp" #include "ActsExamples/TrackFinding/TrackParamsEstimationAlgorithm.hpp" +#include "ActsExamples/TrackFinding/TrackParamsLookupEstimation.hpp" #include #include @@ -293,6 +294,11 @@ void addTrackFinding(Context& ctx) { magneticField, bFieldMin, initialSigmas, initialSigmaPtRel, initialVarInflation, noTimeVarInflation, particleHypothesis); + ACTS_PYTHON_DECLARE_ALGORITHM( + ActsExamples::TrackParamsLookupEstimation, mex, + "TrackParamsLookupEstimation", refLayers, bins, + inputHits, inputParticles, trackLookupGridWriters); + { using Alg = ActsExamples::TrackFindingAlgorithm; using Config = Alg::Config; diff --git a/Examples/Scripts/Python/telescope_track_params_lookup_generation.py b/Examples/Scripts/Python/telescope_track_params_lookup_generation.py new file mode 100644 index 00000000000..7af8e5a315e --- /dev/null +++ b/Examples/Scripts/Python/telescope_track_params_lookup_generation.py @@ -0,0 +1,107 @@ +#!/usr/bin/env python3 + +import argparse + +import acts +import acts.examples +from acts.examples.simulation import ( + addParticleGun, + addFatras, + MomentumConfig, + EtaConfig, + PhiConfig, + ParticleConfig, +) + +u = acts.UnitConstants + +def estimateLookup( + trackingGeometry, + numEvents, + outputPath): + + # Set up the dipole magnetic field + field = acts.ConstantBField(acts.Vector3(50 * u.T, 0, 0)) + + # Fatras simulation of muons + rnd = acts.examples.RandomNumbers(seed=42) + + s = acts.examples.Sequencer(events=numEvents, numThreads=1, logLevel=acts.logging.INFO) + + vertexGen=acts.examples.GaussianVertexGenerator( + stddev=acts.Vector4(0, 0, 0, 0), + mean=acts.Vector4(0, 9, 0, 0) + ) + + addParticleGun( + s=s, + etaConfig=EtaConfig(10.0, 10.0), + phiConfig=PhiConfig(0, 0), + momentumConfig=MomentumConfig(0.5 * u.GeV, 10 * u.GeV), + particleConfig=ParticleConfig(1, acts.PdgParticle.eMuon, False), + multiplicity=1, + rnd=rnd, + vtxGen = vertexGen + ) + + addFatras( + s, + trackingGeometry, + field, + inputParticles="particles_input", + outputSimHits="sim_hits", + rnd=rnd, + preSelectParticles=None + ) + + # Set up the track lookup grid writer + jsonWriterConfig = acts.examples.JsonTrackParamsLookupWriter.Config( + path=outputPath + ) + jsonWriter = acts.examples.JsonTrackParamsLookupWriter(jsonWriterConfig) + + # Set up the track estimation algorithm + surfaces = list(trackingGeometry.geoIdSurfaceMap().values()) + refSurface = surfaces[0] + refGeometryId = refSurface.geometryId() + + trackEstConfig = acts.examples.TrackParamsLookupEstimation.Config( + refLayers={refGeometryId : refSurface}, + bins=(1, 1000), + inputHits="sim_hits", + inputParticles="particles_input", + trackLookupGridWriters = [jsonWriter] + ) + trackEstAlg = acts.examples.TrackParamsLookupEstimation(trackEstConfig, acts.logging.INFO) + + s.addAlgorithm(trackEstAlg) + + s.run() + +if __name__ == "__main__": + p = argparse.ArgumentParser() + + p.add_argument( + "-n", "--events", type=int, default=100000, help="Number of events for lookup estimation" + ) + p.add_argument( + "-o", "--output", type=str, default="lookup.json", help="Output lookup file name" + ) + + args = p.parse_args() + + # Initialize the geometry + detector, trackingGeometry, decorators = acts.examples.TelescopeDetector.create( + bounds=[4, 10], + positions=[30, 60, 90], + stereos=[0, 0, 0], + binValue=2, + surfaceType=0 + ) + + # Estimate the lookup + estimateLookup( + trackingGeometry, + args.events, + args.output) + \ No newline at end of file From 05ffb07def0ecb8622fb5cceda7a0afdfdf56a09 Mon Sep 17 00:00:00 2001 From: ssdetlab Date: Wed, 6 Nov 2024 23:28:57 +0200 Subject: [PATCH 02/23] format --- .../TrackFinding/ITrackParamsLookupReader.hpp | 16 +- .../TrackFinding/ITrackParamsLookupWriter.hpp | 17 +- .../TrackParamsLookupAccumulator.hpp | 69 +++--- .../TrackParamsLookupEstimation.hpp | 82 ++++---- .../TrackFinding/TrackParamsLookupTable.hpp | 38 ++-- .../src/TrackParamsLookupAccumulator.cpp | 77 ++++--- .../src/TrackParamsLookupEstimation.cpp | 170 +++++++-------- .../Io/Json/JsonTrackParamsLookupReader.hpp | 135 ++++++------ .../Io/Json/JsonTrackParamsLookupWriter.hpp | 80 +++---- Examples/Python/src/Json.cpp | 74 +++---- Examples/Python/src/Output.cpp | 16 +- Examples/Python/src/TrackFinding.cpp | 8 +- .../Python/telescope_track_params_lookup.py | 199 ++++++++++++++++++ 13 files changed, 570 insertions(+), 411 deletions(-) create mode 100644 Examples/Scripts/Python/telescope_track_params_lookup.py diff --git a/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/ITrackParamsLookupReader.hpp b/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/ITrackParamsLookupReader.hpp index 9d993fa8197..8b1c387e8f4 100644 --- a/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/ITrackParamsLookupReader.hpp +++ b/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/ITrackParamsLookupReader.hpp @@ -14,14 +14,14 @@ namespace ActsExamples { /// @brief Interface for reading track parameter lookup tables class ITrackParamsLookupReader { - public: - /// Virtual Destructor - virtual ~ITrackParamsLookupReader() = default; - - /// Reader method - /// - /// @param path the path to the file to read - virtual Lookup readLookup(const std::string& path) = 0; + public: + /// Virtual Destructor + virtual ~ITrackParamsLookupReader() = default; + + /// Reader method + /// + /// @param path the path to the file to read + virtual Lookup readLookup(const std::string& path) = 0; }; } // namespace ActsExamples diff --git a/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/ITrackParamsLookupWriter.hpp b/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/ITrackParamsLookupWriter.hpp index 40334704785..e75b7b05bc5 100644 --- a/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/ITrackParamsLookupWriter.hpp +++ b/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/ITrackParamsLookupWriter.hpp @@ -14,15 +14,14 @@ namespace ActsExamples { /// @brief Interface for writing track parameter lookup tables class ITrackParamsLookupWriter { - public: - /// Virtual Destructor - virtual ~ITrackParamsLookupWriter() = default; - - /// Writer method - /// - /// @param lookup track lookup to write - virtual void writeLookup( - const Lookup& lookup) = 0; + public: + /// Virtual Destructor + virtual ~ITrackParamsLookupWriter() = default; + + /// Writer method + /// + /// @param lookup track lookup to write + virtual void writeLookup(const Lookup& lookup) = 0; }; } // namespace ActsExamples diff --git a/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/TrackParamsLookupAccumulator.hpp b/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/TrackParamsLookupAccumulator.hpp index 55b2f29d130..a09b62357cc 100644 --- a/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/TrackParamsLookupAccumulator.hpp +++ b/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/TrackParamsLookupAccumulator.hpp @@ -18,48 +18,47 @@ namespace ActsExamples { /// reference layer grids and average them to create a lookup /// table for track parameter estimation in seeding class TrackParamsLookupAccumulator { - public: - /// @brief Nested configuration struct - struct Config { - /// Axis generator - LookupAxisGen axisGen; - }; + public: + /// @brief Nested configuration struct + struct Config { + /// Axis generator + LookupAxisGen axisGen; + }; - /// @brief Constructor - TrackParamsLookupAccumulator(const Config& config) - : m_cfg(std::move(config)), - m_ipGrid(m_cfg.axisGen()), - m_refGrid(m_cfg.axisGen()) {} + /// @brief Constructor + TrackParamsLookupAccumulator(const Config& config) + : m_cfg(std::move(config)), + m_ipGrid(m_cfg.axisGen()), + m_refGrid(m_cfg.axisGen()) {} - /// @brief Add track parameters to the accumulator - /// - /// @param ipTrackParameters the track parameters at the IP - /// @param refTrackParameters the track parameters at the reference layer - /// @param position local position of the track hit on the reference layer - void addTrack( - const Acts::CurvilinearTrackParameters& ipTrackParameters, - const Acts::CurvilinearTrackParameters& refTrackParameters, - const Acts::Vector2& position); + /// @brief Add track parameters to the accumulator + /// + /// @param ipTrackParameters the track parameters at the IP + /// @param refTrackParameters the track parameters at the reference layer + /// @param position local position of the track hit on the reference layer + void addTrack(const Acts::CurvilinearTrackParameters& ipTrackParameters, + const Acts::CurvilinearTrackParameters& refTrackParameters, + const Acts::Vector2& position); - /// @brief Finalize the lookup table - /// - /// Return the grid with the bin track parameters averaged - LookupGrid finalizeLookup(); + /// @brief Finalize the lookup table + /// + /// Return the grid with the bin track parameters averaged + LookupGrid finalizeLookup(); - /// Get readonly access to the config parameters - const Config& config() const { return m_cfg; } + /// Get readonly access to the config parameters + const Config& config() const { return m_cfg; } - private: - /// Configuration - Config m_cfg; + private: + /// Configuration + Config m_cfg; - /// Mutex for modifying the grid - std::mutex m_writeMutex; + /// Mutex for modifying the grid + std::mutex m_writeMutex; - /// Grids to accumulate IP and reference - /// layer track parameters - LookupAccumGrid m_ipGrid; - LookupAccumGrid m_refGrid; + /// Grids to accumulate IP and reference + /// layer track parameters + LookupAccumGrid m_ipGrid; + LookupAccumGrid m_refGrid; }; } // namespace ActsExamples diff --git a/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/TrackParamsLookupEstimation.hpp b/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/TrackParamsLookupEstimation.hpp index d75146ddaf4..1978915cee8 100644 --- a/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/TrackParamsLookupEstimation.hpp +++ b/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/TrackParamsLookupEstimation.hpp @@ -10,8 +10,8 @@ #include "ActsExamples/EventData/SimHit.hpp" #include "ActsExamples/EventData/SimParticle.hpp" -#include "ActsExamples/Framework/IAlgorithm.hpp" #include "ActsExamples/Framework/DataHandle.hpp" +#include "ActsExamples/Framework/IAlgorithm.hpp" #include "ActsExamples/TrackFinding/ITrackParamsLookupWriter.hpp" #include "ActsExamples/TrackFinding/TrackParamsLookupAccumulator.hpp" @@ -25,52 +25,50 @@ namespace ActsExamples { /// parameters in the grid bins. The track parameters are then averaged /// to create a lookup table for track parameter estimation in seeding. class TrackParamsLookupEstimation : public IAlgorithm { - public: - /// @brief Nested configuration struct - struct Config { - /// Reference tracking layers - std::unordered_map< - Acts::GeometryIdentifier, - const Acts::Surface*> refLayers; - /// Binning of the grid to be emposed - /// onto the reference layers - std::pair bins; - /// Input SimHit container - std::string inputHits = "InputHits"; - /// Input SimParticle container - std::string inputParticles = "InputParticles"; - /// Track lookup writers - std::vector> - trackLookupGridWriters{}; - }; - - /// @brief Constructor - TrackParamsLookupEstimation( - const Config& config, Acts::Logging::Level level); + public: + /// @brief Nested configuration struct + struct Config { + /// Reference tracking layers + std::unordered_map + refLayers; + /// Binning of the grid to be emposed + /// onto the reference layers + std::pair bins; + /// Input SimHit container + std::string inputHits = "InputHits"; + /// Input SimParticle container + std::string inputParticles = "InputParticles"; + /// Track lookup writers + std::vector> + trackLookupGridWriters{}; + }; + + /// @brief Constructor + TrackParamsLookupEstimation(const Config& config, Acts::Logging::Level level); + + /// @brief Destructor + ~TrackParamsLookupEstimation(); + + /// @brief The execute method + ProcessCode execute(const AlgorithmContext& ctx) const override; - /// @brief Destructor - ~TrackParamsLookupEstimation(); + /// Get readonly access to the config parameters + const Config& config() const { return m_cfg; } - /// @brief The execute method - ProcessCode execute(const AlgorithmContext& ctx) const override; + private: + /// Configuration + Config m_cfg; - /// Get readonly access to the config parameters - const Config& config() const { return m_cfg; } + /// Input data handles + ReadDataHandle m_inputParticles{this, + "InputSimParticles"}; - private: - /// Configuration - Config m_cfg; - - /// Input data handles - ReadDataHandle m_inputParticles{ - this, - "InputSimParticles"}; - - ReadDataHandle m_inputSimHits{this, "InputSimHits"}; + ReadDataHandle m_inputSimHits{this, "InputSimHits"}; - /// Accumulators for the track parameters - std::unordered_map> m_accumulators; + /// Accumulators for the track parameters + std::unordered_map> + m_accumulators; }; } // namespace ActsExamples diff --git a/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/TrackParamsLookupTable.hpp b/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/TrackParamsLookupTable.hpp index 39548277424..32e4264e3e0 100644 --- a/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/TrackParamsLookupTable.hpp +++ b/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/TrackParamsLookupTable.hpp @@ -15,47 +15,37 @@ namespace ActsExamples { -/// @brief Track parameters lookup table axis used +/// @brief Track parameters lookup table axis used /// in the track estimation algorithm using LookupAxis = - Acts::Axis< - Acts::AxisType::Equidistant, - Acts::AxisBoundaryType::Open>; + Acts::Axis; /// @brief Track parameters lookup table axis generator -/// used in the track estimation algorithm -using LookupAxisGen = - Acts::GridAxisGenerators::EqOpenEqOpen; +/// used in the track estimation algorithm +using LookupAxisGen = Acts::GridAxisGenerators::EqOpenEqOpen; /// @brief Grid used to accumulate IP track parameters and /// reference layer track parameters for a given position /// in the track estimation algorithm using LookupAccumGrid = - Acts::Grid< - std::vector, - LookupAxis, - LookupAxis>; + Acts::Grid, LookupAxis, + LookupAxis>; /// @brief Container for the lookup accumulation grids to -/// handle multiple reference layers in the track estimation -using LookupAccumGridContainer = - std::unordered_map< - Acts::GeometryIdentifier, LookupAccumGrid>; +/// handle multiple reference layers in the track estimation +using LookupAccumGridContainer = + std::unordered_map; /// @brief IP-reference layer track parameters lookup pair -using LookupPair = std::pair< - std::shared_ptr, - std::shared_ptr>; +using LookupPair = std::pair, + std::shared_ptr>; -/// @brief Lookup grid for track parameters estimation +/// @brief Lookup grid for track parameters estimation /// in a given layer -using LookupGrid = - Acts::Grid; +using LookupGrid = Acts::Grid; /// @brief Lookup table for track parameters estimation /// in the track estimation algorithm -using Lookup = - std::unordered_map< - Acts::GeometryIdentifier, LookupGrid>; +using Lookup = std::unordered_map; } // namespace ActsExamples diff --git a/Examples/Algorithms/TrackFinding/src/TrackParamsLookupAccumulator.cpp b/Examples/Algorithms/TrackFinding/src/TrackParamsLookupAccumulator.cpp index e1084e0f8cc..69fa94a022f 100644 --- a/Examples/Algorithms/TrackFinding/src/TrackParamsLookupAccumulator.cpp +++ b/Examples/Algorithms/TrackFinding/src/TrackParamsLookupAccumulator.cpp @@ -8,69 +8,66 @@ #include "ActsExamples/TrackFinding/TrackParamsLookupAccumulator.hpp" +#include "Acts/EventData/TrackParameters.hpp" #include "Acts/Utilities/Grid.hpp" #include "Acts/Utilities/GridIterator.hpp" -#include "Acts/EventData/TrackParameters.hpp" void ActsExamples::TrackParamsLookupAccumulator::addTrack( const Acts::CurvilinearTrackParameters& ipTrackParameters, const Acts::CurvilinearTrackParameters& refTrackParameters, const Acts::Vector2& position) { - // Lock the write mutex - std::lock_guard lock(m_writeMutex); + // Lock the write mutex + std::lock_guard lock(m_writeMutex); + + // Get the local bins from the position + auto bin = m_ipGrid.localBinsFromPosition(position); - // Get the local bins from the position - auto bin = m_ipGrid.localBinsFromPosition(position); - - // Add the track parameters to the grid - m_ipGrid.atLocalBins(bin).push_back(ipTrackParameters); - m_refGrid.atLocalBins(bin).push_back(refTrackParameters); + // Add the track parameters to the grid + m_ipGrid.atLocalBins(bin).push_back(ipTrackParameters); + m_refGrid.atLocalBins(bin).push_back(refTrackParameters); } -ActsExamples::LookupGrid +ActsExamples::LookupGrid ActsExamples::TrackParamsLookupAccumulator::finalizeLookup() { - // Average track parameters in a given bin - auto meanTrack = [](const std::vector& tracks) { + // Average track parameters in a given bin + auto meanTrack = + [](const std::vector& tracks) { Acts::Vector4 fourPosition = Acts::Vector4::Zero(); Acts::Vector3 direction = Acts::Vector3::Zero(); Acts::ActsScalar qOverP = 0; for (const auto& track : tracks) { - fourPosition += track.fourPosition(); - direction += track.direction(); - qOverP += track.qOverP(); + fourPosition += track.fourPosition(); + direction += track.direction(); + qOverP += track.qOverP(); } fourPosition /= tracks.size(); direction /= tracks.size(); qOverP /= tracks.size(); - + return Acts::CurvilinearTrackParameters( - fourPosition, - direction, - qOverP, - std::nullopt, + fourPosition, direction, qOverP, std::nullopt, tracks.front().particleHypothesis()); - }; + }; - // Create a lookup grid with the same parameters as - // the accumulation grids - ActsExamples::LookupGrid lookupGrid(m_cfg.axisGen()); + // Create a lookup grid with the same parameters as + // the accumulation grids + ActsExamples::LookupGrid lookupGrid(m_cfg.axisGen()); - // Iterate over the bins and average the track parameters - for (auto it = m_ipGrid.begin(); it != m_ipGrid.end(); ++it) { - auto bin = it.localBinsIndices(); - if (m_ipGrid.atLocalBins(bin).empty() || - m_refGrid.atLocalBins(bin).empty()) { - continue; - } - - // Store the IP-reference-position correspondence - lookupGrid.atLocalBins(bin) = - std::make_pair( - std::make_shared( - meanTrack(m_ipGrid.atLocalBins(bin))), - std::make_shared( - meanTrack(m_refGrid.atLocalBins(bin)))); + // Iterate over the bins and average the track parameters + for (auto it = m_ipGrid.begin(); it != m_ipGrid.end(); ++it) { + auto bin = it.localBinsIndices(); + if (m_ipGrid.atLocalBins(bin).empty() || + m_refGrid.atLocalBins(bin).empty()) { + continue; } - return lookupGrid; + // Store the IP-reference-position correspondence + lookupGrid.atLocalBins(bin) = + std::make_pair(std::make_shared( + meanTrack(m_ipGrid.atLocalBins(bin))), + std::make_shared( + meanTrack(m_refGrid.atLocalBins(bin)))); + } + + return lookupGrid; } diff --git a/Examples/Algorithms/TrackFinding/src/TrackParamsLookupEstimation.cpp b/Examples/Algorithms/TrackFinding/src/TrackParamsLookupEstimation.cpp index b93821ee134..3baa25a513e 100644 --- a/Examples/Algorithms/TrackFinding/src/TrackParamsLookupEstimation.cpp +++ b/Examples/Algorithms/TrackFinding/src/TrackParamsLookupEstimation.cpp @@ -14,102 +14,88 @@ ActsExamples::TrackParamsLookupEstimation::TrackParamsLookupEstimation( const Config& config, Acts::Logging::Level level) : IAlgorithm("TrackParamsLookupEstimation", level), - m_cfg(std::move(config)) { - // Iterate over the reference layers and create - // track parameter accumulators - for (const auto& [geoId, refSurface] : m_cfg.refLayers) { - // Get bounds to construct the accumulator grid - auto bounds = - dynamic_cast( - &refSurface->bounds()); - - if (bounds == nullptr) { - throw std::invalid_argument("Only rectangle bounds supported"); - } - - // Initialize the accumulator grid - auto halfX = bounds->halfLengthX(); - auto halfY = bounds->halfLengthY(); - - LookupAxisGen axisGen{ - {-halfX, halfX}, m_cfg.bins.first, - {-halfY, halfY}, m_cfg.bins.second}; - - TrackParamsLookupAccumulator::Config accConfig{ - axisGen}; - - // Each reference layer has its own accumulator - m_accumulators[geoId] = - std::make_unique(accConfig); - } - - m_inputParticles.initialize(m_cfg.inputParticles); - m_inputSimHits.initialize(m_cfg.inputHits); + m_cfg(std::move(config)) { + // Iterate over the reference layers and create + // track parameter accumulators + for (const auto& [geoId, refSurface] : m_cfg.refLayers) { + // Get bounds to construct the accumulator grid + auto bounds = + dynamic_cast(&refSurface->bounds()); + + if (bounds == nullptr) { + throw std::invalid_argument("Only rectangle bounds supported"); + } + + // Initialize the accumulator grid + auto halfX = bounds->halfLengthX(); + auto halfY = bounds->halfLengthY(); + + LookupAxisGen axisGen{ + {-halfX, halfX}, m_cfg.bins.first, {-halfY, halfY}, m_cfg.bins.second}; + + TrackParamsLookupAccumulator::Config accConfig{axisGen}; + + // Each reference layer has its own accumulator + m_accumulators[geoId] = + std::make_unique(accConfig); + } + + m_inputParticles.initialize(m_cfg.inputParticles); + m_inputSimHits.initialize(m_cfg.inputHits); } ActsExamples::TrackParamsLookupEstimation::~TrackParamsLookupEstimation() { - // Finiliaze the lookup tables and write them - ActsExamples::Lookup lookup; - for (auto& [id, acc] : m_accumulators) { - lookup.insert({id, acc->finalizeLookup()}); - } - for (auto& writer : m_cfg.trackLookupGridWriters) { - writer->writeLookup(lookup); - } + // Finiliaze the lookup tables and write them + ActsExamples::Lookup lookup; + for (auto& [id, acc] : m_accumulators) { + lookup.insert({id, acc->finalizeLookup()}); + } + for (auto& writer : m_cfg.trackLookupGridWriters) { + writer->writeLookup(lookup); + } }; -ActsExamples::ProcessCode -ActsExamples::TrackParamsLookupEstimation::execute( +ActsExamples::ProcessCode ActsExamples::TrackParamsLookupEstimation::execute( const ActsExamples::AlgorithmContext& ctx) const { - // Get the particles and hits - const auto& particles = m_inputParticles(ctx); - const auto& hits = m_inputSimHits(ctx); - - // Iterate over the reference layer hits and - // accumulate the track parameters - for (const auto& [geoId, refSurface] : m_cfg.refLayers) { - // Get reference layer hits - auto refLayerHits = hits.equal_range( - geoId); - - for (auto hit = refLayerHits.first; hit != refLayerHits.second; ++hit) { - // Get the corresponding particle - const auto& id = hit->particleId(); - const auto& particle = particles.find(id); - - if (particle == particles.end()) { - throw std::invalid_argument("Particle not found"); - } - - // Hit stores the reference layer parameters - auto refLayerPars = Acts::CurvilinearTrackParameters( - hit->fourPosition(), - hit->direction(), - particle->qOverP(), - std::nullopt, - particle->hypothesis()); - - // Particle stores the IP parameters - auto ipPars = Acts::CurvilinearTrackParameters( - particle->fourPosition(), - particle->direction(), - particle->qOverP(), - std::nullopt, - particle->hypothesis()); - - // Get the local position of the hit - auto localPos = refSurface->globalToLocal( - ctx.geoContext, - hit->position(), - Acts::Vector3{0, 1, 0}).value(); - - // Add the track parameters to the accumulator grid - m_accumulators.at(geoId)->addTrack( - ipPars, - refLayerPars, - localPos); - } - } - - return ActsExamples::ProcessCode::SUCCESS; + // Get the particles and hits + const auto& particles = m_inputParticles(ctx); + const auto& hits = m_inputSimHits(ctx); + + // Iterate over the reference layer hits and + // accumulate the track parameters + for (const auto& [geoId, refSurface] : m_cfg.refLayers) { + // Get reference layer hits + auto refLayerHits = hits.equal_range(geoId); + + for (auto hit = refLayerHits.first; hit != refLayerHits.second; ++hit) { + // Get the corresponding particle + const auto& id = hit->particleId(); + const auto& particle = particles.find(id); + + if (particle == particles.end()) { + throw std::invalid_argument("Particle not found"); + } + + // Hit stores the reference layer parameters + auto refLayerPars = Acts::CurvilinearTrackParameters( + hit->fourPosition(), hit->direction(), particle->qOverP(), + std::nullopt, particle->hypothesis()); + + // Particle stores the IP parameters + auto ipPars = Acts::CurvilinearTrackParameters( + particle->fourPosition(), particle->direction(), particle->qOverP(), + std::nullopt, particle->hypothesis()); + + // Get the local position of the hit + auto localPos = refSurface + ->globalToLocal(ctx.geoContext, hit->position(), + Acts::Vector3{0, 1, 0}) + .value(); + + // Add the track parameters to the accumulator grid + m_accumulators.at(geoId)->addTrack(ipPars, refLayerPars, localPos); + } + } + + return ActsExamples::ProcessCode::SUCCESS; } diff --git a/Examples/Io/Json/include/ActsExamples/Io/Json/JsonTrackParamsLookupReader.hpp b/Examples/Io/Json/include/ActsExamples/Io/Json/JsonTrackParamsLookupReader.hpp index c9665b3278a..f5d0bc63095 100644 --- a/Examples/Io/Json/include/ActsExamples/Io/Json/JsonTrackParamsLookupReader.hpp +++ b/Examples/Io/Json/include/ActsExamples/Io/Json/JsonTrackParamsLookupReader.hpp @@ -12,9 +12,9 @@ #include "Acts/Plugins/Json/ActsJson.hpp" #include "Acts/Plugins/Json/GridJsonConverter.hpp" #include "Acts/Plugins/Json/TrackParametersJsonConverter.hpp" -#include "ActsExamples/TrackFinding/ITrackParamsLookupReader.hpp" #include "Acts/Surfaces/RectangleBounds.hpp" #include "Acts/Utilities/GridAxisGenerators.hpp" +#include "ActsExamples/TrackFinding/ITrackParamsLookupReader.hpp" #include #include @@ -29,73 +29,72 @@ namespace ActsExamples { /// from a json file to be later used in track parameter estimation /// for seeding class JsonTrackParamsLookupReader final : public ITrackParamsLookupReader { - public: - /// @brief Nested configuration struct - struct Config { - /// Reference tracking layers - std::unordered_map< - Acts::GeometryIdentifier, - const Acts::Surface*> refLayers; - /// Binning of the grid to be emposed - /// onto the reference layers - std::pair bins; - }; - - JsonTrackParamsLookupReader(const Config& config) : m_cfg(config) {}; - - ~JsonTrackParamsLookupReader() override = default; - - Lookup readLookup(const std::string& path) final { - // Read the json file - std::ifstream ifj(path); - nlohmann::json jLookup; - ifj >> jLookup; - - Lookup lookup; - // Iterate over the json and deserialize the grids - for (const auto& jGrid : jLookup) { - Acts::GeometryIdentifier id(jGrid["geo_id"]); - - if (m_cfg.refLayers.find(id) == m_cfg.refLayers.end()) { - throw std::invalid_argument("Geometry identifier not found"); - } - - const auto* refSurface = m_cfg.refLayers.at(id); - - // Get bounds to construct the lookup grid - auto bounds = - dynamic_cast(&refSurface->bounds()); - - if (bounds == nullptr) { - throw std::invalid_argument("Only rectangle bounds supported"); - } - - // Axis is not deserilizable, so we need to recreate it - auto halfX = bounds->halfLengthX(); - auto halfY = bounds->halfLengthY(); - - LookupAxisGen axisGen{ - {-halfX, halfX}, m_cfg.bins.first, - {-halfY, halfY}, m_cfg.bins.second}; - - // Deserialize the grid - LookupGrid grid = Acts::GridJsonConverter::fromJson< - LookupAxisGen, - LookupPair>( - jGrid["grid"], axisGen); - - lookup.insert({id, grid}); - } - - return lookup; - }; - - /// Readonly access to the config - const Config& config() const { return m_cfg; } - - private: - /// The config of the writer - Config m_cfg; + public: + /// @brief Nested configuration struct + struct Config { + /// Reference tracking layers + std::unordered_map + refLayers; + /// Binning of the grid to be emposed + /// onto the reference layers + std::pair bins; + }; + + JsonTrackParamsLookupReader(const Config& config) : m_cfg(config){}; + + ~JsonTrackParamsLookupReader() override = default; + + Lookup readLookup(const std::string& path) final { + // Read the json file + std::ifstream ifj(path); + nlohmann::json jLookup; + ifj >> jLookup; + + Lookup lookup; + // Iterate over the json and deserialize the grids + for (const auto& jGrid : jLookup) { + Acts::GeometryIdentifier id(jGrid["geo_id"]); + + if (m_cfg.refLayers.find(id) == m_cfg.refLayers.end()) { + throw std::invalid_argument("Geometry identifier not found"); + } + + const auto* refSurface = m_cfg.refLayers.at(id); + + // Get bounds to construct the lookup grid + auto bounds = + dynamic_cast(&refSurface->bounds()); + + if (bounds == nullptr) { + throw std::invalid_argument("Only rectangle bounds supported"); + } + + // Axis is not deserilizable, so we need to recreate it + auto halfX = bounds->halfLengthX(); + auto halfY = bounds->halfLengthY(); + + LookupAxisGen axisGen{{-halfX, halfX}, + m_cfg.bins.first, + {-halfY, halfY}, + m_cfg.bins.second}; + + // Deserialize the grid + LookupGrid grid = + Acts::GridJsonConverter::fromJson( + jGrid["grid"], axisGen); + + lookup.insert({id, grid}); + } + + return lookup; + }; + + /// Readonly access to the config + const Config& config() const { return m_cfg; } + + private: + /// The config of the writer + Config m_cfg; }; } // namespace ActsExamples diff --git a/Examples/Io/Json/include/ActsExamples/Io/Json/JsonTrackParamsLookupWriter.hpp b/Examples/Io/Json/include/ActsExamples/Io/Json/JsonTrackParamsLookupWriter.hpp index 8f8ed02bb86..6e6c3cd2817 100644 --- a/Examples/Io/Json/include/ActsExamples/Io/Json/JsonTrackParamsLookupWriter.hpp +++ b/Examples/Io/Json/include/ActsExamples/Io/Json/JsonTrackParamsLookupWriter.hpp @@ -27,47 +27,47 @@ namespace ActsExamples { /// to a json file to be later used in track parameter estimation /// for seeding class JsonTrackParamsLookupWriter final : public ITrackParamsLookupWriter { - public: - /// @brief Nested configuration struct - struct Config { - /// Output file name - std::string path; - }; + public: + /// @brief Nested configuration struct + struct Config { + /// Output file name + std::string path; + }; - /// Constructor - /// - /// @param config The configuration struct of the writer - JsonTrackParamsLookupWriter(const Config& config) : m_cfg(config) {}; - - /// Virtual destructor - ~JsonTrackParamsLookupWriter() override = default; - - /// Write out the material map - /// - /// @param lookup The lookup to write - void writeLookup(const Lookup& lookup) final { - nlohmann::json jLookup; - - // Iterate over the lookup and serialize the grids - for (const auto& [id, grid] : lookup) { - nlohmann::json jGrid; - jGrid["geo_id"] = id.value(); - jGrid["grid"] = Acts::GridJsonConverter::toJson(grid); - - jLookup.push_back(jGrid); - } - - // Write the json file - std::ofstream ofj(m_cfg.path, std::ios::out); - ofj << std::setw(4) << jLookup << std::endl; - }; - - /// Readonly access to the config - const Config& config() const { return m_cfg; } - - private: - /// The config of the writer - Config m_cfg; + /// Constructor + /// + /// @param config The configuration struct of the writer + JsonTrackParamsLookupWriter(const Config& config) : m_cfg(config){}; + + /// Virtual destructor + ~JsonTrackParamsLookupWriter() override = default; + + /// Write out the material map + /// + /// @param lookup The lookup to write + void writeLookup(const Lookup& lookup) final { + nlohmann::json jLookup; + + // Iterate over the lookup and serialize the grids + for (const auto& [id, grid] : lookup) { + nlohmann::json jGrid; + jGrid["geo_id"] = id.value(); + jGrid["grid"] = Acts::GridJsonConverter::toJson(grid); + + jLookup.push_back(jGrid); + } + + // Write the json file + std::ofstream ofj(m_cfg.path, std::ios::out); + ofj << std::setw(4) << jLookup << std::endl; + }; + + /// Readonly access to the config + const Config& config() const { return m_cfg; } + + private: + /// The config of the writer + Config m_cfg; }; } // namespace ActsExamples diff --git a/Examples/Python/src/Json.cpp b/Examples/Python/src/Json.cpp index bb03d67bd98..491d2fc67e4 100644 --- a/Examples/Python/src/Json.cpp +++ b/Examples/Python/src/Json.cpp @@ -19,8 +19,8 @@ #include "ActsExamples/Io/Json/JsonMaterialWriter.hpp" #include "ActsExamples/Io/Json/JsonSurfacesReader.hpp" #include "ActsExamples/Io/Json/JsonSurfacesWriter.hpp" -#include "ActsExamples/Io/Json/JsonTrackParamsLookupWriter.hpp" #include "ActsExamples/Io/Json/JsonTrackParamsLookupReader.hpp" +#include "ActsExamples/Io/Json/JsonTrackParamsLookupWriter.hpp" #include #include @@ -41,12 +41,11 @@ class IMaterialWriter; class IWriter; namespace Experimental { - class ITrackParamsLookupWriter; +class ITrackParamsLookupWriter; } // namespace Experimental } // namespace ActsExamples - namespace py = pybind11; using namespace pybind11::literals; @@ -124,17 +123,15 @@ void addJson(Context& ctx) { using Writer = ActsExamples::JsonTrackParamsLookupWriter; using Config = Writer::Config; - auto cls = - py::class_>( - mex, "JsonTrackParamsLookupWriter") - .def(py::init(), py::arg("config")) - .def("writeLookup", &Writer::writeLookup) - .def_property_readonly("config", &Writer::config); + auto cls = py::class_>( + mex, "JsonTrackParamsLookupWriter") + .def(py::init(), py::arg("config")) + .def("writeLookup", &Writer::writeLookup) + .def_property_readonly("config", &Writer::config); - auto c = - py::class_(cls, "Config") - .def(py::init<>()) - .def(py::init(), py::arg("path")); + auto c = py::class_(cls, "Config") + .def(py::init<>()) + .def(py::init(), py::arg("path")); ACTS_PYTHON_STRUCT_BEGIN(c, Config); ACTS_PYTHON_MEMBER(path); @@ -146,23 +143,19 @@ void addJson(Context& ctx) { using Reader = ActsExamples::JsonTrackParamsLookupReader; using Config = Reader::Config; - auto cls = - py::class_>( - mex, "JsonTrackParamsLookupReader") - .def(py::init(), py::arg("config")) - .def("readLookup", &Reader::readLookup) - .def_property_readonly("config", &Reader::config); + auto cls = py::class_>( + mex, "JsonTrackParamsLookupReader") + .def(py::init(), py::arg("config")) + .def("readLookup", &Reader::readLookup) + .def_property_readonly("config", &Reader::config); + + auto c = py::class_(cls, "Config") + .def(py::init<>()) + .def(py::init, + std::pair>(), + py::arg("refLayers"), py::arg("bins")); - auto c = - py::class_(cls, "Config") - .def(py::init<>()) - .def(py::init< - std::unordered_map< - Acts::GeometryIdentifier, - const Acts::Surface*>, - std::pair>(), - py::arg("refLayers"), py::arg("bins")); - ACTS_PYTHON_STRUCT_BEGIN(c, Config); ACTS_PYTHON_MEMBER(refLayers); ACTS_PYTHON_MEMBER(bins); @@ -281,17 +274,18 @@ void addJson(Context& ctx) { } { - mex.def("readDetectorFromJson", - [](const Acts::GeometryContext& gctx, - const std::string& fileName) -> auto { - auto in = std::ifstream( - fileName, std::ifstream::in | std::ifstream::binary); - nlohmann::json jDetectorIn; - in >> jDetectorIn; - in.close(); - - return Acts::DetectorJsonConverter::fromJson(gctx, jDetectorIn); - }); + mex.def( + "readDetectorFromJson", + [](const Acts::GeometryContext& gctx, + const std::string& fileName) -> auto{ + auto in = std::ifstream(fileName, + std::ifstream::in | std::ifstream::binary); + nlohmann::json jDetectorIn; + in >> jDetectorIn; + in.close(); + + return Acts::DetectorJsonConverter::fromJson(gctx, jDetectorIn); + }); } } } // namespace Acts::Python diff --git a/Examples/Python/src/Output.cpp b/Examples/Python/src/Output.cpp index 598119ebb48..5aa2d121b2b 100644 --- a/Examples/Python/src/Output.cpp +++ b/Examples/Python/src/Output.cpp @@ -49,8 +49,8 @@ #include "ActsExamples/MaterialMapping/IMaterialWriter.hpp" #include "ActsExamples/Plugins/Obj/ObjPropagationStepsWriter.hpp" #include "ActsExamples/Plugins/Obj/ObjTrackingGeometryWriter.hpp" -#include "ActsExamples/TrackFinding/ITrackParamsLookupWriter.hpp" #include "ActsExamples/TrackFinding/ITrackParamsLookupReader.hpp" +#include "ActsExamples/TrackFinding/ITrackParamsLookupWriter.hpp" #include #include @@ -292,15 +292,13 @@ void addOutput(Context& ctx) { py::class_>( mex, "IMaterialWriter"); - py::class_< - ActsExamples::ITrackParamsLookupWriter, - std::shared_ptr>( - mex, "ITrackParamsLookupWriter"); + py::class_>( + mex, "ITrackParamsLookupWriter"); - py::class_< - ActsExamples::ITrackParamsLookupReader, - std::shared_ptr>( - mex, "ITrackParamsLookupReader"); + py::class_>( + mex, "ITrackParamsLookupReader"); { using Writer = ActsExamples::RootMaterialWriter; diff --git a/Examples/Python/src/TrackFinding.cpp b/Examples/Python/src/TrackFinding.cpp index 69a4ce899b3..54eb7e76641 100644 --- a/Examples/Python/src/TrackFinding.cpp +++ b/Examples/Python/src/TrackFinding.cpp @@ -294,10 +294,10 @@ void addTrackFinding(Context& ctx) { magneticField, bFieldMin, initialSigmas, initialSigmaPtRel, initialVarInflation, noTimeVarInflation, particleHypothesis); - ACTS_PYTHON_DECLARE_ALGORITHM( - ActsExamples::TrackParamsLookupEstimation, mex, - "TrackParamsLookupEstimation", refLayers, bins, - inputHits, inputParticles, trackLookupGridWriters); + ACTS_PYTHON_DECLARE_ALGORITHM(ActsExamples::TrackParamsLookupEstimation, mex, + "TrackParamsLookupEstimation", refLayers, bins, + inputHits, inputParticles, + trackLookupGridWriters); { using Alg = ActsExamples::TrackFindingAlgorithm; diff --git a/Examples/Scripts/Python/telescope_track_params_lookup.py b/Examples/Scripts/Python/telescope_track_params_lookup.py new file mode 100644 index 00000000000..0f0ab96df8e --- /dev/null +++ b/Examples/Scripts/Python/telescope_track_params_lookup.py @@ -0,0 +1,199 @@ +#!/usr/bin/env python3 + +import argparse + +import acts +import acts.examples +from acts.examples.simulation import ( + addParticleGun, + addFatras, + MomentumConfig, + EtaConfig, + PhiConfig, + ParticleConfig, +) + +u = acts.UnitConstants + +def estimateLookup( + trackingGeometry, + numEvents, + outputPath): + + # Set up the magnetic field + field = acts.ConstantBField(acts.Vector3(50 * u.T, 0, 0)) + + # Fatras simulation of muons + rnd = acts.examples.RandomNumbers(seed=42) + + s = acts.examples.Sequencer(events=numEvents, numThreads=1, logLevel=acts.logging.INFO) + + vertexGen=acts.examples.GaussianVertexGenerator( + stddev=acts.Vector4(0, 0, 0, 0), + mean=acts.Vector4(0, 9, 0, 0) + ) + + addParticleGun( + s=s, + etaConfig=EtaConfig(10.0, 10.0), + phiConfig=PhiConfig(0, 0), + momentumConfig=MomentumConfig(0.5 * u.GeV, 10 * u.GeV), + particleConfig=ParticleConfig(1, acts.PdgParticle.eMuon, False), + multiplicity=1, + rnd=rnd, + vtxGen = vertexGen + ) + + addFatras( + s, + trackingGeometry, + field, + inputParticles="particles_input", + outputSimHits="sim_hits", + rnd=rnd, + preSelectParticles=None + ) + + # Set up the track lookup grid writer + jsonWriterConfig = acts.examples.JsonTrackParamsLookupWriter.Config( + path=outputPath + ) + jsonWriter = acts.examples.JsonTrackParamsLookupWriter(jsonWriterConfig) + + # Set up the track estimation algorithm + surfaces = list(trackingGeometry.geoIdSurfaceMap().values()) + refSurface = surfaces[0] + refGeometryId = refSurface.geometryId() + + trackEstConfig = acts.examples.TrackParamsLookupEstimation.Config( + refLayers={refGeometryId : refSurface}, + bins=(1, 1000), + inputHits="sim_hits", + inputParticles="particles_input", + trackLookupGridWriters = [jsonWriter] + ) + trackEstAlg = acts.examples.TrackParamsLookupEstimation(trackEstConfig, acts.logging.INFO) + + s.addAlgorithm(trackEstAlg) + + s.run() + +def validateLookup( + trackingGeometry, + numEvents, + inputPath): + + # Set up the magnetic field + field = acts.ConstantBField(acts.Vector3(50 * u.T, 0, 0)) + + # Fatras simulation of muons + rnd = acts.examples.RandomNumbers(seed=92) + + s = acts.examples.Sequencer(events=numEvents, numThreads=1, logLevel=acts.logging.INFO) + + vertexGen=acts.examples.GaussianVertexGenerator( + stddev=acts.Vector4(0, 0, 0, 0), + mean=acts.Vector4(0, 9, 0, 0) + ) + + addParticleGun( + s=s, + etaConfig=EtaConfig(10.0, 10.0), + phiConfig=PhiConfig(0, 0), + momentumConfig=MomentumConfig(0.5 * u.GeV, 10 * u.GeV), + particleConfig=ParticleConfig(1, acts.PdgParticle.eMuon, False), + multiplicity=1, + rnd=rnd, + vtxGen = vertexGen + ) + + addFatras( + s, + trackingGeometry, + field, + inputParticles="particles_input", + outputSimHits="sim_hits", + rnd=rnd, + preSelectParticles=None + ) + + # Set up the track lookup grid reader + surfaces = list(trackingGeometry.geoIdSurfaceMap().values()) + refSurface = surfaces[0] + refGeometryId = refSurface.geometryId() + + jsonReaderConfig = acts.examples.JsonTrackParamsLookupReader.Config( + refLayers={refGeometryId : refSurface}, + bins=(1, 1000)) + jsonReader = acts.examples.JsonTrackParamsLookupReader(jsonReaderConfig) + + lookupConfig = acts.examples.TrackParamsLookupProvider.Config( + jsonReader, + inputPath) + lookup = acts.examples.TrackParamsLookupProvider(lookupConfig) + + refSurf = list(trackingGeometry.geoIdSurfaceMap().values())[0] + + validaterConfig = acts.examples.TrackParamsLookupValidation.Config() + validaterConfig.refLayers={refSurf.geometryId(): refSurf} + validaterConfig.lookup=lookup + validaterConfig.inputHits="sim_hits" + validaterConfig.inputParticles="particles_input" + validaterConfig.outputIpPars="ip_pars" + validaterConfig.outputRefLayerPars="ref_layer_pars" + validaterConfig.outputIpParsEst="ip_pars_est" + validaterConfig.outputRefLayerParsEst="ref_layer_pars_est" + alg = acts.examples.TrackParamsLookupValidation(validaterConfig, acts.logging.INFO) + + s.addAlgorithm(alg) + + # writer + writerConfig = acts.examples.RootTrackParamsValidationWriter.Config() + + writerConfig.inputIpPars="ip_pars" + writerConfig.inputRefLayerPars="ref_layer_pars" + writerConfig.inputIpParsEst="ip_pars_est" + writerConfig.inputRefLayerParsEst="ref_layer_pars_est" + writerConfig.path=inputPath.replace(".json", ".root") + writerConfig.treeName="test" + + writer = acts.examples.RootTrackParamsValidationWriter(writerConfig, acts.logging.INFO) + + s.addWriter(writer) + + s.run() + +if __name__ == "__main__": + p = argparse.ArgumentParser() + + p.add_argument( + "-nest", "--estimate", type=int, default=10000000, help="Number of events for lookup estimation" + ) + p.add_argument( + "-nval", "--validate", type=int, default=100000, help="Number of events for lookup validation" + ) + p.add_argument( + "-o", "--output", type=str, default="/home/romanurmanov/tools/acts/acts_telescope_geo/ActsTelescopeGeometryDevelopment_build/test2", help="Output lookup file name" + ) + + args = p.parse_args() + + # Initialize the geometry + detector, trackingGeometry, decorators = acts.examples.TelescopeDetector.create( + bounds=[4, 10], + positions=[30, 60, 90], + stereos=[0, 0, 0], + binValue=2, + surfaceType=0 + ) + + estimateLookup( + trackingGeometry, + args.estimate, + args.output) + + validateLookup( + trackingGeometry, + args.validate, + args.output + ".json") + \ No newline at end of file From c956e4d6a641f09702a48575010be45d75696584 Mon Sep 17 00:00:00 2001 From: ssdetlab <113530373+ssdetlab@users.noreply.github.com> Date: Wed, 6 Nov 2024 23:29:27 +0200 Subject: [PATCH 03/23] Delete Examples/Scripts/Python/telescope_track_params_lookup.py --- .../Python/telescope_track_params_lookup.py | 199 ------------------ 1 file changed, 199 deletions(-) delete mode 100644 Examples/Scripts/Python/telescope_track_params_lookup.py diff --git a/Examples/Scripts/Python/telescope_track_params_lookup.py b/Examples/Scripts/Python/telescope_track_params_lookup.py deleted file mode 100644 index 0f0ab96df8e..00000000000 --- a/Examples/Scripts/Python/telescope_track_params_lookup.py +++ /dev/null @@ -1,199 +0,0 @@ -#!/usr/bin/env python3 - -import argparse - -import acts -import acts.examples -from acts.examples.simulation import ( - addParticleGun, - addFatras, - MomentumConfig, - EtaConfig, - PhiConfig, - ParticleConfig, -) - -u = acts.UnitConstants - -def estimateLookup( - trackingGeometry, - numEvents, - outputPath): - - # Set up the magnetic field - field = acts.ConstantBField(acts.Vector3(50 * u.T, 0, 0)) - - # Fatras simulation of muons - rnd = acts.examples.RandomNumbers(seed=42) - - s = acts.examples.Sequencer(events=numEvents, numThreads=1, logLevel=acts.logging.INFO) - - vertexGen=acts.examples.GaussianVertexGenerator( - stddev=acts.Vector4(0, 0, 0, 0), - mean=acts.Vector4(0, 9, 0, 0) - ) - - addParticleGun( - s=s, - etaConfig=EtaConfig(10.0, 10.0), - phiConfig=PhiConfig(0, 0), - momentumConfig=MomentumConfig(0.5 * u.GeV, 10 * u.GeV), - particleConfig=ParticleConfig(1, acts.PdgParticle.eMuon, False), - multiplicity=1, - rnd=rnd, - vtxGen = vertexGen - ) - - addFatras( - s, - trackingGeometry, - field, - inputParticles="particles_input", - outputSimHits="sim_hits", - rnd=rnd, - preSelectParticles=None - ) - - # Set up the track lookup grid writer - jsonWriterConfig = acts.examples.JsonTrackParamsLookupWriter.Config( - path=outputPath - ) - jsonWriter = acts.examples.JsonTrackParamsLookupWriter(jsonWriterConfig) - - # Set up the track estimation algorithm - surfaces = list(trackingGeometry.geoIdSurfaceMap().values()) - refSurface = surfaces[0] - refGeometryId = refSurface.geometryId() - - trackEstConfig = acts.examples.TrackParamsLookupEstimation.Config( - refLayers={refGeometryId : refSurface}, - bins=(1, 1000), - inputHits="sim_hits", - inputParticles="particles_input", - trackLookupGridWriters = [jsonWriter] - ) - trackEstAlg = acts.examples.TrackParamsLookupEstimation(trackEstConfig, acts.logging.INFO) - - s.addAlgorithm(trackEstAlg) - - s.run() - -def validateLookup( - trackingGeometry, - numEvents, - inputPath): - - # Set up the magnetic field - field = acts.ConstantBField(acts.Vector3(50 * u.T, 0, 0)) - - # Fatras simulation of muons - rnd = acts.examples.RandomNumbers(seed=92) - - s = acts.examples.Sequencer(events=numEvents, numThreads=1, logLevel=acts.logging.INFO) - - vertexGen=acts.examples.GaussianVertexGenerator( - stddev=acts.Vector4(0, 0, 0, 0), - mean=acts.Vector4(0, 9, 0, 0) - ) - - addParticleGun( - s=s, - etaConfig=EtaConfig(10.0, 10.0), - phiConfig=PhiConfig(0, 0), - momentumConfig=MomentumConfig(0.5 * u.GeV, 10 * u.GeV), - particleConfig=ParticleConfig(1, acts.PdgParticle.eMuon, False), - multiplicity=1, - rnd=rnd, - vtxGen = vertexGen - ) - - addFatras( - s, - trackingGeometry, - field, - inputParticles="particles_input", - outputSimHits="sim_hits", - rnd=rnd, - preSelectParticles=None - ) - - # Set up the track lookup grid reader - surfaces = list(trackingGeometry.geoIdSurfaceMap().values()) - refSurface = surfaces[0] - refGeometryId = refSurface.geometryId() - - jsonReaderConfig = acts.examples.JsonTrackParamsLookupReader.Config( - refLayers={refGeometryId : refSurface}, - bins=(1, 1000)) - jsonReader = acts.examples.JsonTrackParamsLookupReader(jsonReaderConfig) - - lookupConfig = acts.examples.TrackParamsLookupProvider.Config( - jsonReader, - inputPath) - lookup = acts.examples.TrackParamsLookupProvider(lookupConfig) - - refSurf = list(trackingGeometry.geoIdSurfaceMap().values())[0] - - validaterConfig = acts.examples.TrackParamsLookupValidation.Config() - validaterConfig.refLayers={refSurf.geometryId(): refSurf} - validaterConfig.lookup=lookup - validaterConfig.inputHits="sim_hits" - validaterConfig.inputParticles="particles_input" - validaterConfig.outputIpPars="ip_pars" - validaterConfig.outputRefLayerPars="ref_layer_pars" - validaterConfig.outputIpParsEst="ip_pars_est" - validaterConfig.outputRefLayerParsEst="ref_layer_pars_est" - alg = acts.examples.TrackParamsLookupValidation(validaterConfig, acts.logging.INFO) - - s.addAlgorithm(alg) - - # writer - writerConfig = acts.examples.RootTrackParamsValidationWriter.Config() - - writerConfig.inputIpPars="ip_pars" - writerConfig.inputRefLayerPars="ref_layer_pars" - writerConfig.inputIpParsEst="ip_pars_est" - writerConfig.inputRefLayerParsEst="ref_layer_pars_est" - writerConfig.path=inputPath.replace(".json", ".root") - writerConfig.treeName="test" - - writer = acts.examples.RootTrackParamsValidationWriter(writerConfig, acts.logging.INFO) - - s.addWriter(writer) - - s.run() - -if __name__ == "__main__": - p = argparse.ArgumentParser() - - p.add_argument( - "-nest", "--estimate", type=int, default=10000000, help="Number of events for lookup estimation" - ) - p.add_argument( - "-nval", "--validate", type=int, default=100000, help="Number of events for lookup validation" - ) - p.add_argument( - "-o", "--output", type=str, default="/home/romanurmanov/tools/acts/acts_telescope_geo/ActsTelescopeGeometryDevelopment_build/test2", help="Output lookup file name" - ) - - args = p.parse_args() - - # Initialize the geometry - detector, trackingGeometry, decorators = acts.examples.TelescopeDetector.create( - bounds=[4, 10], - positions=[30, 60, 90], - stereos=[0, 0, 0], - binValue=2, - surfaceType=0 - ) - - estimateLookup( - trackingGeometry, - args.estimate, - args.output) - - validateLookup( - trackingGeometry, - args.validate, - args.output + ".json") - \ No newline at end of file From bd0ded92d2725adae7f09f0287572bca008b78b0 Mon Sep 17 00:00:00 2001 From: ssdetlab Date: Wed, 6 Nov 2024 23:39:31 +0200 Subject: [PATCH 04/23] lint --- .../Io/Json/JsonTrackParamsLookupReader.hpp | 2 +- .../Io/Json/JsonTrackParamsLookupWriter.hpp | 2 +- Examples/Python/src/Json.cpp | 23 +++++----- ...elescope_track_params_lookup_generation.py | 43 +++++++++++-------- 4 files changed, 38 insertions(+), 32 deletions(-) diff --git a/Examples/Io/Json/include/ActsExamples/Io/Json/JsonTrackParamsLookupReader.hpp b/Examples/Io/Json/include/ActsExamples/Io/Json/JsonTrackParamsLookupReader.hpp index f5d0bc63095..b3f63e2a738 100644 --- a/Examples/Io/Json/include/ActsExamples/Io/Json/JsonTrackParamsLookupReader.hpp +++ b/Examples/Io/Json/include/ActsExamples/Io/Json/JsonTrackParamsLookupReader.hpp @@ -40,7 +40,7 @@ class JsonTrackParamsLookupReader final : public ITrackParamsLookupReader { std::pair bins; }; - JsonTrackParamsLookupReader(const Config& config) : m_cfg(config){}; + JsonTrackParamsLookupReader(const Config& config) : m_cfg(config) {}; ~JsonTrackParamsLookupReader() override = default; diff --git a/Examples/Io/Json/include/ActsExamples/Io/Json/JsonTrackParamsLookupWriter.hpp b/Examples/Io/Json/include/ActsExamples/Io/Json/JsonTrackParamsLookupWriter.hpp index 6e6c3cd2817..30c37f0d7f4 100644 --- a/Examples/Io/Json/include/ActsExamples/Io/Json/JsonTrackParamsLookupWriter.hpp +++ b/Examples/Io/Json/include/ActsExamples/Io/Json/JsonTrackParamsLookupWriter.hpp @@ -37,7 +37,7 @@ class JsonTrackParamsLookupWriter final : public ITrackParamsLookupWriter { /// Constructor /// /// @param config The configuration struct of the writer - JsonTrackParamsLookupWriter(const Config& config) : m_cfg(config){}; + JsonTrackParamsLookupWriter(const Config& config) : m_cfg(config) {}; /// Virtual destructor ~JsonTrackParamsLookupWriter() override = default; diff --git a/Examples/Python/src/Json.cpp b/Examples/Python/src/Json.cpp index 491d2fc67e4..12baaa9f6d3 100644 --- a/Examples/Python/src/Json.cpp +++ b/Examples/Python/src/Json.cpp @@ -274,18 +274,17 @@ void addJson(Context& ctx) { } { - mex.def( - "readDetectorFromJson", - [](const Acts::GeometryContext& gctx, - const std::string& fileName) -> auto{ - auto in = std::ifstream(fileName, - std::ifstream::in | std::ifstream::binary); - nlohmann::json jDetectorIn; - in >> jDetectorIn; - in.close(); - - return Acts::DetectorJsonConverter::fromJson(gctx, jDetectorIn); - }); + mex.def("readDetectorFromJson", + [](const Acts::GeometryContext& gctx, + const std::string& fileName) -> auto { + auto in = std::ifstream( + fileName, std::ifstream::in | std::ifstream::binary); + nlohmann::json jDetectorIn; + in >> jDetectorIn; + in.close(); + + return Acts::DetectorJsonConverter::fromJson(gctx, jDetectorIn); + }); } } } // namespace Acts::Python diff --git a/Examples/Scripts/Python/telescope_track_params_lookup_generation.py b/Examples/Scripts/Python/telescope_track_params_lookup_generation.py index 7af8e5a315e..ed566b04468 100644 --- a/Examples/Scripts/Python/telescope_track_params_lookup_generation.py +++ b/Examples/Scripts/Python/telescope_track_params_lookup_generation.py @@ -26,11 +26,12 @@ def estimateLookup( # Fatras simulation of muons rnd = acts.examples.RandomNumbers(seed=42) - s = acts.examples.Sequencer(events=numEvents, numThreads=1, logLevel=acts.logging.INFO) + s = acts.examples.Sequencer( + events=numEvents, numThreads=1, logLevel=acts.logging.INFO + ) vertexGen=acts.examples.GaussianVertexGenerator( - stddev=acts.Vector4(0, 0, 0, 0), - mean=acts.Vector4(0, 9, 0, 0) + stddev=acts.Vector4(0, 0, 0, 0), mean=acts.Vector4(0, 9, 0, 0) ) addParticleGun( @@ -41,7 +42,7 @@ def estimateLookup( particleConfig=ParticleConfig(1, acts.PdgParticle.eMuon, False), multiplicity=1, rnd=rnd, - vtxGen = vertexGen + vtxGen=vertexGen, ) addFatras( @@ -51,13 +52,11 @@ def estimateLookup( inputParticles="particles_input", outputSimHits="sim_hits", rnd=rnd, - preSelectParticles=None + preSelectParticles=None, ) # Set up the track lookup grid writer - jsonWriterConfig = acts.examples.JsonTrackParamsLookupWriter.Config( - path=outputPath - ) + jsonWriterConfig = acts.examples.JsonTrackParamsLookupWriter.Config(path=outputPath) jsonWriter = acts.examples.JsonTrackParamsLookupWriter(jsonWriterConfig) # Set up the track estimation algorithm @@ -66,26 +65,37 @@ def estimateLookup( refGeometryId = refSurface.geometryId() trackEstConfig = acts.examples.TrackParamsLookupEstimation.Config( - refLayers={refGeometryId : refSurface}, + refLayers={refGeometryId: refSurface}, bins=(1, 1000), inputHits="sim_hits", inputParticles="particles_input", - trackLookupGridWriters = [jsonWriter] + trackLookupGridWriters = [jsonWriter], + ) + trackEstAlg = acts.examples.TrackParamsLookupEstimation( + trackEstConfig, acts.logging.INFO ) - trackEstAlg = acts.examples.TrackParamsLookupEstimation(trackEstConfig, acts.logging.INFO) s.addAlgorithm(trackEstAlg) s.run() + if __name__ == "__main__": p = argparse.ArgumentParser() p.add_argument( - "-n", "--events", type=int, default=100000, help="Number of events for lookup estimation" + "-n", + "--events", + type=int, + default=100000, + help="Number of events for lookup estimation", ) p.add_argument( - "-o", "--output", type=str, default="lookup.json", help="Output lookup file name" + "-o", + "--output", + type=str, + default="lookup.json", + help="Output lookup file name", ) args = p.parse_args() @@ -96,12 +106,9 @@ def estimateLookup( positions=[30, 60, 90], stereos=[0, 0, 0], binValue=2, - surfaceType=0 + surfaceType=0, ) # Estimate the lookup - estimateLookup( - trackingGeometry, - args.events, - args.output) + estimateLookup(trackingGeometry, args.events, args.output) \ No newline at end of file From 4a7b23de0b2c628c1cf0e21cbb13bbcb9c32f952 Mon Sep 17 00:00:00 2001 From: ssdetlab Date: Wed, 6 Nov 2024 23:44:50 +0200 Subject: [PATCH 05/23] lint --- ...elescope_track_params_lookup_generation.py | 26 ++++++++----------- 1 file changed, 11 insertions(+), 15 deletions(-) diff --git a/Examples/Scripts/Python/telescope_track_params_lookup_generation.py b/Examples/Scripts/Python/telescope_track_params_lookup_generation.py index ed566b04468..b1d322f10d4 100644 --- a/Examples/Scripts/Python/telescope_track_params_lookup_generation.py +++ b/Examples/Scripts/Python/telescope_track_params_lookup_generation.py @@ -15,10 +15,7 @@ u = acts.UnitConstants -def estimateLookup( - trackingGeometry, - numEvents, - outputPath): +def estimateLookup(trackingGeometry, numEvents, outputPath): # Set up the dipole magnetic field field = acts.ConstantBField(acts.Vector3(50 * u.T, 0, 0)) @@ -30,7 +27,7 @@ def estimateLookup( events=numEvents, numThreads=1, logLevel=acts.logging.INFO ) - vertexGen=acts.examples.GaussianVertexGenerator( + vertexGen = acts.examples.GaussianVertexGenerator( stddev=acts.Vector4(0, 0, 0, 0), mean=acts.Vector4(0, 9, 0, 0) ) @@ -69,7 +66,7 @@ def estimateLookup( bins=(1, 1000), inputHits="sim_hits", inputParticles="particles_input", - trackLookupGridWriters = [jsonWriter], + trackLookupGridWriters=[jsonWriter], ) trackEstAlg = acts.examples.TrackParamsLookupEstimation( trackEstConfig, acts.logging.INFO @@ -84,17 +81,17 @@ def estimateLookup( p = argparse.ArgumentParser() p.add_argument( - "-n", - "--events", - type=int, - default=100000, + "-n", + "--events", + type=int, + default=100000, help="Number of events for lookup estimation", ) p.add_argument( - "-o", - "--output", - type=str, - default="lookup.json", + "-o", + "--output", + type=str, + default="lookup.json", help="Output lookup file name", ) @@ -111,4 +108,3 @@ def estimateLookup( # Estimate the lookup estimateLookup(trackingGeometry, args.events, args.output) - \ No newline at end of file From bee43543c5437ce8b23152c9f236d291aa087bcc Mon Sep 17 00:00:00 2001 From: ssdetlab Date: Wed, 6 Nov 2024 23:47:07 +0200 Subject: [PATCH 06/23] lint --- .../Scripts/Python/telescope_track_params_lookup_generation.py | 1 + 1 file changed, 1 insertion(+) diff --git a/Examples/Scripts/Python/telescope_track_params_lookup_generation.py b/Examples/Scripts/Python/telescope_track_params_lookup_generation.py index b1d322f10d4..ecdffc20ec3 100644 --- a/Examples/Scripts/Python/telescope_track_params_lookup_generation.py +++ b/Examples/Scripts/Python/telescope_track_params_lookup_generation.py @@ -15,6 +15,7 @@ u = acts.UnitConstants + def estimateLookup(trackingGeometry, numEvents, outputPath): # Set up the dipole magnetic field From 472cd7ea6098a628bbf2cdae8b36461528ee5b46 Mon Sep 17 00:00:00 2001 From: ssdetlab Date: Mon, 11 Nov 2024 22:53:20 +0200 Subject: [PATCH 07/23] core accumulator, cleanup --- .../TrackParamsLookupAccumulator.hpp | 210 +++++++++++++++++ .../Algorithms/TrackFinding/CMakeLists.txt | 1 - .../TrackFinding/ITrackParamsLookupReader.hpp | 2 +- .../TrackFinding/ITrackParamsLookupWriter.hpp | 2 +- .../TrackParamsLookupAccumulator.hpp | 64 ----- .../TrackParamsLookupEstimation.hpp | 9 +- .../TrackFinding/TrackParamsLookupTable.hpp | 35 ++- .../src/TrackParamsLookupAccumulator.cpp | 73 ------ .../Io/Json/JsonTrackParamsLookupReader.hpp | 31 +-- .../Io/Json/JsonTrackParamsLookupWriter.hpp | 8 +- .../Core/TrackFinding/CMakeLists.txt | 1 + .../TrackParamsLookupAccumulatorTests.cpp | 220 ++++++++++++++++++ 12 files changed, 473 insertions(+), 183 deletions(-) create mode 100644 Core/include/Acts/TrackFinding/TrackParamsLookupAccumulator.hpp delete mode 100644 Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/TrackParamsLookupAccumulator.hpp delete mode 100644 Examples/Algorithms/TrackFinding/src/TrackParamsLookupAccumulator.cpp create mode 100644 Tests/UnitTests/Core/TrackFinding/TrackParamsLookupAccumulatorTests.cpp diff --git a/Core/include/Acts/TrackFinding/TrackParamsLookupAccumulator.hpp b/Core/include/Acts/TrackFinding/TrackParamsLookupAccumulator.hpp new file mode 100644 index 00000000000..96e1e330caf --- /dev/null +++ b/Core/include/Acts/TrackFinding/TrackParamsLookupAccumulator.hpp @@ -0,0 +1,210 @@ +// This file is part of the ACTS project. +// +// Copyright (C) 2016 CERN for the benefit of the ACTS project +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +#pragma once + +#include "Acts/EventData/GenericBoundTrackParameters.hpp" +#include "Acts/EventData/TrackParametersConcept.hpp" +#include "Acts/Geometry/GeometryContext.hpp" + +#include +#include +#include +#include +#include + +namespace { + +/// @brief Shorthand for track parameters +template +concept TrackParameters = Acts::FreeTrackParametersConcept || + Acts::BoundTrackParametersConcept; + +/// @brief Shorthand for GenericBoundTrackParameters +template +concept IsGenericBound = + std::same_as>; + +/// @brief Concept that restricts the type of the +/// accumulation grid cell +template +concept TrackParamsGrid = requires { + std::same_as>, + std::shared_ptr>>>; + + std::same_as; + + TrackParameters< + std::remove_pointer_t>; + TrackParameters< + std::remove_pointer_t>; +}; + +} // namespace + +namespace Acts { + +/// @brief Class to accumulate and average track lookup tables +/// +/// @tparam Grid type for track parameters accumulation +/// +/// This class is used to accumulate track parameters in +/// reference layer grids and average them to create a lookup +/// table for track parameter estimation in seeding +/// +/// @note Geometry context is left to be handled by the user +/// outside of accumulation +template +class TrackParamsLookupAccumulator { + public: + using LookupGrid = grid_t; + using TrackParameters = std::pointer_traits< + typename grid_t::value_type::first_type>::element_type; + + /// @brief Constructor + TrackParamsLookupAccumulator(grid_t grid) : m_grid(std::move(grid)) {} + + /// @brief Add track parameters to the accumulator + /// + /// @param gctx Geometry context + /// @param ipTrackParameters Track parameters at the IP + /// @param refTrackParameters Track parameters at the reference layer + /// @param position Local position of the track hit on the reference layer + void addTrack(const TrackParameters& ipTrackParameters, + const TrackParameters& refTrackParameters, + const Vector2& position) { + auto bin = m_grid.localBinsFromPosition(position); + + if (m_countGrid[bin] == 0) { + m_grid.atLocalBins(bin).first = + std::make_shared(ipTrackParameters); + m_grid.atLocalBins(bin).second = + std::make_shared(refTrackParameters); + + m_countGrid.at(bin)++; + return; + } + + *m_grid.atLocalBins(bin).first = + addTrackParameters(*m_grid.atLocalBins(bin).first, ipTrackParameters); + *m_grid.atLocalBins(bin).second = + addTrackParameters(*m_grid.atLocalBins(bin).second, refTrackParameters); + m_countGrid.at(bin)++; + } + + /// @brief Finalize the lookup table + /// + /// @return Grid with the bin track parameters averaged + LookupGrid finalizeLookup() { + auto meanTrack = [&](const TrackParameters& track, std::size_t count) { + if constexpr (IsGenericBound) { + Acts::GeometryContext gctx; + + auto res = TrackParameters::create( + track.referenceSurface().getSharedPtr(), gctx, + track.fourPosition(gctx) / count, track.momentum().normalized(), + count * track.charge() / track.momentum().norm(), + track.covariance(), track.particleHypothesis()); + + if (!res.ok()) { + throw std::invalid_argument("Bound track grid finalization failed"); + } + return res.value(); + } else { + return TrackParameters(track.fourPosition() / count, + track.momentum().normalized(), + count * track.charge() / track.momentum().norm(), + track.covariance(), track.particleHypothesis()); + } + }; + + for (auto [bin, count] : m_countGrid) { + if (count == 0) { + continue; + } + *m_grid.atLocalBins(bin).first = + meanTrack(*m_grid.atLocalBins(bin).first, count); + *m_grid.atLocalBins(bin).second = + meanTrack(*m_grid.atLocalBins(bin).second, count); + } + + return m_grid; + } + + private: + /// @brief Add two track parameters + /// + /// @param gctx Geometry context + /// @param a First track parameter in the sum + /// @param b Second track parameter in the sum + /// + /// @return Sum of track parameters a + b + /// + /// @note Covariances of the track parameters + /// are not added and instead assumed to be + /// generated by the same random process for + /// both a and b, making its averaging redundant + TrackParameters addTrackParameters(const TrackParameters& a, + const TrackParameters& b) { + if (a.particleHypothesis() != b.particleHypothesis()) { + throw std::invalid_argument( + "Cannot accumulate track parameters with different particle " + "hypotheses"); + } + if (a.charge() != b.charge()) { + throw std::invalid_argument( + "Cannot accumulate track parameters with different charges"); + } + if constexpr (IsGenericBound) { + if (a.referenceSurface() != b.referenceSurface()) { + throw std::invalid_argument( + "Cannot accumulate bound track parameters with different reference " + "surfaces"); + } + } + + Acts::Vector3 momentum = a.momentum() + b.momentum(); + + // Assume track parameters being i.i.d. + if constexpr (IsGenericBound) { + Acts::GeometryContext gctx; + + Acts::Vector4 fourPosition = a.fourPosition(gctx) + b.fourPosition(gctx); + + auto res = TrackParameters::create( + a.referenceSurface().getSharedPtr(), gctx, fourPosition, + momentum.normalized(), a.charge() / momentum.norm(), a.covariance(), + a.particleHypothesis()); + + if (!res.ok()) { + throw std::invalid_argument("Invalid bound track parameters"); + } + return res.value(); + } else { + Acts::Vector4 fourPosition = a.fourPosition() + b.fourPosition(); + return TrackParameters(fourPosition, momentum.normalized(), + a.charge() / momentum.norm(), a.covariance(), + a.particleHypothesis()); + } + } + + /// Grids to accumulate IP and reference + /// layer track parameters + LookupGrid m_grid; + + /// Map to keep the accumulation count + /// in the occupied grid bins + std::map, std::size_t> m_countGrid; +}; + +} // namespace Acts diff --git a/Examples/Algorithms/TrackFinding/CMakeLists.txt b/Examples/Algorithms/TrackFinding/CMakeLists.txt index 733ed6d2d7b..33b924e35aa 100644 --- a/Examples/Algorithms/TrackFinding/CMakeLists.txt +++ b/Examples/Algorithms/TrackFinding/CMakeLists.txt @@ -10,7 +10,6 @@ add_library( src/TrackParamsEstimationAlgorithm.cpp src/MuonHoughSeeder.cpp src/GbtsSeedingAlgorithm.cpp - src/TrackParamsLookupAccumulator.cpp src/TrackParamsLookupEstimation.cpp ) diff --git a/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/ITrackParamsLookupReader.hpp b/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/ITrackParamsLookupReader.hpp index 8b1c387e8f4..1c1af6894b5 100644 --- a/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/ITrackParamsLookupReader.hpp +++ b/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/ITrackParamsLookupReader.hpp @@ -21,7 +21,7 @@ class ITrackParamsLookupReader { /// Reader method /// /// @param path the path to the file to read - virtual Lookup readLookup(const std::string& path) = 0; + virtual TrackParamsLookup readLookup(const std::string& path) = 0; }; } // namespace ActsExamples diff --git a/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/ITrackParamsLookupWriter.hpp b/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/ITrackParamsLookupWriter.hpp index e75b7b05bc5..9cddadae062 100644 --- a/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/ITrackParamsLookupWriter.hpp +++ b/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/ITrackParamsLookupWriter.hpp @@ -21,7 +21,7 @@ class ITrackParamsLookupWriter { /// Writer method /// /// @param lookup track lookup to write - virtual void writeLookup(const Lookup& lookup) = 0; + virtual void writeLookup(const TrackParamsLookup& lookup) const = 0; }; } // namespace ActsExamples diff --git a/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/TrackParamsLookupAccumulator.hpp b/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/TrackParamsLookupAccumulator.hpp deleted file mode 100644 index a09b62357cc..00000000000 --- a/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/TrackParamsLookupAccumulator.hpp +++ /dev/null @@ -1,64 +0,0 @@ -// This file is part of the ACTS project. -// -// Copyright (C) 2016 CERN for the benefit of the ACTS project -// -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this -// file, You can obtain one at https://mozilla.org/MPL/2.0/. - -#pragma once - -#include "ActsExamples/TrackFinding/TrackParamsLookupTable.hpp" - -namespace ActsExamples { - -/// @brief Class to accumulate and average track lookup tables -/// -/// This class is used to accumulate track parameters in -/// reference layer grids and average them to create a lookup -/// table for track parameter estimation in seeding -class TrackParamsLookupAccumulator { - public: - /// @brief Nested configuration struct - struct Config { - /// Axis generator - LookupAxisGen axisGen; - }; - - /// @brief Constructor - TrackParamsLookupAccumulator(const Config& config) - : m_cfg(std::move(config)), - m_ipGrid(m_cfg.axisGen()), - m_refGrid(m_cfg.axisGen()) {} - - /// @brief Add track parameters to the accumulator - /// - /// @param ipTrackParameters the track parameters at the IP - /// @param refTrackParameters the track parameters at the reference layer - /// @param position local position of the track hit on the reference layer - void addTrack(const Acts::CurvilinearTrackParameters& ipTrackParameters, - const Acts::CurvilinearTrackParameters& refTrackParameters, - const Acts::Vector2& position); - - /// @brief Finalize the lookup table - /// - /// Return the grid with the bin track parameters averaged - LookupGrid finalizeLookup(); - - /// Get readonly access to the config parameters - const Config& config() const { return m_cfg; } - - private: - /// Configuration - Config m_cfg; - - /// Mutex for modifying the grid - std::mutex m_writeMutex; - - /// Grids to accumulate IP and reference - /// layer track parameters - LookupAccumGrid m_ipGrid; - LookupAccumGrid m_refGrid; -}; - -} // namespace ActsExamples diff --git a/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/TrackParamsLookupEstimation.hpp b/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/TrackParamsLookupEstimation.hpp index 1978915cee8..27187024421 100644 --- a/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/TrackParamsLookupEstimation.hpp +++ b/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/TrackParamsLookupEstimation.hpp @@ -8,12 +8,14 @@ #pragma once +#include "Acts/TrackFinding/TrackParamsLookupAccumulator.hpp" #include "ActsExamples/EventData/SimHit.hpp" #include "ActsExamples/EventData/SimParticle.hpp" #include "ActsExamples/Framework/DataHandle.hpp" #include "ActsExamples/Framework/IAlgorithm.hpp" #include "ActsExamples/TrackFinding/ITrackParamsLookupWriter.hpp" -#include "ActsExamples/TrackFinding/TrackParamsLookupAccumulator.hpp" + +#include namespace ActsExamples { @@ -26,6 +28,9 @@ namespace ActsExamples { /// to create a lookup table for track parameter estimation in seeding. class TrackParamsLookupEstimation : public IAlgorithm { public: + using TrackParamsLookupAccumulator = + Acts::TrackParamsLookupAccumulator; + /// @brief Nested configuration struct struct Config { /// Reference tracking layers @@ -52,6 +57,8 @@ class TrackParamsLookupEstimation : public IAlgorithm { /// @brief The execute method ProcessCode execute(const AlgorithmContext& ctx) const override; + ProcessCode finalize() override; + /// Get readonly access to the config parameters const Config& config() const { return m_cfg; } diff --git a/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/TrackParamsLookupTable.hpp b/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/TrackParamsLookupTable.hpp index 32e4264e3e0..5b9c1fabd83 100644 --- a/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/TrackParamsLookupTable.hpp +++ b/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/TrackParamsLookupTable.hpp @@ -9,43 +9,36 @@ #pragma once #include "Acts/EventData/TrackParameters.hpp" -#include "Acts/Utilities/Axis.hpp" #include "Acts/Utilities/Grid.hpp" #include "Acts/Utilities/GridAxisGenerators.hpp" +#include +#include + namespace ActsExamples { +using TrackParamsLookupPair = + std::pair, + std::shared_ptr>; + /// @brief Track parameters lookup table axis used /// in the track estimation algorithm -using LookupAxis = +using TrackParamsLookupAxis = Acts::Axis; /// @brief Track parameters lookup table axis generator /// used in the track estimation algorithm -using LookupAxisGen = Acts::GridAxisGenerators::EqOpenEqOpen; - -/// @brief Grid used to accumulate IP track parameters and -/// reference layer track parameters for a given position -/// in the track estimation algorithm -using LookupAccumGrid = - Acts::Grid, LookupAxis, - LookupAxis>; - -/// @brief Container for the lookup accumulation grids to -/// handle multiple reference layers in the track estimation -using LookupAccumGridContainer = - std::unordered_map; - -/// @brief IP-reference layer track parameters lookup pair -using LookupPair = std::pair, - std::shared_ptr>; +using TrackParamsLookupAxisGen = Acts::GridAxisGenerators::EqOpenEqOpen; /// @brief Lookup grid for track parameters estimation /// in a given layer -using LookupGrid = Acts::Grid; +using TrackParamsLookupGrid = + Acts::Grid; /// @brief Lookup table for track parameters estimation /// in the track estimation algorithm -using Lookup = std::unordered_map; +using TrackParamsLookup = + std::unordered_map; } // namespace ActsExamples diff --git a/Examples/Algorithms/TrackFinding/src/TrackParamsLookupAccumulator.cpp b/Examples/Algorithms/TrackFinding/src/TrackParamsLookupAccumulator.cpp deleted file mode 100644 index 69fa94a022f..00000000000 --- a/Examples/Algorithms/TrackFinding/src/TrackParamsLookupAccumulator.cpp +++ /dev/null @@ -1,73 +0,0 @@ -// This file is part of the ACTS project. -// -// Copyright (C) 2016 CERN for the benefit of the ACTS project -// -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this -// file, You can obtain one at https://mozilla.org/MPL/2.0/. - -#include "ActsExamples/TrackFinding/TrackParamsLookupAccumulator.hpp" - -#include "Acts/EventData/TrackParameters.hpp" -#include "Acts/Utilities/Grid.hpp" -#include "Acts/Utilities/GridIterator.hpp" - -void ActsExamples::TrackParamsLookupAccumulator::addTrack( - const Acts::CurvilinearTrackParameters& ipTrackParameters, - const Acts::CurvilinearTrackParameters& refTrackParameters, - const Acts::Vector2& position) { - // Lock the write mutex - std::lock_guard lock(m_writeMutex); - - // Get the local bins from the position - auto bin = m_ipGrid.localBinsFromPosition(position); - - // Add the track parameters to the grid - m_ipGrid.atLocalBins(bin).push_back(ipTrackParameters); - m_refGrid.atLocalBins(bin).push_back(refTrackParameters); -} - -ActsExamples::LookupGrid -ActsExamples::TrackParamsLookupAccumulator::finalizeLookup() { - // Average track parameters in a given bin - auto meanTrack = - [](const std::vector& tracks) { - Acts::Vector4 fourPosition = Acts::Vector4::Zero(); - Acts::Vector3 direction = Acts::Vector3::Zero(); - Acts::ActsScalar qOverP = 0; - for (const auto& track : tracks) { - fourPosition += track.fourPosition(); - direction += track.direction(); - qOverP += track.qOverP(); - } - fourPosition /= tracks.size(); - direction /= tracks.size(); - qOverP /= tracks.size(); - - return Acts::CurvilinearTrackParameters( - fourPosition, direction, qOverP, std::nullopt, - tracks.front().particleHypothesis()); - }; - - // Create a lookup grid with the same parameters as - // the accumulation grids - ActsExamples::LookupGrid lookupGrid(m_cfg.axisGen()); - - // Iterate over the bins and average the track parameters - for (auto it = m_ipGrid.begin(); it != m_ipGrid.end(); ++it) { - auto bin = it.localBinsIndices(); - if (m_ipGrid.atLocalBins(bin).empty() || - m_refGrid.atLocalBins(bin).empty()) { - continue; - } - - // Store the IP-reference-position correspondence - lookupGrid.atLocalBins(bin) = - std::make_pair(std::make_shared( - meanTrack(m_ipGrid.atLocalBins(bin))), - std::make_shared( - meanTrack(m_refGrid.atLocalBins(bin)))); - } - - return lookupGrid; -} diff --git a/Examples/Io/Json/include/ActsExamples/Io/Json/JsonTrackParamsLookupReader.hpp b/Examples/Io/Json/include/ActsExamples/Io/Json/JsonTrackParamsLookupReader.hpp index b3f63e2a738..0346112ec81 100644 --- a/Examples/Io/Json/include/ActsExamples/Io/Json/JsonTrackParamsLookupReader.hpp +++ b/Examples/Io/Json/include/ActsExamples/Io/Json/JsonTrackParamsLookupReader.hpp @@ -8,16 +8,11 @@ #pragma once -#include "Acts/Definitions/Algebra.hpp" -#include "Acts/Plugins/Json/ActsJson.hpp" #include "Acts/Plugins/Json/GridJsonConverter.hpp" -#include "Acts/Plugins/Json/TrackParametersJsonConverter.hpp" #include "Acts/Surfaces/RectangleBounds.hpp" -#include "Acts/Utilities/GridAxisGenerators.hpp" #include "ActsExamples/TrackFinding/ITrackParamsLookupReader.hpp" #include -#include #include @@ -40,17 +35,22 @@ class JsonTrackParamsLookupReader final : public ITrackParamsLookupReader { std::pair bins; }; - JsonTrackParamsLookupReader(const Config& config) : m_cfg(config) {}; + JsonTrackParamsLookupReader(const Config& config) : m_cfg(config){}; ~JsonTrackParamsLookupReader() override = default; - Lookup readLookup(const std::string& path) final { + /// @brief Read the lookup from a json file + /// + /// @param path path to the json file + /// + /// @return lookup table for track parameter estimation + TrackParamsLookup readLookup(const std::string& path) final { // Read the json file std::ifstream ifj(path); nlohmann::json jLookup; ifj >> jLookup; - Lookup lookup; + TrackParamsLookup lookup; // Iterate over the json and deserialize the grids for (const auto& jGrid : jLookup) { Acts::GeometryIdentifier id(jGrid["geo_id"]); @@ -73,17 +73,18 @@ class JsonTrackParamsLookupReader final : public ITrackParamsLookupReader { auto halfX = bounds->halfLengthX(); auto halfY = bounds->halfLengthY(); - LookupAxisGen axisGen{{-halfX, halfX}, - m_cfg.bins.first, - {-halfY, halfY}, - m_cfg.bins.second}; + TrackParamsLookupAxisGen axisGen{{-halfX, halfX}, + m_cfg.bins.first, + {-halfY, halfY}, + m_cfg.bins.second}; // Deserialize the grid - LookupGrid grid = - Acts::GridJsonConverter::fromJson( + TrackParamsLookupGrid grid = + Acts::GridJsonConverter::fromJson( jGrid["grid"], axisGen); - lookup.insert({id, grid}); + lookup.insert({id, std::move(grid)}); } return lookup; diff --git a/Examples/Io/Json/include/ActsExamples/Io/Json/JsonTrackParamsLookupWriter.hpp b/Examples/Io/Json/include/ActsExamples/Io/Json/JsonTrackParamsLookupWriter.hpp index 30c37f0d7f4..1708d1a49fe 100644 --- a/Examples/Io/Json/include/ActsExamples/Io/Json/JsonTrackParamsLookupWriter.hpp +++ b/Examples/Io/Json/include/ActsExamples/Io/Json/JsonTrackParamsLookupWriter.hpp @@ -8,14 +8,10 @@ #pragma once -#include "Acts/Definitions/Algebra.hpp" -#include "Acts/Plugins/Json/ActsJson.hpp" #include "Acts/Plugins/Json/GridJsonConverter.hpp" -#include "Acts/Plugins/Json/TrackParametersJsonConverter.hpp" #include "ActsExamples/TrackFinding/ITrackParamsLookupWriter.hpp" #include -#include #include @@ -42,10 +38,10 @@ class JsonTrackParamsLookupWriter final : public ITrackParamsLookupWriter { /// Virtual destructor ~JsonTrackParamsLookupWriter() override = default; - /// Write out the material map + /// Write out track parameters lookup table /// /// @param lookup The lookup to write - void writeLookup(const Lookup& lookup) final { + void writeLookup(const TrackParamsLookup& lookup) const final { nlohmann::json jLookup; // Iterate over the lookup and serialize the grids diff --git a/Tests/UnitTests/Core/TrackFinding/CMakeLists.txt b/Tests/UnitTests/Core/TrackFinding/CMakeLists.txt index 523200299ac..bf0c520d672 100644 --- a/Tests/UnitTests/Core/TrackFinding/CMakeLists.txt +++ b/Tests/UnitTests/Core/TrackFinding/CMakeLists.txt @@ -1,2 +1,3 @@ add_unittest(CombinatorialKalmanFilter CombinatorialKalmanFilterTests.cpp) add_unittest(TrackSelector TrackSelectorTests.cpp) +add_unittest(TrackParamsLookupAccumulator TrackParamsLookupAccumulatorTests.cpp) diff --git a/Tests/UnitTests/Core/TrackFinding/TrackParamsLookupAccumulatorTests.cpp b/Tests/UnitTests/Core/TrackFinding/TrackParamsLookupAccumulatorTests.cpp new file mode 100644 index 00000000000..19e498c2054 --- /dev/null +++ b/Tests/UnitTests/Core/TrackFinding/TrackParamsLookupAccumulatorTests.cpp @@ -0,0 +1,220 @@ +// This file is part of the ACTS project. +// +// Copyright (C) 2016 CERN for the benefit of the ACTS project +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +#include +#include +#include + +#include "Acts/Definitions/Algebra.hpp" +#include "Acts/EventData/ParticleHypothesis.hpp" +#include "Acts/EventData/TrackParameters.hpp" +#include "Acts/Geometry/GeometryContext.hpp" +#include "Acts/Surfaces/PlaneSurface.hpp" +#include "Acts/Surfaces/RectangleBounds.hpp" +#include "Acts/Surfaces/Surface.hpp" +#include "Acts/Tests/CommonHelpers/FloatComparisons.hpp" +#include "Acts/TrackFinding/TrackParamsLookupAccumulator.hpp" +#include "Acts/Utilities/AxisFwd.hpp" +#include "Acts/Utilities/Grid.hpp" +#include "Acts/Utilities/GridAxisGenerators.hpp" + +#include +#include +#include +#include +#include + +BOOST_AUTO_TEST_SUITE(TrackParamsLookupAccumulator) + +Acts::GeometryContext gctx; + +using Axis = + Acts::Axis; +using AxisGen = Acts::GridAxisGenerators::EqOpenEqOpen; + +using CellBound = std::pair, + std::shared_ptr>; + +using GridBound = Acts::Grid; +using AccBound = Acts::TrackParamsLookupAccumulator; + +using CellCurvilinear = + std::pair, + std::shared_ptr>; + +using GridCurvilinear = Acts::Grid; +using AccCurvilinear = Acts::TrackParamsLookupAccumulator; + +using CellFree = std::pair, + std::shared_ptr>; + +using GridFree = Acts::Grid; +using AccFree = Acts::TrackParamsLookupAccumulator; + +AxisGen axisGen{{-1, 1}, 2, {-1, 1}, 2}; + +BOOST_AUTO_TEST_CASE(Exceptions) { + // Instantiate grid + GridBound grid(axisGen()); + AccBound acc(grid); + + // Create a reference surface for bound parameters + auto tranform = Acts::Transform3::Identity(); + auto bounds1 = std::make_shared(1, 1); + auto bounds2 = std::make_shared(2, 2); + + auto surf1 = Acts::Surface::makeShared(tranform, bounds1); + + auto surf2 = Acts::Surface::makeShared(tranform, bounds2); + + // Create paramters to accumulate + Acts::Vector4 pos{1, 2, 0, 4}; + Acts::Vector3 dir{1, 0, 0}; + Acts::ActsScalar P = 1; + + auto hypothesis1 = Acts::ParticleHypothesis::electron(); + auto hypothesis2 = Acts::ParticleHypothesis::muon(); + + auto pars1 = Acts::BoundTrackParameters::create(surf1, gctx, pos, dir, 1. / P, + std::nullopt, hypothesis1) + .value(); + + auto pars2 = Acts::BoundTrackParameters::create(surf2, gctx, pos, dir, 1. / P, + std::nullopt, hypothesis1) + .value(); + + auto pars3 = Acts::BoundTrackParameters::create(surf1, gctx, pos, dir, 1. / P, + std::nullopt, hypothesis2) + .value(); + + auto pars4 = Acts::BoundTrackParameters::create( + surf1, gctx, pos, dir, -1. / P, std::nullopt, hypothesis2) + .value(); + + // Get the point of the grid + auto bin = grid.localBinsFromGlobalBin(2); + auto center = grid.binCenter(bin); + Acts::Vector2 loc{center.at(0), center.at(1)}; + + // Fill in grid + acc.addTrack(pars1, pars1, loc); + + // Different reference surfaces + BOOST_CHECK_THROW(acc.addTrack(pars2, pars2, loc), std::invalid_argument); + + // Different particle hypotheses + BOOST_CHECK_THROW(acc.addTrack(pars3, pars3, loc), std::invalid_argument); + + // Different charges + BOOST_CHECK_THROW(acc.addTrack(pars4, pars4, loc), std::invalid_argument); +} + +BOOST_AUTO_TEST_CASE(Accumulation) { + // Instantiate grids + GridBound gridBound(axisGen()); + AccBound accBound(gridBound); + + GridCurvilinear gridCurvilinear(axisGen()); + AccCurvilinear accCurvilinear(gridCurvilinear); + + GridFree gridFree(axisGen()); + AccFree accFree(gridFree); + + // Create a reference surface for bound parameters + auto tranform = Acts::Transform3::Identity(); + auto bounds = std::make_shared(1, 1); + auto surf = Acts::Surface::makeShared(tranform, bounds); + + auto hypothesis = Acts::ParticleHypothesis::electron(); + + std::vector avgPoss; + std::vector avgMoms; + for (std::size_t i = 0; i < gridBound.size(); i++) { + // Create paramters to accumulate + Acts::Vector4 pos{1, 2, 0, 4}; + std::array fourPositions = { + pos * (i + 1), + pos * (i + 2), + pos * (i + 3), + pos * (i + 4), + }; + + std::array thetas = {M_PI / (i + 1), M_PI / (i + 2), + M_PI / (i + 3), M_PI / (i + 4)}; + + std::array phis = { + 2 * M_PI / (i + 1), 2 * M_PI / (i + 2), 2 * M_PI / (i + 3), + 2 * M_PI / (i + 4)}; + + Acts::ActsScalar P = 1.5 * (i + 1); + + // Get the point of the grid + auto bin = gridBound.localBinsFromGlobalBin(i); + auto center = gridBound.binCenter(bin); + Acts::Vector2 loc{center.at(0), center.at(1)}; + + // Accumulate + Acts::Vector4 avgPos; + Acts::Vector3 avgMom; + for (std::size_t j = 0; j < fourPositions.size(); j++) { + Acts::Vector3 direction{std::sin(thetas.at(j)) * std::cos(phis.at(j)), + std::sin(thetas.at(j)) * std::sin(phis.at(j)), + std::cos(thetas.at(j))}; + + avgPos += fourPositions.at(j); + avgMom += P * direction; + + // Fill in each grid + auto parsBound = Acts::BoundTrackParameters::create( + surf, gctx, fourPositions.at(j), direction, 1. / P, + std::nullopt, hypothesis) + .value(); + + auto parsCurvilinear = Acts::CurvilinearTrackParameters( + fourPositions.at(j), direction, 1. / P, std::nullopt, hypothesis); + + auto parsFree = Acts::FreeTrackParameters( + fourPositions.at(j), direction, 1. / P, std::nullopt, hypothesis); + + accBound.addTrack(parsBound, parsBound, loc); + accCurvilinear.addTrack(parsCurvilinear, parsCurvilinear, loc); + accFree.addTrack(parsFree, parsFree, loc); + } + avgPoss.push_back(avgPos / fourPositions.size()); + avgMoms.push_back(avgMom / fourPositions.size()); + } + + GridBound avgGridBound = accBound.finalizeLookup(); + GridCurvilinear avgGridCurvilinear = accCurvilinear.finalizeLookup(); + GridFree avgGridFree = accFree.finalizeLookup(); + for (std::size_t i = 0; i < avgGridBound.size(); i++) { + auto [ipBound, refBound] = avgGridBound.at(i); + auto [ipCurvilinear, refCurvilinear] = avgGridCurvilinear.at(i); + auto [ipFree, refFree] = avgGridFree.at(i); + + Acts::Vector4 avgPos = avgPoss.at(i); + + Acts::Vector3 avgMom = avgMoms.at(i); + Acts::Vector3 avgDir = avgMom.normalized(); + Acts::ActsScalar avgP = avgMom.norm(); + + CHECK_CLOSE_ABS(ipBound->fourPosition(gctx), avgPos, 1e-3); + CHECK_CLOSE_ABS(ipBound->direction(), avgDir, 1e-3); + CHECK_CLOSE_ABS(ipBound->absoluteMomentum(), avgP, 1e-3); + + CHECK_CLOSE_ABS(ipCurvilinear->fourPosition(), avgPos, 1e-3); + CHECK_CLOSE_ABS(ipCurvilinear->direction(), avgDir, 1e-3); + CHECK_CLOSE_ABS(ipCurvilinear->absoluteMomentum(), avgP, 1e-3); + + CHECK_CLOSE_ABS(ipFree->fourPosition(), avgPos, 1e-3); + CHECK_CLOSE_ABS(ipFree->direction(), avgDir, 1e-3); + CHECK_CLOSE_ABS(ipFree->absoluteMomentum(), avgP, 1e-3); + } +} + +BOOST_AUTO_TEST_SUITE_END() From 61765906f9395bebed0494cee1cd6c14f3d52561 Mon Sep 17 00:00:00 2001 From: ssdetlab Date: Mon, 11 Nov 2024 23:43:17 +0200 Subject: [PATCH 08/23] requires fixes --- .../TrackParamsLookupAccumulator.hpp | 36 +++++++++++-------- 1 file changed, 22 insertions(+), 14 deletions(-) diff --git a/Core/include/Acts/TrackFinding/TrackParamsLookupAccumulator.hpp b/Core/include/Acts/TrackFinding/TrackParamsLookupAccumulator.hpp index 96e1e330caf..e0bdcfc222d 100644 --- a/Core/include/Acts/TrackFinding/TrackParamsLookupAccumulator.hpp +++ b/Core/include/Acts/TrackFinding/TrackParamsLookupAccumulator.hpp @@ -15,6 +15,7 @@ #include #include #include +#include #include #include @@ -31,23 +32,30 @@ concept IsGenericBound = std::same_as>; +template +using removeShared = std::remove_reference_t())>; + /// @brief Concept that restricts the type of the /// accumulation grid cell template concept TrackParamsGrid = requires { - std::same_as>, - std::shared_ptr>>>; - - std::same_as; - - TrackParameters< - std::remove_pointer_t>; - TrackParameters< - std::remove_pointer_t>; + typename grid_t::value_type::first_type; + typename grid_t::value_type::second_type; + + requires TrackParameters< + removeShared>; + requires TrackParameters< + removeShared>; + + requires requires(grid_t::value_type val) { + { + val.first + } -> std::same_as>&>; + { + val.second + } -> std::same_as>&>; + { val.second } -> std::same_as; + }; }; } // namespace @@ -187,7 +195,7 @@ class TrackParamsLookupAccumulator { a.particleHypothesis()); if (!res.ok()) { - throw std::invalid_argument("Invalid bound track parameters"); + throw std::runtime_error("Invalid bound track parameters"); } return res.value(); } else { From d8c26620633c078f62fc23b80cdb18549af32fa3 Mon Sep 17 00:00:00 2001 From: ssdetlab Date: Mon, 11 Nov 2024 23:52:13 +0200 Subject: [PATCH 09/23] forgotten source --- .../src/TrackParamsLookupEstimation.cpp | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/Examples/Algorithms/TrackFinding/src/TrackParamsLookupEstimation.cpp b/Examples/Algorithms/TrackFinding/src/TrackParamsLookupEstimation.cpp index 3baa25a513e..ed589d4f7e7 100644 --- a/Examples/Algorithms/TrackFinding/src/TrackParamsLookupEstimation.cpp +++ b/Examples/Algorithms/TrackFinding/src/TrackParamsLookupEstimation.cpp @@ -8,8 +8,8 @@ #include "ActsExamples/TrackFinding/TrackParamsLookupEstimation.hpp" -#include "Acts/EventData/SourceLink.hpp" #include "Acts/Surfaces/RectangleBounds.hpp" +#include "ActsExamples/Framework/ProcessCode.hpp" ActsExamples::TrackParamsLookupEstimation::TrackParamsLookupEstimation( const Config& config, Acts::Logging::Level level) @@ -30,29 +30,30 @@ ActsExamples::TrackParamsLookupEstimation::TrackParamsLookupEstimation( auto halfX = bounds->halfLengthX(); auto halfY = bounds->halfLengthY(); - LookupAxisGen axisGen{ + TrackParamsLookupAxisGen axisGen{ {-halfX, halfX}, m_cfg.bins.first, {-halfY, halfY}, m_cfg.bins.second}; - TrackParamsLookupAccumulator::Config accConfig{axisGen}; - // Each reference layer has its own accumulator - m_accumulators[geoId] = - std::make_unique(accConfig); + m_accumulators[geoId] = std::make_unique( + TrackParamsLookupGrid(axisGen())); } m_inputParticles.initialize(m_cfg.inputParticles); m_inputSimHits.initialize(m_cfg.inputHits); } -ActsExamples::TrackParamsLookupEstimation::~TrackParamsLookupEstimation() { +ActsExamples::ProcessCode +ActsExamples::TrackParamsLookupEstimation::finalize() { // Finiliaze the lookup tables and write them - ActsExamples::Lookup lookup; + ActsExamples::TrackParamsLookup lookup; for (auto& [id, acc] : m_accumulators) { lookup.insert({id, acc->finalizeLookup()}); } for (auto& writer : m_cfg.trackLookupGridWriters) { writer->writeLookup(lookup); } + + return ActsExamples::ProcessCode::SUCCESS; }; ActsExamples::ProcessCode ActsExamples::TrackParamsLookupEstimation::execute( From 8608c70d53975802f938cf5099be5adcd3f79809 Mon Sep 17 00:00:00 2001 From: ssdetlab Date: Tue, 12 Nov 2024 00:05:26 +0200 Subject: [PATCH 10/23] lint --- .../TrackParamsLookupAccumulatorTests.cpp | 27 +++++++++++-------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/Tests/UnitTests/Core/TrackFinding/TrackParamsLookupAccumulatorTests.cpp b/Tests/UnitTests/Core/TrackFinding/TrackParamsLookupAccumulatorTests.cpp index 19e498c2054..996c81894a8 100644 --- a/Tests/UnitTests/Core/TrackFinding/TrackParamsLookupAccumulatorTests.cpp +++ b/Tests/UnitTests/Core/TrackFinding/TrackParamsLookupAccumulatorTests.cpp @@ -25,6 +25,7 @@ #include #include +#include #include #include #include @@ -64,15 +65,17 @@ BOOST_AUTO_TEST_CASE(Exceptions) { AccBound acc(grid); // Create a reference surface for bound parameters - auto tranform = Acts::Transform3::Identity(); + auto transform = Acts::Transform3::Identity(); auto bounds1 = std::make_shared(1, 1); auto bounds2 = std::make_shared(2, 2); - auto surf1 = Acts::Surface::makeShared(tranform, bounds1); + auto surf1 = + Acts::Surface::makeShared(transform, bounds1); - auto surf2 = Acts::Surface::makeShared(tranform, bounds2); + auto surf2 = + Acts::Surface::makeShared(transform, bounds2); - // Create paramters to accumulate + // Create parameters to accumulate Acts::Vector4 pos{1, 2, 0, 4}; Acts::Vector3 dir{1, 0, 0}; Acts::ActsScalar P = 1; @@ -126,16 +129,16 @@ BOOST_AUTO_TEST_CASE(Accumulation) { AccFree accFree(gridFree); // Create a reference surface for bound parameters - auto tranform = Acts::Transform3::Identity(); + auto transform = Acts::Transform3::Identity(); auto bounds = std::make_shared(1, 1); - auto surf = Acts::Surface::makeShared(tranform, bounds); + auto surf = Acts::Surface::makeShared(transform, bounds); auto hypothesis = Acts::ParticleHypothesis::electron(); std::vector avgPoss; std::vector avgMoms; for (std::size_t i = 0; i < gridBound.size(); i++) { - // Create paramters to accumulate + // Create parameters to accumulate Acts::Vector4 pos{1, 2, 0, 4}; std::array fourPositions = { pos * (i + 1), @@ -144,12 +147,13 @@ BOOST_AUTO_TEST_CASE(Accumulation) { pos * (i + 4), }; - std::array thetas = {M_PI / (i + 1), M_PI / (i + 2), - M_PI / (i + 3), M_PI / (i + 4)}; + std::array thetas = { + std::numbers::pi / (i + 1), std::numbers::pi / (i + 2), + std::numbers::pi / (i + 3), std::numbers::pi / (i + 4)}; std::array phis = { - 2 * M_PI / (i + 1), 2 * M_PI / (i + 2), 2 * M_PI / (i + 3), - 2 * M_PI / (i + 4)}; + 2 * std::numbers::pi / (i + 1), 2 * std::numbers::pi / (i + 2), + 2 * std::numbers::pi / (i + 3), 2 * std::numbers::pi / (i + 4)}; Acts::ActsScalar P = 1.5 * (i + 1); @@ -189,6 +193,7 @@ BOOST_AUTO_TEST_CASE(Accumulation) { avgMoms.push_back(avgMom / fourPositions.size()); } + // Finalize and compare GridBound avgGridBound = accBound.finalizeLookup(); GridCurvilinear avgGridCurvilinear = accCurvilinear.finalizeLookup(); GridFree avgGridFree = accFree.finalizeLookup(); From 3d990d913b868568ec3720698d3787971bdb3b41 Mon Sep 17 00:00:00 2001 From: ssdetlab Date: Tue, 12 Nov 2024 00:50:00 +0200 Subject: [PATCH 11/23] test discrepancies --- .../Core/TrackFinding/TrackParamsLookupAccumulatorTests.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Tests/UnitTests/Core/TrackFinding/TrackParamsLookupAccumulatorTests.cpp b/Tests/UnitTests/Core/TrackFinding/TrackParamsLookupAccumulatorTests.cpp index 996c81894a8..d19cb482a2c 100644 --- a/Tests/UnitTests/Core/TrackFinding/TrackParamsLookupAccumulatorTests.cpp +++ b/Tests/UnitTests/Core/TrackFinding/TrackParamsLookupAccumulatorTests.cpp @@ -191,6 +191,9 @@ BOOST_AUTO_TEST_CASE(Accumulation) { } avgPoss.push_back(avgPos / fourPositions.size()); avgMoms.push_back(avgMom / fourPositions.size()); + + std::cout << "STORING " << i << ":\n"; + std::cout << avgPoss.back().transpose() << std::endl; } // Finalize and compare @@ -208,6 +211,9 @@ BOOST_AUTO_TEST_CASE(Accumulation) { Acts::Vector3 avgDir = avgMom.normalized(); Acts::ActsScalar avgP = avgMom.norm(); + std::cout << ipBound->fourPosition(gctx).transpose() << " vs " + << avgPos.transpose() << "\n"; + CHECK_CLOSE_ABS(ipBound->fourPosition(gctx), avgPos, 1e-3); CHECK_CLOSE_ABS(ipBound->direction(), avgDir, 1e-3); CHECK_CLOSE_ABS(ipBound->absoluteMomentum(), avgP, 1e-3); From ea796e3ced0d97f1cd3f0a1a45e79efe301f7a1b Mon Sep 17 00:00:00 2001 From: ssdetlab Date: Tue, 12 Nov 2024 01:21:42 +0200 Subject: [PATCH 12/23] memory shenanigans --- .../TrackParamsLookupAccumulatorTests.cpp | 22 +++++-------------- 1 file changed, 6 insertions(+), 16 deletions(-) diff --git a/Tests/UnitTests/Core/TrackFinding/TrackParamsLookupAccumulatorTests.cpp b/Tests/UnitTests/Core/TrackFinding/TrackParamsLookupAccumulatorTests.cpp index d19cb482a2c..10e12747fce 100644 --- a/Tests/UnitTests/Core/TrackFinding/TrackParamsLookupAccumulatorTests.cpp +++ b/Tests/UnitTests/Core/TrackFinding/TrackParamsLookupAccumulatorTests.cpp @@ -137,15 +137,11 @@ BOOST_AUTO_TEST_CASE(Accumulation) { std::vector avgPoss; std::vector avgMoms; + Acts::Vector4 pos{1, 2, 0, 4}; for (std::size_t i = 0; i < gridBound.size(); i++) { // Create parameters to accumulate - Acts::Vector4 pos{1, 2, 0, 4}; - std::array fourPositions = { - pos * (i + 1), - pos * (i + 2), - pos * (i + 3), - pos * (i + 4), - }; + std::array fourPositions = {pos * (i + 1), pos * (i + 2), + pos * (i + 3), pos * (i + 4)}; std::array thetas = { std::numbers::pi / (i + 1), std::numbers::pi / (i + 2), @@ -163,9 +159,9 @@ BOOST_AUTO_TEST_CASE(Accumulation) { Acts::Vector2 loc{center.at(0), center.at(1)}; // Accumulate - Acts::Vector4 avgPos; - Acts::Vector3 avgMom; - for (std::size_t j = 0; j < fourPositions.size(); j++) { + Acts::Vector4 avgPos{0, 0, 0, 0}; + Acts::Vector3 avgMom{0, 0, 0}; + for (std::size_t j = 0; j < 4; j++) { Acts::Vector3 direction{std::sin(thetas.at(j)) * std::cos(phis.at(j)), std::sin(thetas.at(j)) * std::sin(phis.at(j)), std::cos(thetas.at(j))}; @@ -191,9 +187,6 @@ BOOST_AUTO_TEST_CASE(Accumulation) { } avgPoss.push_back(avgPos / fourPositions.size()); avgMoms.push_back(avgMom / fourPositions.size()); - - std::cout << "STORING " << i << ":\n"; - std::cout << avgPoss.back().transpose() << std::endl; } // Finalize and compare @@ -211,9 +204,6 @@ BOOST_AUTO_TEST_CASE(Accumulation) { Acts::Vector3 avgDir = avgMom.normalized(); Acts::ActsScalar avgP = avgMom.norm(); - std::cout << ipBound->fourPosition(gctx).transpose() << " vs " - << avgPos.transpose() << "\n"; - CHECK_CLOSE_ABS(ipBound->fourPosition(gctx), avgPos, 1e-3); CHECK_CLOSE_ABS(ipBound->direction(), avgDir, 1e-3); CHECK_CLOSE_ABS(ipBound->absoluteMomentum(), avgP, 1e-3); From 8d43d18b8103b2a59fafb07412b58800a03c122e Mon Sep 17 00:00:00 2001 From: ssdetlab Date: Tue, 12 Nov 2024 14:11:12 +0200 Subject: [PATCH 13/23] docs and python fixes --- .../TrackParamsLookupAccumulator.hpp | 16 ++-- .../TrackParamsLookupEstimation.hpp | 2 +- .../src/TrackParamsLookupValidation.cpp | 82 +++++++++++++++++++ .../Io/Json/JsonTrackParamsLookupReader.hpp | 2 +- 4 files changed, 91 insertions(+), 11 deletions(-) create mode 100644 Examples/Algorithms/TrackFinding/src/TrackParamsLookupValidation.cpp diff --git a/Core/include/Acts/TrackFinding/TrackParamsLookupAccumulator.hpp b/Core/include/Acts/TrackFinding/TrackParamsLookupAccumulator.hpp index e0bdcfc222d..504c528bfd1 100644 --- a/Core/include/Acts/TrackFinding/TrackParamsLookupAccumulator.hpp +++ b/Core/include/Acts/TrackFinding/TrackParamsLookupAccumulator.hpp @@ -33,7 +33,7 @@ concept IsGenericBound = typename parameters_t::ParticleHypothesis>>; template -using removeShared = std::remove_reference_t())>; +using remove_shared = std::remove_reference_t())>; /// @brief Concept that restricts the type of the /// accumulation grid cell @@ -43,17 +43,17 @@ concept TrackParamsGrid = requires { typename grid_t::value_type::second_type; requires TrackParameters< - removeShared>; + remove_shared>; requires TrackParameters< - removeShared>; + remove_shared>; - requires requires(grid_t::value_type val) { + requires requires(typename grid_t::value_type val) { { val.first - } -> std::same_as>&>; + } -> std::same_as>&>; { val.second - } -> std::same_as>&>; + } -> std::same_as>&>; { val.second } -> std::same_as; }; }; @@ -76,7 +76,7 @@ template class TrackParamsLookupAccumulator { public: using LookupGrid = grid_t; - using TrackParameters = std::pointer_traits< + using TrackParameters = typename std::pointer_traits< typename grid_t::value_type::first_type>::element_type; /// @brief Constructor @@ -84,7 +84,6 @@ class TrackParamsLookupAccumulator { /// @brief Add track parameters to the accumulator /// - /// @param gctx Geometry context /// @param ipTrackParameters Track parameters at the IP /// @param refTrackParameters Track parameters at the reference layer /// @param position Local position of the track hit on the reference layer @@ -152,7 +151,6 @@ class TrackParamsLookupAccumulator { private: /// @brief Add two track parameters /// - /// @param gctx Geometry context /// @param a First track parameter in the sum /// @param b Second track parameter in the sum /// diff --git a/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/TrackParamsLookupEstimation.hpp b/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/TrackParamsLookupEstimation.hpp index 27187024421..fcf1489f042 100644 --- a/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/TrackParamsLookupEstimation.hpp +++ b/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/TrackParamsLookupEstimation.hpp @@ -52,7 +52,7 @@ class TrackParamsLookupEstimation : public IAlgorithm { TrackParamsLookupEstimation(const Config& config, Acts::Logging::Level level); /// @brief Destructor - ~TrackParamsLookupEstimation(); + ~TrackParamsLookupEstimation() = default; /// @brief The execute method ProcessCode execute(const AlgorithmContext& ctx) const override; diff --git a/Examples/Algorithms/TrackFinding/src/TrackParamsLookupValidation.cpp b/Examples/Algorithms/TrackFinding/src/TrackParamsLookupValidation.cpp new file mode 100644 index 00000000000..3f15847537e --- /dev/null +++ b/Examples/Algorithms/TrackFinding/src/TrackParamsLookupValidation.cpp @@ -0,0 +1,82 @@ +// This file is part of the ACTS project. +// +// Copyright (C) 2016 CERN for the benefit of the ACTS project +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +#include "ActsExamples/TrackFinding/TrackParamsLookupValidation.hpp" + +ActsExamples::TrackParamsLookupValidation::TrackParamsLookupValidation( + const Config& config, Acts::Logging::Level level) + : IAlgorithm("TrackParamsLookupValidation", level), + m_cfg(std::move(config)) { + m_inputSimHits.initialize(m_cfg.inputHits); + m_inputParticles.initialize(m_cfg.inputParticles); + + m_outputIpPars.initialize(m_cfg.outputIpPars); + m_outputRefLayerPars.initialize(m_cfg.outputRefLayerPars); + m_outputIpParsEst.initialize(m_cfg.outputIpParsEst); + m_outputRefLayerParsEst.initialize(m_cfg.outputRefLayerParsEst); +} + +ActsExamples::ProcessCode ActsExamples::TrackParamsLookupValidation::execute( + const AlgorithmContext& ctx) const { + auto particles = m_inputParticles(ctx); + auto hits = m_inputSimHits(ctx); + + auto calibrator = + [&, this](const Acts::GeometryContext& gctx, + const ActsExamples::IndexSourceLink& isl) -> Acts::Vector2 { + auto hit = hits.nth(isl.index()); + return m_cfg.refLayers.at(isl.geometryId()) + ->globalToLocal(gctx, hit->position(), Acts::Vector3{0, 1, 0}) + .value(); + }; + + m_cfg.lookup->extensions().sourceLinkCalibrator.connect(calibrator); + + std::vector ipPars; + std::vector refLayerPars; + std::vector ipParsEst; + std::vector refLayerParsEst; + for (const auto& [geoId, refSurface] : m_cfg.refLayers) { + auto refLayerHits = hits.equal_range(geoId); + + for (auto hit = refLayerHits.first; hit != refLayerHits.second; ++hit) { + const auto& id = hit->particleId(); + const auto& particle = particles.find(id); + + if (particle == particles.end()) { + throw std::invalid_argument("Particle not found"); + } + + auto ref = Acts::CurvilinearTrackParameters( + hit->fourPosition(), hit->direction(), particle->qOverP(), + std::nullopt, particle->hypothesis()); + + auto ip = Acts::CurvilinearTrackParameters( + particle->fourPosition(), particle->direction(), particle->qOverP(), + std::nullopt, particle->hypothesis()); + + ActsExamples::Index idx = hits.index_of(hit); + ActsExamples::IndexSourceLink isl{geoId, idx}; + + auto [ipEst, refEst] = + m_cfg.lookup->lookup(ctx.geoContext, Acts::SourceLink{isl}); + + ipPars.push_back(ip); + refLayerPars.push_back(ref); + ipParsEst.push_back(ipEst); + refLayerParsEst.push_back(refEst); + } + } + + m_outputIpPars(ctx, std::move(ipPars)); + m_outputRefLayerPars(ctx, std::move(refLayerPars)); + m_outputIpParsEst(ctx, std::move(ipParsEst)); + m_outputRefLayerParsEst(ctx, std::move(refLayerParsEst)); + + return ProcessCode::SUCCESS; +} diff --git a/Examples/Io/Json/include/ActsExamples/Io/Json/JsonTrackParamsLookupReader.hpp b/Examples/Io/Json/include/ActsExamples/Io/Json/JsonTrackParamsLookupReader.hpp index 0346112ec81..eca5fc01894 100644 --- a/Examples/Io/Json/include/ActsExamples/Io/Json/JsonTrackParamsLookupReader.hpp +++ b/Examples/Io/Json/include/ActsExamples/Io/Json/JsonTrackParamsLookupReader.hpp @@ -35,7 +35,7 @@ class JsonTrackParamsLookupReader final : public ITrackParamsLookupReader { std::pair bins; }; - JsonTrackParamsLookupReader(const Config& config) : m_cfg(config){}; + JsonTrackParamsLookupReader(const Config& config) : m_cfg(config) {}; ~JsonTrackParamsLookupReader() override = default; From 1ff8d2cffa85790e149da8e195586a7288f72e7d Mon Sep 17 00:00:00 2001 From: ssdetlab Date: Tue, 12 Nov 2024 14:25:38 +0200 Subject: [PATCH 14/23] thread safety --- .../Acts/TrackFinding/TrackParamsLookupAccumulator.hpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Core/include/Acts/TrackFinding/TrackParamsLookupAccumulator.hpp b/Core/include/Acts/TrackFinding/TrackParamsLookupAccumulator.hpp index 504c528bfd1..804a0d5b9e7 100644 --- a/Core/include/Acts/TrackFinding/TrackParamsLookupAccumulator.hpp +++ b/Core/include/Acts/TrackFinding/TrackParamsLookupAccumulator.hpp @@ -15,6 +15,7 @@ #include #include #include +#include #include #include #include @@ -90,6 +91,8 @@ class TrackParamsLookupAccumulator { void addTrack(const TrackParameters& ipTrackParameters, const TrackParameters& refTrackParameters, const Vector2& position) { + std::lock_guard lock(m_gridMutex); + auto bin = m_grid.localBinsFromPosition(position); if (m_countGrid[bin] == 0) { @@ -208,6 +211,9 @@ class TrackParamsLookupAccumulator { /// layer track parameters LookupGrid m_grid; + /// Mutex for protecting grid access + std::mutex m_gridMutex; + /// Map to keep the accumulation count /// in the occupied grid bins std::map, std::size_t> m_countGrid; From 252b173196019f2d8820c37e8b453314d78dedc6 Mon Sep 17 00:00:00 2001 From: ssdetlab Date: Tue, 12 Nov 2024 14:25:55 +0200 Subject: [PATCH 15/23] thread safety --- .../Acts/TrackFinding/TrackParamsLookupAccumulator.hpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Core/include/Acts/TrackFinding/TrackParamsLookupAccumulator.hpp b/Core/include/Acts/TrackFinding/TrackParamsLookupAccumulator.hpp index 804a0d5b9e7..228fbca21ac 100644 --- a/Core/include/Acts/TrackFinding/TrackParamsLookupAccumulator.hpp +++ b/Core/include/Acts/TrackFinding/TrackParamsLookupAccumulator.hpp @@ -211,8 +211,8 @@ class TrackParamsLookupAccumulator { /// layer track parameters LookupGrid m_grid; - /// Mutex for protecting grid access - std::mutex m_gridMutex; + /// Mutex for protecting grid access + std::mutex m_gridMutex; /// Map to keep the accumulation count /// in the occupied grid bins From f612334b27cb22f769e7a764d501aede08092686 Mon Sep 17 00:00:00 2001 From: ssdetlab Date: Tue, 12 Nov 2024 14:43:13 +0200 Subject: [PATCH 16/23] check surface type --- .../TrackFinding/src/TrackParamsLookupEstimation.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Examples/Algorithms/TrackFinding/src/TrackParamsLookupEstimation.cpp b/Examples/Algorithms/TrackFinding/src/TrackParamsLookupEstimation.cpp index ed589d4f7e7..44622aacdb3 100644 --- a/Examples/Algorithms/TrackFinding/src/TrackParamsLookupEstimation.cpp +++ b/Examples/Algorithms/TrackFinding/src/TrackParamsLookupEstimation.cpp @@ -25,6 +25,9 @@ ActsExamples::TrackParamsLookupEstimation::TrackParamsLookupEstimation( if (bounds == nullptr) { throw std::invalid_argument("Only rectangle bounds supported"); } + if (refSurface->type() != Acts::Surface::SurfaceType::Plane) { + throw std::invalid_argument("Only plane surfaces supported"); + } // Initialize the accumulator grid auto halfX = bounds->halfLengthX(); From c61b84614cdc208e730bda3df351aa3a62948599 Mon Sep 17 00:00:00 2001 From: ssdetlab <113530373+ssdetlab@users.noreply.github.com> Date: Tue, 12 Nov 2024 14:43:38 +0200 Subject: [PATCH 17/23] Delete Examples/Algorithms/TrackFinding/src/TrackParamsLookupValidation.cpp --- .../src/TrackParamsLookupValidation.cpp | 82 ------------------- 1 file changed, 82 deletions(-) delete mode 100644 Examples/Algorithms/TrackFinding/src/TrackParamsLookupValidation.cpp diff --git a/Examples/Algorithms/TrackFinding/src/TrackParamsLookupValidation.cpp b/Examples/Algorithms/TrackFinding/src/TrackParamsLookupValidation.cpp deleted file mode 100644 index 3f15847537e..00000000000 --- a/Examples/Algorithms/TrackFinding/src/TrackParamsLookupValidation.cpp +++ /dev/null @@ -1,82 +0,0 @@ -// This file is part of the ACTS project. -// -// Copyright (C) 2016 CERN for the benefit of the ACTS project -// -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this -// file, You can obtain one at https://mozilla.org/MPL/2.0/. - -#include "ActsExamples/TrackFinding/TrackParamsLookupValidation.hpp" - -ActsExamples::TrackParamsLookupValidation::TrackParamsLookupValidation( - const Config& config, Acts::Logging::Level level) - : IAlgorithm("TrackParamsLookupValidation", level), - m_cfg(std::move(config)) { - m_inputSimHits.initialize(m_cfg.inputHits); - m_inputParticles.initialize(m_cfg.inputParticles); - - m_outputIpPars.initialize(m_cfg.outputIpPars); - m_outputRefLayerPars.initialize(m_cfg.outputRefLayerPars); - m_outputIpParsEst.initialize(m_cfg.outputIpParsEst); - m_outputRefLayerParsEst.initialize(m_cfg.outputRefLayerParsEst); -} - -ActsExamples::ProcessCode ActsExamples::TrackParamsLookupValidation::execute( - const AlgorithmContext& ctx) const { - auto particles = m_inputParticles(ctx); - auto hits = m_inputSimHits(ctx); - - auto calibrator = - [&, this](const Acts::GeometryContext& gctx, - const ActsExamples::IndexSourceLink& isl) -> Acts::Vector2 { - auto hit = hits.nth(isl.index()); - return m_cfg.refLayers.at(isl.geometryId()) - ->globalToLocal(gctx, hit->position(), Acts::Vector3{0, 1, 0}) - .value(); - }; - - m_cfg.lookup->extensions().sourceLinkCalibrator.connect(calibrator); - - std::vector ipPars; - std::vector refLayerPars; - std::vector ipParsEst; - std::vector refLayerParsEst; - for (const auto& [geoId, refSurface] : m_cfg.refLayers) { - auto refLayerHits = hits.equal_range(geoId); - - for (auto hit = refLayerHits.first; hit != refLayerHits.second; ++hit) { - const auto& id = hit->particleId(); - const auto& particle = particles.find(id); - - if (particle == particles.end()) { - throw std::invalid_argument("Particle not found"); - } - - auto ref = Acts::CurvilinearTrackParameters( - hit->fourPosition(), hit->direction(), particle->qOverP(), - std::nullopt, particle->hypothesis()); - - auto ip = Acts::CurvilinearTrackParameters( - particle->fourPosition(), particle->direction(), particle->qOverP(), - std::nullopt, particle->hypothesis()); - - ActsExamples::Index idx = hits.index_of(hit); - ActsExamples::IndexSourceLink isl{geoId, idx}; - - auto [ipEst, refEst] = - m_cfg.lookup->lookup(ctx.geoContext, Acts::SourceLink{isl}); - - ipPars.push_back(ip); - refLayerPars.push_back(ref); - ipParsEst.push_back(ipEst); - refLayerParsEst.push_back(refEst); - } - } - - m_outputIpPars(ctx, std::move(ipPars)); - m_outputRefLayerPars(ctx, std::move(refLayerPars)); - m_outputIpParsEst(ctx, std::move(ipParsEst)); - m_outputRefLayerParsEst(ctx, std::move(refLayerParsEst)); - - return ProcessCode::SUCCESS; -} From 3432e579fb543c005edb10d46c84e9d0a307731f Mon Sep 17 00:00:00 2001 From: ssdetlab Date: Tue, 12 Nov 2024 17:20:04 +0200 Subject: [PATCH 18/23] some sonarcloud issues --- .../Acts/TrackFinding/TrackParamsLookupAccumulator.hpp | 3 ++- .../TrackFinding/TrackParamsLookupEstimation.hpp | 3 --- .../TrackFinding/src/TrackParamsLookupEstimation.cpp | 5 ++--- .../ActsExamples/Io/Json/JsonTrackParamsLookupReader.hpp | 8 ++++---- .../ActsExamples/Io/Json/JsonTrackParamsLookupWriter.hpp | 4 ++-- 5 files changed, 10 insertions(+), 13 deletions(-) diff --git a/Core/include/Acts/TrackFinding/TrackParamsLookupAccumulator.hpp b/Core/include/Acts/TrackFinding/TrackParamsLookupAccumulator.hpp index 228fbca21ac..3984c8f8f70 100644 --- a/Core/include/Acts/TrackFinding/TrackParamsLookupAccumulator.hpp +++ b/Core/include/Acts/TrackFinding/TrackParamsLookupAccumulator.hpp @@ -81,7 +81,8 @@ class TrackParamsLookupAccumulator { typename grid_t::value_type::first_type>::element_type; /// @brief Constructor - TrackParamsLookupAccumulator(grid_t grid) : m_grid(std::move(grid)) {} + explicit TrackParamsLookupAccumulator(grid_t grid) + : m_grid(std::move(grid)) {} /// @brief Add track parameters to the accumulator /// diff --git a/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/TrackParamsLookupEstimation.hpp b/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/TrackParamsLookupEstimation.hpp index fcf1489f042..e50991cd944 100644 --- a/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/TrackParamsLookupEstimation.hpp +++ b/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/TrackParamsLookupEstimation.hpp @@ -51,9 +51,6 @@ class TrackParamsLookupEstimation : public IAlgorithm { /// @brief Constructor TrackParamsLookupEstimation(const Config& config, Acts::Logging::Level level); - /// @brief Destructor - ~TrackParamsLookupEstimation() = default; - /// @brief The execute method ProcessCode execute(const AlgorithmContext& ctx) const override; diff --git a/Examples/Algorithms/TrackFinding/src/TrackParamsLookupEstimation.cpp b/Examples/Algorithms/TrackFinding/src/TrackParamsLookupEstimation.cpp index 44622aacdb3..4e4b283ddf9 100644 --- a/Examples/Algorithms/TrackFinding/src/TrackParamsLookupEstimation.cpp +++ b/Examples/Algorithms/TrackFinding/src/TrackParamsLookupEstimation.cpp @@ -13,8 +13,7 @@ ActsExamples::TrackParamsLookupEstimation::TrackParamsLookupEstimation( const Config& config, Acts::Logging::Level level) - : IAlgorithm("TrackParamsLookupEstimation", level), - m_cfg(std::move(config)) { + : IAlgorithm("TrackParamsLookupEstimation", level), m_cfg(config) { // Iterate over the reference layers and create // track parameter accumulators for (const auto& [geoId, refSurface] : m_cfg.refLayers) { @@ -52,7 +51,7 @@ ActsExamples::TrackParamsLookupEstimation::finalize() { for (auto& [id, acc] : m_accumulators) { lookup.insert({id, acc->finalizeLookup()}); } - for (auto& writer : m_cfg.trackLookupGridWriters) { + for (const auto& writer : m_cfg.trackLookupGridWriters) { writer->writeLookup(lookup); } diff --git a/Examples/Io/Json/include/ActsExamples/Io/Json/JsonTrackParamsLookupReader.hpp b/Examples/Io/Json/include/ActsExamples/Io/Json/JsonTrackParamsLookupReader.hpp index eca5fc01894..a07edd9a2a7 100644 --- a/Examples/Io/Json/include/ActsExamples/Io/Json/JsonTrackParamsLookupReader.hpp +++ b/Examples/Io/Json/include/ActsExamples/Io/Json/JsonTrackParamsLookupReader.hpp @@ -35,7 +35,7 @@ class JsonTrackParamsLookupReader final : public ITrackParamsLookupReader { std::pair bins; }; - JsonTrackParamsLookupReader(const Config& config) : m_cfg(config) {}; + explicit JsonTrackParamsLookupReader(const Config& config) : m_cfg(config) {}; ~JsonTrackParamsLookupReader() override = default; @@ -44,7 +44,7 @@ class JsonTrackParamsLookupReader final : public ITrackParamsLookupReader { /// @param path path to the json file /// /// @return lookup table for track parameter estimation - TrackParamsLookup readLookup(const std::string& path) final { + TrackParamsLookup readLookup(const std::string& path) override { // Read the json file std::ifstream ifj(path); nlohmann::json jLookup; @@ -55,7 +55,7 @@ class JsonTrackParamsLookupReader final : public ITrackParamsLookupReader { for (const auto& jGrid : jLookup) { Acts::GeometryIdentifier id(jGrid["geo_id"]); - if (m_cfg.refLayers.find(id) == m_cfg.refLayers.end()) { + if (m_cfg.refLayers.contains(id)) { throw std::invalid_argument("Geometry identifier not found"); } @@ -84,7 +84,7 @@ class JsonTrackParamsLookupReader final : public ITrackParamsLookupReader { TrackParamsLookupPair>( jGrid["grid"], axisGen); - lookup.insert({id, std::move(grid)}); + lookup.try_emplace(id, std::move(grid)); } return lookup; diff --git a/Examples/Io/Json/include/ActsExamples/Io/Json/JsonTrackParamsLookupWriter.hpp b/Examples/Io/Json/include/ActsExamples/Io/Json/JsonTrackParamsLookupWriter.hpp index 1708d1a49fe..63a2c083618 100644 --- a/Examples/Io/Json/include/ActsExamples/Io/Json/JsonTrackParamsLookupWriter.hpp +++ b/Examples/Io/Json/include/ActsExamples/Io/Json/JsonTrackParamsLookupWriter.hpp @@ -33,7 +33,7 @@ class JsonTrackParamsLookupWriter final : public ITrackParamsLookupWriter { /// Constructor /// /// @param config The configuration struct of the writer - JsonTrackParamsLookupWriter(const Config& config) : m_cfg(config) {}; + explicit JsonTrackParamsLookupWriter(const Config& config) : m_cfg(config) {}; /// Virtual destructor ~JsonTrackParamsLookupWriter() override = default; @@ -41,7 +41,7 @@ class JsonTrackParamsLookupWriter final : public ITrackParamsLookupWriter { /// Write out track parameters lookup table /// /// @param lookup The lookup to write - void writeLookup(const TrackParamsLookup& lookup) const final { + void writeLookup(const TrackParamsLookup& lookup) const override { nlohmann::json jLookup; // Iterate over the lookup and serialize the grids From 4f36db979730787ceb0e848e65756df4b3323524 Mon Sep 17 00:00:00 2001 From: ssdetlab Date: Tue, 12 Nov 2024 18:43:46 +0200 Subject: [PATCH 19/23] some consts --- .../ActsExamples/TrackFinding/ITrackParamsLookupReader.hpp | 2 +- .../ActsExamples/Io/Json/JsonTrackParamsLookupReader.hpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/ITrackParamsLookupReader.hpp b/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/ITrackParamsLookupReader.hpp index 1c1af6894b5..5777f90ef18 100644 --- a/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/ITrackParamsLookupReader.hpp +++ b/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/ITrackParamsLookupReader.hpp @@ -21,7 +21,7 @@ class ITrackParamsLookupReader { /// Reader method /// /// @param path the path to the file to read - virtual TrackParamsLookup readLookup(const std::string& path) = 0; + virtual TrackParamsLookup readLookup(const std::string& path) const = 0; }; } // namespace ActsExamples diff --git a/Examples/Io/Json/include/ActsExamples/Io/Json/JsonTrackParamsLookupReader.hpp b/Examples/Io/Json/include/ActsExamples/Io/Json/JsonTrackParamsLookupReader.hpp index a07edd9a2a7..52eb7249323 100644 --- a/Examples/Io/Json/include/ActsExamples/Io/Json/JsonTrackParamsLookupReader.hpp +++ b/Examples/Io/Json/include/ActsExamples/Io/Json/JsonTrackParamsLookupReader.hpp @@ -44,7 +44,7 @@ class JsonTrackParamsLookupReader final : public ITrackParamsLookupReader { /// @param path path to the json file /// /// @return lookup table for track parameter estimation - TrackParamsLookup readLookup(const std::string& path) override { + TrackParamsLookup readLookup(const std::string& path) const override { // Read the json file std::ifstream ifj(path); nlohmann::json jLookup; From 07483829c4521b7e4a783b19c10e73ea6408f331 Mon Sep 17 00:00:00 2001 From: ssdetlab Date: Wed, 13 Nov 2024 11:00:32 +0200 Subject: [PATCH 20/23] some fixes and cleanup --- .../TrackFinding/TrackParamsLookupAccumulator.hpp | 14 ++++---------- .../Io/Json/JsonTrackParamsLookupReader.hpp | 2 +- 2 files changed, 5 insertions(+), 11 deletions(-) diff --git a/Core/include/Acts/TrackFinding/TrackParamsLookupAccumulator.hpp b/Core/include/Acts/TrackFinding/TrackParamsLookupAccumulator.hpp index 3984c8f8f70..e4f50ec2537 100644 --- a/Core/include/Acts/TrackFinding/TrackParamsLookupAccumulator.hpp +++ b/Core/include/Acts/TrackFinding/TrackParamsLookupAccumulator.hpp @@ -17,7 +17,6 @@ #include #include #include -#include #include namespace { @@ -33,9 +32,6 @@ concept IsGenericBound = std::same_as>; -template -using remove_shared = std::remove_reference_t())>; - /// @brief Concept that restricts the type of the /// accumulation grid cell template @@ -44,17 +40,15 @@ concept TrackParamsGrid = requires { typename grid_t::value_type::second_type; requires TrackParameters< - remove_shared>; + typename grid_t::value_type::first_type::element_type>; requires TrackParameters< - remove_shared>; + typename grid_t::value_type::first_type::element_type>; requires requires(typename grid_t::value_type val) { { val.first - } -> std::same_as>&>; - { - val.second - } -> std::same_as>&>; + } -> std::same_as< + std::shared_ptr&>; { val.second } -> std::same_as; }; }; diff --git a/Examples/Io/Json/include/ActsExamples/Io/Json/JsonTrackParamsLookupReader.hpp b/Examples/Io/Json/include/ActsExamples/Io/Json/JsonTrackParamsLookupReader.hpp index 52eb7249323..94abea8b903 100644 --- a/Examples/Io/Json/include/ActsExamples/Io/Json/JsonTrackParamsLookupReader.hpp +++ b/Examples/Io/Json/include/ActsExamples/Io/Json/JsonTrackParamsLookupReader.hpp @@ -55,7 +55,7 @@ class JsonTrackParamsLookupReader final : public ITrackParamsLookupReader { for (const auto& jGrid : jLookup) { Acts::GeometryIdentifier id(jGrid["geo_id"]); - if (m_cfg.refLayers.contains(id)) { + if (!m_cfg.refLayers.contains(id)) { throw std::invalid_argument("Geometry identifier not found"); } From 369cfd221755c47d51cdb91f6f7d4ee2c1ec0405 Mon Sep 17 00:00:00 2001 From: ssdetlab Date: Wed, 20 Nov 2024 23:57:16 +0200 Subject: [PATCH 21/23] spearate concepts into detail --- .../EventData/detail/TrackParametersUtils.hpp | 49 +++++++++++++++++++ .../TrackParamsLookupAccumulator.hpp | 48 ++---------------- .../Json/TrackParametersJsonConverter.hpp | 30 +++--------- 3 files changed, 61 insertions(+), 66 deletions(-) create mode 100644 Core/include/Acts/EventData/detail/TrackParametersUtils.hpp diff --git a/Core/include/Acts/EventData/detail/TrackParametersUtils.hpp b/Core/include/Acts/EventData/detail/TrackParametersUtils.hpp new file mode 100644 index 00000000000..2efcef0e763 --- /dev/null +++ b/Core/include/Acts/EventData/detail/TrackParametersUtils.hpp @@ -0,0 +1,49 @@ +// This file is part of the ACTS project. +// +// Copyright (C) 2016 CERN for the benefit of the ACTS project +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +#pragma once + +#include "Acts/EventData/GenericBoundTrackParameters.hpp" +#include "Acts/EventData/TrackParametersConcept.hpp" + +namespace Acts::detail { + +/// @brief Shorthand for Bound or Free track parameters +template +concept isBoundOrFreeTrackParams = + Acts::FreeTrackParametersConcept || + Acts::BoundTrackParametersConcept; + +/// @brief Shorthand for GenericBoundTrackParameters +template +concept isGenericBoundTrackParams = + std::same_as>; + +/// @brief Concept that restricts the type of the +/// accumulation grid cell +template +concept TrackParamsGrid = requires { + typename grid_t::value_type::first_type; + typename grid_t::value_type::second_type; + + requires isBoundOrFreeTrackParams< + typename grid_t::value_type::first_type::element_type>; + requires isBoundOrFreeTrackParams< + typename grid_t::value_type::second_type::element_type>; + + requires requires(typename grid_t::value_type val) { + { + val.first + } -> std::same_as< + std::shared_ptr&>; + { val.second } -> std::same_as; + }; +}; + +} // namespace Acts::detail diff --git a/Core/include/Acts/TrackFinding/TrackParamsLookupAccumulator.hpp b/Core/include/Acts/TrackFinding/TrackParamsLookupAccumulator.hpp index e4f50ec2537..a1e1173335d 100644 --- a/Core/include/Acts/TrackFinding/TrackParamsLookupAccumulator.hpp +++ b/Core/include/Acts/TrackFinding/TrackParamsLookupAccumulator.hpp @@ -8,53 +8,15 @@ #pragma once -#include "Acts/EventData/GenericBoundTrackParameters.hpp" -#include "Acts/EventData/TrackParametersConcept.hpp" +#include "Acts/EventData/detail/TrackParametersUtils.hpp" #include "Acts/Geometry/GeometryContext.hpp" -#include #include #include #include #include #include -namespace { - -/// @brief Shorthand for track parameters -template -concept TrackParameters = Acts::FreeTrackParametersConcept || - Acts::BoundTrackParametersConcept; - -/// @brief Shorthand for GenericBoundTrackParameters -template -concept IsGenericBound = - std::same_as>; - -/// @brief Concept that restricts the type of the -/// accumulation grid cell -template -concept TrackParamsGrid = requires { - typename grid_t::value_type::first_type; - typename grid_t::value_type::second_type; - - requires TrackParameters< - typename grid_t::value_type::first_type::element_type>; - requires TrackParameters< - typename grid_t::value_type::first_type::element_type>; - - requires requires(typename grid_t::value_type val) { - { - val.first - } -> std::same_as< - std::shared_ptr&>; - { val.second } -> std::same_as; - }; -}; - -} // namespace - namespace Acts { /// @brief Class to accumulate and average track lookup tables @@ -67,7 +29,7 @@ namespace Acts { /// /// @note Geometry context is left to be handled by the user /// outside of accumulation -template +template class TrackParamsLookupAccumulator { public: using LookupGrid = grid_t; @@ -112,7 +74,7 @@ class TrackParamsLookupAccumulator { /// @return Grid with the bin track parameters averaged LookupGrid finalizeLookup() { auto meanTrack = [&](const TrackParameters& track, std::size_t count) { - if constexpr (IsGenericBound) { + if constexpr (detail::isGenericBoundTrackParams) { Acts::GeometryContext gctx; auto res = TrackParameters::create( @@ -169,7 +131,7 @@ class TrackParamsLookupAccumulator { throw std::invalid_argument( "Cannot accumulate track parameters with different charges"); } - if constexpr (IsGenericBound) { + if constexpr (detail::isGenericBoundTrackParams) { if (a.referenceSurface() != b.referenceSurface()) { throw std::invalid_argument( "Cannot accumulate bound track parameters with different reference " @@ -180,7 +142,7 @@ class TrackParamsLookupAccumulator { Acts::Vector3 momentum = a.momentum() + b.momentum(); // Assume track parameters being i.i.d. - if constexpr (IsGenericBound) { + if constexpr (detail::isGenericBoundTrackParams) { Acts::GeometryContext gctx; Acts::Vector4 fourPosition = a.fourPosition(gctx) + b.fourPosition(gctx); diff --git a/Plugins/Json/include/Acts/Plugins/Json/TrackParametersJsonConverter.hpp b/Plugins/Json/include/Acts/Plugins/Json/TrackParametersJsonConverter.hpp index ebf7d5c6054..f8683006fb5 100644 --- a/Plugins/Json/include/Acts/Plugins/Json/TrackParametersJsonConverter.hpp +++ b/Plugins/Json/include/Acts/Plugins/Json/TrackParametersJsonConverter.hpp @@ -8,28 +8,12 @@ #pragma once -#include "Acts/EventData/TrackParameters.hpp" -#include "Acts/Plugins/Json/ActsJson.hpp" +#include "Acts/Definitions/PdgParticle.hpp" +#include "Acts/EventData/detail/TrackParametersUtils.hpp" #include "Acts/Plugins/Json/SurfaceJsonConverter.hpp" #include -namespace { - -// Alias to bound adl_serializer specialization -// only to track parameters -template -concept TrackParameters = Acts::FreeTrackParametersConcept || - Acts::BoundTrackParametersConcept; - -// Shorthand for bound track parameters -template -concept IsGenericBound = - std::same_as>; - -} // namespace - namespace Acts { NLOHMANN_JSON_SERIALIZE_ENUM(Acts::PdgParticle, @@ -67,7 +51,7 @@ namespace nlohmann { /// convention is followed. /// /// @tparam parameters_t The track parameters type -template +template struct adl_serializer { /// Covariance matrix type attached to the parameters using CovarianceMatrix = typename parameters_t::CovarianceMatrix; @@ -101,7 +85,7 @@ struct adl_serializer { // Bound track parameters have // reference surface attached // and position takes a geometry context - if constexpr (IsGenericBound) { + if constexpr (Acts::detail::isBoundOrFreeTrackParams) { Acts::GeometryContext gctx; j["position"] = t.fourPosition(gctx); @@ -152,7 +136,7 @@ struct adl_serializer { // reference surface attached // and constructor is hidden // behind a factory method - if constexpr (IsGenericBound) { + if constexpr (Acts::detail::isBoundOrFreeTrackParams) { Acts::GeometryContext gctx; auto referenceSurface = Acts::SurfaceJsonConverter::fromJson(j.at("referenceSurface")); @@ -178,7 +162,7 @@ struct adl_serializer { /// convention is followed. /// /// @tparam parameters_t The track parameters type -template +template struct adl_serializer> { using CovarianceMatrix = typename parameters_t::CovarianceMatrix; static void to_json(nlohmann::json& j, @@ -202,7 +186,7 @@ struct adl_serializer> { /// convention is followed. /// /// @tparam parameters_t The track parameters type -template +template struct adl_serializer> { using CovarianceMatrix = typename parameters_t::CovarianceMatrix; static void to_json(nlohmann::json& j, From 7ce030547c469b7462d258ba2fefe7a9aebc603e Mon Sep 17 00:00:00 2001 From: ssdetlab Date: Thu, 21 Nov 2024 12:56:20 +0200 Subject: [PATCH 22/23] fixing 1am mistakes --- .../Acts/Plugins/Json/TrackParametersJsonConverter.hpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Plugins/Json/include/Acts/Plugins/Json/TrackParametersJsonConverter.hpp b/Plugins/Json/include/Acts/Plugins/Json/TrackParametersJsonConverter.hpp index f8683006fb5..b2453978cd8 100644 --- a/Plugins/Json/include/Acts/Plugins/Json/TrackParametersJsonConverter.hpp +++ b/Plugins/Json/include/Acts/Plugins/Json/TrackParametersJsonConverter.hpp @@ -10,6 +10,7 @@ #include "Acts/Definitions/PdgParticle.hpp" #include "Acts/EventData/detail/TrackParametersUtils.hpp" +#include "Acts/EventData/GenericBoundTrackParameters.hpp" #include "Acts/Plugins/Json/SurfaceJsonConverter.hpp" #include @@ -85,7 +86,7 @@ struct adl_serializer { // Bound track parameters have // reference surface attached // and position takes a geometry context - if constexpr (Acts::detail::isBoundOrFreeTrackParams) { + if constexpr (Acts::detail::isGenericBoundTrackParams) { Acts::GeometryContext gctx; j["position"] = t.fourPosition(gctx); @@ -136,7 +137,7 @@ struct adl_serializer { // reference surface attached // and constructor is hidden // behind a factory method - if constexpr (Acts::detail::isBoundOrFreeTrackParams) { + if constexpr (Acts::detail::isGenericBoundTrackParams) { Acts::GeometryContext gctx; auto referenceSurface = Acts::SurfaceJsonConverter::fromJson(j.at("referenceSurface")); From 149ab41b76cdacfd55b9fa065584a3c49b4795c8 Mon Sep 17 00:00:00 2001 From: ssdetlab Date: Thu, 21 Nov 2024 12:57:18 +0200 Subject: [PATCH 23/23] format --- .../include/Acts/Plugins/Json/TrackParametersJsonConverter.hpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Plugins/Json/include/Acts/Plugins/Json/TrackParametersJsonConverter.hpp b/Plugins/Json/include/Acts/Plugins/Json/TrackParametersJsonConverter.hpp index b2453978cd8..d9670858566 100644 --- a/Plugins/Json/include/Acts/Plugins/Json/TrackParametersJsonConverter.hpp +++ b/Plugins/Json/include/Acts/Plugins/Json/TrackParametersJsonConverter.hpp @@ -9,8 +9,8 @@ #pragma once #include "Acts/Definitions/PdgParticle.hpp" -#include "Acts/EventData/detail/TrackParametersUtils.hpp" #include "Acts/EventData/GenericBoundTrackParameters.hpp" +#include "Acts/EventData/detail/TrackParametersUtils.hpp" #include "Acts/Plugins/Json/SurfaceJsonConverter.hpp" #include