diff --git a/.github/workflows/milestone.yml b/.github/workflows/milestone.yml new file mode 100644 index 00000000000..de5ee80356c --- /dev/null +++ b/.github/workflows/milestone.yml @@ -0,0 +1,58 @@ +name: Check PR milestone + +on: + pull_request_target: + types: [milestoned, demilestoned, opened, reopened] + branches: + - main + +jobs: + check_milestone: + if: ${{ github.event.issue.pull_request || github.event.pull_request }} + + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + + - name: "Check for milestone on PR" + uses: actions/github-script@v7 + with: + script: | + let milestone = context.payload.pull_request.milestone; + + if(context.payload.action === 'opened' || context.payload.action === 'reopened') { + if(milestone !== null) { + core.notice(`Milestone is ${milestone.title}`); + } else { + const milestones = await github.rest.issues.listMilestones({ + owner: context.repo.owner, + repo: context.repo.repo, + state: "open" + }); + for (const default_milestone of milestones.data) { + if (default_milestone.title === "next") { + core.notice(`No milestone set, setting default milestone: ${default_milestone.title}`); + + await github.rest.issues.update({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: context.issue.number, + milestone: default_milestone.number + }); + return; + } + } + + core.warning("Could not find default milestone named 'next'"); + + } + + } + else { + if(milestone !== null) { + core.notice(`Milestone is ${milestone.title}`); + } else { + core.setFailed("No milestone: Please add a version milestone"); + } + } diff --git a/.github/workflows/update-pip-requirements.yml b/.github/workflows/update-pip-requirements.yml new file mode 100755 index 00000000000..e205abc75ce --- /dev/null +++ b/.github/workflows/update-pip-requirements.yml @@ -0,0 +1,76 @@ +name: Update Pip Requirements + +on: + workflow_dispatch: # Allow running on-demand + schedule: + # Runs every Sunday at 1:23 UTC + - cron: '23 1 * * 0' + +jobs: + update-pip-requirements: + # This action checks all monitored (specified in `folder_list` below) requirements.in + # files and generates a new requirements.txt file with pip-compile. If any + # requirements changed, a PR is created with the changes. + runs-on: ubuntu-latest + env: + # This branch will receive updates each time the workflow runs + # It doesn't matter if it's deleted when merged, it'll be re-created + BRANCH_NAME: auto-dependency-upgrades + steps: + - uses: actions/checkout@v4 + + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: 3.12 + + - name: Install pip-tools + run: pip install pip-tools + + - name: Compile all requirements.txt + run: | + # Update this list after adding/removing requirements-files + folder_list=( + CI/clang_tidy + CI/fpe_masks + docs + Examples/Python/tests + Examples/Scripts + ) + for folder in "${folder_list[@]}"; do + pip-compile "${folder}/requirements.in" > "${folder}/requirements.txt" + done + + - name: Detect changes + id: changes + run: + # This output boolean tells us if the dependencies have actually changed + echo "count=$(git status --porcelain=v1 2>/dev/null | wc -l)" >> $GITHUB_OUTPUT + + - name: Commit & push changes + # Only push if changes exist + if: steps.changes.outputs.count > 0 + run: | + git config user.name github-actions + git config user.email github-actions@github.com + git add . + git commit -m "Weekly Update: Regenerate requirements.txt" + git push -f origin ${{ github.ref_name }}:$BRANCH_NAME + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + - name: Open pull request if needed + if: steps.changes.outputs.count > 0 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + # Only open a PR if the branch is not attached to an existing one + run: | + PR=$(gh pr list --head $BRANCH_NAME --json number -q '.[0].number') + if [ -z $PR ]; then + gh pr create \ + --head $BRANCH_NAME \ + --title "chore: automated python requirements upgrades" \ + --body "Full log: https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}" + else + echo "Pull request already exists, won't create a new one." + fi diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index b0a213e607d..c897c947010 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -382,11 +382,7 @@ linux_ubuntu_2204_clang: # Figure out LCG platform name based on version number and OS - > if [ "$OS" = "alma9" ]; then - if [ "$LCG_VERSION" -ge "104" ]; then - export LCG_PLATFORM="el9" - else - export LCG_PLATFORM="centos9" - fi + export LCG_PLATFORM="el9" else export LCG_PLATFORM="$OS" fi @@ -431,3 +427,17 @@ lcg_105: COMPILER: - gcc13 - clang16 + +lcg_106a: + extends: .lcg_base_job + + variables: + LCG_VERSION: "106a" + + parallel: + matrix: + - OS: [alma9] + COMPILER: + - gcc13 + - gcc14 + - clang16 diff --git a/Alignment/include/ActsAlignment/Kernel/detail/AlignmentEngine.hpp b/Alignment/include/ActsAlignment/Kernel/detail/AlignmentEngine.hpp index 1bb21fdc8bd..b26175abcdd 100644 --- a/Alignment/include/ActsAlignment/Kernel/detail/AlignmentEngine.hpp +++ b/Alignment/include/ActsAlignment/Kernel/detail/AlignmentEngine.hpp @@ -208,7 +208,9 @@ TrackAlignmentState trackAlignmentState( measdim) = measCovariance; // (b) Get and fill the bound parameters to measurement projection matrix - const ActsDynamicMatrix H = state.effectiveProjector(); + const ActsDynamicMatrix H = + state.projectorSubspaceHelper().fullProjector().topLeftCorner( + measdim, eBoundSize); alignState.projectionMatrix.block(iMeasurement, iParams, measdim, eBoundSize) = H; // (c) Get and fill the residual diff --git a/CI/clang_tidy/requirements.txt b/CI/clang_tidy/requirements.txt index 6bd13b68d95..d0d78f5904e 100644 --- a/CI/clang_tidy/requirements.txt +++ b/CI/clang_tidy/requirements.txt @@ -4,41 +4,41 @@ # # pip-compile CI/clang_tidy/requirements.in # -annotated-types==0.6.0 +annotated-types==0.7.0 # via pydantic appdirs==1.4.4 # via fs -codereport==0.3.2 +codereport==0.4.0 # via -r CI/clang_tidy/requirements.in fs==2.4.16 # via codereport -jinja2==3.1.2 +jinja2==3.1.4 # via codereport markdown-it-py==3.0.0 # via rich -markupsafe==2.1.3 +markupsafe==3.0.2 # via jinja2 mdurl==0.1.2 # via markdown-it-py -pydantic==2.5.2 +pydantic==2.9.2 # via -r CI/clang_tidy/requirements.in -pydantic-core==2.14.5 +pydantic-core==2.23.4 # via pydantic -pygments==2.17.2 +pygments==2.18.0 # via # codereport # rich python-slugify==6.1.2 # via codereport -pyyaml==6.0.1 +pyyaml==6.0.2 # via -r CI/clang_tidy/requirements.in -rich==13.7.0 +rich==13.9.4 # via -r CI/clang_tidy/requirements.in six==1.16.0 # via fs text-unidecode==1.3 # via python-slugify -typing-extensions==4.8.0 +typing-extensions==4.12.2 # via # pydantic # pydantic-core diff --git a/CI/fpe_masks/requirements.txt b/CI/fpe_masks/requirements.txt index 07e86bd58d5..01f945e3d74 100644 --- a/CI/fpe_masks/requirements.txt +++ b/CI/fpe_masks/requirements.txt @@ -2,49 +2,61 @@ # This file is autogenerated by pip-compile with Python 3.12 # by the following command: # -# pip-compile CI/requirements_fpe_masks.in +# pip-compile CI/fpe_masks/requirements.in # -aiohttp==3.9.1 - # via -r CI/requirements_fpe_masks.in +aiohappyeyeballs==2.4.3 + # via aiohttp +aiohttp==3.11.6 + # via -r CI/fpe_masks/requirements.in aiosignal==1.3.1 # via aiohttp -attrs==23.1.0 +attrs==24.2.0 # via aiohttp -cffi==1.15.1 +cffi==1.17.1 # via cryptography -click==8.1.4 +click==8.1.7 # via typer -cryptography==41.0.1 +cryptography==43.0.3 # via pyjwt -frozenlist==1.4.0 +frozenlist==1.5.0 # via # aiohttp # aiosignal gidgethub==5.3.0 - # via -r CI/requirements_fpe_masks.in -idna==3.4 + # via -r CI/fpe_masks/requirements.in +idna==3.10 # via yarl markdown-it-py==3.0.0 # via rich mdurl==0.1.2 # via markdown-it-py -multidict==6.0.4 +multidict==6.1.0 + # via + # aiohttp + # yarl +propcache==0.2.0 # via # aiohttp # yarl -pycparser==2.21 +pycparser==2.22 # via cffi -pygments==2.15.1 +pygments==2.18.0 # via rich -pyjwt[crypto]==2.7.0 - # via gidgethub -rich==13.4.2 - # via -r CI/requirements_fpe_masks.in -typer==0.9.0 - # via -r CI/requirements_fpe_masks.in -typing-extensions==4.7.1 +pyjwt[crypto]==2.10.0 + # via + # gidgethub + # pyjwt +rich==13.9.4 + # via + # -r CI/fpe_masks/requirements.in + # typer +shellingham==1.5.4 + # via typer +typer==0.13.1 + # via -r CI/fpe_masks/requirements.in +typing-extensions==4.12.2 # via typer uritemplate==4.1.1 # via gidgethub -yarl==1.9.2 +yarl==1.17.2 # via aiohttp diff --git a/CI/physmon/workflows/physmon_trackfinding_1muon.py b/CI/physmon/workflows/physmon_trackfinding_1muon.py index aaa4bc9f71d..90305112099 100755 --- a/CI/physmon/workflows/physmon_trackfinding_1muon.py +++ b/CI/physmon/workflows/physmon_trackfinding_1muon.py @@ -18,7 +18,7 @@ from acts.examples.reconstruction import ( addSeeding, - ParticleSmearingSigmas, + TrackSmearingSigmas, SeedFinderConfigArg, SeedFinderOptionsArg, SeedingAlgorithm, @@ -91,15 +91,15 @@ def run_ckf_tracking(label, seeding): s, setup.trackingGeometry, setup.field, - ParticleSmearingSigmas( # only used by SeedingAlgorithm.TruthSmeared + TrackSmearingSigmas( # only used by SeedingAlgorithm.TruthSmeared # zero eveything so the CKF has a chance to find the measurements - d0=0, - d0PtA=0, - d0PtB=0, - z0=0, - z0PtA=0, - z0PtB=0, - t0=0, + loc0=0, + loc0PtA=0, + loc0PtB=0, + loc1=0, + loc1PtA=0, + loc1PtB=0, + time=0, phi=0, theta=0, ptRel=0, diff --git a/CI/physmon/workflows/physmon_trackfitting_gsf.py b/CI/physmon/workflows/physmon_trackfitting_gsf.py index 694623e2926..4738bc4d397 100755 --- a/CI/physmon/workflows/physmon_trackfitting_gsf.py +++ b/CI/physmon/workflows/physmon_trackfitting_gsf.py @@ -20,9 +20,9 @@ tp = Path(temp) runTruthTrackingGsf( - setup.trackingGeometry, - setup.field, - setup.digiConfig, + trackingGeometry=setup.trackingGeometry, + field=setup.field, + digiConfigFile=setup.digiConfig, outputDir=tp, s=s, ) diff --git a/CMakeLists.txt b/CMakeLists.txt index 601264badc0..04fb58d6825 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -550,13 +550,6 @@ if(ACTS_BUILD_DOCS) find_package(Sphinx REQUIRED) endif() -if(ACTS_CUSTOM_SCALARTYPE) - message( - STATUS - "Building Acts with custom scalar type: ${ACTS_CUSTOM_SCALARTYPE}" - ) -endif() - # core library, core plugins, and other components add_component(Core Core) add_subdirectory(Plugins) diff --git a/Core/CMakeLists.txt b/Core/CMakeLists.txt index 554656f514c..25af0f03d49 100644 --- a/Core/CMakeLists.txt +++ b/Core/CMakeLists.txt @@ -35,13 +35,6 @@ if(ACTS_SOURCELINK_SBO_SIZE) ) endif() -if(ACTS_CUSTOM_SCALARTYPE) - target_compile_definitions( - ActsCore - PUBLIC -DACTS_CUSTOM_SCALARTYPE=${ACTS_CUSTOM_SCALARTYPE} - ) -endif() - if(ACTS_LOG_FAILURE_THRESHOLD) message( STATUS diff --git a/Core/include/Acts/Clusterization/TimedClusterization.hpp b/Core/include/Acts/Clusterization/TimedClusterization.hpp index e92ebce44e2..a53e7793f56 100644 --- a/Core/include/Acts/Clusterization/TimedClusterization.hpp +++ b/Core/include/Acts/Clusterization/TimedClusterization.hpp @@ -17,16 +17,16 @@ namespace Acts::Ccl { template concept HasRetrievableTimeInfo = requires(Cell cell) { - { getCellTime(cell) } -> std::same_as; + { getCellTime(cell) } -> std::same_as; }; template struct TimedConnect : public Acts::Ccl::DefaultConnect { - Acts::ActsScalar timeTolerance{std::numeric_limits::max()}; + double timeTolerance{std::numeric_limits::max()}; TimedConnect() = default; - TimedConnect(Acts::ActsScalar time); - TimedConnect(Acts::ActsScalar time, bool commonCorner) + TimedConnect(double time); + TimedConnect(double time, bool commonCorner) requires(N == 2); ~TimedConnect() override = default; diff --git a/Core/include/Acts/Clusterization/TimedClusterization.ipp b/Core/include/Acts/Clusterization/TimedClusterization.ipp index 0e7b3e5bda8..556d02ccce1 100644 --- a/Core/include/Acts/Clusterization/TimedClusterization.ipp +++ b/Core/include/Acts/Clusterization/TimedClusterization.ipp @@ -9,11 +9,10 @@ namespace Acts::Ccl { template -TimedConnect::TimedConnect(Acts::ActsScalar time) - : timeTolerance(time) {} +TimedConnect::TimedConnect(double time) : timeTolerance(time) {} template -TimedConnect::TimedConnect(Acts::ActsScalar time, bool commonCorner) +TimedConnect::TimedConnect(double time, bool commonCorner) requires(N == 2) : Acts::Ccl::DefaultConnect(commonCorner), timeTolerance(time) {} diff --git a/Core/include/Acts/Definitions/Algebra.hpp b/Core/include/Acts/Definitions/Algebra.hpp index 843958a3282..5684ab44c73 100644 --- a/Core/include/Acts/Definitions/Algebra.hpp +++ b/Core/include/Acts/Definitions/Algebra.hpp @@ -41,30 +41,19 @@ namespace Acts { /// any conditions e.g. square size, for the dynamic-sized case. Consequently, /// no dynamic-sized symmetric matrix type is defined. Use the /// `ActsDynamicMatrix` instead. -/// - -/// Common scalar (floating point type used for the default algebra types. -/// -/// Defaults to `double` but can be customized by the user. -#ifdef ACTS_CUSTOM_SCALARTYPE -using ActsScalar = ACTS_CUSTOM_SCALARTYPE; -#else -using ActsScalar = double; -#endif template -using ActsVector = Eigen::Matrix; +using ActsVector = Eigen::Matrix; template -using ActsMatrix = Eigen::Matrix; +using ActsMatrix = Eigen::Matrix; template -using ActsSquareMatrix = Eigen::Matrix; +using ActsSquareMatrix = Eigen::Matrix; -using ActsDynamicVector = Eigen::Matrix; +using ActsDynamicVector = Eigen::Matrix; -using ActsDynamicMatrix = - Eigen::Matrix; +using ActsDynamicMatrix = Eigen::Matrix; /// @defgroup coordinates-types Fixed-size vector/matrix types for coordinates /// @@ -84,22 +73,22 @@ using SquareMatrix3 = ActsSquareMatrix<3>; using SquareMatrix4 = ActsSquareMatrix<4>; // pure translation transformations -using Translation2 = Eigen::Translation; -using Translation3 = Eigen::Translation; +using Translation2 = Eigen::Translation; +using Translation3 = Eigen::Translation; // linear (rotation) matrices using RotationMatrix2 = ActsMatrix<2, 2>; using RotationMatrix3 = ActsMatrix<3, 3>; // pure rotation defined by a rotation angle around a rotation axis -using AngleAxis3 = Eigen::AngleAxis; +using AngleAxis3 = Eigen::AngleAxis; // combined affine transformations. types are chosen for better data alignment: // - 2d affine compact stored as 2x3 matrix // - 3d affine stored as 4x4 matrix -using Transform2 = Eigen::Transform; -using Transform3 = Eigen::Transform; +using Transform2 = Eigen::Transform; +using Transform3 = Eigen::Transform; -constexpr ActsScalar s_transformEquivalentTolerance = 1e-9; +constexpr double s_transformEquivalentTolerance = 1e-9; } // namespace Acts diff --git a/Core/include/Acts/Definitions/Direction.hpp b/Core/include/Acts/Definitions/Direction.hpp index d07646bab26..985caac0e6c 100644 --- a/Core/include/Acts/Definitions/Direction.hpp +++ b/Core/include/Acts/Definitions/Direction.hpp @@ -41,7 +41,7 @@ class Direction final { /// @param scalar is the signed value /// /// @return a direction enum - static constexpr Direction fromScalar(ActsScalar scalar) { + static constexpr Direction fromScalar(double scalar) { assert(scalar != 0); return scalar >= 0 ? Value::Positive : Value::Negative; } @@ -53,7 +53,7 @@ class Direction final { /// @param scalar is the signed value /// /// @return a direction enum - static constexpr Direction fromScalarZeroAsPositive(ActsScalar scalar) { + static constexpr Direction fromScalarZeroAsPositive(double scalar) { return scalar >= 0 ? Value::Positive : Value::Negative; } diff --git a/Core/include/Acts/Definitions/Tolerance.hpp b/Core/include/Acts/Definitions/Tolerance.hpp index 0b8ef36e55f..3c6fb1e76c0 100644 --- a/Core/include/Acts/Definitions/Tolerance.hpp +++ b/Core/include/Acts/Definitions/Tolerance.hpp @@ -15,19 +15,18 @@ namespace Acts { /// Tolerance for being numerical equal for geometry building -static constexpr ActsScalar s_epsilon = - 3 * std::numeric_limits::epsilon(); +static constexpr double s_epsilon = 3 * std::numeric_limits::epsilon(); /// Tolerance for being on Surface /// /// @note This is intentionally given w/o an explicit unit to avoid having /// to include the units header unnecessarily. With the native length /// unit of mm this corresponds to 0.1um. -static constexpr ActsScalar s_onSurfaceTolerance = 1e-4; +static constexpr double s_onSurfaceTolerance = 1e-4; /// Tolerance for not being within curvilinear projection /// this allows using the same curvilinear frame to eta = 6, /// validity tested with IntegrationTests/PropagationTest -static constexpr ActsScalar s_curvilinearProjTolerance = 0.999995; +static constexpr double s_curvilinearProjTolerance = 0.999995; } // namespace Acts diff --git a/Core/include/Acts/Detector/Blueprint.hpp b/Core/include/Acts/Detector/Blueprint.hpp index 3be0d6353db..1e3ec527674 100644 --- a/Core/include/Acts/Detector/Blueprint.hpp +++ b/Core/include/Acts/Detector/Blueprint.hpp @@ -51,7 +51,7 @@ struct Node final { /// @param cs the children of the node /// @param e the estimated extent of the node (optional) Node(const std::string& n, const Transform3& t, VolumeBounds::BoundsType bt, - const std::vector& bv, const std::vector& bss, + const std::vector& bv, const std::vector& bss, std::vector> cs = {}, const Extent& e = Extent()) : name(n), transform(t), @@ -73,7 +73,7 @@ struct Node final { /// @param isb the internal structure builder (optional) /// @param e the estimated extent of the node (optional) Node(const std::string& n, const Transform3& t, VolumeBounds::BoundsType bt, - const std::vector& bv, + const std::vector& bv, std::shared_ptr isb = nullptr, const Extent& e = Extent()) : name(n), @@ -90,7 +90,7 @@ struct Node final { /// The boundary type VolumeBounds::BoundsType boundsType = VolumeBounds::eOther; /// The associated values - std::vector boundaryValues = {}; + std::vector boundaryValues = {}; /// Parent node - nullptr for root only const Node* parent = nullptr; /// Branch definitions: children diff --git a/Core/include/Acts/Detector/DetectorVolume.hpp b/Core/include/Acts/Detector/DetectorVolume.hpp index 1617721d62f..903532361f7 100644 --- a/Core/include/Acts/Detector/DetectorVolume.hpp +++ b/Core/include/Acts/Detector/DetectorVolume.hpp @@ -61,8 +61,8 @@ class Detector; class DetectorVolume : public std::enable_shared_from_this { public: using BoundingBox = - Acts::AxisAlignedBoundingBox; + Acts::AxisAlignedBoundingBox; friend class DetectorVolumeFactory; diff --git a/Core/include/Acts/Detector/KdtSurfacesProvider.hpp b/Core/include/Acts/Detector/KdtSurfacesProvider.hpp index fd7086e01df..72bea84737f 100644 --- a/Core/include/Acts/Detector/KdtSurfacesProvider.hpp +++ b/Core/include/Acts/Detector/KdtSurfacesProvider.hpp @@ -34,10 +34,10 @@ class KdtSurfaces { public: /// Broadcast the surface KDT type using KDTS = - KDTree, ActsScalar, std::array, bSize>; + KDTree, double, std::array, bSize>; /// Broadcast the query definition - using Query = std::array; + using Query = std::array; /// Broadcast the entry using Entry = std::pair>; @@ -86,7 +86,7 @@ class KdtSurfaces { /// /// @return the matching surfaces from the KDT structure std::vector> surfaces( - const RangeXD& range) const { + const RangeXD& range) const { // Strip the surfaces std::vector> surfacePtrs; auto surfaceQuery = m_kdt->rangeSearchWithKey(range); @@ -101,7 +101,7 @@ class KdtSurfaces { /// /// @return the matching surfaces fpulled from the KDT structure std::vector> surfaces(const Extent& extent) const { - RangeXD qRange; + RangeXD qRange; for (auto [ibv, v] : enumerate(m_casts)) { qRange[ibv] = extent.range(v); } @@ -148,7 +148,7 @@ class KdtSurfaces { float weight = 1. / cQueries.size(); for (auto& q : cQueries) { std::transform(c.begin(), c.end(), q.begin(), c.begin(), - std::plus()); + std::plus()); } std::for_each(c.begin(), c.end(), [&](auto& v) { v *= weight; }); return c; diff --git a/Core/include/Acts/Detector/MultiWireStructureBuilder.hpp b/Core/include/Acts/Detector/MultiWireStructureBuilder.hpp index 939388c223a..48159bf806c 100644 --- a/Core/include/Acts/Detector/MultiWireStructureBuilder.hpp +++ b/Core/include/Acts/Detector/MultiWireStructureBuilder.hpp @@ -38,7 +38,7 @@ class MultiWireStructureBuilder { Transform3 transform = Transform3::Identity(); /// The bounds of the multi-wire volume - std::vector mlBounds = {}; + std::vector mlBounds = {}; // The binning of the multi wire structure std::vector mlBinning = {}; diff --git a/Core/include/Acts/Detector/ProtoBinning.hpp b/Core/include/Acts/Detector/ProtoBinning.hpp index 371bfe60bd2..3700dfc4d6f 100644 --- a/Core/include/Acts/Detector/ProtoBinning.hpp +++ b/Core/include/Acts/Detector/ProtoBinning.hpp @@ -34,7 +34,7 @@ struct ProtoBinning { /// The axis boundary type: Open, Bound or Closed Acts::AxisBoundaryType boundaryType = Acts::AxisBoundaryType::Bound; /// The binning edges - std::vector edges = {}; + std::vector edges = {}; /// An expansion for the filling (in bins) std::size_t expansion = 0u; /// Indication if this is an auto-range binning @@ -47,7 +47,7 @@ struct ProtoBinning { /// @param e the bin edges (variable binning) /// @param exp the expansion (in bins) ProtoBinning(BinningValue bValue, Acts::AxisBoundaryType bType, - const std::vector& e, std::size_t exp = 0u) + const std::vector& e, std::size_t exp = 0u) : binValue(bValue), axisType(Acts::AxisType::Variable), boundaryType(bType), @@ -67,9 +67,8 @@ struct ProtoBinning { /// @param maxE the highest edge of the binning /// @param nbins the number of bins /// @param exp the expansion (in bins) - ProtoBinning(BinningValue bValue, Acts::AxisBoundaryType bType, - ActsScalar minE, ActsScalar maxE, std::size_t nbins, - std::size_t exp = 0u) + ProtoBinning(BinningValue bValue, Acts::AxisBoundaryType bType, double minE, + double maxE, std::size_t nbins, std::size_t exp = 0u) : binValue(bValue), boundaryType(bType), expansion(exp) { if (minE >= maxE) { std::string msg = "ProtoBinning: Invalid binning for value '"; @@ -84,7 +83,7 @@ struct ProtoBinning { "ProtoBinning: Invalid binning, at least one bin is needed."); } - ActsScalar stepE = (maxE - minE) / nbins; + double stepE = (maxE - minE) / nbins; edges.reserve(nbins + 1); for (std::size_t i = 0; i <= nbins; i++) { edges.push_back(minE + i * stepE); @@ -140,7 +139,7 @@ struct BinningDescription { Acts::AxisBoundaryType boundaryType = bData.option == open ? Acts::AxisBoundaryType::Bound : Acts::AxisBoundaryType::Closed; - std::vector edges; + std::vector edges; if (bData.type == equidistant) { bDesc.binning.push_back(ProtoBinning(bData.binvalue, boundaryType, bData.min, bData.max, bData.bins(), @@ -148,7 +147,7 @@ struct BinningDescription { } else { std::for_each(bData.boundaries().begin(), bData.boundaries().end(), - [&](ActsScalar edge) { edges.push_back(edge); }); + [&](double edge) { edges.push_back(edge); }); bDesc.binning.push_back( ProtoBinning(bData.binvalue, boundaryType, edges, 0u)); } @@ -170,7 +169,7 @@ struct BinningDescription { } else { std::vector edges; std::for_each(b.edges.begin(), b.edges.end(), - [&](ActsScalar edge) { edges.push_back(edge); }); + [&](double edge) { edges.push_back(edge); }); binUtility += BinUtility(edges, bOption, b.binValue); } } diff --git a/Core/include/Acts/Detector/ProtoSupport.hpp b/Core/include/Acts/Detector/ProtoSupport.hpp index 8f1e2581e77..abde3a71539 100644 --- a/Core/include/Acts/Detector/ProtoSupport.hpp +++ b/Core/include/Acts/Detector/ProtoSupport.hpp @@ -38,7 +38,7 @@ struct ProtoSupport { Surface::SurfaceType type = Surface::SurfaceType::Other; /// The offset of the support to an estimated position (e.g. from an extent) - ActsScalar offset = 0.; + double offset = 0.; /// A given extent from the volume, this allows to set support surfaces /// to fit into given volume extensions (flagged by the binning value diff --git a/Core/include/Acts/Detector/VolumeStructureBuilder.hpp b/Core/include/Acts/Detector/VolumeStructureBuilder.hpp index aede963c78c..bf236349b31 100644 --- a/Core/include/Acts/Detector/VolumeStructureBuilder.hpp +++ b/Core/include/Acts/Detector/VolumeStructureBuilder.hpp @@ -42,7 +42,7 @@ class VolumeStructureBuilder : public IExternalStructureBuilder { /// The starting transform Transform3 transform = Transform3::Identity(); /// The values (if already defined) - std::vector boundValues = {}; + std::vector boundValues = {}; /// The optional extent to feed into the values std::optional extent = std::nullopt; /// Some auxiliary information diff --git a/Core/include/Acts/Detector/detail/CuboidalDetectorHelper.hpp b/Core/include/Acts/Detector/detail/CuboidalDetectorHelper.hpp index c9ad46744d3..eda1da8452b 100644 --- a/Core/include/Acts/Detector/detail/CuboidalDetectorHelper.hpp +++ b/Core/include/Acts/Detector/detail/CuboidalDetectorHelper.hpp @@ -73,7 +73,7 @@ DetectorComponent::PortalContainer connect( /// @param logLevel is the screen logging level /// /// @return extracted boundary values -std::array, 3u> xyzBoundaries( +std::array, 3u> xyzBoundaries( const GeometryContext& gctx, const std::vector& volumes, Acts::Logging::Level logLevel = Acts::Logging::INFO); diff --git a/Core/include/Acts/Detector/detail/CylindricalDetectorHelper.hpp b/Core/include/Acts/Detector/detail/CylindricalDetectorHelper.hpp index 05815b1325f..d7cf4cb7831 100644 --- a/Core/include/Acts/Detector/detail/CylindricalDetectorHelper.hpp +++ b/Core/include/Acts/Detector/detail/CylindricalDetectorHelper.hpp @@ -174,7 +174,7 @@ DetectorComponent::PortalContainer wrapInZR( /// /// @return extracted boundary values template -std::array, 3u> rzphiBoundaries( +std::array, 3u> rzphiBoundaries( const GeometryContext& gctx, const volume_container_t& volumes, double precision = 0., Acts::Logging::Level logLevel = Acts::Logging::INFO) { @@ -185,8 +185,8 @@ std::array, 3u> rzphiBoundaries( << " volumes."); // The return boundaries - std::array, 3u> uniqueBoundaries; - auto insertWithPrecision = [&](std::size_t is, ActsScalar value) -> void { + std::array, 3u> uniqueBoundaries; + auto insertWithPrecision = [&](std::size_t is, double value) -> void { if (precision == 0.) { uniqueBoundaries[is].insert(value); return; @@ -199,19 +199,19 @@ std::array, 3u> rzphiBoundaries( if (v->volumeBounds().type() == VolumeBounds::BoundsType::eCylinder) { const auto& bValues = v->volumeBounds().values(); // The min/max values - ActsScalar rMin = bValues[CylinderVolumeBounds::BoundValues::eMinR]; - ActsScalar rMax = bValues[CylinderVolumeBounds::BoundValues::eMaxR]; - ActsScalar zCenter = v->transform(gctx).translation().z(); - ActsScalar zHalfLength = + double rMin = bValues[CylinderVolumeBounds::BoundValues::eMinR]; + double rMax = bValues[CylinderVolumeBounds::BoundValues::eMaxR]; + double zCenter = v->transform(gctx).translation().z(); + double zHalfLength = bValues[CylinderVolumeBounds::BoundValues::eHalfLengthZ]; - ActsScalar zMin = zCenter - zHalfLength; - ActsScalar zMax = zCenter + zHalfLength; - ActsScalar phiCenter = + double zMin = zCenter - zHalfLength; + double zMax = zCenter + zHalfLength; + double phiCenter = bValues[CylinderVolumeBounds::BoundValues::eAveragePhi]; - ActsScalar phiSector = + double phiSector = bValues[CylinderVolumeBounds::BoundValues::eHalfPhiSector]; - ActsScalar phiMin = phiCenter - phiSector; - ActsScalar phiMax = phiCenter + phiSector; + double phiMin = phiCenter - phiSector; + double phiMax = phiCenter + phiSector; // Fill the sets insertWithPrecision(0u, rMin); insertWithPrecision(0u, rMax); @@ -229,12 +229,12 @@ std::array, 3u> rzphiBoundaries( ACTS_VERBOSE("- did yield " << uniqueBoundaries[2u].size() << " boundaries in phi."); - return {{std::vector(uniqueBoundaries[0].begin(), - uniqueBoundaries[0].end()), - std::vector(uniqueBoundaries[1].begin(), - uniqueBoundaries[1].end()), - std::vector(uniqueBoundaries[2].begin(), - uniqueBoundaries[2].end())}}; + return {{std::vector(uniqueBoundaries[0].begin(), + uniqueBoundaries[0].end()), + std::vector(uniqueBoundaries[1].begin(), + uniqueBoundaries[1].end()), + std::vector(uniqueBoundaries[2].begin(), + uniqueBoundaries[2].end())}}; } } // namespace detail::CylindricalDetectorHelper diff --git a/Core/include/Acts/Detector/detail/DetectorVolumeConsistency.hpp b/Core/include/Acts/Detector/detail/DetectorVolumeConsistency.hpp index ebea6a7a4d6..f4de79980f3 100644 --- a/Core/include/Acts/Detector/detail/DetectorVolumeConsistency.hpp +++ b/Core/include/Acts/Detector/detail/DetectorVolumeConsistency.hpp @@ -45,7 +45,7 @@ void checkRotationAlignment( /// @note throws exception if the volumes are not ordered /// /// @return a vector with position differences (ordered) -std::vector checkCenterAlignment( +std::vector checkCenterAlignment( const GeometryContext& gctx, const std::vector>& volumes, BinningValue axisValue); diff --git a/Core/include/Acts/Detector/detail/PortalHelper.hpp b/Core/include/Acts/Detector/detail/PortalHelper.hpp index ec17c487098..ba54513976b 100644 --- a/Core/include/Acts/Detector/detail/PortalHelper.hpp +++ b/Core/include/Acts/Detector/detail/PortalHelper.hpp @@ -34,7 +34,7 @@ class Portal; /// gathered from the sub volumes, the binning description using PortalReplacement = std::tuple, unsigned int, Direction, - std::vector, BinningValue>; + std::vector, BinningValue>; namespace detail::PortalHelper { @@ -62,7 +62,7 @@ void attachExternalNavigationDelegate( void attachDetectorVolumesUpdater( const GeometryContext& gctx, Portal& portal, const std::vector>& volumes, - const Direction& direction, const std::vector& boundaries, + const Direction& direction, const std::vector& boundaries, const BinningValue& binning); /// @brief Create and attach the multi link updator, the portal will get diff --git a/Core/include/Acts/Detector/detail/SupportSurfacesHelper.hpp b/Core/include/Acts/Detector/detail/SupportSurfacesHelper.hpp index e956e215e4f..9c52e961498 100644 --- a/Core/include/Acts/Detector/detail/SupportSurfacesHelper.hpp +++ b/Core/include/Acts/Detector/detail/SupportSurfacesHelper.hpp @@ -32,7 +32,7 @@ using namespace UnitLiterals; namespace Experimental::detail::SupportSurfacesHelper { using SupportSurfaceComponents = - std::tuple, Acts::Transform3>; + std::tuple, Acts::Transform3>; /// @brief A support creator turns an extend into a vector of bound values using SurfaceComponentsCreator = @@ -44,15 +44,15 @@ struct CylindricalSupport { /// - negative indicates inner support /// - zero is centered (not recommended) /// - positive indicates outer support - ActsScalar rOffset = 0.; + double rOffset = 0.; /// Clearance in z in order to make the support surfaces /// not touch the volume boundaries - std::array zClearance = {1_mm, 1_mm}; + std::array zClearance = {1_mm, 1_mm}; /// Clearance in phi if a sectoral support is chosen /// not to touch the volume boundaries - std::array phiClearance = {0.0001_rad, 0.0001_rad}; + std::array phiClearance = {0.0001_rad, 0.0001_rad}; // Type is obviously a cylinder static constexpr Surface::SurfaceType type = Surface::SurfaceType::Cylinder; @@ -71,15 +71,15 @@ struct DiscSupport { /// - negative indicates support an z min /// - zero is centered /// - positive indicates support at z max - ActsScalar zOffset = 0.; + double zOffset = 0.; /// Clearance in r in order to make the support surfaces /// not touch the volume boundaries - std::array rClearance = {1_mm, 1_mm}; + std::array rClearance = {1_mm, 1_mm}; /// Clearance in phi if a sectoral support is chosen /// not to touch the volume boundaries - std::array phiClearance = {0.0001_rad, 0.0001_rad}; + std::array phiClearance = {0.0001_rad, 0.0001_rad}; // Type is obviously a disc static constexpr Surface::SurfaceType type = Surface::SurfaceType::Disc; @@ -98,14 +98,14 @@ struct RectangularSupport { BinningValue pPlacement = BinningValue::binZ; /// Offset in position placement - ActsScalar pOffset = 0.; + double pOffset = 0.; /// Clearance in first local direction - cyclic order - std::array loc0Clearance = {1_mm, 1_mm}; + std::array loc0Clearance = {1_mm, 1_mm}; /// Clearance in phi if a sectoral support is chosen /// not to touch the volume boundaries - std::array loc1Clearance = {1_mm, 1_mm}; + std::array loc1Clearance = {1_mm, 1_mm}; // Type is obviously a plane static constexpr Surface::SurfaceType type = Surface::SurfaceType::Plane; diff --git a/Core/include/Acts/EventData/Charge.hpp b/Core/include/Acts/EventData/Charge.hpp index 6ae62b3d963..64073538a3f 100644 --- a/Core/include/Acts/EventData/Charge.hpp +++ b/Core/include/Acts/EventData/Charge.hpp @@ -67,17 +67,16 @@ struct Neutral { constexpr float absQ() const noexcept { return 0; } - constexpr float extractCharge(ActsScalar /*qOverP*/) const noexcept { + constexpr float extractCharge(double /*qOverP*/) const noexcept { return 0.0f; } - constexpr ActsScalar extractMomentum(ActsScalar qOverP) const noexcept { + constexpr double extractMomentum(double qOverP) const noexcept { assert(qOverP >= 0 && "qOverP cannot be negative"); return 1.0f / qOverP; } - constexpr ActsScalar qOverP(ActsScalar momentum, - float signedQ) const noexcept { + constexpr double qOverP(double momentum, float signedQ) const noexcept { assert((signedQ != 0) && "charge must be 0"); (void)signedQ; return 1.0f / momentum; @@ -110,16 +109,15 @@ struct SinglyCharged { constexpr float absQ() const noexcept { return UnitConstants::e; } - constexpr float extractCharge(ActsScalar qOverP) const noexcept { + constexpr float extractCharge(double qOverP) const noexcept { return std::copysign(UnitConstants::e, qOverP); } - constexpr ActsScalar extractMomentum(ActsScalar qOverP) const noexcept { + constexpr double extractMomentum(double qOverP) const noexcept { return extractCharge(qOverP) / qOverP; } - constexpr ActsScalar qOverP(ActsScalar momentum, - float signedQ) const noexcept { + constexpr double qOverP(double momentum, float signedQ) const noexcept { assert((std::abs(signedQ) == UnitConstants::e) && "absolute charge must be e"); return signedQ / momentum; @@ -151,15 +149,14 @@ class NonNeutralCharge { constexpr float absQ() const noexcept { return m_absQ; } - constexpr float extractCharge(ActsScalar qOverP) const noexcept { + constexpr float extractCharge(double qOverP) const noexcept { return std::copysign(m_absQ, qOverP); } - constexpr ActsScalar extractMomentum(ActsScalar qOverP) const noexcept { + constexpr double extractMomentum(double qOverP) const noexcept { return extractCharge(qOverP) / qOverP; } - constexpr ActsScalar qOverP(ActsScalar momentum, - float signedQ) const noexcept { + constexpr double qOverP(double momentum, float signedQ) const noexcept { assert(std::abs(signedQ) == m_absQ && "inconsistent charge"); return signedQ / momentum; } @@ -194,15 +191,14 @@ class AnyCharge { constexpr float absQ() const noexcept { return m_absQ; } - constexpr float extractCharge(ActsScalar qOverP) const noexcept { + constexpr float extractCharge(double qOverP) const noexcept { return std::copysign(m_absQ, qOverP); } - constexpr ActsScalar extractMomentum(ActsScalar qOverP) const noexcept { + constexpr double extractMomentum(double qOverP) const noexcept { return (m_absQ != 0.0f) ? extractCharge(qOverP) / qOverP : 1.0f / qOverP; } - constexpr ActsScalar qOverP(ActsScalar momentum, - float signedQ) const noexcept { + constexpr double qOverP(double momentum, float signedQ) const noexcept { assert(std::abs(signedQ) == m_absQ && "inconsistent charge"); return (m_absQ != 0.0f) ? signedQ / momentum : 1.0f / momentum; } diff --git a/Core/include/Acts/EventData/GenericBoundTrackParameters.hpp b/Core/include/Acts/EventData/GenericBoundTrackParameters.hpp index 38f297764b1..22567d8adf5 100644 --- a/Core/include/Acts/EventData/GenericBoundTrackParameters.hpp +++ b/Core/include/Acts/EventData/GenericBoundTrackParameters.hpp @@ -36,7 +36,6 @@ namespace Acts { template class GenericBoundTrackParameters { public: - using Scalar = ActsScalar; using ParametersVector = BoundVector; using CovarianceMatrix = BoundSquareMatrix; using ParticleHypothesis = particle_hypothesis_t; @@ -92,10 +91,10 @@ class GenericBoundTrackParameters { /// successfully be converted to on-surface parameters. static Result create( std::shared_ptr surface, const GeometryContext& geoCtx, - const Vector4& pos4, const Vector3& dir, Scalar qOverP, + const Vector4& pos4, const Vector3& dir, double qOverP, std::optional cov, ParticleHypothesis particleHypothesis, - ActsScalar tolerance = s_onSurfaceTolerance) { + double tolerance = s_onSurfaceTolerance) { Result bound = transformFreeToBoundParameters(pos4.segment<3>(ePos0), pos4[eTime], dir, qOverP, *surface, geoCtx, tolerance); @@ -168,7 +167,7 @@ class GenericBoundTrackParameters { /// /// @tparam kIndex Track parameter index template - Scalar get() const { + double get() const { return m_params[kIndex]; } @@ -203,14 +202,14 @@ class GenericBoundTrackParameters { return m_surface->localToGlobal(geoCtx, localPosition(), direction()); } /// Time coordinate. - Scalar time() const { return m_params[eBoundTime]; } + double time() const { return m_params[eBoundTime]; } /// Phi direction. - Scalar phi() const { return m_params[eBoundPhi]; } + double phi() const { return m_params[eBoundPhi]; } /// Theta direction. - Scalar theta() const { return m_params[eBoundTheta]; } + double theta() const { return m_params[eBoundTheta]; } /// Charge over momentum. - Scalar qOverP() const { return m_params[eBoundQOverP]; } + double qOverP() const { return m_params[eBoundQOverP]; } /// Unit direction three-vector, i.e. the normalized momentum /// three-vector. @@ -219,18 +218,18 @@ class GenericBoundTrackParameters { m_params[eBoundTheta]); } /// Absolute momentum. - Scalar absoluteMomentum() const { + double absoluteMomentum() const { return m_particleHypothesis.extractMomentum(m_params[eBoundQOverP]); } /// Transverse momentum. - Scalar transverseMomentum() const { + double transverseMomentum() const { return std::sin(m_params[eBoundTheta]) * absoluteMomentum(); } /// Momentum three-vector. Vector3 momentum() const { return absoluteMomentum() * direction(); } /// Particle electric charge. - Scalar charge() const { + double charge() const { return m_particleHypothesis.extractCharge(get()); } diff --git a/Core/include/Acts/EventData/GenericCurvilinearTrackParameters.hpp b/Core/include/Acts/EventData/GenericCurvilinearTrackParameters.hpp index 6e4ed9bae7a..9764ad68cfc 100644 --- a/Core/include/Acts/EventData/GenericCurvilinearTrackParameters.hpp +++ b/Core/include/Acts/EventData/GenericCurvilinearTrackParameters.hpp @@ -30,7 +30,6 @@ class GenericCurvilinearTrackParameters using Base = GenericBoundTrackParameters; public: - using Scalar = ActsScalar; using ParametersVector = BoundVector; using CovarianceMatrix = BoundSquareMatrix; using ParticleHypothesis = particle_hypothesis_t; @@ -43,7 +42,7 @@ class GenericCurvilinearTrackParameters /// @param cov Curvilinear bound parameters covariance matrix /// @param particleHypothesis Particle hypothesis GenericCurvilinearTrackParameters(const Vector4& pos4, const Vector3& dir, - Scalar qOverP, + double qOverP, std::optional cov, ParticleHypothesis particleHypothesis) : Base(CurvilinearSurface(pos4.segment<3>(ePos0), dir).surface(), @@ -58,8 +57,8 @@ class GenericCurvilinearTrackParameters /// @param qOverP Charge over momentum /// @param cov Curvilinear bound parameters covariance matrix /// @param particleHypothesis Particle hypothesis - GenericCurvilinearTrackParameters(const Vector4& pos4, Scalar phi, - Scalar theta, Scalar qOverP, + GenericCurvilinearTrackParameters(const Vector4& pos4, double phi, + double theta, double qOverP, std::optional cov, ParticleHypothesis particleHypothesis) : Base(CurvilinearSurface(pos4.segment<3>(ePos0), diff --git a/Core/include/Acts/EventData/GenericFreeTrackParameters.hpp b/Core/include/Acts/EventData/GenericFreeTrackParameters.hpp index 7a2b4b46522..b0499dd3137 100644 --- a/Core/include/Acts/EventData/GenericFreeTrackParameters.hpp +++ b/Core/include/Acts/EventData/GenericFreeTrackParameters.hpp @@ -33,7 +33,6 @@ namespace Acts { template class GenericFreeTrackParameters { public: - using Scalar = ActsScalar; using ParametersVector = FreeVector; using CovarianceMatrix = FreeSquareMatrix; using ParticleHypothesis = particle_hypothesis_t; @@ -66,7 +65,7 @@ class GenericFreeTrackParameters { /// @param cov Free parameters covariance matrix /// @param particleHypothesis Particle hypothesis GenericFreeTrackParameters(const Vector4& pos4, const Vector3& dir, - Scalar qOverP, std::optional cov, + double qOverP, std::optional cov, ParticleHypothesis particleHypothesis) : m_params(FreeVector::Zero()), m_cov(std::move(cov)), @@ -91,8 +90,8 @@ class GenericFreeTrackParameters { /// @param qOverP Charge over momentum /// @param cov Free parameters covariance matrix /// @param particleHypothesis Particle hypothesis - GenericFreeTrackParameters(const Vector4& pos4, Scalar phi, Scalar theta, - Scalar qOverP, std::optional cov, + GenericFreeTrackParameters(const Vector4& pos4, double phi, double theta, + double qOverP, std::optional cov, ParticleHypothesis particleHypothesis) : m_params(FreeVector::Zero()), m_cov(std::move(cov)), @@ -146,7 +145,7 @@ class GenericFreeTrackParameters { /// /// @tparam kIndex Track parameter index template - Scalar get() const { + double get() const { return m_params[kIndex]; } @@ -162,33 +161,33 @@ class GenericFreeTrackParameters { /// Spatial position three-vector. Vector3 position() const { return m_params.segment<3>(eFreePos0); } /// Time coordinate. - Scalar time() const { return m_params[eFreeTime]; } + double time() const { return m_params[eFreeTime]; } /// Phi direction. - Scalar phi() const { return VectorHelpers::phi(direction()); } + double phi() const { return VectorHelpers::phi(direction()); } /// Theta direction. - Scalar theta() const { return VectorHelpers::theta(direction()); } + double theta() const { return VectorHelpers::theta(direction()); } /// Charge over momentum. - Scalar qOverP() const { return m_params[eFreeQOverP]; } + double qOverP() const { return m_params[eFreeQOverP]; } /// Unit direction three-vector, i.e. the normalized momentum three-vector. Vector3 direction() const { return m_params.segment<3>(eFreeDir0).normalized(); } /// Absolute momentum. - Scalar absoluteMomentum() const { + double absoluteMomentum() const { return m_particleHypothesis.extractMomentum(m_params[eFreeQOverP]); } /// Transverse momentum. - Scalar transverseMomentum() const { + double transverseMomentum() const { // direction vector w/ arbitrary normalization can be parametrized as // [f*sin(theta)*cos(phi), f*sin(theta)*sin(phi), f*cos(theta)] // w/ f,sin(theta) positive, the transverse magnitude is then // sqrt(f^2*sin^2(theta)) = f*sin(theta) - Scalar transverseMagnitude2 = + double transverseMagnitude2 = square(m_params[eFreeDir0]) + square(m_params[eFreeDir1]); // absolute magnitude is f by construction - Scalar magnitude2 = transverseMagnitude2 + square(m_params[eFreeDir2]); + double magnitude2 = transverseMagnitude2 + square(m_params[eFreeDir2]); // such that we can extract sin(theta) = f*sin(theta) / f return std::sqrt(transverseMagnitude2 / magnitude2) * absoluteMomentum(); } @@ -196,7 +195,7 @@ class GenericFreeTrackParameters { Vector3 momentum() const { return absoluteMomentum() * direction(); } /// Particle electric charge. - Scalar charge() const { + double charge() const { return m_particleHypothesis.extractCharge(get()); } diff --git a/Core/include/Acts/EventData/MultiComponentTrackParameters.hpp b/Core/include/Acts/EventData/MultiComponentTrackParameters.hpp index 70ad87f8d77..cf932fc0470 100644 --- a/Core/include/Acts/EventData/MultiComponentTrackParameters.hpp +++ b/Core/include/Acts/EventData/MultiComponentTrackParameters.hpp @@ -34,7 +34,6 @@ class MultiComponentBoundTrackParameters { public: using Parameters = BoundTrackParameters; using ParticleHypothesis = Parameters::ParticleHypothesis; - using Scalar = typename Parameters::Scalar; using ParametersVector = typename Parameters::ParametersVector; using CovarianceMatrix = typename Parameters::CovarianceMatrix; @@ -159,7 +158,7 @@ class MultiComponentBoundTrackParameters { /// /// @tparam kIndex Track parameter index template - Scalar get() const { + double get() const { return reduce([&](const Parameters& p) { return p.get(); }); } @@ -180,7 +179,7 @@ class MultiComponentBoundTrackParameters { } /// Time coordinate. - Scalar time() const { + double time() const { return reduce([](const Parameters& p) { return p.time(); }); } @@ -192,21 +191,21 @@ class MultiComponentBoundTrackParameters { } /// Phi direction. - Scalar phi() const { return VectorHelpers::phi(direction()); } + double phi() const { return VectorHelpers::phi(direction()); } /// Theta direction. - Scalar theta() const { return VectorHelpers::theta(direction()); } + double theta() const { return VectorHelpers::theta(direction()); } /// Charge over momentum. - Scalar qOverP() const { return get(); } + double qOverP() const { return get(); } /// Absolute momentum. - Scalar absoluteMomentum() const { + double absoluteMomentum() const { return reduce([](const Parameters& p) { return p.absoluteMomentum(); }); } /// Transverse momentum. - Scalar transverseMomentum() const { + double transverseMomentum() const { return reduce([](const Parameters& p) { return p.transverseMomentum(); }); } @@ -216,7 +215,7 @@ class MultiComponentBoundTrackParameters { } /// Particle electric charge. - Scalar charge() const { + double charge() const { return reduce([](const Parameters& p) { return p.charge(); }); } @@ -238,8 +237,8 @@ class MultiComponentCurvilinearTrackParameters using covariance_t = BoundSquareMatrix; public: - using ConstructionTuple = std::tuple; + using ConstructionTuple = + std::tuple; private: using Base = MultiComponentBoundTrackParameters; diff --git a/Core/include/Acts/EventData/MultiTrajectory.hpp b/Core/include/Acts/EventData/MultiTrajectory.hpp index 1c065fd7e12..e293c6c9c5f 100644 --- a/Core/include/Acts/EventData/MultiTrajectory.hpp +++ b/Core/include/Acts/EventData/MultiTrajectory.hpp @@ -8,6 +8,7 @@ #pragma once +#include "Acts/Definitions/Algebra.hpp" #include "Acts/Definitions/TrackParametrization.hpp" #include "Acts/EventData/MeasurementHelpers.hpp" #include "Acts/EventData/SourceLink.hpp" @@ -687,13 +688,24 @@ class MultiTrajectory { /// Allocate storage for a calibrated measurement of specified dimension /// @param istate The track state to store for /// @param measdim the dimension of the measurement to store - /// @note Is a noop if the track state already has an allocation - /// an the dimension is the same. + /// @note In case an allocation is already present, no additional allocation + /// will be performed, but the existing allocation will be zeroed. void allocateCalibrated(IndexType istate, std::size_t measdim) { throw_assert(measdim > 0 && measdim <= eBoundSize, "Invalid measurement dimension detected"); - self().allocateCalibrated_impl(istate, measdim); + visit_measurement(measdim, [this, istate]( + std::integral_constant) { + self().template allocateCalibrated_impl( + istate, ActsVector{ActsVector::Zero()}, + ActsSquareMatrix{ActsSquareMatrix::Zero()}); + }); + } + + template + void allocateCalibrated(IndexType istate, const Eigen::DenseBase& val, + const Eigen::DenseBase& cov) { + self().template allocateCalibrated_impl(istate, val, cov); } void setUncalibratedSourceLink(IndexType istate, SourceLink&& sourceLink) diff --git a/Core/include/Acts/EventData/MultiTrajectoryBackendConcept.hpp b/Core/include/Acts/EventData/MultiTrajectoryBackendConcept.hpp index 92ae47270bc..83f2593d647 100644 --- a/Core/include/Acts/EventData/MultiTrajectoryBackendConcept.hpp +++ b/Core/include/Acts/EventData/MultiTrajectoryBackendConcept.hpp @@ -130,7 +130,15 @@ concept MutableMultiTrajectoryBackend = { v.template addColumn_impl(col) }; { v.template addColumn_impl(col) }; - { v.allocateCalibrated_impl(istate, dim) }; + { + v.template allocateCalibrated_impl(istate, ActsVector<1>{}, + ActsSquareMatrix<1>{}) + }; + // Assuming intermediate values also work + { + v.template allocateCalibrated_impl(istate, ActsVector{}, + ActsSquareMatrix{}) + }; { v.setUncalibratedSourceLink_impl(istate, std::move(sl)) }; diff --git a/Core/include/Acts/EventData/SubspaceHelpers.hpp b/Core/include/Acts/EventData/SubspaceHelpers.hpp index 029dbf372b3..f48690cf036 100644 --- a/Core/include/Acts/EventData/SubspaceHelpers.hpp +++ b/Core/include/Acts/EventData/SubspaceHelpers.hpp @@ -14,8 +14,7 @@ #include "Acts/Utilities/AlgebraHelpers.hpp" #include "Acts/Utilities/Enumerate.hpp" -#include -#include +#include #include @@ -25,30 +24,30 @@ namespace Acts { /// /// Indices must be unique and within the full size of the subspace /// -/// @tparam Container type of the container +/// @tparam index_range_t the type of the container of indices /// -/// @param container the container of indices +/// @param indexRange the range of indices /// @param fullSize the full size of the subspace /// @param subspaceSize the size of the subspace /// /// @return true if the indices are consistent -template -inline static bool checkSubspaceIndices(const Container& container, +template +inline static bool checkSubspaceIndices(const index_range_t& indexRange, std::size_t fullSize, std::size_t subspaceSize) { if (subspaceSize > fullSize) { return false; } - if (static_cast(container.size()) != subspaceSize) { + if (static_cast(indexRange.size()) != subspaceSize) { return false; } - for (auto it = container.begin(); it != container.end();) { + for (auto it = indexRange.begin(); it != indexRange.end();) { auto index = *it; if (index >= fullSize) { return false; } ++it; - if (std::find(it, container.end(), index) != container.end()) { + if (std::find(it, indexRange.end(), index) != indexRange.end()) { return false; } } @@ -69,7 +68,8 @@ inline static SerializedSubspaceIndices serializeSubspaceIndices( { SerializedSubspaceIndices result = 0; for (std::size_t i = 0; i < FullSize; ++i) { - result |= static_cast(indices[i]) << (i * 8); + result |= static_cast(indices[i] & 0xFF) + << (i * 8); } return result; } @@ -88,7 +88,7 @@ inline static SubspaceIndices deserializeSubspaceIndices( { SubspaceIndices result; for (std::size_t i = 0; i < FullSize; ++i) { - result[i] = static_cast(serialized >> (i * 8)); + result[i] = static_cast((serialized >> (i * 8)) & 0xFF); } return result; } @@ -187,8 +187,8 @@ class VariableSubspaceHelper using IndexType = index_t; using Container = boost::container::static_vector; - template - explicit VariableSubspaceHelper(const OtherContainer& indices) { + template + explicit VariableSubspaceHelper(const other_index_range_t& indices) { assert(checkSubspaceIndices(indices, kFullSize, indices.size()) && "Invalid indices"); m_indices.resize(indices.size()); @@ -236,8 +236,8 @@ class FixedSubspaceHelper using IndexType = index_t; using Container = std::array; - template - explicit FixedSubspaceHelper(const OtherContainer& indices) { + template + explicit FixedSubspaceHelper(const other_index_range_t& indices) { assert(checkSubspaceIndices(indices, kFullSize, kSubspaceSize) && "Invalid indices"); std::transform(indices.begin(), indices.end(), m_indices.begin(), diff --git a/Core/include/Acts/EventData/TrackParametersConcept.hpp b/Core/include/Acts/EventData/TrackParametersConcept.hpp index 5e4982545a4..4369fe57141 100644 --- a/Core/include/Acts/EventData/TrackParametersConcept.hpp +++ b/Core/include/Acts/EventData/TrackParametersConcept.hpp @@ -21,7 +21,6 @@ class Surface; namespace Concepts { template concept BasicTrackParameters = requires { - typename Parameters::Scalar; typename Parameters::ParametersVector; typename Parameters::CovarianceMatrix; diff --git a/Core/include/Acts/EventData/TrackProxy.hpp b/Core/include/Acts/EventData/TrackProxy.hpp index 6ccb0f402b2..7e62eea943d 100644 --- a/Core/include/Acts/EventData/TrackProxy.hpp +++ b/Core/include/Acts/EventData/TrackProxy.hpp @@ -243,27 +243,27 @@ class TrackProxy { /// Access the theta parameter of the track at the reference surface /// @return The theta parameter - ActsScalar theta() const { return parameters()[eBoundTheta]; } + double theta() const { return parameters()[eBoundTheta]; } /// Access the phi parameter of the track at the reference surface /// @return The phi parameter - ActsScalar phi() const { return parameters()[eBoundPhi]; } + double phi() const { return parameters()[eBoundPhi]; } /// Access the loc0 parameter of the track at the reference surface /// @return The loc0 parameter - ActsScalar loc0() const { return parameters()[eBoundLoc0]; } + double loc0() const { return parameters()[eBoundLoc0]; } /// Access the loc1 parameter of the track at the reference surface /// @return The loc1 parameter - ActsScalar loc1() const { return parameters()[eBoundLoc1]; } + double loc1() const { return parameters()[eBoundLoc1]; } /// Access the time parameter of the track at the reference surface /// @return The time parameter - ActsScalar time() const { return parameters()[eBoundTime]; } + double time() const { return parameters()[eBoundTime]; } /// Access the q/p (curvature) parameter of the track at the reference surface /// @return The q/p parameter - ActsScalar qOverP() const { return parameters()[eBoundQOverP]; } + double qOverP() const { return parameters()[eBoundQOverP]; } /// Get the particle hypothesis /// @return the particle hypothesis @@ -284,17 +284,17 @@ class TrackProxy { /// Get the charge of the tack /// @note this depends on the charge hypothesis /// @return The absolute track momentum - ActsScalar charge() const { return particleHypothesis().qFromQOP(qOverP()); } + double charge() const { return particleHypothesis().qFromQOP(qOverP()); } /// Get the absolute momentum of the tack /// @return The absolute track momentum - ActsScalar absoluteMomentum() const { + double absoluteMomentum() const { return particleHypothesis().extractMomentum(qOverP()); } /// Get the transverse momentum of the track /// @return The track transverse momentum value - ActsScalar transverseMomentum() const { + double transverseMomentum() const { return std::sin(theta()) * absoluteMomentum(); } @@ -577,9 +577,6 @@ class TrackProxy { // append track states (cheap), but they're in the wrong order for (const auto& srcTrackState : other.trackStatesReversed()) { auto destTrackState = appendTrackState(srcTrackState.getMask()); - if (srcTrackState.hasCalibrated()) { - destTrackState.allocateCalibrated(srcTrackState.calibratedSize()); - } destTrackState.copyFrom(srcTrackState, Acts::TrackStatePropMask::All, true); } diff --git a/Core/include/Acts/EventData/TrackStateProxy.hpp b/Core/include/Acts/EventData/TrackStateProxy.hpp index 741bfa5b511..4338c434f77 100644 --- a/Core/include/Acts/EventData/TrackStateProxy.hpp +++ b/Core/include/Acts/EventData/TrackStateProxy.hpp @@ -8,7 +8,6 @@ #pragma once -#include "Acts/Definitions/Algebra.hpp" #include "Acts/Definitions/TrackParametrization.hpp" #include "Acts/EventData/SourceLink.hpp" #include "Acts/EventData/SubspaceHelpers.hpp" @@ -17,11 +16,11 @@ #include "Acts/EventData/TrackStateType.hpp" #include "Acts/EventData/Types.hpp" #include "Acts/Surfaces/Surface.hpp" -#include "Acts/Utilities/AlgebraHelpers.hpp" #include "Acts/Utilities/HashedString.hpp" #include "Acts/Utilities/Helpers.hpp" #include +#include #include #include @@ -82,17 +81,15 @@ template struct FixedSizeTypes { constexpr static auto Flags = Eigen::ColMajor | Eigen::AutoAlign; - using Scalar = ActsScalar; - // single items - using Coefficients = Eigen::Matrix; - using Covariance = Eigen::Matrix; + using Coefficients = Eigen::Matrix; + using Covariance = Eigen::Matrix; using CoefficientsMap = Eigen::Map>; using CovarianceMap = Eigen::Map>; - using DynamicCoefficients = Eigen::Matrix; + using DynamicCoefficients = Eigen::Matrix; using DynamicCovariance = - Eigen::Matrix; + Eigen::Matrix; using DynamicCoefficientsMap = Eigen::Map>; using DynamicCovarianceMap = @@ -105,11 +102,9 @@ template struct DynamicSizeTypes { constexpr static auto Flags = Eigen::ColMajor | Eigen::AutoAlign; - using Scalar = ActsScalar; - - using Coefficients = Eigen::Matrix; + using Coefficients = Eigen::Matrix; using Covariance = - Eigen::Matrix; + Eigen::Matrix; using CoefficientsMap = Eigen::Map>; using CovarianceMap = Eigen::Map>; }; @@ -119,8 +114,6 @@ struct DynamicSizeTypes { // This is public template struct TrackStateTraits { - using Scalar = ActsScalar; - using Parameters = typename detail_lt::FixedSizeTypes::CoefficientsMap; using Covariance = @@ -133,11 +126,6 @@ struct TrackStateTraits { typename detail_lt::DynamicSizeTypes::CoefficientsMap; using EffectiveCalibratedCovariance = typename detail_lt::DynamicSizeTypes::CovarianceMap; - - constexpr static auto ProjectorFlags = Eigen::RowMajor | Eigen::AutoAlign; - using Projector = Eigen::Matrix; - using EffectiveProjector = Eigen::Matrix; }; /// Proxy object to access a single point on the trajectory. @@ -213,17 +201,6 @@ class TrackStateProxy { /// Sentinel value that indicates an invalid index static constexpr IndexType kInvalid = kTrackIndexInvalid; - /// Matrix representing the projector (measurement mapping function) for a - /// measurement. This is not a map type, but an actual matrix. This matrix - /// is always \f$M \times M\f$, even if the local measurement dimension is lower. - /// The actual \f$N\times M\f$ projector is given by the top \f$N\f$ rows. - using Projector = typename TrackStateTraits::Projector; - - /// Dynamic variant of the projector matrix - /// @warning Using this type is discouraged, as it has a runtime overhead - using EffectiveProjector = - typename TrackStateTraits::EffectiveProjector; - /// The track state container backend given as a template parameter using Trajectory = trajectory_t; @@ -621,145 +598,61 @@ class TrackStateProxy { /// /// @{ - /// Returns the projector (measurement mapping function) for this track - /// state. It is derived from the uncalibrated measurement - /// @note This function returns the overallocated projector. This means it - /// is of dimension MxM, where M is the maximum number of measurement - /// dimensions. The NxM submatrix, where N is the actual dimension of the - /// measurement, is located in the top left corner, everything else is zero. - /// @return The overallocated projector - Projector projector() const; - - /// Returns whether a projector is set - /// @return Whether it is set - bool hasProjector() const { return has(); } - - /// Returns the projector (measurement mapping function) for this track - /// state. It is derived from the uncalibrated measurement - /// @warning This function returns the effective projector. This means it - /// is of dimension \f$N\times M\f$, where \f$N\f$ is the actual dimension of the - /// measurement. - /// @return The effective projector - EffectiveProjector effectiveProjector() const { - return projector().topLeftCorner(calibratedSize(), M); - } - - /// Set the projector on this track state - /// This will convert the projector to a more compact bitset representation - /// and store it. - /// @param projector The projector in the form of a dense matrix - /// @note @p projector is assumed to only have 0s or 1s as components. - template - [[deprecated("use setProjector(span) instead")]] void setProjector( - const Eigen::MatrixBase& projector) - requires(!ReadOnly) + /// Set the projector subspace indices + /// @param subspaceIndices The projector subspace indices to set + template + void setProjectorSubspaceIndices(const index_range_t& subspaceIndices) + requires(!ReadOnly && + std::convertible_to, + std::uint8_t>) { - constexpr int rows = Eigen::MatrixBase::RowsAtCompileTime; - constexpr int cols = Eigen::MatrixBase::ColsAtCompileTime; - - static_assert(rows != -1 && cols != -1, - "Assignment of dynamic matrices is currently not supported."); - assert(has()); - - static_assert(rows <= M, "Given projector has too many rows"); - static_assert(cols <= eBoundSize, "Given projector has too many columns"); - - // set up full size projector with only zeros - typename TrackStateProxy::Projector fullProjector = - decltype(fullProjector)::Zero(); - - // assign (potentially) smaller actual projector to matrix, preserving - // zeroes outside of smaller matrix block. - fullProjector.template topLeftCorner() = projector; - - // convert to bitset before storing - ProjectorBitset projectorBitset = matrixToBitset(fullProjector).to_ulong(); - setProjectorBitset(projectorBitset); - } - - /// Directly get the projector bitset, a compressed form of a projection - /// matrix - /// @note This is mainly to copy explicitly a projector from one state - /// to another. Use the `projector` or `effectiveProjector` method if - /// you want to access the matrix. - /// @return The projector bitset - [[deprecated("use projector() instead")]] ProjectorBitset projectorBitset() - const { - return variableBoundSubspaceHelper().projectorBitset(); + assert(subspaceIndices.size() <= eBoundSize); + BoundSubspaceIndices boundSubspace{}; + std::transform(subspaceIndices.begin(), subspaceIndices.end(), + boundSubspace.begin(), + [](auto i) { return static_cast(i); }); + component() = + serializeSubspaceIndices(boundSubspace); } - /// Set the projector bitset, a compressed form of a projection matrix - /// @param proj The projector bitset - /// - /// @note This is mainly to copy explicitly a projector from one state - /// to another. If you have a projection matrix, set it with - /// `setProjector`. - [[deprecated("use setProjector(span) instead")]] void setProjectorBitset( - ProjectorBitset proj) - requires(!ReadOnly) - { - BoundMatrix projMatrix = bitsetToMatrix(proj); - BoundSubspaceIndices boundSubspace = - projectorToSubspaceIndices(projMatrix); - setBoundSubspaceIndices(boundSubspace); - } + /// Returns whether a projector is set + /// @return Whether it is set + bool hasProjector() const { return has(); } - BoundSubspaceIndices boundSubspaceIndices() const { + /// Returns the projector subspace indices + /// @return The projector subspace indices + BoundSubspaceIndices projectorSubspaceIndices() const { assert(has()); return deserializeSubspaceIndices( component()); } + /// Returns the projector subspace indices + /// @return The projector subspace indices template - SubspaceIndices subspaceIndices() const { - BoundSubspaceIndices boundSubspace = BoundSubspaceIndices(); + SubspaceIndices projectorSubspaceIndices() const { + BoundSubspaceIndices boundSubspace = projectorSubspaceIndices(); SubspaceIndices subspace; std::copy(boundSubspace.begin(), boundSubspace.begin() + measdim, subspace.begin()); return subspace; } - void setBoundSubspaceIndices(BoundSubspaceIndices boundSubspace) - requires(!ReadOnly) - { - assert(has()); - component() = - serializeSubspaceIndices(boundSubspace); - } - - template - void setSubspaceIndices(SubspaceIndices subspace) - requires(!ReadOnly && measdim <= eBoundSize) - { - assert(has()); - BoundSubspaceIndices boundSubspace{}; - std::copy(subspace.begin(), subspace.end(), boundSubspace.begin()); - setBoundSubspaceIndices(boundSubspace); - } - - template - void setSubspaceIndices(std::array subspaceIndices) - requires(!ReadOnly && measdim <= eBoundSize) - { - assert(has()); - BoundSubspaceIndices boundSubspace{}; - std::transform(subspaceIndices.begin(), subspaceIndices.end(), - boundSubspace.begin(), - [](index_t i) { return static_cast(i); }); - setBoundSubspaceIndices(boundSubspace); - } - - VariableBoundSubspaceHelper variableBoundSubspaceHelper() const { - BoundSubspaceIndices boundSubspace = boundSubspaceIndices(); + /// Creates a variable size subspace helper + /// @return The subspace helper + VariableBoundSubspaceHelper projectorSubspaceHelper() const { + BoundSubspaceIndices boundSubspace = projectorSubspaceIndices(); std::span validSubspaceIndices( boundSubspace.begin(), boundSubspace.begin() + calibratedSize()); return VariableBoundSubspaceHelper(validSubspaceIndices); } + /// Creates a fixed size subspace helper + /// @return The subspace helper template - FixedBoundSubspaceHelper fixedBoundSubspaceHelper() const { - SubspaceIndices subspace = subspaceIndices(); + FixedBoundSubspaceHelper projectorSubspaceHelper() const { + SubspaceIndices subspace = projectorSubspaceIndices(); return FixedBoundSubspaceHelper(subspace); } @@ -871,10 +764,35 @@ class TrackStateProxy { /// Allocate storage to be able to store a measurement of size @p measdim. /// This must be called **before** setting the measurement content. + /// @note This does not allocate if an allocation of the same size already exists + /// @note This will zero-initialize the allocated storage + /// @note This is an error if an existing allocation has different size void allocateCalibrated(std::size_t measdim) { m_traj->allocateCalibrated(m_istate, measdim); } + /// Allocate storage and assign the given vector and covariance to it. + /// The dimension is inferred from the given vector and matrix. + /// @tparam val_t Type of the vector + /// @tparam cov_t Type of the covariance matrix + /// @param val The measurement vector + /// @param cov The covariance matrix + /// @note This does not allocate if an allocation of the same size already exists + /// @note This throws an exception if an existing allocation has different size + template + void allocateCalibrated(const Eigen::DenseBase& val, + const Eigen::DenseBase& cov) + requires(Eigen::PlainObjectBase::RowsAtCompileTime > 0 && + Eigen::PlainObjectBase::RowsAtCompileTime <= eBoundSize && + Eigen::PlainObjectBase::RowsAtCompileTime == + Eigen::PlainObjectBase::RowsAtCompileTime && + Eigen::PlainObjectBase::RowsAtCompileTime == + Eigen::PlainObjectBase::ColsAtCompileTime) + { + m_traj->template allocateCalibrated< + Eigen::PlainObjectBase::RowsAtCompileTime>(m_istate, val, cov); + } + /// @} /// @anchor track_state_share_copy @@ -999,20 +917,17 @@ class TrackStateProxy { } if (ACTS_CHECK_BIT(src, PM::Calibrated)) { - allocateCalibrated(other.calibratedSize()); - // workaround for gcc8 bug: // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=86594 auto* self = this; visit_measurement(other.calibratedSize(), [&](auto N) { constexpr int measdim = decltype(N)::value; - self->template calibrated() = - other.template calibrated(); - self->template calibratedCovariance() = - other.template calibratedCovariance(); + self->allocateCalibrated( + other.template calibrated().eval(), + other.template calibratedCovariance().eval()); }); - setBoundSubspaceIndices(other.boundSubspaceIndices()); + setProjectorSubspaceIndices(other.projectorSubspaceIndices()); } } else { if (ACTS_CHECK_BIT(mask, PM::Predicted) && @@ -1047,20 +962,17 @@ class TrackStateProxy { // may be not yet allocated if (ACTS_CHECK_BIT(mask, PM::Calibrated) && other.template has()) { - allocateCalibrated(other.calibratedSize()); - // workaround for gcc8 bug: // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=86594 auto* self = this; visit_measurement(other.calibratedSize(), [&](auto N) { constexpr int measdim = decltype(N)::value; - self->template calibrated() = - other.template calibrated(); - self->template calibratedCovariance() = - other.template calibratedCovariance(); + self->allocateCalibrated( + other.template calibrated().eval(), + other.template calibratedCovariance().eval()); }); - setBoundSubspaceIndices(other.boundSubspaceIndices()); + setProjectorSubspaceIndices(other.projectorSubspaceIndices()); } } diff --git a/Core/include/Acts/EventData/TrackStateProxy.ipp b/Core/include/Acts/EventData/TrackStateProxy.ipp index e36be5f3c25..16abe8fb3aa 100644 --- a/Core/include/Acts/EventData/TrackStateProxy.ipp +++ b/Core/include/Acts/EventData/TrackStateProxy.ipp @@ -61,11 +61,6 @@ inline auto TrackStateProxy::covariance() const } } -template -inline auto TrackStateProxy::projector() const -> Projector { - return variableBoundSubspaceHelper().fullProjector(); -} - template inline auto TrackStateProxy::getUncalibratedSourceLink() const -> SourceLink { diff --git a/Core/include/Acts/EventData/TrackStateProxyConcept.hpp b/Core/include/Acts/EventData/TrackStateProxyConcept.hpp index d148d3c4940..4b8a713f864 100644 --- a/Core/include/Acts/EventData/TrackStateProxyConcept.hpp +++ b/Core/include/Acts/EventData/TrackStateProxyConcept.hpp @@ -111,12 +111,6 @@ concept TrackStateProxyConcept = { cv.hasProjector() } -> std::same_as; { v.hasProjector() } -> std::same_as; - { cv.effectiveProjector() } -> std::same_as; - { v.effectiveProjector() } -> std::same_as; - - { cv.projectorBitset() } -> std::same_as; - { v.projectorBitset() } -> std::same_as; - { cv.getUncalibratedSourceLink() } -> std::same_as; { v.getUncalibratedSourceLink() } -> std::same_as; @@ -248,6 +242,13 @@ concept MutableTrackStateProxyConcept = { v.allocateCalibrated(measdim) }; + { v.allocateCalibrated(ActsVector<1>{}, ActsSquareMatrix<1>{}) }; + // Assuming intermediate values are also allowed + { + v.allocateCalibrated(ActsVector{}, + ActsSquareMatrix{}) + }; + { v.chi2() } -> std::same_as; { v.pathLength() } -> std::same_as; diff --git a/Core/include/Acts/EventData/TransformationHelpers.hpp b/Core/include/Acts/EventData/TransformationHelpers.hpp index e31e29fd3c0..e5877744c4b 100644 --- a/Core/include/Acts/EventData/TransformationHelpers.hpp +++ b/Core/include/Acts/EventData/TransformationHelpers.hpp @@ -69,7 +69,7 @@ FreeVector transformBoundToFreeParameters(const Surface& surface, /// @return Bound track parameters vector on the given surface Result transformFreeToBoundParameters( const FreeVector& freeParams, const Surface& surface, - const GeometryContext& geoCtx, ActsScalar tolerance = s_onSurfaceTolerance); + const GeometryContext& geoCtx, double tolerance = s_onSurfaceTolerance); /// Convert position and direction to bound track parameters. /// @@ -83,9 +83,9 @@ Result transformFreeToBoundParameters( /// /// @return Equivalent bound parameters vector on the given surface Result transformFreeToBoundParameters( - const Vector3& position, ActsScalar time, const Vector3& direction, - ActsScalar qOverP, const Surface& surface, const GeometryContext& geoCtx, - ActsScalar tolerance = s_onSurfaceTolerance); + const Vector3& position, double time, const Vector3& direction, + double qOverP, const Surface& surface, const GeometryContext& geoCtx, + double tolerance = s_onSurfaceTolerance); /// Convert direction to curvilinear track parameters. /// @@ -97,9 +97,9 @@ Result transformFreeToBoundParameters( /// @note The parameters are assumed to be defined at the origin of the /// curvilinear frame derived from the direction vector. The local /// coordinates are zero by construction. -BoundVector transformFreeToCurvilinearParameters(ActsScalar time, +BoundVector transformFreeToCurvilinearParameters(double time, const Vector3& direction, - ActsScalar qOverP); + double qOverP); /// Convert direction angles to curvilinear track parameters. /// @@ -112,9 +112,7 @@ BoundVector transformFreeToCurvilinearParameters(ActsScalar time, /// @note The parameters are assumed to be defined at the origin of the /// curvilinear frame derived from the direction angles. The local /// coordinates are zero by construction. -BoundVector transformFreeToCurvilinearParameters(ActsScalar time, - ActsScalar phi, - ActsScalar theta, - ActsScalar qOverP); +BoundVector transformFreeToCurvilinearParameters(double time, double phi, + double theta, double qOverP); } // namespace Acts diff --git a/Core/include/Acts/EventData/VectorMultiTrajectory.hpp b/Core/include/Acts/EventData/VectorMultiTrajectory.hpp index 3859239ae69..e13498cea2c 100644 --- a/Core/include/Acts/EventData/VectorMultiTrajectory.hpp +++ b/Core/include/Acts/EventData/VectorMultiTrajectory.hpp @@ -47,6 +47,33 @@ using MultiTrajectoryTraits::IndexType; constexpr auto kInvalid = MultiTrajectoryTraits::kInvalid; constexpr auto MeasurementSizeMax = MultiTrajectoryTraits::MeasurementSizeMax; +template +struct NonInitializingAllocator { + using value_type = T; + + NonInitializingAllocator() noexcept = default; + + template + explicit NonInitializingAllocator( + const NonInitializingAllocator& /*other*/) noexcept {} + + template + bool operator==(const NonInitializingAllocator& /*other*/) const noexcept { + return true; + } + + T* allocate(std::size_t n) const { return std::allocator{}.allocate(n); } + + void deallocate(T* const p, std::size_t n) const noexcept { + std::allocator{}.deallocate(p, n); + } + + void construct(T* /*p*/) const { + // This construct function intentionally does not initialize the object! + // Be very careful when using this allocator. + } +}; + class VectorMultiTrajectoryBase { public: struct Statistics { @@ -320,9 +347,9 @@ class VectorMultiTrajectoryBase { m_params; std::vector::Covariance> m_cov; - std::vector m_meas; + std::vector> m_meas; std::vector m_measOffset; - std::vector m_measCov; + std::vector> m_measCov; std::vector m_measCovOffset; std::vector::Covariance> m_jac; @@ -464,23 +491,44 @@ class VectorMultiTrajectory final return detail_vmt::VectorMultiTrajectoryBase::hasColumn_impl(*this, key); } - void allocateCalibrated_impl(IndexType istate, std::size_t measdim) { - throw_assert(measdim > 0 && measdim <= eBoundSize, - "Invalid measurement dimension detected"); + template + void allocateCalibrated_impl(IndexType istate, + const Eigen::DenseBase& val, + const Eigen::DenseBase& cov) + + requires(Eigen::PlainObjectBase::RowsAtCompileTime > 0 && + Eigen::PlainObjectBase::RowsAtCompileTime <= eBoundSize && + Eigen::PlainObjectBase::RowsAtCompileTime == + Eigen::PlainObjectBase::RowsAtCompileTime && + Eigen::PlainObjectBase::RowsAtCompileTime == + Eigen::PlainObjectBase::ColsAtCompileTime) + { + constexpr std::size_t measdim = val_t::RowsAtCompileTime; + + if (m_index[istate].measdim != kInvalid && + m_index[istate].measdim != measdim) { + throw std::invalid_argument{ + "Measurement dimension does not match the allocated dimension"}; + } + + if (m_measOffset[istate] == kInvalid || + m_measCovOffset[istate] == kInvalid) { + m_measOffset[istate] = static_cast(m_meas.size()); + m_meas.resize(m_meas.size() + measdim); - if (m_measOffset[istate] != kInvalid && - m_measCovOffset[istate] != kInvalid && - m_index[istate].measdim == measdim) { - return; + m_measCovOffset[istate] = static_cast(m_measCov.size()); + m_measCov.resize(m_measCov.size() + measdim * measdim); } m_index[istate].measdim = measdim; - m_measOffset[istate] = static_cast(m_meas.size()); - m_meas.resize(m_meas.size() + measdim); + double* measPtr = &m_meas[m_measOffset[istate]]; + Eigen::Map> valMap(measPtr); + valMap = val; - m_measCovOffset[istate] = static_cast(m_measCov.size()); - m_measCov.resize(m_measCov.size() + measdim * measdim); + double* covPtr = &m_measCov[m_measCovOffset[istate]]; + Eigen::Map> covMap(covPtr); + covMap = cov; } void setUncalibratedSourceLink_impl(IndexType istate, diff --git a/Core/include/Acts/EventData/VectorTrackContainer.hpp b/Core/include/Acts/EventData/VectorTrackContainer.hpp index 8734f69eb4c..d0ce9cf402d 100644 --- a/Core/include/Acts/EventData/VectorTrackContainer.hpp +++ b/Core/include/Acts/EventData/VectorTrackContainer.hpp @@ -253,6 +253,7 @@ class VectorTrackContainer final : public detail_vtc::VectorTrackContainerBase { void reserve(IndexType size); void clear(); + std::size_t size() const; void setReferenceSurface_impl(IndexType itrack, std::shared_ptr surface) { diff --git a/Core/include/Acts/EventData/detail/CorrectedTransformationFreeToBound.hpp b/Core/include/Acts/EventData/detail/CorrectedTransformationFreeToBound.hpp index 58283dcfebe..72cb0965507 100644 --- a/Core/include/Acts/EventData/detail/CorrectedTransformationFreeToBound.hpp +++ b/Core/include/Acts/EventData/detail/CorrectedTransformationFreeToBound.hpp @@ -27,12 +27,12 @@ struct FreeToBoundCorrection { bool apply = false; /// UKF tuning parameters - ActsScalar alpha = 0.1; - ActsScalar beta = 2; + double alpha = 0.1; + double beta = 2; /// The cutoff of incident angles cosine for correction - ActsScalar cosIncidentAngleMinCutoff = 1e-5; - ActsScalar cosIncidentAngleMaxCutoff = 0.99500417; + double cosIncidentAngleMinCutoff = 1e-5; + double cosIncidentAngleMaxCutoff = 0.99500417; /// Default constructor FreeToBoundCorrection() = default; @@ -42,7 +42,7 @@ struct FreeToBoundCorrection { /// @param apply_ Whether to apply correction /// @param alpha_ The UKF tuning parameter alpha /// @param beta_ The UKF tuning parameter beta - FreeToBoundCorrection(bool apply_, ActsScalar alpha_, ActsScalar beta_); + FreeToBoundCorrection(bool apply_, double alpha_, double beta_); /// Construct from boolean only /// @@ -65,9 +65,9 @@ struct CorrectedFreeToBoundTransformer { /// @param beta The UKF tuning parameter beta /// @param cosIncidentAngleMinCutoff The cosine of max incident angle /// @param cosIncidentAngleMaxCutoff The cosine of min incident angle - CorrectedFreeToBoundTransformer(ActsScalar alpha, ActsScalar beta, - ActsScalar cosIncidentAngleMinCutoff, - ActsScalar cosIncidentAngleMaxCutoff); + CorrectedFreeToBoundTransformer(double alpha, double beta, + double cosIncidentAngleMinCutoff, + double cosIncidentAngleMaxCutoff); /// Construct from a FreeToBoundCorrection /// @@ -101,16 +101,16 @@ struct CorrectedFreeToBoundTransformer { private: /// The parameters to tune the weight in UKF (0 < alpha <=1) - ActsScalar m_alpha = 0.1; - ActsScalar m_beta = 2; + double m_alpha = 0.1; + double m_beta = 2; /// The maximum incident angle (i.e. minimum cos incident angle) cutoff for /// correction - ActsScalar m_cosIncidentAngleMinCutoff = 1e-5; + double m_cosIncidentAngleMinCutoff = 1e-5; /// The minimum incident angle (i.e. maximum cos incident angle) cutoff for /// correction, note cos(0.1) = 0.99500417 - ActsScalar m_cosIncidentAngleMaxCutoff = 0.99500417; + double m_cosIncidentAngleMaxCutoff = 0.99500417; }; } // namespace detail diff --git a/Core/include/Acts/EventData/detail/GenerateParameters.hpp b/Core/include/Acts/EventData/detail/GenerateParameters.hpp index 64e7bc3405b..b06d853faa6 100644 --- a/Core/include/Acts/EventData/detail/GenerateParameters.hpp +++ b/Core/include/Acts/EventData/detail/GenerateParameters.hpp @@ -236,7 +236,7 @@ template inline std::pair generateBoundParametersCovariance( generator_t& rng, const GenerateBoundParametersOptions& options) { auto params = generateBoundParameters(rng, options); - auto cov = generateCovariance(rng); + auto cov = generateCovariance(rng); return {params, cov}; } @@ -293,7 +293,7 @@ template inline std::pair generateFreeParametersCovariance( generator_t& rng, const GenerateFreeParametersOptions& options) { auto params = generateFreeParameters(rng, options); - auto cov = generateCovariance(rng); + auto cov = generateCovariance(rng); return {params, cov}; } diff --git a/Core/include/Acts/EventData/detail/MultiTrajectoryTestsCommon.hpp b/Core/include/Acts/EventData/detail/MultiTrajectoryTestsCommon.hpp index a2e374c0cc2..7926ca3ba77 100644 --- a/Core/include/Acts/EventData/detail/MultiTrajectoryTestsCommon.hpp +++ b/Core/include/Acts/EventData/detail/MultiTrajectoryTestsCommon.hpp @@ -10,6 +10,7 @@ #include +#include "Acts/Definitions/Algebra.hpp" #include "Acts/Definitions/TrackParametrization.hpp" #include "Acts/EventData/TrackStatePropMask.hpp" #include "Acts/EventData/VectorMultiTrajectory.hpp" @@ -20,6 +21,7 @@ #include "Acts/Utilities/HashedString.hpp" #include +#include namespace Acts::detail::Test { @@ -196,6 +198,9 @@ class MultiTrajectoryTestsCommon { alwaysPresent(ts); ts.allocateCalibrated(5); BOOST_CHECK(ts.hasCalibrated()); + BOOST_CHECK_EQUAL(ts.template calibrated<5>(), ActsVector<5>::Zero()); + BOOST_CHECK_EQUAL(ts.template calibratedCovariance<5>(), + ActsSquareMatrix<5>::Zero()); ts = t.getTrackState(t.addTrackState(PM::None)); BOOST_CHECK(!ts.hasPredicted()); @@ -242,6 +247,9 @@ class MultiTrajectoryTestsCommon { BOOST_CHECK(!ts.hasJacobian()); ts.allocateCalibrated(5); BOOST_CHECK(ts.hasCalibrated()); + BOOST_CHECK_EQUAL(ts.template calibrated<5>(), ActsVector<5>::Zero()); + BOOST_CHECK_EQUAL(ts.template calibratedCovariance<5>(), + ActsSquareMatrix<5>::Zero()); ts = t.getTrackState(t.addTrackState(PM::Jacobian)); BOOST_CHECK(!ts.hasPredicted()); @@ -300,6 +308,9 @@ class MultiTrajectoryTestsCommon { BOOST_CHECK(ts.hasSmoothed()); BOOST_CHECK(ts.hasCalibrated()); BOOST_CHECK(!ts.hasJacobian()); + BOOST_CHECK_EQUAL(ts.template calibrated<5>(), ActsVector<5>::Zero()); + BOOST_CHECK_EQUAL(ts.template calibratedCovariance<5>(), + ActsSquareMatrix<5>::Zero()); ts.addComponents(PM::Jacobian); BOOST_CHECK(ts.hasPredicted()); @@ -378,7 +389,13 @@ class MultiTrajectoryTestsCommon { { // reset measurements w/ full parameters auto [measPar, measCov] = generateBoundParametersCovariance(rng, {}); + // Explicitly unset to avoid error below + tsb.unset(TrackStatePropMask::Calibrated); tsb.allocateCalibrated(eBoundSize); + BOOST_CHECK_EQUAL(tsb.template calibrated(), + BoundVector::Zero()); + BOOST_CHECK_EQUAL(tsb.template calibratedCovariance(), + BoundMatrix::Zero()); tsb.template calibrated() = measPar; tsb.template calibratedCovariance() = measCov; BOOST_CHECK_EQUAL(tsa.template calibrated(), measPar); @@ -394,7 +411,15 @@ class MultiTrajectoryTestsCommon { std::size_t nMeasurements = tsb.effectiveCalibrated().rows(); auto effPar = measPar.head(nMeasurements); auto effCov = measCov.topLeftCorner(nMeasurements, nMeasurements); - tsb.allocateCalibrated(eBoundSize); + tsb.allocateCalibrated( + eBoundSize); // no allocation, but we expect it to be reset to zero + // with this overload + BOOST_CHECK_EQUAL(tsa.effectiveCalibrated(), BoundVector::Zero()); + BOOST_CHECK_EQUAL(tsa.effectiveCalibratedCovariance(), + BoundMatrix::Zero()); + BOOST_CHECK_EQUAL(tsa.effectiveCalibrated(), BoundVector::Zero()); + BOOST_CHECK_EQUAL(tsa.effectiveCalibratedCovariance(), + BoundMatrix::Zero()); tsb.effectiveCalibrated() = effPar; tsb.effectiveCalibratedCovariance() = effCov; BOOST_CHECK_EQUAL(tsa.effectiveCalibrated(), effPar); @@ -444,8 +469,10 @@ class MultiTrajectoryTestsCommon { BOOST_CHECK_EQUAL( ts.getUncalibratedSourceLink().template get().sourceId, pc.sourceLink.sourceId); - testSourceLinkCalibratorReturn( - gctx, cctx, SourceLink{ttsb.sourceLink}, ts); + // Explicitly unset to avoid error below + ts.unset(TrackStatePropMask::Calibrated); + testSourceLinkCalibrator(gctx, cctx, + SourceLink{ttsb.sourceLink}, ts); BOOST_CHECK_EQUAL( ts.getUncalibratedSourceLink().template get().sourceId, ttsb.sourceLink.sourceId); @@ -522,21 +549,6 @@ class MultiTrajectoryTestsCommon { BOOST_CHECK_EQUAL(ts.template calibratedCovariance(), expCov); }); } - - BOOST_CHECK(ts.hasProjector()); - ActsMatrix fullProj; - fullProj.setZero(); - { - Acts::GeometryContext gctx; - Acts::CalibrationContext cctx; - // create a temporary measurement to extract the projector matrix - testSourceLinkCalibratorReturn( - gctx, cctx, SourceLink{pc.sourceLink}, ts); - fullProj = ts.projector(); - } - BOOST_CHECK_EQUAL(ts.effectiveProjector(), - fullProj.topLeftCorner(nMeasurements, eBoundSize)); - BOOST_CHECK_EQUAL(ts.projector(), fullProj); } void testTrackStateProxyAllocations(std::default_random_engine& rng) { @@ -755,13 +767,16 @@ class MultiTrajectoryTestsCommon { }); BOOST_CHECK_NE(ts1.calibratedSize(), ts2.calibratedSize()); - BOOST_CHECK_NE(ts1.projector(), ts2.projector()); + BOOST_CHECK(ts1.projectorSubspaceIndices() != + ts2.projectorSubspaceIndices()); BOOST_CHECK_NE(ts1.jacobian(), ts2.jacobian()); BOOST_CHECK_NE(ts1.chi2(), ts2.chi2()); BOOST_CHECK_NE(ts1.pathLength(), ts2.pathLength()); BOOST_CHECK_NE(&ts1.referenceSurface(), &ts2.referenceSurface()); + // Explicitly unset to avoid error below + ts1.unset(TrackStatePropMask::Calibrated); ts1.copyFrom(ts2); BOOST_CHECK_EQUAL(ts1.predicted(), ts2.predicted()); @@ -784,7 +799,8 @@ class MultiTrajectoryTestsCommon { }); BOOST_CHECK_EQUAL(ts1.calibratedSize(), ts2.calibratedSize()); - BOOST_CHECK_EQUAL(ts1.projector(), ts2.projector()); + BOOST_CHECK(ts1.projectorSubspaceIndices() == + ts2.projectorSubspaceIndices()); BOOST_CHECK_EQUAL(ts1.jacobian(), ts2.jacobian()); BOOST_CHECK_EQUAL(ts1.chi2(), ts2.chi2()); @@ -795,6 +811,8 @@ class MultiTrajectoryTestsCommon { ts2 = mkts(PM::Predicted | PM::Jacobian | PM::Calibrated); ts2.copyFrom(ots2, PM::Predicted | PM::Jacobian | PM::Calibrated); // copy into empty ts, only copy some + // explicitly unset to avoid error below + ts1.unset(TrackStatePropMask::Calibrated); ts1.copyFrom(ots1); // reset to original // is different again BOOST_CHECK_NE(ts1.predicted(), ts2.predicted()); @@ -809,13 +827,16 @@ class MultiTrajectoryTestsCommon { }); BOOST_CHECK_NE(ts1.calibratedSize(), ts2.calibratedSize()); - BOOST_CHECK_NE(ts1.projector(), ts2.projector()); + BOOST_CHECK(ts1.projectorSubspaceIndices() != + ts2.projectorSubspaceIndices()); BOOST_CHECK_NE(ts1.jacobian(), ts2.jacobian()); BOOST_CHECK_NE(ts1.chi2(), ts2.chi2()); BOOST_CHECK_NE(ts1.pathLength(), ts2.pathLength()); BOOST_CHECK_NE(&ts1.referenceSurface(), &ts2.referenceSurface()); + // Explicitly unset to avoid error below + ts1.unset(TrackStatePropMask::Calibrated); ts1.copyFrom(ts2); // some components are same now @@ -831,7 +852,8 @@ class MultiTrajectoryTestsCommon { }); BOOST_CHECK_EQUAL(ts1.calibratedSize(), ts2.calibratedSize()); - BOOST_CHECK_EQUAL(ts1.projector(), ts2.projector()); + BOOST_CHECK(ts1.projectorSubspaceIndices() == + ts2.projectorSubspaceIndices()); BOOST_CHECK_EQUAL(ts1.jacobian(), ts2.jacobian()); BOOST_CHECK_EQUAL(ts1.chi2(), ts2.chi2()); // always copied @@ -1133,10 +1155,10 @@ class MultiTrajectoryTestsCommon { BOOST_CHECK_EQUAL(ts1.template component(col), value); }; - test("std::uint32_t", std::uint32_t{1}); - test("std::uint64_t", std::uint64_t{2}); - test("std::int32_t", std::int32_t{-3}); - test("std::int64_t", std::int64_t{-4}); + test("std_uint32_t", std::uint32_t{1}); + test("std_uint64_t", std::uint64_t{2}); + test("std_int32_t", std::int32_t{-3}); + test("std_int64_t", std::int64_t{-4}); test("float", float{8.9}); test("double", double{656.2}); @@ -1193,5 +1215,41 @@ class MultiTrajectoryTestsCommon { // runTest([](const std::string& c) { return c; }); // runTest([](std::string_view c) { return c; }); } + + void testMultiTrajectoryAllocateCalibratedInit( + std::default_random_engine& rng) { + trajectory_t traj = m_factory.create(); + auto ts = traj.makeTrackState(TrackStatePropMask::All); + + BOOST_CHECK_EQUAL(ts.calibratedSize(), MultiTrajectoryTraits::kInvalid); + + auto [par, cov] = generateBoundParametersCovariance(rng, {}); + + ts.template allocateCalibrated(par.head<3>(), cov.topLeftCorner<3, 3>()); + + BOOST_CHECK_EQUAL(ts.calibratedSize(), 3); + BOOST_CHECK_EQUAL(ts.template calibrated<3>(), par.head<3>()); + BOOST_CHECK_EQUAL(ts.template calibratedCovariance<3>(), + (cov.topLeftCorner<3, 3>())); + + auto [par2, cov2] = generateBoundParametersCovariance(rng, {}); + + ts.allocateCalibrated(3); + BOOST_CHECK_EQUAL(ts.template calibrated<3>(), ActsVector<3>::Zero()); + BOOST_CHECK_EQUAL(ts.template calibratedCovariance<3>(), + ActsSquareMatrix<3>::Zero()); + + ts.template allocateCalibrated(par2.head<3>(), cov2.topLeftCorner<3, 3>()); + BOOST_CHECK_EQUAL(ts.calibratedSize(), 3); + // The values are re-assigned + BOOST_CHECK_EQUAL(ts.template calibrated<3>(), par2.head<3>()); + BOOST_CHECK_EQUAL(ts.template calibratedCovariance<3>(), + (cov2.topLeftCorner<3, 3>())); + + // Re-allocation with a different measurement dimension is an error + BOOST_CHECK_THROW(ts.template allocateCalibrated( + par2.head<4>(), cov2.topLeftCorner<4, 4>()), + std::invalid_argument); + } }; } // namespace Acts::detail::Test diff --git a/Core/include/Acts/EventData/detail/PrintParameters.hpp b/Core/include/Acts/EventData/detail/PrintParameters.hpp index 38670c230e0..de4be653866 100644 --- a/Core/include/Acts/EventData/detail/PrintParameters.hpp +++ b/Core/include/Acts/EventData/detail/PrintParameters.hpp @@ -46,8 +46,8 @@ void printFreeParameters(std::ostream& os, const FreeVector& params, /// @param params Parameters vector data, must contain size elements /// @param cov Optional Covariance matrix data, must contain sizexsize elements void printMeasurement(std::ostream& os, BoundIndices size, - const std::uint8_t* indices, const ActsScalar* params, - const ActsScalar* cov); + const std::uint8_t* indices, const double* params, + const double* cov); /// Print free measurement content to the output stream. /// @@ -57,8 +57,8 @@ void printMeasurement(std::ostream& os, BoundIndices size, /// @param params Parameters vector data, must contain size elements /// @param cov Optional Covariance matrix data, must contain sizexsize elements void printMeasurement(std::ostream& os, FreeIndices size, - const std::uint8_t* indices, const ActsScalar* params, - const ActsScalar* cov); + const std::uint8_t* indices, const double* params, + const double* cov); } // namespace detail } // namespace Acts diff --git a/Core/include/Acts/EventData/detail/TestSourceLink.hpp b/Core/include/Acts/EventData/detail/TestSourceLink.hpp index affec84aafa..9a6350e7df4 100644 --- a/Core/include/Acts/EventData/detail/TestSourceLink.hpp +++ b/Core/include/Acts/EventData/detail/TestSourceLink.hpp @@ -18,9 +18,7 @@ #include "Acts/Geometry/TrackingGeometry.hpp" #include "Acts/Utilities/CalibrationContext.hpp" -#include #include -#include #include #include #include @@ -47,7 +45,7 @@ struct TestSourceLink final { Acts::ActsSquareMatrix<2> covariance; /// Construct a source link for a 1d measurement. - TestSourceLink(BoundIndices idx, ActsScalar val, ActsScalar var, + TestSourceLink(BoundIndices idx, double val, double var, GeometryIdentifier gid = GeometryIdentifier(), std::size_t sid = 0u) : m_geometryId(gid), @@ -126,7 +124,7 @@ inline std::ostream& operator<<(std::ostream& os, /// @param gctx Unused /// @param trackState TrackState to calibrated template -void testSourceLinkCalibratorReturn( +void testSourceLinkCalibrator( const GeometryContext& /*gctx*/, const CalibrationContext& /*cctx*/, const SourceLink& sourceLink, typename trajectory_t::TrackStateProxy trackState) { @@ -139,30 +137,18 @@ void testSourceLinkCalibratorReturn( trackState.allocateCalibrated(2); trackState.template calibrated<2>() = sl.parameters; trackState.template calibratedCovariance<2>() = sl.covariance; - trackState.setSubspaceIndices(std::array{sl.indices[0], sl.indices[1]}); + trackState.setProjectorSubspaceIndices( + std::array{sl.indices[0], sl.indices[1]}); } else if (sl.indices[0] != Acts::eBoundSize) { trackState.allocateCalibrated(1); trackState.template calibrated<1>() = sl.parameters.head<1>(); trackState.template calibratedCovariance<1>() = sl.covariance.topLeftCorner<1, 1>(); - trackState.setSubspaceIndices(std::array{sl.indices[0]}); + trackState.setProjectorSubspaceIndices(std::array{sl.indices[0]}); } else { throw std::runtime_error( "Tried to extract measurement from invalid TestSourceLink"); } } -/// Extract the measurement from a TestSourceLink. -/// -/// @param gctx Unused -/// @param trackState TrackState to calibrated -template -void testSourceLinkCalibrator( - const GeometryContext& gctx, const CalibrationContext& cctx, - const SourceLink& sourceLink, - typename trajectory_t::TrackStateProxy trackState) { - testSourceLinkCalibratorReturn(gctx, cctx, sourceLink, - trackState); -} - } // namespace Acts::detail::Test diff --git a/Core/include/Acts/EventData/detail/TestTrackState.hpp b/Core/include/Acts/EventData/detail/TestTrackState.hpp index 514ae073c2f..26ef78d8084 100644 --- a/Core/include/Acts/EventData/detail/TestTrackState.hpp +++ b/Core/include/Acts/EventData/detail/TestTrackState.hpp @@ -46,7 +46,7 @@ struct TestTrackState { ParticleHypothesis::pion()), jacobian(BoundMatrix::Identity()), chi2(std::chi_squared_distribution(measdim)(rng)), - pathLength(std::uniform_real_distribution( + pathLength(std::uniform_real_distribution( 1 * Acts::UnitConstants::mm, 10 * Acts::UnitConstants::mm)(rng)) { // set a random geometry identifier to uniquely identify each surface auto geoId = @@ -55,10 +55,10 @@ struct TestTrackState { // create source link w/ inline 1d or 2d measurement data if (measdim == 1u) { - auto [par, cov] = generateParametersCovariance(rng); + auto [par, cov] = generateParametersCovariance(rng); sourceLink = TestSourceLink(eBoundLoc0, par[0], cov(0, 0), geoId); } else if (measdim == 2u) { - auto [par, cov] = generateParametersCovariance(rng); + auto [par, cov] = generateParametersCovariance(rng); sourceLink = TestSourceLink(eBoundLoc1, eBoundQOverP, par, cov, geoId); } else { throw std::runtime_error("invalid number of measurement dimensions"); @@ -85,7 +85,7 @@ struct TestTrackState { for (Eigen::Index c = 0; c < jacobian.cols(); ++c) { for (Eigen::Index r = 0; r < jacobian.rows(); ++r) { jacobian(c, r) += - std::uniform_real_distribution(-0.125, 0.125)(rng); + std::uniform_real_distribution(-0.125, 0.125)(rng); } } } 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/Geometry/ConeVolumeBounds.hpp b/Core/include/Acts/Geometry/ConeVolumeBounds.hpp index 23c8d33b26d..e3f0c36a25c 100644 --- a/Core/include/Acts/Geometry/ConeVolumeBounds.hpp +++ b/Core/include/Acts/Geometry/ConeVolumeBounds.hpp @@ -56,10 +56,9 @@ class ConeVolumeBounds : public VolumeBounds { /// @param halflengthZ The minimum z value of the inner and outer cones /// @param averagePhi The phi orientation of the sector /// @param halfPhiSector The opening angle phi sector - ConeVolumeBounds(ActsScalar innerAlpha, ActsScalar innerOffsetZ, - ActsScalar outerAlpha, ActsScalar outerOffsetZ, - ActsScalar halflengthZ, ActsScalar averagePhi, - ActsScalar halfPhiSector) noexcept(false); + ConeVolumeBounds(double innerAlpha, double innerOffsetZ, double outerAlpha, + double outerOffsetZ, double halflengthZ, double averagePhi, + double halfPhiSector) noexcept(false); /// Constructor - for general cylidner-cone setups /// @@ -72,14 +71,14 @@ class ConeVolumeBounds : public VolumeBounds { /// /// @note depending on cylinderR > coneR it is constructing a cone with /// cylindrical cutout or a cylinder with conical cutout - ConeVolumeBounds(ActsScalar cylinderR, ActsScalar alpha, ActsScalar offsetZ, - ActsScalar halflengthZ, ActsScalar averagePhi, - ActsScalar halfPhiSector) noexcept(false); + ConeVolumeBounds(double cylinderR, double alpha, double offsetZ, + double halflengthZ, double averagePhi, + double halfPhiSector) noexcept(false); /// Constructor - from a fixed size array /// /// @param values The bound values - ConeVolumeBounds(const std::array& values) noexcept(false) + ConeVolumeBounds(const std::array& values) noexcept(false) : m_values(values) { checkConsistency(); buildSurfaceBounds(); @@ -94,14 +93,14 @@ class ConeVolumeBounds : public VolumeBounds { /// Return the bound values as dynamically sized vector /// /// @return this returns a copy of the internal values - std::vector values() const final; + std::vector values() const final; /// This method checks if position in the 3D volume /// frame is inside the cylinder /// /// @param pos is the position in volume frame to be checked /// @param tol is the absolute tolerance to be applied - bool inside(const Vector3& pos, ActsScalar tol = 0.) const final; + bool inside(const Vector3& pos, double tol = 0.) const final; /// Oriented surfaces, i.e. the decomposed boundary surfaces and the /// according navigation direction into the volume given the normal @@ -127,25 +126,25 @@ class ConeVolumeBounds : public VolumeBounds { /// Access to the bound values /// @param bValue the class nested enum for the array access - ActsScalar get(BoundValues bValue) const { return m_values[bValue]; } + double get(BoundValues bValue) const { return m_values[bValue]; } // Return the derived innerRmin - ActsScalar innerRmin() const; + double innerRmin() const; // Return the derived innerRmin - ActsScalar innerRmax() const; + double innerRmax() const; // Return the derived inner tan(alpha) - ActsScalar innerTanAlpha() const; + double innerTanAlpha() const; // Return the derived outerRmin - ActsScalar outerRmin() const; + double outerRmin() const; // Return the derived outerRmax - ActsScalar outerRmax() const; + double outerRmax() const; // Return the derived outer tan(alpha) - ActsScalar outerTanAlpha() const; + double outerTanAlpha() const; /// Output Method for std::ostream /// @@ -161,7 +160,7 @@ class ConeVolumeBounds : public VolumeBounds { void buildSurfaceBounds(); /// The bound values - std::array m_values; + std::array m_values; std::shared_ptr m_innerCylinderBounds{nullptr}; std::shared_ptr m_innerConeBounds{nullptr}; std::shared_ptr m_outerConeBounds{nullptr}; @@ -171,12 +170,12 @@ class ConeVolumeBounds : public VolumeBounds { std::shared_ptr m_sectorBounds{nullptr}; /// Derived values - ActsScalar m_innerRmin = 0.; - ActsScalar m_innerRmax = 0.; - ActsScalar m_innerTanAlpha = 0.; - ActsScalar m_outerRmin = 0.; - ActsScalar m_outerRmax = 0.; - ActsScalar m_outerTanAlpha = 0.; + double m_innerRmin = 0.; + double m_innerRmax = 0.; + double m_innerTanAlpha = 0.; + double m_outerRmin = 0.; + double m_outerRmax = 0.; + double m_outerTanAlpha = 0.; }; } // namespace Acts diff --git a/Core/include/Acts/Geometry/CuboidVolumeBounds.hpp b/Core/include/Acts/Geometry/CuboidVolumeBounds.hpp index 8b8437a91a5..bc3c75ac70d 100644 --- a/Core/include/Acts/Geometry/CuboidVolumeBounds.hpp +++ b/Core/include/Acts/Geometry/CuboidVolumeBounds.hpp @@ -63,13 +63,12 @@ class CuboidVolumeBounds : public VolumeBounds { /// @param halex is the half length of the cube in x /// @param haley is the half length of the cube in y /// @param halez is the half length of the cube in z - CuboidVolumeBounds(ActsScalar halex, ActsScalar haley, - ActsScalar halez) noexcept(false); + CuboidVolumeBounds(double halex, double haley, double halez) noexcept(false); /// Constructor - from a fixed size array /// /// @param values iw the bound values - CuboidVolumeBounds(const std::array& values); + CuboidVolumeBounds(const std::array& values); /// Copy Constructor /// @@ -88,14 +87,14 @@ class CuboidVolumeBounds : public VolumeBounds { /// Return the bound values as dynamically sized vector /// /// @return this returns a copy of the internal values - std::vector values() const final; + std::vector values() const final; /// This method checks if position in the 3D volume /// frame is inside the cylinder /// /// @param pos is the position in volume frame to be checked /// @param tol is the absolute tolerance to be applied - bool inside(const Vector3& pos, ActsScalar tol = 0.) const override; + bool inside(const Vector3& pos, double tol = 0.) const override; /// Oriented surfaces, i.e. the decomposed boundary surfaces and the /// according navigation direction into the volume given the normal @@ -128,25 +127,25 @@ class CuboidVolumeBounds : public VolumeBounds { Acts::BinningValue::binZ}; }; - /// Binning borders in ActsScalar + /// Binning borders in double /// /// @param bValue is the binning schema used /// /// @return float offset to be used for the binning - ActsScalar binningBorder(BinningValue bValue) const final; + double binningBorder(BinningValue bValue) const final; /// Access to the bound values /// @param bValue the class nested enum for the array access - ActsScalar get(BoundValues bValue) const { return m_values[bValue]; } + double get(BoundValues bValue) const { return m_values[bValue]; } /// Set a bound value /// @param bValue the bound value identifier /// @param value the value to be set - void set(BoundValues bValue, ActsScalar value); + void set(BoundValues bValue, double value); /// Set a range of bound values /// @param keyValues the initializer list of key value pairs - void set(std::initializer_list> keyValues); + void set(std::initializer_list> keyValues); /// Output Method for std::ostream /// @@ -155,7 +154,7 @@ class CuboidVolumeBounds : public VolumeBounds { private: /// The bound values ordered in a fixed size array - std::array m_values; + std::array m_values; std::shared_ptr m_xyBounds{nullptr}; std::shared_ptr m_yzBounds{nullptr}; diff --git a/Core/include/Acts/Geometry/CuboidVolumeBuilder.hpp b/Core/include/Acts/Geometry/CuboidVolumeBuilder.hpp index 5912b21ed98..185d55f229d 100644 --- a/Core/include/Acts/Geometry/CuboidVolumeBuilder.hpp +++ b/Core/include/Acts/Geometry/CuboidVolumeBuilder.hpp @@ -74,11 +74,11 @@ class CuboidVolumeBuilder : public ITrackingVolumeBuilder { // Bins in Z direction std::size_t binsZ = 1; // Envelope in X - std::array envelopeX{0, 0}; + std::array envelopeX{0, 0}; // Envelope in Y - std::array envelopeY{0, 0}; + std::array envelopeY{0, 0}; // Envelope in Z - std::array envelopeZ{0, 0}; + std::array envelopeZ{0, 0}; // An optional rotation for this std::optional rotation{std::nullopt}; // Dimension for the binning diff --git a/Core/include/Acts/Geometry/CylinderVolumeBounds.hpp b/Core/include/Acts/Geometry/CylinderVolumeBounds.hpp index 7f368442f40..3e5d8862cd8 100644 --- a/Core/include/Acts/Geometry/CylinderVolumeBounds.hpp +++ b/Core/include/Acts/Geometry/CylinderVolumeBounds.hpp @@ -105,27 +105,26 @@ class CylinderVolumeBounds : public VolumeBounds { /// @param avgphi The average phi value /// @param bevelMinZ The bevel angle, in radians, for the negative side /// @param bevelMaxZ The bevel angle, in radians, for the positive side - CylinderVolumeBounds(ActsScalar rmin, ActsScalar rmax, ActsScalar halfz, - ActsScalar halfphi = std::numbers::pi_v, - ActsScalar avgphi = 0., ActsScalar bevelMinZ = 0., - ActsScalar bevelMaxZ = 0.); + CylinderVolumeBounds(double rmin, double rmax, double halfz, + double halfphi = std::numbers::pi, double avgphi = 0., + double bevelMinZ = 0., double bevelMaxZ = 0.); /// Constructor - from a fixed size array /// /// @param values The bound values - CylinderVolumeBounds(const std::array& values); + CylinderVolumeBounds(const std::array& values); /// Constructor - extruded from cylinder bounds and thickness /// /// @param cBounds the cylinder bounds /// @param thickness of the extrusion - CylinderVolumeBounds(const CylinderBounds& cBounds, ActsScalar thickness); + CylinderVolumeBounds(const CylinderBounds& cBounds, double thickness); /// Constructor - extruded from radial bounds and thickness /// /// @param rBounds the Radial bounds /// @param thickness - CylinderVolumeBounds(const RadialBounds& rBounds, ActsScalar thickness); + CylinderVolumeBounds(const RadialBounds& rBounds, double thickness); /// Copy Constructor /// @@ -142,14 +141,14 @@ class CylinderVolumeBounds : public VolumeBounds { /// Return the bound values as dynamically sized vector /// /// @return this returns a copy of the internal values - std::vector values() const final; + std::vector values() const final; /// This method checks if position in the 3D volume /// frame is inside the cylinder /// /// @param pos is a global position to be checked /// @param tol is the tolerance for the check - bool inside(const Vector3& pos, ActsScalar tol = 0.) const override; + bool inside(const Vector3& pos, double tol = 0.) const override; /// Oriented surfaces, i.e. the decomposed boundary surfaces and the /// according navigation direction into the volume given the normal @@ -187,10 +186,10 @@ class CylinderVolumeBounds : public VolumeBounds { /// @param bValue is the type used for the binning Vector3 binningOffset(BinningValue bValue) const override; - /// Binning borders in ActsScalar + /// Binning borders in double /// /// @param bValue is the type used for the binning - ActsScalar binningBorder(BinningValue bValue) const override; + double binningBorder(BinningValue bValue) const override; /// Output Method for std::ostream /// @param os is the output stream @@ -198,20 +197,20 @@ class CylinderVolumeBounds : public VolumeBounds { /// Access to the bound values /// @param bValue the class nested enum for the array access - ActsScalar get(BoundValues bValue) const { return m_values[bValue]; } + double get(BoundValues bValue) const { return m_values[bValue]; } /// Set a bound value /// @param bValue the bound value identifier /// @param value the value to be set - void set(BoundValues bValue, ActsScalar value); + void set(BoundValues bValue, double value); /// Set a range of bound values /// @param keyValues the initializer list of key value pairs - void set(std::initializer_list> keyValues); + void set(std::initializer_list> keyValues); private: - /// The internal version of the bounds can be float/ActsScalar - std::array m_values{}; + /// The internal version of the bounds can be float/double + std::array m_values{}; /// Bounds of the inner CylinderBounds std::shared_ptr m_innerCylinderBounds{nullptr}; diff --git a/Core/include/Acts/Geometry/CylinderVolumeBuilder.hpp b/Core/include/Acts/Geometry/CylinderVolumeBuilder.hpp index 1e09b95e114..4356e26f313 100644 --- a/Core/include/Acts/Geometry/CylinderVolumeBuilder.hpp +++ b/Core/include/Acts/Geometry/CylinderVolumeBuilder.hpp @@ -65,9 +65,9 @@ struct VolumeConfig { /// Adapt to the dimensions of another config in Z /// it will take the maximum/minimum values and just overwrite them /// - /// @param [in] lConfig is the config to which it should be adapded + /// @param [in] lConfig is the config to which it should be adapted void adaptZ(const VolumeConfig& lConfig) { - if (lConfig) { + if (lConfig.present) { zMin = std::min(zMin, lConfig.zMin); zMax = std::max(zMax, lConfig.zMax); } @@ -76,9 +76,9 @@ struct VolumeConfig { /// Adapt to the dimensions of another config in R /// it will take the maximum/minimum values and just overwrite them /// - /// @param [in] lConfig is the config to which it should be adapded + /// @param [in] lConfig is the config to which it should be adapted void adaptR(const VolumeConfig& lConfig) { - if (lConfig) { + if (lConfig.present) { rMin = std::min(rMin, lConfig.rMin); rMax = std::max(rMax, lConfig.rMax); } @@ -87,7 +87,7 @@ struct VolumeConfig { /// Adapt to the dimensions of another config /// it will take the maximum/minimum values and just overwrite them /// - /// @param [in] lConfig is the config to which it should be adapded + /// @param [in] lConfig is the config to which it should be adapted void adapt(const VolumeConfig& lConfig) { adaptZ(lConfig); adaptR(lConfig); @@ -184,9 +184,6 @@ struct VolumeConfig { sl << rMin << ", " << rMax << " / " << zMin << ", " << zMax; return sl.str(); } - - /// Conversion operator to bool - operator bool() const { return present; } }; /// @brief The WrappingSetup that is happening here @@ -222,39 +219,40 @@ struct WrappingConfig { containerVolumeConfig.present = true; std::string wConditionAddon = ""; // if we have more than one config present - if ((nVolumeConfig && cVolumeConfig) || (cVolumeConfig && pVolumeConfig) || - (nVolumeConfig && pVolumeConfig)) { + if ((nVolumeConfig.present && cVolumeConfig.present) || + (cVolumeConfig.present && pVolumeConfig.present) || + (nVolumeConfig.present && pVolumeConfig.present)) { wCondition = Wrapping; wConditionScreen = "grouped to "; } // adapt the new volume config to the existing configs - if (nVolumeConfig) { + if (nVolumeConfig.present) { containerVolumeConfig.adapt(nVolumeConfig); wConditionScreen += "[n]"; } - if (cVolumeConfig) { + if (cVolumeConfig.present) { containerVolumeConfig.adapt(cVolumeConfig); wConditionScreen += "[c]"; } - if (pVolumeConfig) { + if (pVolumeConfig.present) { containerVolumeConfig.adapt(pVolumeConfig); wConditionScreen += "[p]"; } // adapt the external one - if (externalVolumeConfig) { + if (externalVolumeConfig.present) { containerVolumeConfig.adapt(externalVolumeConfig); } // attach the volume configs - if (nVolumeConfig && cVolumeConfig) { + if (nVolumeConfig.present && cVolumeConfig.present) { nVolumeConfig.midPointAttachZ(cVolumeConfig); } - if (cVolumeConfig && pVolumeConfig) { + if (cVolumeConfig.present && pVolumeConfig.present) { cVolumeConfig.midPointAttachZ(pVolumeConfig); } // adapt r afterwards // - easy if no existing volume // - possible if no central volume - if (!existingVolumeConfig || !cVolumeConfig) { + if (!existingVolumeConfig.present || !cVolumeConfig.present) { nVolumeConfig.adaptR(containerVolumeConfig); cVolumeConfig.adaptR(containerVolumeConfig); pVolumeConfig.adaptR(containerVolumeConfig); @@ -265,17 +263,19 @@ struct WrappingConfig { void wrapInsertAttach() { // action is only needed if an existing volume // is present - if (existingVolumeConfig) { + if (existingVolumeConfig.present) { // 0 - simple attachment case - if (!cVolumeConfig) { + if (!cVolumeConfig.present) { // check if it can be easily attached - if (nVolumeConfig && nVolumeConfig.zMax < existingVolumeConfig.zMin) { + if (nVolumeConfig.present && + nVolumeConfig.zMax < existingVolumeConfig.zMin) { nVolumeConfig.attachZ(existingVolumeConfig); // will attach the new volume(s) wCondition = Attaching; wConditionScreen = "[n attached]"; } - if (pVolumeConfig && pVolumeConfig.zMin > existingVolumeConfig.zMax) { + if (pVolumeConfig.present && + pVolumeConfig.zMin > existingVolumeConfig.zMax) { pVolumeConfig.attachZ(existingVolumeConfig); // will attach the new volume(s) wCondition = Attaching; @@ -385,9 +385,9 @@ struct WrappingConfig { fGapVolumeConfig.zMax = existingVolumeConfig.zMin; } else { // adapt lower z boundary - if (nVolumeConfig) { + if (nVolumeConfig.present) { nVolumeConfig.zMin = existingVolumeConfig.zMin; - } else if (cVolumeConfig) { + } else if (cVolumeConfig.present) { cVolumeConfig.zMin = existingVolumeConfig.zMin; } } @@ -399,9 +399,9 @@ struct WrappingConfig { sGapVolumeConfig.zMax = referenceVolume.zMax; } else { // adapt higher z boundary - if (pVolumeConfig) { + if (pVolumeConfig.present) { pVolumeConfig.zMax = existingVolumeConfig.zMax; - } else if (cVolumeConfig) { + } else if (cVolumeConfig.present) { cVolumeConfig.zMax = existingVolumeConfig.zMax; } } @@ -414,31 +414,31 @@ struct WrappingConfig { std::string toString() const { // for screen output std::stringstream sl; - if (containerVolumeConfig) { + if (containerVolumeConfig.present) { sl << "New container built with configuration: " << containerVolumeConfig.toString() << '\n'; } // go through the new ones first - if (nVolumeConfig) { + if (nVolumeConfig.present) { sl << " - n: Negative Endcap, current configuration: " << nVolumeConfig.toString() << '\n'; } - if (cVolumeConfig) { + if (cVolumeConfig.present) { sl << " - c: Barrel, current configuration: " << cVolumeConfig.toString() << '\n'; } - if (pVolumeConfig) { + if (pVolumeConfig.present) { sl << " - p: Negative Endcap, current configuration: " << pVolumeConfig.toString() << '\n'; } - if (existingVolumeConfig) { + if (existingVolumeConfig.present) { sl << "Existing volume with configuration: " << existingVolumeConfig.toString() << '\n'; - if (fGapVolumeConfig) { + if (fGapVolumeConfig.present) { sl << " - g1: First gap volume, configuration : " << fGapVolumeConfig.toString() << '\n'; } - if (sGapVolumeConfig) { + if (sGapVolumeConfig.present) { sl << " - g2: Second gap volume, configuration : " << sGapVolumeConfig.toString() << '\n'; } @@ -452,7 +452,7 @@ struct WrappingConfig { /// @class CylinderVolumeBuilder /// -/// A volume builder to be used for building a concentrical cylindrical volumes +/// A volume builder to be used for building concentric cylinder volumes /// - a) configured volume /// - b) wrapping around a cylindrical/disk layer config /// diff --git a/Core/include/Acts/Geometry/CylinderVolumeStack.hpp b/Core/include/Acts/Geometry/CylinderVolumeStack.hpp index 3fcb8f1039b..06e1e75dd58 100644 --- a/Core/include/Acts/Geometry/CylinderVolumeStack.hpp +++ b/Core/include/Acts/Geometry/CylinderVolumeStack.hpp @@ -149,7 +149,7 @@ class CylinderVolumeStack : public Volume { /// @param volumes is the vector of volumes /// @param logger is the logger /// @return tuple of the minimum and maximum radii - std::pair synchronizeRBounds( + std::pair synchronizeRBounds( std::vector& volumes, const Logger& logger); /// Helper function that checks overlaps and attaches in r direction @@ -165,7 +165,7 @@ class CylinderVolumeStack : public Volume { /// @param volumes is the vector of volumes /// @param logger is the logger /// @return tuple of the minimum and maximum z extent - std::pair synchronizeZBounds( + std::pair synchronizeZBounds( std::vector& volumes, const Logger& logger); /// Helper functions that checks if the cylinder volume bounds diff --git a/Core/include/Acts/Geometry/Extent.hpp b/Core/include/Acts/Geometry/Extent.hpp index 8728728996b..ca4d439e9ba 100644 --- a/Core/include/Acts/Geometry/Extent.hpp +++ b/Core/include/Acts/Geometry/Extent.hpp @@ -24,7 +24,7 @@ namespace Acts { -using Envelope = std::array; +using Envelope = std::array; constexpr Envelope zeroEnvelope = {0, 0}; @@ -182,19 +182,19 @@ class Extent { /// @param bValue the binning identification /// @param min the minimum parameter /// @param max the maximum parameter - void set(BinningValue bValue, ActsScalar min, ActsScalar max); + void set(BinningValue bValue, double min, double max); /// Set a min value for a dedicated binning value /// /// @param bValue the binning identification /// @param min the minimum parameter - void setMin(BinningValue bValue, ActsScalar min); + void setMin(BinningValue bValue, double min); /// Set a max value for a dedicated binning value /// /// @param bValue the binning identification /// @param max the maximum parameter - void setMax(BinningValue bValue, ActsScalar max); + void setMax(BinningValue bValue, double max); /// (re-)Set the envelope /// @@ -213,10 +213,10 @@ class Extent { /// @param bValue is the binning value to be returned /// /// @return a one dimensional arrange - Range1D range(BinningValue bValue) const; + Range1D range(BinningValue bValue) const; /// Return the N-dimension range - const RangeXD& range() const; + const RangeXD& range() const; /// Return an D-dimensional sub range according to the /// the given binvalues @@ -224,9 +224,9 @@ class Extent { /// @param binValues the binning values /// @return the sub range template - RangeXD range( + RangeXD range( const std::array& binValues) const { - RangeXD rRange; + RangeXD rRange; for (auto [i, v] : enumerate(binValues)) { rRange[i] = range(v); } @@ -242,27 +242,27 @@ class Extent { /// Return the histogram store /// /// The histogram store can be used for automated binning detection - const std::array, numBinningValues()>& - valueHistograms() const; + const std::array, numBinningValues()>& valueHistograms() + const; /// Access the minimum parameter /// /// @param bValue the binning identification - ActsScalar min(BinningValue bValue) const { + double min(BinningValue bValue) const { return m_range[toUnderlying(bValue)].min(); } /// Access the maximum parameter /// /// @param bValue the binning identification - ActsScalar max(BinningValue bValue) const { + double max(BinningValue bValue) const { return m_range[toUnderlying(bValue)].max(); } /// Access the midpoint /// /// @param bValue the binning identification - ActsScalar medium(BinningValue bValue) const { + double medium(BinningValue bValue) const { return 0.5 * (m_range[toUnderlying(bValue)].min() + m_range[toUnderlying(bValue)].max()); } @@ -270,7 +270,7 @@ class Extent { /// Access the parameter interval (i.e. the range span) /// /// @param bValue the binning identification - ActsScalar interval(BinningValue bValue) const { + double interval(BinningValue bValue) const { return m_range[toUnderlying(bValue)].size(); } @@ -318,18 +318,18 @@ class Extent { /// A bitset that remembers the constraint values std::bitset m_constrains{0}; /// The actual range store - RangeXD m_range; + RangeXD m_range; /// A potential envelope ExtentEnvelope m_envelope = ExtentEnvelope::Zero(); /// (Optional) Value histograms for bin detection - std::array, numBinningValues()> m_valueHistograms; + std::array, numBinningValues()> m_valueHistograms; }; -inline Range1D Acts::Extent::range(BinningValue bValue) const { +inline Range1D Acts::Extent::range(BinningValue bValue) const { return m_range[toUnderlying(bValue)]; } -inline const RangeXD& Extent::range() const { +inline const RangeXD& Extent::range() const { return m_range; } @@ -341,7 +341,7 @@ inline const ExtentEnvelope& Extent::envelope() const { return m_envelope; } -inline const std::array, numBinningValues()>& +inline const std::array, numBinningValues()>& Extent::valueHistograms() const { return m_valueHistograms; } diff --git a/Core/include/Acts/Geometry/GridPortalLink.hpp b/Core/include/Acts/Geometry/GridPortalLink.hpp index 411e6bb9962..8bf1d06ee08 100644 --- a/Core/include/Acts/Geometry/GridPortalLink.hpp +++ b/Core/include/Acts/Geometry/GridPortalLink.hpp @@ -396,7 +396,7 @@ class GridPortalLink : public PortalLinkBase { /// @tparam Axes The axis types of the grid template requires(sizeof...(Axes) <= 2) -class GridPortalLinkT final : public GridPortalLink { +class GridPortalLinkT : public GridPortalLink { public: /// The internal grid type using GridType = Grid; diff --git a/Core/include/Acts/Geometry/KDTreeTrackingGeometryBuilder.hpp b/Core/include/Acts/Geometry/KDTreeTrackingGeometryBuilder.hpp index 25fc8ebf30b..4a7a01e214d 100644 --- a/Core/include/Acts/Geometry/KDTreeTrackingGeometryBuilder.hpp +++ b/Core/include/Acts/Geometry/KDTreeTrackingGeometryBuilder.hpp @@ -58,7 +58,7 @@ class KDTreeTrackingGeometryBuilder : public ITrackingGeometryBuilder { }; using SurfaceKDT = - KDTree<2u, std::shared_ptr, ActsScalar, std::array, 100>; + KDTree<2u, std::shared_ptr, double, std::array, 100>; /// Constructor /// diff --git a/Core/include/Acts/Geometry/SurfaceArrayCreator.hpp b/Core/include/Acts/Geometry/SurfaceArrayCreator.hpp index 584e8ee6992..9906fda7939 100644 --- a/Core/include/Acts/Geometry/SurfaceArrayCreator.hpp +++ b/Core/include/Acts/Geometry/SurfaceArrayCreator.hpp @@ -381,8 +381,8 @@ class SurfaceArrayCreator { Axis axisB(pAxisB.min, pAxisB.max, pAxisB.nBins); using SGL = SurfaceArray::SurfaceGridLookup; - ptr = std::unique_ptr(static_cast( - new SGL(globalToLocal, localToGlobal, std::make_tuple(axisA, axisB), {pAxisA.bValue, pAxisB.bValue}))); + ptr = std::make_unique( + globalToLocal, localToGlobal, std::pair{axisA, axisB}, std::vector{pAxisA.bValue, pAxisB.bValue}); } else if (pAxisA.bType == equidistant && pAxisB.bType == arbitrary) { @@ -390,8 +390,8 @@ class SurfaceArrayCreator { Axis axisB(pAxisB.binEdges); using SGL = SurfaceArray::SurfaceGridLookup; - ptr = std::unique_ptr(static_cast( - new SGL(globalToLocal, localToGlobal, std::make_tuple(axisA, axisB), {pAxisA.bValue, pAxisB.bValue}))); + ptr = std::make_unique( + globalToLocal, localToGlobal, std::pair{axisA, axisB}, std::vector{pAxisA.bValue, pAxisB.bValue}); } else if (pAxisA.bType == arbitrary && pAxisB.bType == equidistant) { @@ -399,8 +399,8 @@ class SurfaceArrayCreator { Axis axisB(pAxisB.min, pAxisB.max, pAxisB.nBins); using SGL = SurfaceArray::SurfaceGridLookup; - ptr = std::unique_ptr(static_cast( - new SGL(globalToLocal, localToGlobal, std::make_tuple(axisA, axisB), {pAxisA.bValue, pAxisB.bValue}))); + ptr = std::make_unique( + globalToLocal, localToGlobal, std::pair{axisA, axisB}, std::vector{pAxisA.bValue, pAxisB.bValue}); } else /*if (pAxisA.bType == arbitrary && pAxisB.bType == arbitrary)*/ { @@ -408,8 +408,8 @@ class SurfaceArrayCreator { Axis axisB(pAxisB.binEdges); using SGL = SurfaceArray::SurfaceGridLookup; - ptr = std::unique_ptr(static_cast( - new SGL(globalToLocal, localToGlobal, std::make_tuple(axisA, axisB), {pAxisA.bValue, pAxisB.bValue}))); + ptr = std::make_unique( + globalToLocal, localToGlobal, std::pair{axisA, axisB}, std::vector{pAxisA.bValue, pAxisB.bValue}); } // clang-format on diff --git a/Core/include/Acts/Geometry/TrapezoidVolumeBounds.hpp b/Core/include/Acts/Geometry/TrapezoidVolumeBounds.hpp index c34234287c8..9ce660e5856 100644 --- a/Core/include/Acts/Geometry/TrapezoidVolumeBounds.hpp +++ b/Core/include/Acts/Geometry/TrapezoidVolumeBounds.hpp @@ -68,8 +68,8 @@ class TrapezoidVolumeBounds : public VolumeBounds { /// @param maxhalex is the half length in x at maximal y /// @param haley is the half length in y /// @param halez is the half length in z - TrapezoidVolumeBounds(ActsScalar minhalex, ActsScalar maxhalex, - ActsScalar haley, ActsScalar halez) noexcept(false); + TrapezoidVolumeBounds(double minhalex, double maxhalex, double haley, + double halez) noexcept(false); /// Constructor - the trapezoid boundaries (arbitrary trapezoid) /// @@ -78,14 +78,13 @@ class TrapezoidVolumeBounds : public VolumeBounds { /// @param halez is the half length in z /// @param alpha is the opening angle at -x,-y /// @param beta is the opening angle at +x,-y - TrapezoidVolumeBounds(ActsScalar minhalex, ActsScalar haley, ActsScalar halez, - ActsScalar alpha, ActsScalar beta) noexcept(false); + TrapezoidVolumeBounds(double minhalex, double haley, double halez, + double alpha, double beta) noexcept(false); /// Constructor - from a fixed size array /// /// @param values The bound values - TrapezoidVolumeBounds(const std::array& values) noexcept( - false) + TrapezoidVolumeBounds(const std::array& values) noexcept(false) : m_values(values) { checkConsistency(); buildSurfaceBounds(); @@ -103,7 +102,7 @@ class TrapezoidVolumeBounds : public VolumeBounds { /// Return the bound values as dynamically sized vector /// /// @return this returns a copy of the internal values - std::vector values() const final; + std::vector values() const final; /// This method checks if position in the 3D volume frame /// is inside the cylinder @@ -112,7 +111,7 @@ class TrapezoidVolumeBounds : public VolumeBounds { /// @param tol is the tolerance applied /// /// @return boolean indicator if position is inside - bool inside(const Vector3& pos, ActsScalar tol = 0.) const override; + bool inside(const Vector3& pos, double tol = 0.) const override; /// Oriented surfaces, i.e. the decomposed boundary surfaces and the /// according navigation direction into the volume given the normal @@ -142,11 +141,11 @@ class TrapezoidVolumeBounds : public VolumeBounds { /// Access to the bound values /// @param bValue the class nested enum for the array access - ActsScalar get(BoundValues bValue) const { return m_values[bValue]; } + double get(BoundValues bValue) const { return m_values[bValue]; } private: - /// The internal version of the bounds can be float/ActsScalar - std::array m_values{}; + /// The internal version of the bounds can be float/double + std::array m_values{}; /// The face PlaneSurface parallel to local xy plane std::shared_ptr m_faceXYTrapezoidBounds{nullptr}; /// Thhe face PlaneSurface attached to alpha (negative local x) diff --git a/Core/include/Acts/Geometry/Volume.hpp b/Core/include/Acts/Geometry/Volume.hpp index da8932b1eab..92085819676 100644 --- a/Core/include/Acts/Geometry/Volume.hpp +++ b/Core/include/Acts/Geometry/Volume.hpp @@ -32,7 +32,7 @@ class VolumeBounds; /// information. class Volume : public GeometryObject { public: - using BoundingBox = AxisAlignedBoundingBox; + using BoundingBox = AxisAlignedBoundingBox; /// Explicit constructor with shared arguments /// @@ -106,7 +106,7 @@ class Volume : public GeometryObject { /// @param tol is the tolerance parameter /// /// @return boolean indicator if the position is inside - bool inside(const Vector3& gpos, ActsScalar tol = 0.) const; + bool inside(const Vector3& gpos, double tol = 0.) const; /// The binning position method /// - as default the center is given, but may be overloaded diff --git a/Core/include/Acts/Material/BinnedSurfaceMaterial.hpp b/Core/include/Acts/Material/BinnedSurfaceMaterial.hpp index 97d3347c9e1..d5534803d08 100644 --- a/Core/include/Acts/Material/BinnedSurfaceMaterial.hpp +++ b/Core/include/Acts/Material/BinnedSurfaceMaterial.hpp @@ -13,9 +13,7 @@ #include "Acts/Material/MaterialSlab.hpp" #include "Acts/Utilities/BinUtility.hpp" -#include #include -#include namespace Acts { @@ -83,10 +81,10 @@ class BinnedSurfaceMaterial : public ISurfaceMaterial { /// Destructor ~BinnedSurfaceMaterial() override = default; - /// Scale operator + /// Scale operation /// - /// @param scale is the scale factor for the full material - BinnedSurfaceMaterial& operator*=(double scale) final; + /// @param factor is the scale factor for the full material + BinnedSurfaceMaterial& scale(double factor) final; /// Return the BinUtility const BinUtility& binUtility() const; diff --git a/Core/include/Acts/Material/GridSurfaceMaterial.hpp b/Core/include/Acts/Material/GridSurfaceMaterial.hpp index 6c2d6045ca2..d27912c85f3 100644 --- a/Core/include/Acts/Material/GridSurfaceMaterial.hpp +++ b/Core/include/Acts/Material/GridSurfaceMaterial.hpp @@ -11,10 +11,8 @@ #include "Acts/Definitions/Algebra.hpp" #include "Acts/Material/ISurfaceMaterial.hpp" #include "Acts/Material/MaterialSlab.hpp" -#include "Acts/Utilities/BinningType.hpp" #include "Acts/Utilities/Delegate.hpp" #include "Acts/Utilities/GridAccessHelpers.hpp" -#include "Acts/Utilities/VectorHelpers.hpp" #include #include @@ -44,7 +42,7 @@ struct GridMaterialAccessor { /// /// @note this is not particularly fast template - void scale(grid_type& grid, ActsScalar scale) { + void scale(grid_type& grid, double scale) { // Loop through the grid bins, get the indices and scale the material for (std::size_t ib = 0; ib < grid.size(); ++ib) { grid.at(ib).scaleThickness(scale); @@ -74,7 +72,7 @@ struct IndexedMaterialAccessor { /// /// @param scale the amount of the scaling template - void scale(grid_type& /*grid*/, ActsScalar scale) { + void scale(grid_type& /*grid*/, double scale) { for (auto& m : material) { m.scaleThickness(scale); } @@ -118,7 +116,7 @@ struct GloballyIndexedMaterialAccessor { /// outcome is unpredictable. /// template - void scale(grid_type& grid, ActsScalar scale) { + void scale(grid_type& grid, double scale) { if (sharedEntries) { throw std::invalid_argument( "GloballyIndexedMaterialAccessor: shared entry scaling is not " @@ -197,9 +195,9 @@ class GridSurfaceMaterialT : public ISurfaceMaterial { /// Scale operator /// - /// @param scale is the scale factor applied - ISurfaceMaterial& operator*=(ActsScalar scale) final { - m_materialAccessor.scale(m_grid, scale); + /// @param factor is the scale factor applied + ISurfaceMaterial& scale(double factor) final { + m_materialAccessor.scale(m_grid, factor); return (*this); } diff --git a/Core/include/Acts/Material/HomogeneousSurfaceMaterial.hpp b/Core/include/Acts/Material/HomogeneousSurfaceMaterial.hpp index 1ea14e632ac..37cad2a18d6 100644 --- a/Core/include/Acts/Material/HomogeneousSurfaceMaterial.hpp +++ b/Core/include/Acts/Material/HomogeneousSurfaceMaterial.hpp @@ -12,7 +12,6 @@ #include "Acts/Material/ISurfaceMaterial.hpp" #include "Acts/Material/MaterialSlab.hpp" -#include #include namespace Acts { @@ -62,13 +61,8 @@ class HomogeneousSurfaceMaterial : public ISurfaceMaterial { /// Scale operator /// - it is effectively a thickness scaling /// - /// @param scale is the scale factor - HomogeneousSurfaceMaterial& operator*=(double scale) final; - - /// Equality operator - /// - /// @param hsm is the source material - bool operator==(const HomogeneousSurfaceMaterial& hsm) const; + /// @param factor is the scale factor + HomogeneousSurfaceMaterial& scale(double factor) final; /// @copydoc ISurfaceMaterial::materialSlab(const Vector2&) const /// @@ -94,22 +88,21 @@ class HomogeneousSurfaceMaterial : public ISurfaceMaterial { private: /// The five different MaterialSlab - MaterialSlab m_fullMaterial = MaterialSlab(); -}; - -inline const MaterialSlab& HomogeneousSurfaceMaterial::materialSlab( - const Vector2& /*lp*/) const { - return (m_fullMaterial); -} + MaterialSlab m_fullMaterial; -inline const MaterialSlab& HomogeneousSurfaceMaterial::materialSlab( - const Vector3& /*gp*/) const { - return (m_fullMaterial); -} - -inline bool HomogeneousSurfaceMaterial::operator==( - const HomogeneousSurfaceMaterial& hsm) const { - return (m_fullMaterial == hsm.m_fullMaterial); -} + /// @brief Check if two materials are exactly equal. + /// + /// This is a strict equality check, i.e. the materials must have identical + /// properties. + /// + /// @param lhs is the left hand side material + /// @param rhs is the right hand side material + /// + /// @return true if the materials are equal + friend constexpr bool operator==(const HomogeneousSurfaceMaterial& lhs, + const HomogeneousSurfaceMaterial& rhs) { + return lhs.m_fullMaterial == rhs.m_fullMaterial; + } +}; } // namespace Acts diff --git a/Core/include/Acts/Material/HomogeneousVolumeMaterial.hpp b/Core/include/Acts/Material/HomogeneousVolumeMaterial.hpp index 91005dcae55..2034387e764 100644 --- a/Core/include/Acts/Material/HomogeneousVolumeMaterial.hpp +++ b/Core/include/Acts/Material/HomogeneousVolumeMaterial.hpp @@ -46,11 +46,6 @@ class HomogeneousVolumeMaterial : public IVolumeMaterial { HomogeneousVolumeMaterial& operator=(const HomogeneousVolumeMaterial& hvm) = default; - /// Equality operator - /// - /// @param hvm is the source material - bool operator==(const HomogeneousVolumeMaterial& hvm) const; - /// Access to actual material /// /// @param position is the request position for the material call @@ -64,17 +59,21 @@ class HomogeneousVolumeMaterial : public IVolumeMaterial { std::ostream& toStream(std::ostream& sl) const final; private: - Material m_material = Material(); -}; - -inline const Material HomogeneousVolumeMaterial::material( - const Vector3& /*position*/) const { - return (m_material); -} + Material m_material; -inline bool HomogeneousVolumeMaterial::operator==( - const HomogeneousVolumeMaterial& hvm) const { - return (m_material == hvm.m_material); -} + /// @brief Check if two materials are exactly equal. + /// + /// This is a strict equality check, i.e. the materials must have identical + /// properties. + /// + /// @param lhs is the left hand side material + /// @param rhs is the right hand side material + /// + /// @return true if the materials are equal + friend constexpr bool operator==(const HomogeneousVolumeMaterial& lhs, + const HomogeneousVolumeMaterial& rhs) { + return lhs.m_material == rhs.m_material; + } +}; } // namespace Acts diff --git a/Core/include/Acts/Material/ISurfaceMaterial.hpp b/Core/include/Acts/Material/ISurfaceMaterial.hpp index a379e18e715..cad6832441a 100644 --- a/Core/include/Acts/Material/ISurfaceMaterial.hpp +++ b/Core/include/Acts/Material/ISurfaceMaterial.hpp @@ -11,12 +11,9 @@ #include "Acts/Definitions/Algebra.hpp" #include "Acts/Definitions/Common.hpp" #include "Acts/Definitions/Direction.hpp" -#include "Acts/Geometry/GeometryIdentifier.hpp" #include "Acts/Material/MaterialSlab.hpp" -#include #include -#include namespace Acts { @@ -50,10 +47,10 @@ class ISurfaceMaterial { /// Destructor virtual ~ISurfaceMaterial() = default; - /// Scale operator + /// Scale material /// - /// @param scale is the scale factor applied - virtual ISurfaceMaterial& operator*=(double scale) = 0; + /// @param factor is the scale factor applied + virtual ISurfaceMaterial& scale(double factor) = 0; /// Return method for full material description of the Surface /// - from local coordinate on the surface @@ -128,9 +125,11 @@ class ISurfaceMaterial { } protected: - double m_splitFactor{1.}; //!< the split factor in favour of oppositePre - MappingType m_mappingType{ - Acts::MappingType::Default}; //!< Use the default mapping type by default + /// the split factor in favour of oppositePre + double m_splitFactor{1.}; + + /// Use the default mapping type by default + MappingType m_mappingType{Acts::MappingType::Default}; }; inline double ISurfaceMaterial::factor(Direction pDir, diff --git a/Core/include/Acts/Material/Material.hpp b/Core/include/Acts/Material/Material.hpp index ae42e08cf68..1caf59e97ec 100644 --- a/Core/include/Acts/Material/Material.hpp +++ b/Core/include/Acts/Material/Material.hpp @@ -8,11 +8,10 @@ #pragma once -#include "Acts/Definitions/Algebra.hpp" - #include #include -#include + +#include namespace Acts { @@ -112,6 +111,15 @@ class Material { float m_z = 0.0f; float m_molarRho = 0.0f; + /// @brief Check if two materials are exactly equal. + /// + /// This is a strict equality check, i.e. the materials must have identical + /// properties. + /// + /// @param lhs is the left hand side material + /// @param rhs is the right hand side material + /// + /// @return true if the materials are equal friend constexpr bool operator==(const Material& lhs, const Material& rhs) { return (lhs.m_x0 == rhs.m_x0) && (lhs.m_l0 == rhs.m_l0) && (lhs.m_ar == rhs.m_ar) && (lhs.m_z == rhs.m_z) && diff --git a/Core/include/Acts/Material/MaterialSlab.hpp b/Core/include/Acts/Material/MaterialSlab.hpp index 71c56c1a154..63fd7378e8b 100644 --- a/Core/include/Acts/Material/MaterialSlab.hpp +++ b/Core/include/Acts/Material/MaterialSlab.hpp @@ -79,6 +79,15 @@ class MaterialSlab { float m_thicknessInX0 = 0.0f; float m_thicknessInL0 = 0.0f; + /// @brief Check if two materials are exactly equal. + /// + /// This is a strict equality check, i.e. the materials must have identical + /// properties. + /// + /// @param lhs is the left hand side material + /// @param rhs is the right hand side material + /// + /// @return true if the materials are equal friend constexpr bool operator==(const MaterialSlab& lhs, const MaterialSlab& rhs) { // t/X0 and t/L0 are dependent variables and need not be checked diff --git a/Core/include/Acts/Material/ProtoSurfaceMaterial.hpp b/Core/include/Acts/Material/ProtoSurfaceMaterial.hpp index 58dee9d01c7..8b6dfed3287 100644 --- a/Core/include/Acts/Material/ProtoSurfaceMaterial.hpp +++ b/Core/include/Acts/Material/ProtoSurfaceMaterial.hpp @@ -14,7 +14,6 @@ #include "Acts/Material/MaterialSlab.hpp" #include "Acts/Utilities/BinUtility.hpp" -#include #include namespace Acts { @@ -67,9 +66,9 @@ class ProtoSurfaceMaterialT : public ISurfaceMaterial { ProtoSurfaceMaterialT& operator=( ProtoSurfaceMaterialT&& smproxy) = default; - /// Scale operator - dummy implementation + /// Scale operation - dummy implementation /// - ProtoSurfaceMaterialT& operator*=(double /*scale*/) final { + ProtoSurfaceMaterialT& scale(double /*factor*/) final { return (*this); } diff --git a/Core/include/Acts/Navigation/DetectorNavigator.hpp b/Core/include/Acts/Navigation/DetectorNavigator.hpp index 61d8525106c..3bc324e187f 100644 --- a/Core/include/Acts/Navigation/DetectorNavigator.hpp +++ b/Core/include/Acts/Navigation/DetectorNavigator.hpp @@ -17,6 +17,7 @@ #include "Acts/Geometry/Layer.hpp" #include "Acts/Navigation/NavigationState.hpp" #include "Acts/Propagator/NavigatorOptions.hpp" +#include "Acts/Propagator/NavigatorStatistics.hpp" #include "Acts/Propagator/Propagator.hpp" #include "Acts/Surfaces/BoundaryTolerance.hpp" #include "Acts/Surfaces/Surface.hpp" @@ -68,6 +69,9 @@ class DetectorNavigator { bool targetReached = false; /// Navigation state : a break has been detected bool navigationBreak = false; + + /// Navigation statistics + NavigatorStatistics statistics; }; /// Constructor with configuration object @@ -219,7 +223,7 @@ class DetectorNavigator { ACTS_VERBOSE(volInfo(state) << posInfo(state, stepper) << "surface status is " << surfaceStatus); - if (surfaceStatus == Intersection3D::Status::reachable) { + if (surfaceStatus == IntersectionStatus::reachable) { ACTS_VERBOSE(volInfo(state) << posInfo(state, stepper) << "surface " << surface.center(state.geoContext).transpose() @@ -288,7 +292,7 @@ class DetectorNavigator { state.options.surfaceTolerance, logger()); // Check if we are at a surface - if (surfaceStatus == Intersection3D::Status::onSurface) { + if (surfaceStatus == IntersectionStatus::onSurface) { ACTS_VERBOSE(volInfo(state) << posInfo(state, stepper) << "landed on surface"); diff --git a/Core/include/Acts/Navigation/MultiLayerNavigation.hpp b/Core/include/Acts/Navigation/MultiLayerNavigation.hpp index 4434f24e7d4..7a56086971a 100644 --- a/Core/include/Acts/Navigation/MultiLayerNavigation.hpp +++ b/Core/include/Acts/Navigation/MultiLayerNavigation.hpp @@ -92,9 +92,9 @@ class MultiLayerNavigation : public IInternalNavigation { /// Cast into a lookup position /// /// @param position is the position of the update call - std::array castPosition( + std::array castPosition( const Vector3& position) const { - std::array casted{}; + std::array casted{}; fillCasts(position, casted, std::make_integer_sequence{}); return casted; @@ -133,7 +133,7 @@ class MultiLayerNavigation : public IInternalNavigation { /// in the grid struct PathGridSurfacesGenerator { std::vector operator()(Vector3 startPosition, - const Vector3& direction, ActsScalar stepSize, + const Vector3& direction, double stepSize, std::size_t numberOfSteps) const { std::vector pathCoordinates = {}; pathCoordinates.reserve(numberOfSteps); diff --git a/Core/include/Acts/Navigation/NavigationState.hpp b/Core/include/Acts/Navigation/NavigationState.hpp index 6cfc8a17e46..0e0d8e5af9c 100644 --- a/Core/include/Acts/Navigation/NavigationState.hpp +++ b/Core/include/Acts/Navigation/NavigationState.hpp @@ -60,10 +60,10 @@ struct NavigationState { Vector3 direction = Vector3(0., 0., 0.); /// The current absolute momentum - ActsScalar absMomentum = 0.; + double absMomentum = 0.; /// The current absolute charge - ActsScalar absCharge = 0.; + double absCharge = 0.; /// The current magnetic field Vector3 magneticField = Vector3(0., 0., 0.); @@ -88,7 +88,7 @@ struct NavigationState { BoundaryTolerance surfaceBoundaryTolerance = BoundaryTolerance::None(); /// An overstep tolerance - ActsScalar overstepTolerance = -100 * UnitConstants::um; + double overstepTolerance = -100 * UnitConstants::um; /// Auxiliary attached information std::any auxiliary; diff --git a/Core/include/Acts/Navigation/NavigationStateUpdaters.hpp b/Core/include/Acts/Navigation/NavigationStateUpdaters.hpp index df5e750db54..83b7bfd5016 100644 --- a/Core/include/Acts/Navigation/NavigationStateUpdaters.hpp +++ b/Core/include/Acts/Navigation/NavigationStateUpdaters.hpp @@ -50,7 +50,7 @@ inline void intitializeCandidates(const GeometryContext& gctx, const Surface& surface = sc.surface != nullptr ? *sc.surface : sc.portal->surface(); // Only allow overstepping if it's not a portal - ActsScalar overstepTolerance = + double overstepTolerance = sc.portal != nullptr ? s_onSurfaceTolerance : nState.overstepTolerance; // Boundary tolerance is forced to 0 for portals BoundaryTolerance boundaryTolerance = diff --git a/Core/include/Acts/Navigation/NavigationStream.hpp b/Core/include/Acts/Navigation/NavigationStream.hpp index 97e154214d7..067831b181e 100644 --- a/Core/include/Acts/Navigation/NavigationStream.hpp +++ b/Core/include/Acts/Navigation/NavigationStream.hpp @@ -9,13 +9,13 @@ #pragma once #include "Acts/Definitions/Algebra.hpp" +#include "Acts/Definitions/Tolerance.hpp" #include "Acts/Geometry/GeometryContext.hpp" #include "Acts/Geometry/Portal.hpp" #include "Acts/Surfaces/BoundaryTolerance.hpp" #include "Acts/Utilities/Intersection.hpp" #include -#include #include namespace Acts { @@ -63,7 +63,7 @@ class NavigationStream { /// Convenience access to surface const Surface& surface() const { return *intersection.object(); } /// Cinvencience access to the path length - ActsScalar pathLength() const { return intersection.pathLength(); } + double pathLength() const { return intersection.pathLength(); } /// Order along the path length /// @@ -156,7 +156,7 @@ class NavigationStream { bool initialize(const GeometryContext& gctx, const NavigationStream::QueryPoint& queryPoint, const BoundaryTolerance& cTolerance, - ActsScalar onSurfaceTolerance = s_onSurfaceTolerance); + double onSurfaceTolerance = s_onSurfaceTolerance); /// Convenience method to update a stream from a new query point, /// this could be called from navigation delegates that do not require @@ -169,7 +169,7 @@ class NavigationStream { /// @return true if the stream is active, false indicate no valid candidates left bool update(const GeometryContext& gctx, const NavigationStream::QueryPoint& queryPoint, - ActsScalar onSurfaceTolerance = s_onSurfaceTolerance); + double onSurfaceTolerance = s_onSurfaceTolerance); private: /// The candidates of this navigation stream diff --git a/Core/include/Acts/Navigation/PortalNavigation.hpp b/Core/include/Acts/Navigation/PortalNavigation.hpp index 638f2397760..b810e179c69 100644 --- a/Core/include/Acts/Navigation/PortalNavigation.hpp +++ b/Core/include/Acts/Navigation/PortalNavigation.hpp @@ -86,7 +86,7 @@ struct BoundVolumesGrid1Navigation : public IExternalNavigation { /// @param cVolumes the contained volumes /// @param bTransform is the optional transform BoundVolumesGrid1Navigation( - const std::vector& gBoundaries, BinningValue bValue, + const std::vector& gBoundaries, BinningValue bValue, const std::vector& cVolumes, const Transform3& bTransform = Transform3::Identity()) noexcept(false) : indexedUpdater(IndexedUpdater(VariableBoundIndexGrid1(std::make_tuple( diff --git a/Core/include/Acts/Propagator/AtlasStepper.hpp b/Core/include/Acts/Propagator/AtlasStepper.hpp index f31aadbffab..cb78e828f17 100644 --- a/Core/include/Acts/Propagator/AtlasStepper.hpp +++ b/Core/include/Acts/Propagator/AtlasStepper.hpp @@ -21,6 +21,7 @@ #include "Acts/MagneticField/MagneticFieldProvider.hpp" #include "Acts/Propagator/ConstrainedStep.hpp" #include "Acts/Propagator/StepperOptions.hpp" +#include "Acts/Propagator/StepperStatistics.hpp" #include "Acts/Propagator/detail/SteppingHelper.hpp" #include "Acts/Surfaces/Surface.hpp" #include "Acts/Utilities/Intersection.hpp" @@ -305,6 +306,9 @@ class AtlasStepper { /// buffer & formatting for consistent output std::size_t debugPfxWidth = 30; std::size_t debugMsgWidth = 50; + + /// The statistics of the stepper + StepperStatistics statistics; }; explicit AtlasStepper(std::shared_ptr bField) @@ -415,10 +419,10 @@ class AtlasStepper { /// @param [in] boundaryTolerance The boundary check for this status update /// @param [in] surfaceTolerance Surface tolerance used for intersection /// @param [in] logger Logger instance to use - Intersection3D::Status updateSurfaceStatus( + IntersectionStatus updateSurfaceStatus( State& state, const Surface& surface, std::uint8_t index, Direction navDir, const BoundaryTolerance& boundaryTolerance, - ActsScalar surfaceTolerance = s_onSurfaceTolerance, + double surfaceTolerance = s_onSurfaceTolerance, const Logger& logger = getDummyLogger()) const { return detail::updateSingleSurfaceStatus( *this, state, surface, index, navDir, boundaryTolerance, diff --git a/Core/include/Acts/Propagator/ConstrainedStep.hpp b/Core/include/Acts/Propagator/ConstrainedStep.hpp index e957b001281..412f308bac9 100644 --- a/Core/include/Acts/Propagator/ConstrainedStep.hpp +++ b/Core/include/Acts/Propagator/ConstrainedStep.hpp @@ -40,11 +40,9 @@ namespace Acts { /// The hierarchy is: /// - Overstepping resolution / backpropagation /// - Convergence -/// - Step into the void with `std::numeric_limits::max()` +/// - Step into the void with `std::numeric_limits::max()` class ConstrainedStep { public: - using Scalar = ActsScalar; - /// the types of constraints /// from actor - this would be a typical navigation step /// from aborter - this would be a target condition @@ -53,26 +51,26 @@ class ConstrainedStep { constexpr ConstrainedStep() = default; - /// constructor from Scalar + /// constructor /// @param value is the user given initial value - constexpr explicit ConstrainedStep(Scalar value) { setUser(value); } + constexpr explicit ConstrainedStep(double value) { setUser(value); } - /// set accuracy by one Scalar + /// set accuracy /// /// this will set only the accuracy, as this is the most /// exposed to the Propagator /// /// @param value is the new accuracy value - constexpr void setAccuracy(Scalar value) { + constexpr void setAccuracy(double value) { assert(value > 0 && "ConstrainedStep accuracy must be > 0."); // set the accuracy value m_accuracy = value; } - /// set user by one Scalar + /// set user /// /// @param value is the new user value - constexpr void setUser(Scalar value) { + constexpr void setUser(double value) { // TODO enable assert; see https://github.com/acts-project/acts/issues/2543 // assert(value != 0 && "ConstrainedStep user must be != 0."); // set the user value @@ -80,20 +78,20 @@ class ConstrainedStep { } /// returns the min step size - constexpr Scalar value() const { - Scalar min = *std::min_element(m_values.begin(), m_values.end()); + constexpr double value() const { + double min = *std::min_element(m_values.begin(), m_values.end()); // accuracy is always positive and therefore handled separately - Scalar result = std::min(std::abs(min), m_accuracy); + double result = std::min(std::abs(min), m_accuracy); return std::signbit(min) ? -result : result; } /// Access a specific value /// /// @param type is the requested parameter type - constexpr Scalar value(Type type) const { return m_values[type]; } + constexpr double value(Type type) const { return m_values[type]; } /// Access the accuracy value - constexpr Scalar accuracy() const { return m_accuracy; } + constexpr double accuracy() const { return m_accuracy; } /// release a certain constraint value /// @@ -111,7 +109,7 @@ class ConstrainedStep { /// @param value is the new value to be updated /// @param type is the constraint type /// @param releaseStep Allow step size to increase again - constexpr void update(Scalar value, Type type, bool releaseStep = false) { + constexpr void update(double value, Type type, bool releaseStep = false) { if (releaseStep) { release(type); } @@ -127,7 +125,7 @@ class ConstrainedStep { std::ostream& toStream(std::ostream& os) const { // Helper method to avoid unreadable screen output - auto streamValue = [&](Scalar val) { + auto streamValue = [&](double val) { os << std::setw(5); if (std::abs(val) == kNotSet) { os << (val > 0 ? "+∞" : "-∞"); @@ -156,12 +154,12 @@ class ConstrainedStep { } private: - static constexpr auto kNotSet = std::numeric_limits::max(); + static constexpr auto kNotSet = std::numeric_limits::max(); /// the step size tuple - std::array m_values = {kNotSet, kNotSet, kNotSet}; + std::array m_values = {kNotSet, kNotSet, kNotSet}; /// the accuracy value - this can vary up and down given a good step estimator - Scalar m_accuracy = kNotSet; + double m_accuracy = kNotSet; }; inline std::ostream& operator<<(std::ostream& os, const ConstrainedStep& step) { diff --git a/Core/include/Acts/Propagator/DirectNavigator.hpp b/Core/include/Acts/Propagator/DirectNavigator.hpp index eb9db91e71f..d2f66468168 100644 --- a/Core/include/Acts/Propagator/DirectNavigator.hpp +++ b/Core/include/Acts/Propagator/DirectNavigator.hpp @@ -9,19 +9,18 @@ #pragma once #include "Acts/Definitions/Direction.hpp" -#include "Acts/Geometry/BoundarySurfaceT.hpp" +#include "Acts/Definitions/Units.hpp" #include "Acts/Geometry/Layer.hpp" #include "Acts/Geometry/TrackingGeometry.hpp" #include "Acts/Geometry/TrackingVolume.hpp" +#include "Acts/Propagator/ConstrainedStep.hpp" #include "Acts/Propagator/NavigatorOptions.hpp" -#include "Acts/Propagator/Propagator.hpp" +#include "Acts/Propagator/NavigatorStatistics.hpp" #include "Acts/Surfaces/BoundaryTolerance.hpp" #include "Acts/Surfaces/Surface.hpp" #include "Acts/Utilities/Intersection.hpp" #include "Acts/Utilities/Logger.hpp" -#include -#include #include #include #include @@ -75,6 +74,9 @@ class DirectNavigator { /// Navigation state - external interface: a break has been detected bool navigationBreak = false; + /// Navigation statistics + NavigatorStatistics statistics; + const Surface* navSurface() const { return options.surfaces.at(surfaceIndex); } @@ -255,7 +257,7 @@ class DirectNavigator { state.stepping, surface, index, state.options.direction, BoundaryTolerance::Infinite(), state.options.surfaceTolerance, *m_logger); - if (surfaceStatus == Intersection3D::Status::unreachable) { + if (surfaceStatus == IntersectionStatus::unreachable) { ACTS_VERBOSE( "Surface not reachable anymore, switching to next one in " "sequence"); @@ -309,7 +311,7 @@ class DirectNavigator { state.stepping, surface, index, state.options.direction, BoundaryTolerance::Infinite(), state.options.surfaceTolerance, *m_logger); - if (surfaceStatus == Intersection3D::Status::onSurface) { + if (surfaceStatus == IntersectionStatus::onSurface) { // Set the current surface state.navigation.currentSurface = state.navigation.navSurface(); ACTS_VERBOSE("Current surface set to " @@ -322,7 +324,7 @@ class DirectNavigator { .at(state.navigation.surfaceIndex) ->geometryId()); } - } else if (surfaceStatus == Intersection3D::Status::reachable) { + } else if (surfaceStatus == IntersectionStatus::reachable) { ACTS_VERBOSE("Next surface reachable at distance " << stepper.outputStepSize(state.stepping)); } diff --git a/Core/include/Acts/Propagator/EigenStepper.hpp b/Core/include/Acts/Propagator/EigenStepper.hpp index fb1062b0c9b..00cec761f3c 100644 --- a/Core/include/Acts/Propagator/EigenStepper.hpp +++ b/Core/include/Acts/Propagator/EigenStepper.hpp @@ -13,7 +13,6 @@ #include "Acts/Definitions/Algebra.hpp" #include "Acts/Definitions/Tolerance.hpp" -#include "Acts/Definitions/Units.hpp" #include "Acts/EventData/TrackParameters.hpp" #include "Acts/EventData/detail/CorrectedTransformationFreeToBound.hpp" #include "Acts/Geometry/GeometryContext.hpp" @@ -23,6 +22,7 @@ #include "Acts/Propagator/EigenStepperDefaultExtension.hpp" #include "Acts/Propagator/PropagatorTraits.hpp" #include "Acts/Propagator/StepperOptions.hpp" +#include "Acts/Propagator/StepperStatistics.hpp" #include "Acts/Propagator/detail/SteppingHelper.hpp" #include "Acts/Utilities/Intersection.hpp" #include "Acts/Utilities/Result.hpp" @@ -164,6 +164,9 @@ class EigenStepper { /// k_i elements of the momenta std::array kQoP{}; } stepData; + + /// Statistics of the stepper + StepperStatistics statistics; }; /// Constructor requires knowledge of the detector's magnetic field @@ -267,10 +270,10 @@ class EigenStepper { /// @param [in] boundaryTolerance The boundary check for this status update /// @param [in] surfaceTolerance Surface tolerance used for intersection /// @param [in] logger A @c Logger instance - Intersection3D::Status updateSurfaceStatus( + IntersectionStatus updateSurfaceStatus( State& state, const Surface& surface, std::uint8_t index, Direction navDir, const BoundaryTolerance& boundaryTolerance, - ActsScalar surfaceTolerance = s_onSurfaceTolerance, + double surfaceTolerance = s_onSurfaceTolerance, const Logger& logger = getDummyLogger()) const { return detail::updateSingleSurfaceStatus( *this, state, surface, index, navDir, boundaryTolerance, diff --git a/Core/include/Acts/Propagator/EigenStepper.ipp b/Core/include/Acts/Propagator/EigenStepper.ipp index 84b305ae431..4ee3a41b04a 100644 --- a/Core/include/Acts/Propagator/EigenStepper.ipp +++ b/Core/include/Acts/Propagator/EigenStepper.ipp @@ -6,6 +6,7 @@ // 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 "Acts/Definitions/Direction.hpp" #include "Acts/EventData/TransformationHelpers.hpp" #include "Acts/Propagator/ConstrainedStep.hpp" #include "Acts/Propagator/EigenStepperError.hpp" @@ -259,7 +260,9 @@ Acts::Result Acts::EigenStepper::step( // Select and adjust the appropriate Runge-Kutta step size as given // ATL-SOFT-PUB-2009-001 while (true) { - nStepTrials++; + ++nStepTrials; + ++state.stepping.statistics.nAttemptedSteps; + auto res = tryRungeKuttaStep(h); if (!res.ok()) { return res.error(); @@ -268,6 +271,8 @@ Acts::Result Acts::EigenStepper::step( break; } + ++state.stepping.statistics.nRejectedSteps; + const double stepSizeScaling = calcStepSizeScaling(errorEstimate); h *= stepSizeScaling; @@ -351,6 +356,14 @@ Acts::Result Acts::EigenStepper::step( ++state.stepping.nSteps; state.stepping.nStepTrials += nStepTrials; + ++state.stepping.statistics.nSuccessfulSteps; + if (state.options.direction != + Direction::fromScalarZeroAsPositive(initialH)) { + ++state.stepping.statistics.nReverseSteps; + } + state.stepping.statistics.pathLength += h; + state.stepping.statistics.absolutePathLength += std::abs(h); + const double stepSizeScaling = calcStepSizeScaling(errorEstimate); const double nextAccuracy = std::abs(h * stepSizeScaling); const double previousAccuracy = std::abs(state.stepping.stepSize.accuracy()); diff --git a/Core/include/Acts/Propagator/EigenStepperDefaultExtension.hpp b/Core/include/Acts/Propagator/EigenStepperDefaultExtension.hpp index 2810b11a2a2..cb7939534f5 100644 --- a/Core/include/Acts/Propagator/EigenStepperDefaultExtension.hpp +++ b/Core/include/Acts/Propagator/EigenStepperDefaultExtension.hpp @@ -16,14 +16,10 @@ namespace Acts { -/// @brief Default evaluater of the k_i's and elements of the transport matrix +/// @brief Default evaluator of the k_i's and elements of the transport matrix /// D of the RKN4 stepping. This is a pure implementation by textbook. struct EigenStepperDefaultExtension { - using Scalar = ActsScalar; - /// @brief Vector3 replacement for the custom scalar type - using ThisVector3 = Eigen::Matrix; - - /// @brief Evaluater of the k_i's of the RKN4. For the case of i = 0 this + /// @brief Evaluator of the k_i's of the RKN4. For the case of i = 0 this /// step sets up qop, too. /// /// @tparam i Index of the k_i, i = [0, 3] @@ -43,9 +39,9 @@ struct EigenStepperDefaultExtension { template bool k(const propagator_state_t& state, const stepper_t& stepper, - const navigator_t& /*navigator*/, ThisVector3& knew, - const Vector3& bField, std::array& kQoP, - const double h = 0., const ThisVector3& kprev = ThisVector3::Zero()) + const navigator_t& /*navigator*/, Vector3& knew, const Vector3& bField, + std::array& kQoP, const double h = 0., + const Vector3& kprev = Vector3::Zero()) requires(i >= 0 && i <= 3) { auto qop = stepper.qOverP(state.stepping); diff --git a/Core/include/Acts/Propagator/EigenStepperDenseExtension.hpp b/Core/include/Acts/Propagator/EigenStepperDenseExtension.hpp index 70dbb1cb820..a3d88ea1997 100644 --- a/Core/include/Acts/Propagator/EigenStepperDenseExtension.hpp +++ b/Core/include/Acts/Propagator/EigenStepperDenseExtension.hpp @@ -21,44 +21,40 @@ namespace Acts { -/// @brief Evaluater of the k_i's and elements of the transport matrix +/// @brief Evaluator of the k_i's and elements of the transport matrix /// D of the RKN4 stepping. This implementation involves energy loss due to -/// ioninisation, bremsstrahlung, pair production and photonuclear interaction -/// in the propagation and the jacobian. These effects will only occur if the +/// ionisation, bremsstrahlung, pair production and photonuclear interaction +/// in the propagation and the Jacobian. These effects will only occur if the /// propagation is in a TrackingVolume with attached material. struct EigenStepperDenseExtension { - using Scalar = ActsScalar; - /// @brief Vector3 replacement for the custom scalar type - using ThisVector3 = Eigen::Matrix; - /// Fallback extension EigenStepperDefaultExtension defaultExtension; /// Momentum at a certain point - Scalar currentMomentum = 0.; + double currentMomentum = 0.; /// Particles momentum at k1 - Scalar initialMomentum = 0.; + double initialMomentum = 0.; /// Material that will be passed /// TODO : Might not be needed anymore Material material; /// Derivatives dLambda''dlambda at each sub-step point - std::array dLdl{}; + std::array dLdl{}; /// q/p at each sub-step - std::array qop{}; + std::array qop{}; /// Derivatives dPds at each sub-step - std::array dPds{}; + std::array dPds{}; /// Derivative d(dEds)d(q/p) evaluated at the initial point - Scalar dgdqopValue = 0.; + double dgdqopValue = 0.; /// Derivative dEds at the initial point - Scalar g = 0.; + double g = 0.; /// k_i equivalent for the time propagation - std::array tKi{}; + std::array tKi{}; /// Lambda''_i - std::array Lambdappi{}; + std::array Lambdappi{}; /// Energy at each sub-step - std::array energy{}; + std::array energy{}; - /// @brief Evaluater of the k_i's of the RKN4. For the case of i = 0 this + /// @brief Evaluator of the k_i's of the RKN4. For the case of i = 0 this /// step sets up member parameters, too. /// /// @tparam i Index of the k_i, i = [0, 3] @@ -79,9 +75,9 @@ struct EigenStepperDenseExtension { template bool k(const propagator_state_t& state, const stepper_t& stepper, - const navigator_t& navigator, ThisVector3& knew, const Vector3& bField, - std::array& kQoP, const double h = 0., - const ThisVector3& kprev = ThisVector3::Zero()) + const navigator_t& navigator, Vector3& knew, const Vector3& bField, + std::array& kQoP, const double h = 0., + const Vector3& kprev = Vector3::Zero()) requires(i >= 0 && i <= 3) { const auto* volumeMaterial = @@ -98,7 +94,7 @@ struct EigenStepperDenseExtension { // i = 0 is used for setup and evaluation of k if constexpr (i == 0) { // Set up for energy loss - ThisVector3 position = stepper.position(state.stepping); + Vector3 position = stepper.position(state.stepping); material = volumeMaterial->material(position.template cast()); initialMomentum = stepper.absoluteMomentum(state.stepping); currentMomentum = initialMomentum; @@ -217,7 +213,7 @@ struct EigenStepperDenseExtension { } private: - /// @brief Evaluates the transport matrix D for the jacobian + /// @brief Evaluates the transport matrix D for the Jacobian /// /// @tparam propagator_state_t Type of the state of the propagator /// @tparam stepper_t Type of the stepper diff --git a/Core/include/Acts/Propagator/MultiEigenStepperLoop.hpp b/Core/include/Acts/Propagator/MultiEigenStepperLoop.hpp index 1bb4ab8f55a..a5236e571e3 100644 --- a/Core/include/Acts/Propagator/MultiEigenStepperLoop.hpp +++ b/Core/include/Acts/Propagator/MultiEigenStepperLoop.hpp @@ -14,17 +14,14 @@ #include "Acts/Definitions/Algebra.hpp" #include "Acts/Definitions/Direction.hpp" #include "Acts/Definitions/TrackParametrization.hpp" -#include "Acts/Definitions/Units.hpp" #include "Acts/EventData/MultiComponentTrackParameters.hpp" #include "Acts/EventData/TrackParameters.hpp" #include "Acts/EventData/detail/CorrectedTransformationFreeToBound.hpp" #include "Acts/MagneticField/MagneticFieldProvider.hpp" #include "Acts/Propagator/ConstrainedStep.hpp" #include "Acts/Propagator/EigenStepper.hpp" -#include "Acts/Propagator/EigenStepperError.hpp" -#include "Acts/Propagator/MultiStepperError.hpp" -#include "Acts/Propagator/Propagator.hpp" #include "Acts/Propagator/StepperOptions.hpp" +#include "Acts/Propagator/StepperStatistics.hpp" #include "Acts/Propagator/detail/LoopStepperUtils.hpp" #include "Acts/Surfaces/Surface.hpp" #include "Acts/Utilities/Intersection.hpp" @@ -35,7 +32,6 @@ #include #include #include -#include #include #include @@ -82,13 +78,13 @@ struct SingleComponentReducer { } template - static ActsScalar qOverP(const stepper_state_t& s) { + static double qOverP(const stepper_state_t& s) { const auto cmp = component_chooser_t{}(s.components); return cmp->state.pars[eFreeQOverP]; } template - static ActsScalar absoluteMomentum(const stepper_state_t& s) { + static double absoluteMomentum(const stepper_state_t& s) { const auto cmp = component_chooser_t{}(s.components); return s.particleHypothesis.extractMomentum(cmp->state.pars[eFreeQOverP]); } @@ -101,13 +97,13 @@ struct SingleComponentReducer { } template - static ActsScalar charge(const stepper_state_t& s) { + static double charge(const stepper_state_t& s) { const auto cmp = component_chooser_t{}(s.components); return s.particleHypothesis.extractCharge(cmp->state.pars[eFreeQOverP]); } template - static ActsScalar time(const stepper_state_t& s) { + static double time(const stepper_state_t& s) { return component_chooser_t{}(s.components)->state.pars[eFreeTime]; } @@ -169,11 +165,11 @@ class MultiEigenStepperLoop : public EigenStepper { /// @brief Define an own bound state using BoundState = - std::tuple; + std::tuple; /// @brief Define an own curvilinear state - using CurvilinearState = std::tuple; + using CurvilinearState = + std::tuple; /// @brief The reducer type using Reducer = component_reducer_t; @@ -195,8 +191,8 @@ class MultiEigenStepperLoop : public EigenStepper { /// The struct that stores the individual components struct Component { SingleState state; - ActsScalar weight; - Intersection3D::Status status; + double weight; + IntersectionStatus status; }; /// Particle hypothesis @@ -219,6 +215,9 @@ class MultiEigenStepperLoop : public EigenStepper { /// reached a surface std::optional stepCounterAfterFirstComponentOnSurface; + /// The stepper statistics + StepperStatistics statistics; + /// No default constructor is provided State() = delete; @@ -251,7 +250,7 @@ class MultiEigenStepperLoop : public EigenStepper { const auto& [weight, singlePars] = multipars[i]; components.push_back( {SingleState(gctx, bfield->makeCache(mctx), singlePars, ssize), - weight, Intersection3D::Status::onSurface}); + weight, IntersectionStatus::onSurface}); } if (std::get<2>(multipars.components().front())) { @@ -394,7 +393,7 @@ class MultiEigenStepperLoop : public EigenStepper { void removeMissedComponents(State& state) const { auto new_end = std::remove_if( state.components.begin(), state.components.end(), [](const auto& cmp) { - return cmp.status == Intersection3D::Status::missed; + return cmp.status == IntersectionStatus::unreachable; }); state.components.erase(new_end, state.components.end()); @@ -404,7 +403,7 @@ class MultiEigenStepperLoop : public EigenStepper { /// /// @param [in,out] state The stepping state (thread-local cache) void reweightComponents(State& state) const { - ActsScalar sumOfWeights = 0.0; + double sumOfWeights = 0.0; for (const auto& cmp : state.components) { sumOfWeights += cmp.weight; } @@ -437,7 +436,7 @@ class MultiEigenStepperLoop : public EigenStepper { {SingleState(state.geoContext, SingleStepper::m_bField->makeCache(state.magContext), pars), - weight, Intersection3D::Status::onSurface}); + weight, IntersectionStatus::onSurface}); return ComponentProxy{state.components.back(), state}; } @@ -516,12 +515,12 @@ class MultiEigenStepperLoop : public EigenStepper { /// @param [in] boundaryTolerance The boundary check for this status update /// @param [in] surfaceTolerance Surface tolerance used for intersection /// @param [in] logger A @c Logger instance - Intersection3D::Status updateSurfaceStatus( + IntersectionStatus updateSurfaceStatus( State& state, const Surface& surface, std::uint8_t index, Direction navDir, const BoundaryTolerance& boundaryTolerance, - ActsScalar surfaceTolerance = s_onSurfaceTolerance, + double surfaceTolerance = s_onSurfaceTolerance, const Logger& logger = getDummyLogger()) const { - using Status = Intersection3D::Status; + using Status = IntersectionStatus; std::array counts = {0, 0, 0}; @@ -577,10 +576,8 @@ class MultiEigenStepperLoop : public EigenStepper { } else if (counts[static_cast(Status::onSurface)] > 0) { state.stepCounterAfterFirstComponentOnSurface.reset(); return Status::onSurface; - } else if (counts[static_cast(Status::unreachable)] > 0) { - return Status::unreachable; } else { - return Status::missed; + return Status::unreachable; } } diff --git a/Core/include/Acts/Propagator/MultiEigenStepperLoop.ipp b/Core/include/Acts/Propagator/MultiEigenStepperLoop.ipp index fab3e3f0779..3eac67c27b3 100644 --- a/Core/include/Acts/Propagator/MultiEigenStepperLoop.ipp +++ b/Core/include/Acts/Propagator/MultiEigenStepperLoop.ipp @@ -7,6 +7,7 @@ // file, You can obtain one at https://mozilla.org/MPL/2.0/. #include "Acts/Propagator/MultiEigenStepperLoop.hpp" +#include "Acts/Propagator/MultiStepperError.hpp" #include "Acts/Utilities/Logger.hpp" namespace Acts { @@ -67,8 +68,7 @@ auto MultiEigenStepperLoop::curvilinearState( State& state, bool transportCov) const -> CurvilinearState { assert(!state.components.empty()); - std::vector< - std::tuple> + std::vector> cmps; cmps.reserve(numberComponents(state)); double accumulatedPathLength = 0.0; @@ -93,7 +93,7 @@ template template Result MultiEigenStepperLoop::step( propagator_state_t& state, const navigator_t& navigator) const { - using Status = Acts::Intersection3D::Status; + using Status = Acts::IntersectionStatus; State& stepping = state.stepping; auto& components = stepping.components; @@ -112,7 +112,7 @@ Result MultiEigenStepperLoop::step( m_stepLimitAfterFirstComponentOnSurface) { for (auto& cmp : components) { if (cmp.status != Status::onSurface) { - cmp.status = Status::missed; + cmp.status = Status::unreachable; } } @@ -137,10 +137,9 @@ Result MultiEigenStepperLoop::step( // If at least one component is on a surface, we can remove all missed // components before the step. If not, we must keep them for the case that all // components miss and we need to retarget - const auto cmpsOnSurface = - std::count_if(components.cbegin(), components.cend(), [&](auto& cmp) { - return cmp.status == Intersection3D::Status::onSurface; - }); + const auto cmpsOnSurface = std::count_if( + components.cbegin(), components.cend(), + [&](auto& cmp) { return cmp.status == IntersectionStatus::onSurface; }); if (cmpsOnSurface > 0) { removeMissedComponents(stepping); diff --git a/Core/include/Acts/Propagator/MultiStepperAborters.hpp b/Core/include/Acts/Propagator/MultiStepperAborters.hpp index 0e28375df94..e42d3387e2f 100644 --- a/Core/include/Acts/Propagator/MultiStepperAborters.hpp +++ b/Core/include/Acts/Propagator/MultiStepperAborters.hpp @@ -59,12 +59,12 @@ struct MultiStepperSurfaceReached : public SurfaceReached { averageOnSurfaceTolerance) .closest(); - if (sIntersection.status() == Intersection3D::Status::onSurface) { + if (sIntersection.status() == IntersectionStatus::onSurface) { ACTS_VERBOSE( "MultiStepperSurfaceReached aborter | " "Reached target in average mode"); for (auto cmp : stepper.componentIterable(state.stepping)) { - cmp.status() = Intersection3D::Status::onSurface; + cmp.status() = IntersectionStatus::onSurface; } return true; @@ -84,10 +84,10 @@ struct MultiStepperSurfaceReached : public SurfaceReached { if (!SurfaceReached::checkAbort(singleState, singleStepper, navigator, logger)) { - cmp.status() = Acts::Intersection3D::Status::reachable; + cmp.status() = Acts::IntersectionStatus::reachable; reached = false; } else { - cmp.status() = Acts::Intersection3D::Status::onSurface; + cmp.status() = Acts::IntersectionStatus::onSurface; } } diff --git a/Core/include/Acts/Propagator/Navigator.hpp b/Core/include/Acts/Propagator/Navigator.hpp index c2a9427257c..504912b507f 100644 --- a/Core/include/Acts/Propagator/Navigator.hpp +++ b/Core/include/Acts/Propagator/Navigator.hpp @@ -8,13 +8,13 @@ #pragma once -#include "Acts/Definitions/Units.hpp" #include "Acts/Geometry/GeometryIdentifier.hpp" #include "Acts/Geometry/Layer.hpp" #include "Acts/Geometry/TrackingGeometry.hpp" #include "Acts/Geometry/TrackingVolume.hpp" #include "Acts/Propagator/ConstrainedStep.hpp" #include "Acts/Propagator/NavigatorOptions.hpp" +#include "Acts/Propagator/NavigatorStatistics.hpp" #include "Acts/Surfaces/BoundaryTolerance.hpp" #include "Acts/Surfaces/Surface.hpp" #include "Acts/Utilities/Logger.hpp" @@ -176,9 +176,12 @@ class Navigator { bool targetReached = false; /// Navigation state : a break has been detected bool navigationBreak = false; - // The navigation stage (@todo: integrate break, target) + /// The navigation stage (@todo: integrate break, target) Stage navigationStage = Stage::undefined; + /// Navigation statistics + NavigatorStatistics statistics; + void reset() { navSurfaces.clear(); navSurfaceIndex = navSurfaces.size(); @@ -427,6 +430,7 @@ class Navigator { << "No targets found, we got lost! Attempt renavigation."); state.navigation.reset(); + ++state.navigation.statistics.nRenavigations; // We might have punched through a boundary and entered another volume // so we have to reinitialize @@ -576,6 +580,7 @@ class Navigator { state.navigation.navBoundaries.clear(); state.navigation.navBoundaryIndex = state.navigation.navBoundaries.size(); + ++state.navigation.statistics.nVolumeSwitches; } } else { // Set the navigation stage back to boundary target @@ -644,7 +649,7 @@ class Navigator { auto surfaceStatus = stepper.updateSurfaceStatus( state.stepping, *surface, intersection.index(), state.options.direction, BoundaryTolerance::None(), state.options.surfaceTolerance, logger()); - if (surfaceStatus == Intersection3D::Status::onSurface) { + if (surfaceStatus == IntersectionStatus::onSurface) { ACTS_VERBOSE(volInfo(state) << "Status Surface successfully hit, storing it."); // Set in navigation state, so actors and aborters can access it @@ -720,7 +725,7 @@ class Navigator { state.stepping, *surface, intersection.index(), state.options.direction, boundaryTolerance, state.options.surfaceTolerance, logger()); - if (surfaceStatus == Intersection3D::Status::reachable) { + if (surfaceStatus == IntersectionStatus::reachable) { ACTS_VERBOSE(volInfo(state) << "Surface reachable, step size updated to " << stepper.outputStepSize(state.stepping)); @@ -772,8 +777,6 @@ class Navigator { /// @return boolean return triggers exit to stepper template bool targetLayers(propagator_state_t& state, const stepper_t& stepper) const { - using namespace UnitLiterals; - if (state.navigation.navigationBreak) { return false; } @@ -812,7 +815,7 @@ class Navigator { state.stepping, *layerSurface, intersection.index(), state.options.direction, BoundaryTolerance::None(), state.options.surfaceTolerance, logger()); - if (layerStatus == Intersection3D::Status::reachable) { + if (layerStatus == IntersectionStatus::reachable) { ACTS_VERBOSE(volInfo(state) << "Layer reachable, step size updated to " << stepper.outputStepSize(state.stepping)); return true; @@ -934,7 +937,7 @@ class Navigator { state.stepping, *boundarySurface, intersection.index(), state.options.direction, BoundaryTolerance::None(), state.options.surfaceTolerance, logger()); - if (boundaryStatus == Intersection3D::Status::reachable) { + if (boundaryStatus == IntersectionStatus::reachable) { ACTS_VERBOSE(volInfo(state) << "Boundary reachable, step size updated to " << stepper.outputStepSize(state.stepping)); @@ -1157,7 +1160,7 @@ class Navigator { state.options.direction, BoundaryTolerance::None(), state.options.surfaceTolerance, logger()); // the only advance could have been to the target - if (targetStatus == Intersection3D::Status::onSurface) { + if (targetStatus == IntersectionStatus::onSurface) { // set the target surface state.navigation.currentSurface = state.navigation.targetSurface; ACTS_VERBOSE(volInfo(state) diff --git a/Core/include/Acts/Propagator/NavigatorStatistics.hpp b/Core/include/Acts/Propagator/NavigatorStatistics.hpp new file mode 100644 index 00000000000..fd73d36c568 --- /dev/null +++ b/Core/include/Acts/Propagator/NavigatorStatistics.hpp @@ -0,0 +1,26 @@ +// 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 + +namespace Acts { + +/// @struct NavigatorStatistics +/// +/// @brief A struct to hold statistics of the navigator +struct NavigatorStatistics { + /// Number of renavigation attempts + std::size_t nRenavigations = 0; + + /// Number of volume switches + std::size_t nVolumeSwitches = 0; +}; + +} // namespace Acts diff --git a/Core/include/Acts/Propagator/Propagator.ipp b/Core/include/Acts/Propagator/Propagator.ipp index a7c12309bb7..8a7c560a725 100644 --- a/Core/include/Acts/Propagator/Propagator.ipp +++ b/Core/include/Acts/Propagator/Propagator.ipp @@ -341,6 +341,9 @@ void Acts::Propagator::moveStateToResult(propagator_state_t& state, result.steps = state.steps; result.pathLength = state.pathLength; + + result.statistics.stepping = state.stepping.statistics; + result.statistics.navigation = state.navigation.statistics; } template diff --git a/Core/include/Acts/Propagator/PropagatorResult.hpp b/Core/include/Acts/Propagator/PropagatorResult.hpp index 232211b8495..a67543f7b4b 100644 --- a/Core/include/Acts/Propagator/PropagatorResult.hpp +++ b/Core/include/Acts/Propagator/PropagatorResult.hpp @@ -9,6 +9,7 @@ #pragma once #include "Acts/Definitions/TrackParametrization.hpp" +#include "Acts/Propagator/PropagatorStatistics.hpp" #include "Acts/Utilities/detail/Extendable.hpp" #include @@ -36,6 +37,9 @@ struct PropagatorResult : private detail::Extendable { /// Signed distance over which the parameters were propagated double pathLength = 0.; + + /// Propagator statistics + PropagatorStatistics statistics; }; } // namespace Acts diff --git a/Core/include/Acts/Propagator/PropagatorState.hpp b/Core/include/Acts/Propagator/PropagatorState.hpp index 29e1baeeb30..03346cfd57d 100644 --- a/Core/include/Acts/Propagator/PropagatorState.hpp +++ b/Core/include/Acts/Propagator/PropagatorState.hpp @@ -9,6 +9,7 @@ #pragma once #include "Acts/Geometry/GeometryContext.hpp" +#include "Acts/Propagator/PropagatorStatistics.hpp" #include "Acts/Utilities/detail/Extendable.hpp" #include @@ -72,6 +73,9 @@ struct PropagatorState : private detail::Extendable { /// Signed distance over which the parameters were propagated double pathLength = 0.; + + /// Statistics of the propagation + PropagatorStatistics statistics; }; } // namespace Acts diff --git a/Core/include/Acts/Propagator/PropagatorStatistics.hpp b/Core/include/Acts/Propagator/PropagatorStatistics.hpp new file mode 100644 index 00000000000..843be215bd9 --- /dev/null +++ b/Core/include/Acts/Propagator/PropagatorStatistics.hpp @@ -0,0 +1,26 @@ +// 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 +#include + +namespace Acts { + +/// @struct PropagatorStatistics +/// +/// @brief A struct to hold statistics of the propagator +struct PropagatorStatistics { + /// Statistics of the stepper + StepperStatistics stepping; + /// Statistics of the navigator + NavigatorStatistics navigation; +}; + +} // namespace Acts diff --git a/Core/include/Acts/Propagator/StandardAborters.hpp b/Core/include/Acts/Propagator/StandardAborters.hpp index 706b0ce0697..271ebd85239 100644 --- a/Core/include/Acts/Propagator/StandardAborters.hpp +++ b/Core/include/Acts/Propagator/StandardAborters.hpp @@ -118,7 +118,7 @@ struct SurfaceReached { bool reached = false; - if (closest.status() == Intersection3D::Status::onSurface) { + if (closest.status() == IntersectionStatus::onSurface) { const double distance = closest.pathLength(); ACTS_VERBOSE( "SurfaceReached aborter | " diff --git a/Core/include/Acts/Propagator/StepperConcept.hpp b/Core/include/Acts/Propagator/StepperConcept.hpp index d869b90b301..fb4ea187bcd 100644 --- a/Core/include/Acts/Propagator/StepperConcept.hpp +++ b/Core/include/Acts/Propagator/StepperConcept.hpp @@ -54,8 +54,7 @@ concept CommonStepper = requires { }; requires requires(const Surface& sf, std::uint8_t ui, Direction d, - const BoundaryTolerance& bt, ActsScalar sc, - const Logger& l) { + const BoundaryTolerance& bt, double sc, const Logger& l) { { s.updateSurfaceStatus(t, sf, ui, d, bt, sc, l) }; }; diff --git a/Core/include/Acts/Propagator/StepperStatistics.hpp b/Core/include/Acts/Propagator/StepperStatistics.hpp new file mode 100644 index 00000000000..64abf5bde00 --- /dev/null +++ b/Core/include/Acts/Propagator/StepperStatistics.hpp @@ -0,0 +1,34 @@ +// 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 + +namespace Acts { + +/// @struct StepperStatistics +/// +/// @brief A struct to hold statistics of the stepper +struct StepperStatistics { + /// Number of attempted steps + std::size_t nAttemptedSteps = 0; + /// Number of rejected steps + std::size_t nRejectedSteps = 0; + /// Number of successful steps + std::size_t nSuccessfulSteps = 0; + /// Number of steps that were reversed + std::size_t nReverseSteps = 0; + + /// Signed sum of the step lengths + double pathLength = 0; + /// Unsigned sum of the step lengths + double absolutePathLength = 0; +}; + +} // namespace Acts diff --git a/Core/include/Acts/Propagator/StraightLineStepper.hpp b/Core/include/Acts/Propagator/StraightLineStepper.hpp index 8ba0d72fe81..1227397fefb 100644 --- a/Core/include/Acts/Propagator/StraightLineStepper.hpp +++ b/Core/include/Acts/Propagator/StraightLineStepper.hpp @@ -23,6 +23,7 @@ #include "Acts/Propagator/ConstrainedStep.hpp" #include "Acts/Propagator/PropagatorTraits.hpp" #include "Acts/Propagator/StepperOptions.hpp" +#include "Acts/Propagator/StepperStatistics.hpp" #include "Acts/Propagator/detail/SteppingHelper.hpp" #include "Acts/Surfaces/BoundaryTolerance.hpp" #include "Acts/Surfaces/Surface.hpp" @@ -142,6 +143,9 @@ class StraightLineStepper { // Cache the geometry context of this propagation std::reference_wrapper geoContext; + + /// Statistics of the stepper + StepperStatistics statistics; }; StraightLineStepper() = default; @@ -238,10 +242,10 @@ class StraightLineStepper { /// @param [in] boundaryTolerance The boundary check for this status update /// @param [in] surfaceTolerance Surface tolerance used for intersection /// @param [in] logger A logger instance - Intersection3D::Status updateSurfaceStatus( + IntersectionStatus updateSurfaceStatus( State& state, const Surface& surface, std::uint8_t index, Direction navDir, const BoundaryTolerance& boundaryTolerance, - ActsScalar surfaceTolerance = s_onSurfaceTolerance, + double surfaceTolerance = s_onSurfaceTolerance, const Logger& logger = getDummyLogger()) const { return detail::updateSingleSurfaceStatus( *this, state, surface, index, navDir, boundaryTolerance, @@ -430,6 +434,7 @@ class StraightLineStepper { Vector3 dir = direction(state.stepping); state.stepping.pars.template segment<3>(eFreePos0) += h * dir; state.stepping.pars[eFreeTime] += h * dtds; + // Propagate the jacobian if (state.stepping.covTransport) { // The step transport matrix in global coordinates @@ -450,7 +455,14 @@ class StraightLineStepper { ++state.stepping.nSteps; ++state.stepping.nStepTrials; - // return h + ++state.stepping.statistics.nAttemptedSteps; + ++state.stepping.statistics.nSuccessfulSteps; + if (state.options.direction != Direction::fromScalarZeroAsPositive(h)) { + ++state.stepping.statistics.nReverseSteps; + } + state.stepping.statistics.pathLength += h; + state.stepping.statistics.absolutePathLength += std::abs(h); + return h; } }; diff --git a/Core/include/Acts/Propagator/SympyStepper.hpp b/Core/include/Acts/Propagator/SympyStepper.hpp index 1e771a53ba7..7d30c24b431 100644 --- a/Core/include/Acts/Propagator/SympyStepper.hpp +++ b/Core/include/Acts/Propagator/SympyStepper.hpp @@ -22,6 +22,7 @@ #include "Acts/Propagator/ConstrainedStep.hpp" #include "Acts/Propagator/PropagatorTraits.hpp" #include "Acts/Propagator/StepperOptions.hpp" +#include "Acts/Propagator/StepperStatistics.hpp" #include "Acts/Propagator/detail/SteppingHelper.hpp" namespace Acts { @@ -132,15 +133,8 @@ class SympyStepper { /// The geometry context std::reference_wrapper geoContext; - /// @brief Storage of magnetic field and the sub steps during a RKN4 step - struct { - /// Magnetic field evaulations - Vector3 B_first, B_middle, B_last; - /// k_i of the RKN4 algorithm - Vector3 k1, k2, k3, k4; - /// k_i elements of the momenta - std::array kQoP{}; - } stepData; + /// Statistics of the stepper + StepperStatistics statistics; }; /// Constructor requires knowledge of the detector's magnetic field @@ -243,10 +237,10 @@ class SympyStepper { /// @param [in] boundaryTolerance The boundary check for this status update /// @param [in] surfaceTolerance Surface tolerance used for intersection /// @param [in] logger A @c Logger instance - Intersection3D::Status updateSurfaceStatus( + IntersectionStatus updateSurfaceStatus( State& state, const Surface& surface, std::uint8_t index, Direction navDir, const BoundaryTolerance& boundaryTolerance, - ActsScalar surfaceTolerance = s_onSurfaceTolerance, + double surfaceTolerance = s_onSurfaceTolerance, const Logger& logger = getDummyLogger()) const { return detail::updateSingleSurfaceStatus( *this, state, surface, index, navDir, boundaryTolerance, diff --git a/Core/include/Acts/Propagator/TryAllNavigator.hpp b/Core/include/Acts/Propagator/TryAllNavigator.hpp index 83d7cbc64a4..7470fa0da0c 100644 --- a/Core/include/Acts/Propagator/TryAllNavigator.hpp +++ b/Core/include/Acts/Propagator/TryAllNavigator.hpp @@ -14,6 +14,7 @@ #include "Acts/Geometry/TrackingVolume.hpp" #include "Acts/Propagator/ConstrainedStep.hpp" #include "Acts/Propagator/NavigatorOptions.hpp" +#include "Acts/Propagator/NavigatorStatistics.hpp" #include "Acts/Propagator/detail/NavigationHelpers.hpp" #include "Acts/Surfaces/BoundaryTolerance.hpp" #include "Acts/Surfaces/Surface.hpp" @@ -86,6 +87,9 @@ class TryAllNavigatorBase { bool targetReached = false; /// If a break has been detected bool navigationBreak = false; + + /// Navigation statistics + NavigatorStatistics statistics; }; /// Constructor with configuration object @@ -430,7 +434,7 @@ class TryAllNavigator : public TryAllNavigatorBase { const auto& intersection = candidate.intersection; const Surface& surface = *intersection.object(); - Intersection3D::Status surfaceStatus = stepper.updateSurfaceStatus( + IntersectionStatus surfaceStatus = stepper.updateSurfaceStatus( state.stepping, surface, intersection.index(), state.options.direction, BoundaryTolerance::Infinite(), state.options.surfaceTolerance, logger()); @@ -459,7 +463,7 @@ class TryAllNavigator : public TryAllNavigatorBase { const auto& intersection = candidate.intersection; const Surface& surface = *intersection.object(); - Intersection3D::Status surfaceStatus = stepper.updateSurfaceStatus( + IntersectionStatus surfaceStatus = stepper.updateSurfaceStatus( state.stepping, surface, intersection.index(), state.options.direction, BoundaryTolerance::None(), state.options.surfaceTolerance, logger()); @@ -784,7 +788,7 @@ class TryAllOverstepNavigator : public TryAllNavigatorBase { const auto& intersection = candidate.intersection; const Surface& surface = *intersection.object(); - Intersection3D::Status surfaceStatus = stepper.updateSurfaceStatus( + IntersectionStatus surfaceStatus = stepper.updateSurfaceStatus( state.stepping, surface, intersection.index(), state.options.direction, BoundaryTolerance::Infinite(), state.options.surfaceTolerance, logger()); @@ -811,7 +815,7 @@ class TryAllOverstepNavigator : public TryAllNavigatorBase { const auto& intersection = candidate.intersection; const Surface& surface = *intersection.object(); - Intersection3D::Status surfaceStatus = stepper.updateSurfaceStatus( + IntersectionStatus surfaceStatus = stepper.updateSurfaceStatus( state.stepping, surface, intersection.index(), state.options.direction, BoundaryTolerance::None(), state.options.surfaceTolerance, logger()); diff --git a/Core/include/Acts/Propagator/VoidNavigator.hpp b/Core/include/Acts/Propagator/VoidNavigator.hpp index d6732998d4b..6b461f79210 100644 --- a/Core/include/Acts/Propagator/VoidNavigator.hpp +++ b/Core/include/Acts/Propagator/VoidNavigator.hpp @@ -9,6 +9,7 @@ #pragma once #include "Acts/Propagator/NavigatorOptions.hpp" +#include "Acts/Propagator/NavigatorStatistics.hpp" namespace Acts { class Surface; @@ -30,6 +31,9 @@ struct VoidNavigator { /// @brief Nested State struct, minimal requirement struct State { Options options; + + /// Navigation statistics + NavigatorStatistics statistics; }; State makeState(const Options& options) const { diff --git a/Core/include/Acts/Propagator/detail/NavigationHelpers.hpp b/Core/include/Acts/Propagator/detail/NavigationHelpers.hpp index 16e8c089e4f..8965dacae45 100644 --- a/Core/include/Acts/Propagator/detail/NavigationHelpers.hpp +++ b/Core/include/Acts/Propagator/detail/NavigationHelpers.hpp @@ -36,7 +36,7 @@ struct NavigationObjectCandidate { std::pair intersect( const GeometryContext& gctx, const Vector3& position, - const Vector3& direction, ActsScalar tolerance) const { + const Vector3& direction, double tolerance) const { if (std::holds_alternative(object)) { const auto& surface = std::get(object); auto intersection = representation->intersect( diff --git a/Core/include/Acts/Propagator/detail/SteppingHelper.hpp b/Core/include/Acts/Propagator/detail/SteppingHelper.hpp index c78f0ea1f51..5c79b4f9f0e 100644 --- a/Core/include/Acts/Propagator/detail/SteppingHelper.hpp +++ b/Core/include/Acts/Propagator/detail/SteppingHelper.hpp @@ -32,10 +32,10 @@ namespace Acts::detail { /// @param surface [in] The surface provided /// @param boundaryTolerance [in] The boundary check for this status update template -Acts::Intersection3D::Status updateSingleSurfaceStatus( +Acts::IntersectionStatus updateSingleSurfaceStatus( const stepper_t& stepper, typename stepper_t::State& state, const Surface& surface, std::uint8_t index, Direction navDir, - const BoundaryTolerance& boundaryTolerance, ActsScalar surfaceTolerance, + const BoundaryTolerance& boundaryTolerance, double surfaceTolerance, const Logger& logger) { ACTS_VERBOSE("Update single surface status for surface: " << surface.geometryId() << " index " << static_cast(index)); @@ -46,11 +46,11 @@ Acts::Intersection3D::Status updateSingleSurfaceStatus( surfaceTolerance)[index]; // The intersection is on surface already - if (sIntersection.status() == Intersection3D::Status::onSurface) { + if (sIntersection.status() == IntersectionStatus::onSurface) { // Release navigation step size state.stepSize.release(ConstrainedStep::actor); ACTS_VERBOSE("Intersection: state is ON SURFACE"); - return Intersection3D::Status::onSurface; + return IntersectionStatus::onSurface; } const double nearLimit = std::numeric_limits::lowest(); @@ -62,11 +62,11 @@ Acts::Intersection3D::Status updateSingleSurfaceStatus( ACTS_VERBOSE("Surface is reachable"); stepper.updateStepSize(state, sIntersection.pathLength(), ConstrainedStep::actor); - return Intersection3D::Status::reachable; + return IntersectionStatus::reachable; } ACTS_VERBOSE("Surface is NOT reachable"); - return Intersection3D::Status::unreachable; + return IntersectionStatus::unreachable; } /// Update the Step size - single component diff --git a/Core/include/Acts/Seeding/EstimateTrackParamsFromSeed.hpp b/Core/include/Acts/Seeding/EstimateTrackParamsFromSeed.hpp index c59a55ad533..e4618296b50 100644 --- a/Core/include/Acts/Seeding/EstimateTrackParamsFromSeed.hpp +++ b/Core/include/Acts/Seeding/EstimateTrackParamsFromSeed.hpp @@ -8,17 +8,14 @@ #pragma once +#include "Acts/Definitions/Algebra.hpp" #include "Acts/Definitions/TrackParametrization.hpp" #include "Acts/Definitions/Units.hpp" #include "Acts/Geometry/GeometryContext.hpp" #include "Acts/Surfaces/Surface.hpp" -#include "Acts/Utilities/Logger.hpp" -#include "Acts/Utilities/MathHelpers.hpp" #include "Acts/Utilities/Zip.hpp" #include -#include -#include #include #include @@ -27,17 +24,16 @@ namespace Acts { /// Estimate the full track parameters from three space points /// /// This method is based on the conformal map transformation. It estimates the -/// full free track parameters, i.e. (x, y, z, t, dx, dy, dz, q/p) at the -/// bottom space point. The bottom space is assumed to be the first element -/// in the range defined by the iterators. The magnetic field (which might be -/// along any direction) is also necessary for the momentum estimation. +/// full free track parameters, i.e. (x, y, z, t, dx, dy, dz, q/p) at the bottom +/// space point. The bottom space is assumed to be the first element in the +/// range defined by the iterators. The magnetic field (which might be along any +/// direction) is also necessary for the momentum estimation. /// /// This is a purely spatial estimation, i.e. the time parameter will be set to /// 0. /// -/// It resembles the method used in ATLAS for the track parameters -/// estimated from seed, i.e. the function InDet::SiTrackMaker_xk::getAtaPlane -/// here: +/// It resembles the method used in ATLAS for the track parameters estimated +/// from seed, i.e. the function InDet::SiTrackMaker_xk::getAtaPlane here: /// https://acode-browser.usatlas.bnl.gov/lxr/source/athena/InnerDetector/InDetRecTools/SiTrackMakerTool_xk/src/SiTrackMaker_xk.cxx /// /// @tparam spacepoint_iterator_t The type of space point iterator @@ -55,14 +51,13 @@ FreeVector estimateTrackParamsFromSeed(const Vector3& sp0, const Vector3& sp1, /// Estimate the full track parameters from three space points /// /// This method is based on the conformal map transformation. It estimates the -/// full free track parameters, i.e. (x, y, z, t, dx, dy, dz, q/p) at the -/// bottom space point. The bottom space is assumed to be the first element -/// in the range defined by the iterators. The magnetic field (which might be -/// along any direction) is also necessary for the momentum estimation. +/// full free track parameters, i.e. (x, y, z, t, dx, dy, dz, q/p) at the bottom +/// space point. The bottom space is assumed to be the first element in the +/// range defined by the iterators. The magnetic field (which might be along any +/// direction) is also necessary for the momentum estimation. /// -/// It resembles the method used in ATLAS for the track parameters -/// estimated from seed, i.e. the function InDet::SiTrackMaker_xk::getAtaPlane -/// here: +/// It resembles the method used in ATLAS for the track parameters estimated +/// from seed, i.e. the function InDet::SiTrackMaker_xk::getAtaPlane here: /// https://acode-browser.usatlas.bnl.gov/lxr/source/athena/InnerDetector/InDetRecTools/SiTrackMakerTool_xk/src/SiTrackMaker_xk.cxx /// /// @tparam spacepoint_iterator_t The type of space point iterator @@ -107,150 +102,53 @@ FreeVector estimateTrackParamsFromSeed(spacepoint_range_t spRange, /// This method is based on the conformal map transformation. It estimates the /// full bound track parameters, i.e. (loc0, loc1, phi, theta, q/p, t) at the /// bottom space point. The bottom space is assumed to be the first element -/// in the range defined by the iterators. It must lie on the surface -/// provided for the representation of the bound track parameters. The magnetic -/// field (which might be along any direction) is also necessary for the -/// momentum estimation. +/// in the range defined by the iterators. It must lie on the surface provided +/// for the representation of the bound track parameters. The magnetic field +/// (which might be along any direction) is also necessary for the momentum +/// estimation. /// -/// It resembles the method used in ATLAS for the track parameters -/// estimated from seed, i.e. the function InDet::SiTrackMaker_xk::getAtaPlane -/// here: +/// It resembles the method used in ATLAS for the track parameters estimated +/// from seed, i.e. the function InDet::SiTrackMaker_xk::getAtaPlane here: /// https://acode-browser.usatlas.bnl.gov/lxr/source/athena/InnerDetector/InDetRecTools/SiTrackMakerTool_xk/src/SiTrackMaker_xk.cxx /// /// @tparam spacepoint_iterator_t The type of space point iterator /// /// @param gctx is the geometry context -/// @param spBegin is the begin iterator for the space points -/// @param spEnd is the end iterator for the space points +/// @param spRange is the range of space points /// @param surface is the surface of the bottom space point. The estimated bound /// track parameters will be represented also at this surface /// @param bField is the magnetic field vector -/// @param logger A logger instance /// -/// @return optional bound parameters -template -std::optional estimateTrackParamsFromSeed( - const GeometryContext& gctx, spacepoint_iterator_t spBegin, - spacepoint_iterator_t spEnd, const Surface& surface, const Vector3& bField, - const Acts::Logger& logger = getDummyLogger()) { - // Check the number of provided space points - std::size_t numSP = std::distance(spBegin, spEnd); - if (numSP != 3) { - ACTS_ERROR("There should be exactly three space points provided."); - return std::nullopt; - } - - // The global positions of the bottom, middle and space points - std::array spGlobalPositions = {Vector3::Zero(), Vector3::Zero(), - Vector3::Zero()}; - std::array, 3> spGlobalTimes = { - std::nullopt, std::nullopt, std::nullopt}; - // The first, second and third space point are assumed to be bottom, middle - // and top space point, respectively - for (std::size_t isp = 0; isp < 3; ++isp) { - spacepoint_iterator_t it = std::next(spBegin, isp); - if (*it == nullptr) { - ACTS_ERROR("Empty space point found. This should not happen."); - return std::nullopt; - } - const auto& sp = *it; - spGlobalPositions[isp] = Vector3(sp->x(), sp->y(), sp->z()); - spGlobalTimes[isp] = sp->t(); - } - - // Define a new coordinate frame with its origin at the bottom space point, z - // axis long the magnetic field direction and y axis perpendicular to vector - // from the bottom to middle space point. Hence, the projection of the middle - // space point on the transverse plane will be located at the x axis of the - // new frame. - Vector3 relVec = spGlobalPositions[1] - spGlobalPositions[0]; - Vector3 newZAxis = bField.normalized(); - Vector3 newYAxis = newZAxis.cross(relVec).normalized(); - Vector3 newXAxis = newYAxis.cross(newZAxis); - RotationMatrix3 rotation; - rotation.col(0) = newXAxis; - rotation.col(1) = newYAxis; - rotation.col(2) = newZAxis; - // The center of the new frame is at the bottom space point - Translation3 trans(spGlobalPositions[0]); - // The transform which constructs the new frame - Transform3 transform(trans * rotation); - - // The coordinate of the middle and top space point in the new frame - Vector3 local1 = transform.inverse() * spGlobalPositions[1]; - Vector3 local2 = transform.inverse() * spGlobalPositions[2]; - - // In the new frame the bottom sp is at the origin, while the middle - // sp in along the x axis. As such, the x-coordinate of the circle is - // at: x-middle / 2. - // The y coordinate can be found by using the straight line passing - // between the mid point between the middle and top sp and perpendicular to - // the line connecting them - Vector2 circleCenter; - circleCenter(0) = 0.5 * local1(0); +/// @return bound parameters +template +Result estimateTrackParamsFromSeed(const GeometryContext& gctx, + spacepoint_range_t spRange, + const Surface& surface, + const Vector3& bField) { + FreeVector freeParams = estimateTrackParamsFromSeed(spRange, bField); - ActsScalar deltaX21 = local2(0) - local1(0); - ActsScalar sumX21 = local2(0) + local1(0); - // straight line connecting the two points - // y = a * x + c (we don't care about c right now) - // we simply need the slope - // we compute 1./a since this is what we need for the following computation - ActsScalar ia = deltaX21 / local2(1); - // Perpendicular line is then y = -1/a *x + b - // we can evaluate b given we know a already by imposing - // the line passes through P = (0.5 * (x2 + x1), 0.5 * y2) - ActsScalar b = 0.5 * (local2(1) + ia * sumX21); - circleCenter(1) = -ia * circleCenter(0) + b; - // Radius is a signed distance between circleCenter and first sp, which is at - // (0, 0) in the new frame. Sign depends on the slope a (positive vs negative) - int sign = ia > 0 ? -1 : 1; - const ActsScalar R = circleCenter.norm(); - ActsScalar invTanTheta = - local2.z() / (2 * R * std::asin(local2.head<2>().norm() / (2 * R))); - // The momentum direction in the new frame (the center of the circle has the - // coordinate (-1.*A/(2*B), 1./(2*B))) - ActsScalar A = -circleCenter(0) / circleCenter(1); - Vector3 transDirection(1., A, fastHypot(1, A) * invTanTheta); - // Transform it back to the original frame - Vector3 direction = rotation * transDirection.normalized(); + const auto* sp0 = *spRange.begin(); + Vector3 origin = Vector3(sp0->x(), sp0->y(), sp0->z()); + Vector3 direction = freeParams.segment<3>(eFreeDir0); - // Initialize the bound parameters vector BoundVector params = BoundVector::Zero(); - - // The estimated phi and theta params[eBoundPhi] = VectorHelpers::phi(direction); params[eBoundTheta] = VectorHelpers::theta(direction); + params[eBoundQOverP] = freeParams[eFreeQOverP]; // Transform the bottom space point to local coordinates of the provided // surface - auto lpResult = surface.globalToLocal(gctx, spGlobalPositions[0], direction); + auto lpResult = surface.globalToLocal(gctx, origin, direction); if (!lpResult.ok()) { - ACTS_ERROR( - "Global to local transformation did not succeed. Please make sure the " - "bottom space point lies on the provided surface."); - return std::nullopt; + return Result::failure(lpResult.error()); } Vector2 bottomLocalPos = lpResult.value(); // The estimated loc0 and loc1 params[eBoundLoc0] = bottomLocalPos.x(); params[eBoundLoc1] = bottomLocalPos.y(); - params[eBoundTime] = spGlobalTimes[0].value_or(0.); - - ActsScalar bFieldStrength = bField.norm(); - // The estimated q/pt in [GeV/c]^-1 (note that the pt is the projection of - // momentum on the transverse plane of the new frame) - ActsScalar qOverPt = sign / (bFieldStrength * R); - // The estimated q/p in [GeV/c]^-1 - params[eBoundQOverP] = qOverPt / fastHypot(1., invTanTheta); + params[eBoundTime] = sp0->t().value_or(0); - if (params.hasNaN()) { - ACTS_ERROR( - "The NaN value exists at the estimated track parameters from seed with" - << "\nbottom sp: " << spGlobalPositions[0] << "\nmiddle sp: " - << spGlobalPositions[1] << "\ntop sp: " << spGlobalPositions[2]); - return std::nullopt; - } - return params; + return Result::success(params); } /// Configuration for the estimation of the covariance matrix of the track diff --git a/Core/include/Acts/Seeding/GbtsDataStorage.hpp b/Core/include/Acts/Seeding/GbtsDataStorage.hpp index c28b0cc2413..8c7ba861bcd 100644 --- a/Core/include/Acts/Seeding/GbtsDataStorage.hpp +++ b/Core/include/Acts/Seeding/GbtsDataStorage.hpp @@ -13,6 +13,7 @@ #include "Acts/Seeding/GbtsGeometry.hpp" #include +#include #include #include #include @@ -47,13 +48,6 @@ struct GbtsSP { template class GbtsNode { public: - struct CompareByPhi { - bool operator()(const GbtsNode *n1, - const GbtsNode *n2) { - return (n1->m_spGbts.phi() < n2->m_spGbts.phi()); - } - }; - GbtsNode(const GbtsSP &spGbts, float minT = -100.0, float maxT = 100.0) : m_spGbts(spGbts), m_minCutOnTau(minT), m_maxCutOnTau(maxT) {} @@ -97,27 +91,20 @@ class GbtsEtaBin { public: GbtsEtaBin() { m_vn.clear(); } - ~GbtsEtaBin() { - for (typename std::vector *>::iterator it = - m_vn.begin(); - it != m_vn.end(); ++it) { - delete (*it); - } - } - void sortByPhi() { - std::ranges::sort(m_vn, - typename Acts::GbtsNode::CompareByPhi()); + std::ranges::sort(m_vn, [](const auto &n1, const auto &n2) { + return (n1->m_spGbts.phi() < n2->m_spGbts.phi()); + }); } bool empty() const { return m_vn.empty(); } void generatePhiIndexing(float dphi) { for (unsigned int nIdx = 0; nIdx < m_vn.size(); nIdx++) { - GbtsNode *pN = m_vn.at(nIdx); + GbtsNode &pN = *m_vn.at(nIdx); // float phi = pN->m_sp.phi(); // float phi = (std::atan(pN->m_sp.x() / pN->m_sp.y())); - float phi = pN->m_spGbts.phi(); + float phi = pN.m_spGbts.phi(); if (phi <= std::numbers::pi_v - dphi) { continue; } @@ -127,14 +114,14 @@ class GbtsEtaBin { } for (unsigned int nIdx = 0; nIdx < m_vn.size(); nIdx++) { - GbtsNode *pN = m_vn.at(nIdx); - float phi = pN->m_spGbts.phi(); + GbtsNode &pN = *m_vn.at(nIdx); + float phi = pN.m_spGbts.phi(); m_vPhiNodes.push_back(std::pair(phi, nIdx)); } for (unsigned int nIdx = 0; nIdx < m_vn.size(); nIdx++) { - GbtsNode *pN = m_vn.at(nIdx); - float phi = pN->m_spGbts.phi(); + GbtsNode &pN = *m_vn.at(nIdx); + float phi = pN.m_spGbts.phi(); if (phi >= -std::numbers::pi_v + dphi) { break; } @@ -143,9 +130,7 @@ class GbtsEtaBin { } } - std::vector *> m_vn; - // TODO change to - // std::vector>> m_vn; + std::vector>> m_vn; std::vector> m_vPhiNodes; }; @@ -186,8 +171,9 @@ class GbtsDataStorage { 1.6 + 0.15 / (cluster_width + 0.2) + 6.1 * (cluster_width - 0.2); } - m_etaBins.at(binIndex).m_vn.push_back(new GbtsNode( - sp, min_tau, max_tau)); // adding ftf member to nodes + m_etaBins.at(binIndex).m_vn.push_back( + std::make_unique>( + sp, min_tau, max_tau)); // adding ftf member to nodes } else { if (useClusterWidth) { float cluster_width = 1; // temporary while cluster width not available @@ -195,7 +181,8 @@ class GbtsDataStorage { return -3; } } - m_etaBins.at(binIndex).m_vn.push_back(new GbtsNode(sp)); + m_etaBins.at(binIndex).m_vn.push_back( + std::make_unique>(sp)); } return 0; @@ -218,16 +205,14 @@ class GbtsDataStorage { vn.clear(); vn.reserve(numberOfNodes()); for (const auto &b : m_etaBins) { - for (typename std::vector *>::const_iterator nIt = - b.m_vn.begin(); - nIt != b.m_vn.end(); ++nIt) { - if ((*nIt)->m_in.empty()) { + for (const auto &n : b.m_vn) { + if (n->m_in.empty()) { continue; } - if ((*nIt)->m_out.empty()) { + if (n->m_out.empty()) { continue; } - vn.push_back(*nIt); + vn.push_back(n.get()); } } } diff --git a/Core/include/Acts/Seeding/GbtsGeometry.hpp b/Core/include/Acts/Seeding/GbtsGeometry.hpp index 54931b200b8..cc1af647d28 100644 --- a/Core/include/Acts/Seeding/GbtsGeometry.hpp +++ b/Core/include/Acts/Seeding/GbtsGeometry.hpp @@ -13,6 +13,7 @@ #include #include +#include #include #include #include @@ -277,15 +278,10 @@ class GbtsGeometry { // calculating bin tables in the connector... - for (std::map>::const_iterator it = - m_connector->m_connMap.begin(); - it != m_connector->m_connMap.end(); ++it) { - const std::vector &vConn = (*it).second; - - for (std::vector::const_iterator cIt = vConn.begin(); - cIt != vConn.end(); ++cIt) { - unsigned int src = (*cIt)->m_src; // n2 : the new connectors - unsigned int dst = (*cIt)->m_dst; // n1 + for (auto &[_, vConn] : m_connector->m_connMap) { + for (auto &c : vConn) { + unsigned int src = c->m_src; // n2 : the new connectors + unsigned int dst = c->m_dst; // n1 const GbtsLayer *pL1 = getGbtsLayerByKey(dst); const GbtsLayer *pL2 = getGbtsLayerByKey(src); @@ -301,7 +297,7 @@ class GbtsGeometry { int nSrcBins = pL2->m_bins.size(); int nDstBins = pL1->m_bins.size(); - (*cIt)->m_binTable.resize(nSrcBins * nDstBins, 0); + c->m_binTable.resize(nSrcBins * nDstBins, 0); for (int b1 = 0; b1 < nDstBins; b1++) { // loop over bins in Layer 1 for (int b2 = 0; b2 < nSrcBins; b2++) { // loop over bins in Layer 2 @@ -309,7 +305,7 @@ class GbtsGeometry { continue; } int address = b1 + b2 * nDstBins; - (*cIt)->m_binTable.at(address) = 1; + c->m_binTable.at(address) = 1; } } } @@ -322,17 +318,6 @@ class GbtsGeometry { GbtsGeometry(const GbtsGeometry &) = delete; GbtsGeometry &operator=(const GbtsGeometry &) = delete; - ~GbtsGeometry() { - for (typename std::vector *>::iterator it = - m_layArray.begin(); - it != m_layArray.end(); ++it) { - delete (*it); - } - - m_layMap.clear(); - m_layArray.clear(); - } - const GbtsLayer *getGbtsLayerByKey(unsigned int key) const { typename std::map *>::const_iterator it = m_layMap.find(key); @@ -344,7 +329,7 @@ class GbtsGeometry { } const GbtsLayer *getGbtsLayerByIndex(int idx) const { - return m_layArray.at(idx); + return m_layArray.at(idx).get(); } int num_bins() const { return m_nEtaBins; } @@ -357,18 +342,19 @@ class GbtsGeometry { unsigned int layerKey = l.m_subdet; // this should be combined ID float ew = m_etaBinWidth; - GbtsLayer *pHL = new GbtsLayer(l, ew, bin0); + auto upHL = std::make_unique>(l, ew, bin0); + auto *pHL = upHL.get(); m_layMap.insert( std::pair *>(layerKey, pHL)); - m_layArray.push_back(pHL); + m_layArray.push_back(std::move(upHL)); return pHL; } float m_etaBinWidth{}; std::map *> m_layMap; - std::vector *> m_layArray; + std::vector>> m_layArray; int m_nEtaBins{0}; diff --git a/Core/include/Acts/Seeding/PathSeeder.hpp b/Core/include/Acts/Seeding/PathSeeder.hpp index d4475c022df..87ceda365c8 100644 --- a/Core/include/Acts/Seeding/PathSeeder.hpp +++ b/Core/include/Acts/Seeding/PathSeeder.hpp @@ -81,7 +81,7 @@ class PathSeeder { /// /// @return The path width in the bin0 and bin1 direction /// defined with respect to the surface normal - using PathWidthLookup = Delegate( + using PathWidthLookup = Delegate( const GeometryContext&, const GeometryIdentifier&)>; /// @brief The nested configuration struct @@ -146,10 +146,10 @@ class PathSeeder { m_cfg.pathWidthProvider(gctx, geoId); // Get the bounds of the path - ActsScalar top0 = refPoint[0] + pathWidth0; - ActsScalar bot0 = refPoint[0] - pathWidth0; - ActsScalar top1 = refPoint[1] + pathWidth1; - ActsScalar bot1 = refPoint[1] - pathWidth1; + double top0 = refPoint[0] + pathWidth0; + double bot0 = refPoint[0] - pathWidth0; + double top1 = refPoint[1] + pathWidth1; + double bot1 = refPoint[1] - pathWidth1; // Get the lookup table for the source links auto grid = sourceLinkGridLookup.at(geoId); diff --git a/Core/include/Acts/Seeding/SeedFinderGbts.ipp b/Core/include/Acts/Seeding/SeedFinderGbts.ipp index ed2fe157acf..fb2722db616 100644 --- a/Core/include/Acts/Seeding/SeedFinderGbts.ipp +++ b/Core/include/Acts/Seeding/SeedFinderGbts.ipp @@ -160,12 +160,7 @@ void SeedFinderGbts::runGbts_TrackFinder( } unsigned int first_it = 0; - for (typename std::vector< - GbtsNode*>::const_iterator n1It = - B1.m_vn.begin(); - n1It != B1.m_vn.end(); ++n1It) { // loop over nodes in Layer 1 - - GbtsNode* n1 = (*n1It); + for (const auto& n1 : B1.m_vn) { // loop over nodes in Layer 1 if (n1->m_in.size() >= MAX_SEG_PER_NODE) { continue; @@ -195,7 +190,7 @@ void SeedFinderGbts::runGbts_TrackFinder( } GbtsNode* n2 = - B2.m_vn.at(B2.m_vPhiNodes.at(n2PhiIdx).second); + B2.m_vn.at(B2.m_vPhiNodes.at(n2PhiIdx).second).get(); if (n2->m_out.size() >= MAX_SEG_PER_NODE) { continue; @@ -304,8 +299,8 @@ void SeedFinderGbts::runGbts_TrackFinder( float dPhi1 = std::asin(curv * r1); if (nEdges < m_config.MaxEdges) { - edgeStorage.emplace_back(n1, n2, exp_eta, curv, phi1 + dPhi1, - phi2 + dPhi2); + edgeStorage.emplace_back(n1.get(), n2, exp_eta, curv, + phi1 + dPhi1, phi2 + dPhi2); n1->addIn(nEdges); n2->addOut(nEdges); @@ -332,21 +327,20 @@ void SeedFinderGbts::runGbts_TrackFinder( int nNodes = vNodes.size(); for (int nodeIdx = 0; nodeIdx < nNodes; nodeIdx++) { - const GbtsNode* pN = vNodes.at(nodeIdx); + const GbtsNode& pN = *vNodes.at(nodeIdx); std::vector> in_sort, out_sort; - in_sort.resize(pN->m_in.size()); - out_sort.resize(pN->m_out.size()); + in_sort.resize(pN.m_in.size()); + out_sort.resize(pN.m_out.size()); - for (int inIdx = 0; inIdx < static_cast(pN->m_in.size()); inIdx++) { - int inEdgeIdx = pN->m_in.at(inIdx); + for (int inIdx = 0; inIdx < static_cast(pN.m_in.size()); inIdx++) { + int inEdgeIdx = pN.m_in.at(inIdx); Acts::GbtsEdge* pS = &(edgeStorage.at(inEdgeIdx)); in_sort[inIdx].second = inEdgeIdx; in_sort[inIdx].first = pS->m_p[0]; } - for (int outIdx = 0; outIdx < static_cast(pN->m_out.size()); - outIdx++) { - int outEdgeIdx = pN->m_out.at(outIdx); + for (int outIdx = 0; outIdx < static_cast(pN.m_out.size()); outIdx++) { + int outEdgeIdx = pN.m_out.at(outIdx); Acts::GbtsEdge* pS = &(edgeStorage.at(outEdgeIdx)); out_sort[outIdx].second = outEdgeIdx; out_sort[outIdx].first = pS->m_p[0]; diff --git a/Core/include/Acts/Seeding/SeedFinderOrthogonal.hpp b/Core/include/Acts/Seeding/SeedFinderOrthogonal.hpp index a4129fad556..29405f0e222 100644 --- a/Core/include/Acts/Seeding/SeedFinderOrthogonal.hpp +++ b/Core/include/Acts/Seeding/SeedFinderOrthogonal.hpp @@ -48,7 +48,7 @@ class SeedFinderOrthogonal { * has leaf size 4. */ using tree_t = - KDTree; + KDTree; /** * @brief Construct a new orthogonal seed finder. diff --git a/Core/include/Acts/SpacePointFormation/detail/SpacePointBuilder.ipp b/Core/include/Acts/SpacePointFormation/detail/SpacePointBuilder.ipp index 532d2c90ec7..557b005fe6d 100644 --- a/Core/include/Acts/SpacePointFormation/detail/SpacePointBuilder.ipp +++ b/Core/include/Acts/SpacePointFormation/detail/SpacePointBuilder.ipp @@ -27,9 +27,9 @@ void SpacePointBuilder::buildSpacePoint( const unsigned int num_slinks = sourceLinks.size(); Acts::Vector3 gPos = Acts::Vector3::Zero(); - std::optional gTime = std::nullopt; + std::optional gTime = std::nullopt; Acts::Vector2 gCov = Acts::Vector2::Zero(); - std::optional gCovT = std::nullopt; + std::optional gCovT = std::nullopt; if (num_slinks == 1) { // pixel SP formation auto slink = sourceLinks.at(0); diff --git a/Core/include/Acts/Surfaces/CylinderSurface.hpp b/Core/include/Acts/Surfaces/CylinderSurface.hpp index 53c52f13f50..971ff7039f7 100644 --- a/Core/include/Acts/Surfaces/CylinderSurface.hpp +++ b/Core/include/Acts/Surfaces/CylinderSurface.hpp @@ -198,7 +198,7 @@ class CylinderSurface : public RegularSurface { const Vector3& direction, const BoundaryTolerance& boundaryTolerance = BoundaryTolerance::Infinite(), - ActsScalar tolerance = s_onSurfaceTolerance) const final; + double tolerance = s_onSurfaceTolerance) const final; /// Path correction due to incident of the track /// diff --git a/Core/include/Acts/Surfaces/DiscSurface.hpp b/Core/include/Acts/Surfaces/DiscSurface.hpp index d2db14fc566..6a3144a00aa 100644 --- a/Core/include/Acts/Surfaces/DiscSurface.hpp +++ b/Core/include/Acts/Surfaces/DiscSurface.hpp @@ -294,7 +294,7 @@ class DiscSurface : public RegularSurface { const Vector3& direction, const BoundaryTolerance& boundaryTolerance = BoundaryTolerance::Infinite(), - ActsScalar tolerance = s_onSurfaceTolerance) const final; + double tolerance = s_onSurfaceTolerance) const final; /// Implement the binningValue /// diff --git a/Core/include/Acts/Surfaces/LineSurface.hpp b/Core/include/Acts/Surfaces/LineSurface.hpp index d07e9f6dc37..15af6aa6be8 100644 --- a/Core/include/Acts/Surfaces/LineSurface.hpp +++ b/Core/include/Acts/Surfaces/LineSurface.hpp @@ -248,7 +248,7 @@ class LineSurface : public Surface { const Vector3& direction, const BoundaryTolerance& boundaryTolerance = BoundaryTolerance::Infinite(), - ActsScalar tolerance = s_onSurfaceTolerance) const final; + double tolerance = s_onSurfaceTolerance) const final; /// the pathCorrection for derived classes with thickness /// is by definition 1 for LineSurfaces diff --git a/Core/include/Acts/Surfaces/PlaneSurface.hpp b/Core/include/Acts/Surfaces/PlaneSurface.hpp index 2bc65398f8d..e4fda361828 100644 --- a/Core/include/Acts/Surfaces/PlaneSurface.hpp +++ b/Core/include/Acts/Surfaces/PlaneSurface.hpp @@ -193,7 +193,7 @@ class PlaneSurface : public RegularSurface { const Vector3& direction, const BoundaryTolerance& boundaryTolerance = BoundaryTolerance::Infinite(), - ActsScalar tolerance = s_onSurfaceTolerance) const final; + double tolerance = s_onSurfaceTolerance) const final; /// Return a Polyhedron for the surfaces /// diff --git a/Core/include/Acts/Surfaces/Surface.hpp b/Core/include/Acts/Surfaces/Surface.hpp index 79153e8c98e..43d8161aa8c 100644 --- a/Core/include/Acts/Surfaces/Surface.hpp +++ b/Core/include/Acts/Surfaces/Surface.hpp @@ -399,7 +399,7 @@ class Surface : public virtual GeometryObject, const Vector3& direction, const BoundaryTolerance& boundaryTolerance = BoundaryTolerance::Infinite(), - ActsScalar tolerance = s_onSurfaceTolerance) const = 0; + double tolerance = s_onSurfaceTolerance) const = 0; /// Helper method for printing: the returned object captures the /// surface and the geometry context and will print the surface diff --git a/Core/include/Acts/Surfaces/detail/AnnulusBoundsHelper.hpp b/Core/include/Acts/Surfaces/detail/AnnulusBoundsHelper.hpp index 84f2d4ec61a..7f7db63086e 100644 --- a/Core/include/Acts/Surfaces/detail/AnnulusBoundsHelper.hpp +++ b/Core/include/Acts/Surfaces/detail/AnnulusBoundsHelper.hpp @@ -33,7 +33,7 @@ namespace detail::AnnulusBoundsHelper { /// /// @return AnnulusBounds std::tuple, Transform3> create( - const Transform3& transform, ActsScalar rMin, ActsScalar rMax, + const Transform3& transform, double rMin, double rMax, std::vector vertices); } // namespace detail::AnnulusBoundsHelper diff --git a/Core/include/Acts/Surfaces/detail/IntersectionHelper2D.hpp b/Core/include/Acts/Surfaces/detail/IntersectionHelper2D.hpp index db6860006a3..cafa4349740 100644 --- a/Core/include/Acts/Surfaces/detail/IntersectionHelper2D.hpp +++ b/Core/include/Acts/Surfaces/detail/IntersectionHelper2D.hpp @@ -37,8 +37,7 @@ struct IntersectionHelper2D { /// @param dir The Direction of intersection line /// /// @return the intersection points - static std::array intersectEllipse(ActsScalar Rx, - ActsScalar Ry, + static std::array intersectEllipse(double Rx, double Ry, const Vector2& origin, const Vector2& dir); @@ -50,7 +49,7 @@ struct IntersectionHelper2D { /// /// @return the intersection points static inline std::array intersectCircle( - ActsScalar R, const Vector2& origin, const Vector2& dir) { + double R, const Vector2& origin, const Vector2& dir) { return intersectEllipse(R, R, origin, dir); } @@ -65,8 +64,8 @@ struct IntersectionHelper2D { /// @param dir The Direction of intersection line /// /// @return the intersection points - static Intersection2D intersectCircleSegment(ActsScalar R, ActsScalar phiMin, - ActsScalar phiMax, + static Intersection2D intersectCircleSegment(double R, double phiMin, + double phiMax, const Vector2& origin, const Vector2& dir); diff --git a/Core/include/Acts/Surfaces/detail/MergeHelper.hpp b/Core/include/Acts/Surfaces/detail/MergeHelper.hpp index a0121173591..ed396c9e6ad 100644 --- a/Core/include/Acts/Surfaces/detail/MergeHelper.hpp +++ b/Core/include/Acts/Surfaces/detail/MergeHelper.hpp @@ -23,9 +23,9 @@ namespace Acts::detail { /// a half phi sector in the range [0,pi). The two /// ranges need to line up, i.e. that one of the sector /// ends exactly where the other one starts. -std::tuple mergedPhiSector( - ActsScalar hlPhi1, ActsScalar avgPhi1, ActsScalar hlPhi2, - ActsScalar avgPhi2, const Logger& logger = getDummyLogger(), - ActsScalar tolerance = s_onSurfaceTolerance); +std::tuple mergedPhiSector( + double hlPhi1, double avgPhi1, double hlPhi2, double avgPhi2, + const Logger& logger = getDummyLogger(), + double tolerance = s_onSurfaceTolerance); } // namespace Acts::detail diff --git a/Core/include/Acts/Surfaces/detail/PlanarHelper.hpp b/Core/include/Acts/Surfaces/detail/PlanarHelper.hpp index f7b21a960aa..8faa345a213 100644 --- a/Core/include/Acts/Surfaces/detail/PlanarHelper.hpp +++ b/Core/include/Acts/Surfaces/detail/PlanarHelper.hpp @@ -23,21 +23,20 @@ namespace Acts::PlanarHelper { /// @return The intersection inline Intersection3D intersect(const Transform3& transform, const Vector3& position, - const Vector3& direction, - ActsScalar tolerance) { + const Vector3& direction, double tolerance) { // Get the matrix from the transform (faster access) const auto& tMatrix = transform.matrix(); const Vector3 pnormal = tMatrix.block<3, 1>(0, 2).transpose(); const Vector3 pcenter = tMatrix.block<3, 1>(0, 3).transpose(); // It is solvable, so go on - ActsScalar denom = direction.dot(pnormal); + double denom = direction.dot(pnormal); if (denom != 0.0) { // Translate that into a path - ActsScalar path = (pnormal.dot((pcenter - position))) / (denom); + double path = (pnormal.dot((pcenter - position))) / (denom); // Is valid hence either on surface or reachable - Intersection3D::Status status = std::abs(path) < std::abs(tolerance) - ? Intersection3D::Status::onSurface - : Intersection3D::Status::reachable; + IntersectionStatus status = std::abs(path) < std::abs(tolerance) + ? IntersectionStatus::onSurface + : IntersectionStatus::reachable; // Return the intersection return Intersection3D{(position + path * direction), path, status}; } diff --git a/Core/include/Acts/Surfaces/detail/VerticesHelper.hpp b/Core/include/Acts/Surfaces/detail/VerticesHelper.hpp index 4384c17139c..24373a59c5c 100644 --- a/Core/include/Acts/Surfaces/detail/VerticesHelper.hpp +++ b/Core/include/Acts/Surfaces/detail/VerticesHelper.hpp @@ -30,11 +30,10 @@ namespace Acts::detail::VerticesHelper { /// @param quarterSegments number of segments used to approximate a segment quarter /// /// @return a vector of generated phi values -std::vector phiSegments( - ActsScalar phiMin = -std::numbers::pi_v, - ActsScalar phiMax = std::numbers::pi_v, - const std::vector& phiRefs = {}, - unsigned int quarterSegments = 2u); +std::vector phiSegments(double phiMin = -std::numbers::pi, + double phiMax = std::numbers::pi, + const std::vector& phiRefs = {}, + unsigned int quarterSegments = 2u); /// Helper method to create a regular 2 or 3 D segment /// between two phi values with a given number of segments @@ -56,15 +55,14 @@ std::vector phiSegments( /// @return a vector of vertices template std::vector segmentVertices( - std::pair rXY, ActsScalar phiMin, ActsScalar phiMax, - const std::vector& phiRefs = {}, - unsigned int quarterSegments = 2u, + std::pair rXY, double phiMin, double phiMax, + const std::vector& phiRefs = {}, unsigned int quarterSegments = 2u, const vertex_t& offset = vertex_t::Zero(), const transform_t& transform = transform_t::Identity()) { std::vector vertices; - std::vector phis = + std::vector phis = phiSegments(phiMin, phiMax, phiRefs, quarterSegments); - for (ActsScalar phi : phis) { + for (double phi : phis) { vertex_t vertex = vertex_t::Zero(); vertex(0) = rXY.first * std::cos(phi); vertex(1) = rXY.second * std::sin(phi); @@ -85,11 +83,11 @@ std::vector segmentVertices( /// @param quarterSegments number of segments used to approximate a segment quarter /// /// @return a vector of 2d-vectors -std::vector ellipsoidVertices( - ActsScalar innerRx, ActsScalar innerRy, ActsScalar outerRx, - ActsScalar outerRy, ActsScalar avgPhi = 0., - ActsScalar halfPhi = std::numbers::pi_v, - unsigned int quarterSegments = 2u); +std::vector ellipsoidVertices(double innerRx, double innerRy, + double outerRx, double outerRy, + double avgPhi = 0., + double halfPhi = std::numbers::pi, + unsigned int quarterSegments = 2u); /// Construct vertices on an disc/wheel-like bound object. /// @@ -100,10 +98,10 @@ std::vector ellipsoidVertices( /// @param quarterSegments number of segments used to approximate a segment quarter /// /// @return a vector of 2d-vectors -std::vector circularVertices( - ActsScalar innerR, ActsScalar outerR, ActsScalar avgPhi = 0., - ActsScalar halfPhi = std::numbers::pi_v, - unsigned int quarterSegments = 2u); +std::vector circularVertices(double innerR, double outerR, + double avgPhi = 0., + double halfPhi = std::numbers::pi, + unsigned int quarterSegments = 2u); /// Check if the point is inside the polygon w/o any tolerances. /// @@ -174,7 +172,7 @@ bool isInsideRectangle(const vertex_t& point, const vertex_t& lowerLeft, /// @param tolerance The allowed out of plane tolerance /// @return boolean to indicate if all points are inside/outside bool onHyperPlane(const std::vector& vertices, - ActsScalar tolerance = s_onSurfaceTolerance); + double tolerance = s_onSurfaceTolerance); /// Calculate the closest point on the polygon. inline Vector2 computeClosestPointOnPolygon(const Vector2& point, diff --git a/Core/include/Acts/TrackFinding/CombinatorialKalmanFilter.hpp b/Core/include/Acts/TrackFinding/CombinatorialKalmanFilter.hpp index 35acbc49feb..90a7ab5f134 100644 --- a/Core/include/Acts/TrackFinding/CombinatorialKalmanFilter.hpp +++ b/Core/include/Acts/TrackFinding/CombinatorialKalmanFilter.hpp @@ -464,7 +464,6 @@ class CombinatorialKalmanFilter { } // either copy ALL or everything except for predicted and jacobian - trackState.allocateCalibrated(candidateTrackState.calibratedSize()); trackState.copyFrom(candidateTrackState, mask, false); auto typeFlags = trackState.typeFlags(); @@ -739,7 +738,7 @@ class CombinatorialKalmanFilter { slRange = m_sourceLinkAccessor(*surface); hasMeasurements = slRange->first != slRange->second; } - bool isHole = isSensitive && !hasMeasurements; + bool isHole = isSensitive && expectMeasurements && !hasMeasurements; if (isHole) { ACTS_VERBOSE("Detected hole before measurement selection on surface " @@ -747,7 +746,7 @@ class CombinatorialKalmanFilter { } // Transport the covariance to the surface - if (isHole || isMaterialOnly) { + if (isMaterialOnly) { stepper.transportCovarianceToCurvilinear(state.stepping); } else { stepper.transportCovarianceToBound(state.stepping, *surface); diff --git a/Core/include/Acts/TrackFinding/GbtsConnector.hpp b/Core/include/Acts/TrackFinding/GbtsConnector.hpp index f4cddd2527b..d4724929ac2 100644 --- a/Core/include/Acts/TrackFinding/GbtsConnector.hpp +++ b/Core/include/Acts/TrackFinding/GbtsConnector.hpp @@ -11,8 +11,8 @@ // TODO: update to C++17 style // Consider to moving to detail subdirectory #include -#include #include +#include #include namespace Acts { @@ -39,15 +39,10 @@ class GbtsConnector { GbtsConnector(std::ifstream &inFile); - ~GbtsConnector(); - float m_etaBin{}; std::map> m_layerGroups; - std::map> m_connMap; - // TODO: change to std::map > - // m_connMap; or std::map> > m_connMap; + std::map>> m_connMap; }; } // namespace Acts diff --git a/Core/include/Acts/TrackFinding/MeasurementSelector.ipp b/Core/include/Acts/TrackFinding/MeasurementSelector.ipp index 30d09c002be..5e13ffd904a 100644 --- a/Core/include/Acts/TrackFinding/MeasurementSelector.ipp +++ b/Core/include/Acts/TrackFinding/MeasurementSelector.ipp @@ -63,7 +63,7 @@ MeasurementSelector::select( trackState.effectiveCalibrated().data(), trackState.effectiveCalibratedCovariance().data(), trackState.predicted(), trackState.predictedCovariance(), - trackState.boundSubspaceIndices(), trackState.calibratedSize()); + trackState.projectorSubspaceIndices(), trackState.calibratedSize()); trackState.chi2() = chi2; if (chi2 < minChi2) { diff --git a/Core/include/Acts/TrackFinding/TrackParamsLookupAccumulator.hpp b/Core/include/Acts/TrackFinding/TrackParamsLookupAccumulator.hpp new file mode 100644 index 00000000000..a1e1173335d --- /dev/null +++ b/Core/include/Acts/TrackFinding/TrackParamsLookupAccumulator.hpp @@ -0,0 +1,179 @@ +// 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/detail/TrackParametersUtils.hpp" +#include "Acts/Geometry/GeometryContext.hpp" + +#include +#include +#include +#include +#include + +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 = typename std::pointer_traits< + typename grid_t::value_type::first_type>::element_type; + + /// @brief Constructor + explicit TrackParamsLookupAccumulator(grid_t grid) + : m_grid(std::move(grid)) {} + + /// @brief Add track parameters to the accumulator + /// + /// @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) { + std::lock_guard lock(m_gridMutex); + + 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 (detail::isGenericBoundTrackParams) { + 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 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 (detail::isGenericBoundTrackParams) { + 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 (detail::isGenericBoundTrackParams) { + 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::runtime_error("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; + + /// 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; +}; + +} // namespace Acts diff --git a/Core/include/Acts/TrackFinding/TrackSelector.hpp b/Core/include/Acts/TrackFinding/TrackSelector.hpp index 5a2cf53df27..fe4287a38b0 100644 --- a/Core/include/Acts/TrackFinding/TrackSelector.hpp +++ b/Core/include/Acts/TrackFinding/TrackSelector.hpp @@ -80,6 +80,10 @@ class TrackSelector { std::size_t maxSharedHits = std::numeric_limits::max(); double maxChi2 = inf; + /// Whether a reference surface is required for the track + /// If false, the parameter cuts are not evaluated + bool requireReferenceSurface = true; + // Defaults to: no cut MeasurementCounter measurementCounter; @@ -447,22 +451,33 @@ bool TrackSelector::isValidTrack(const track_proxy_t& track) const { const Config& cuts = *cutsPtr; - return track.hasReferenceSurface() && - within(track.transverseMomentum(), cuts.ptMin, cuts.ptMax) && - (!m_isUnbinned || (within(absEta(), cuts.absEtaMin, cuts.absEtaMax) && - within(_eta, cuts.etaMin, cuts.etaMax))) && - within(track.phi(), cuts.phiMin, cuts.phiMax) && - within(track.loc0(), cuts.loc0Min, cuts.loc0Max) && - within(track.loc1(), cuts.loc1Min, cuts.loc1Max) && - within(track.time(), cuts.timeMin, cuts.timeMax) && - checkMin(track.nMeasurements(), cuts.minMeasurements) && - checkMax(track.nHoles(), cuts.maxHoles) && - checkMax(track.nOutliers(), cuts.maxOutliers) && - checkMax(track.nHoles() + track.nOutliers(), - cuts.maxHolesAndOutliers) && - checkMax(track.nSharedHits(), cuts.maxSharedHits) && - checkMax(track.chi2(), cuts.maxChi2) && - cuts.measurementCounter.isValidTrack(track); + auto parameterCuts = [&]() { + return within(track.transverseMomentum(), cuts.ptMin, cuts.ptMax) && + (!m_isUnbinned || + (within(absEta(), cuts.absEtaMin, cuts.absEtaMax) && + within(_eta, cuts.etaMin, cuts.etaMax))) && + within(track.phi(), cuts.phiMin, cuts.phiMax) && + within(track.loc0(), cuts.loc0Min, cuts.loc0Max) && + within(track.loc1(), cuts.loc1Min, cuts.loc1Max) && + within(track.time(), cuts.timeMin, cuts.timeMax); + }; + + auto trackCuts = [&]() { + return checkMin(track.nMeasurements(), cuts.minMeasurements) && + checkMax(track.nHoles(), cuts.maxHoles) && + checkMax(track.nOutliers(), cuts.maxOutliers) && + checkMax(track.nHoles() + track.nOutliers(), + cuts.maxHolesAndOutliers) && + checkMax(track.nSharedHits(), cuts.maxSharedHits) && + checkMax(track.chi2(), cuts.maxChi2) && + cuts.measurementCounter.isValidTrack(track); + }; + + if (cuts.requireReferenceSurface) { + return track.hasReferenceSurface() && parameterCuts() && trackCuts(); + } else { + return trackCuts(); + } } inline TrackSelector::TrackSelector( diff --git a/Core/include/Acts/TrackFitting/BetheHeitlerApprox.hpp b/Core/include/Acts/TrackFitting/BetheHeitlerApprox.hpp index 5d0c5601bea..543ac3e4376 100644 --- a/Core/include/Acts/TrackFitting/BetheHeitlerApprox.hpp +++ b/Core/include/Acts/TrackFitting/BetheHeitlerApprox.hpp @@ -31,9 +31,9 @@ namespace Acts { namespace detail { struct GaussianComponent { - ActsScalar weight = 0.0; - ActsScalar mean = 0.0; - ActsScalar var = 0.0; + double weight = 0.0; + double mean = 0.0; + double var = 0.0; }; /// Transform a gaussian component to a space where all values are defined from @@ -73,7 +73,7 @@ struct BetheHeitlerApproxSingleCmp { /// Checks if an input is valid for the parameterization. The threshold for /// x/x0 is 0.002 and orientates on the values used in ATLAS - constexpr bool validXOverX0(ActsScalar x) const { + constexpr bool validXOverX0(double x) const { return x < 0.002; ; } @@ -82,7 +82,7 @@ struct BetheHeitlerApproxSingleCmp { /// Bethe-Heitler-Distribution /// /// @param x pathlength in terms of the radiation length - static auto mixture(const ActsScalar x) { + static auto mixture(const double x) { std::array ret{}; ret[0].weight = 1.0; @@ -109,9 +109,9 @@ class AtlasBetheHeitlerApprox { public: struct PolyData { - std::array weightCoeffs; - std::array meanCoeffs; - std::array varCoeffs; + std::array weightCoeffs; + std::array meanCoeffs; + std::array varCoeffs; }; using Data = std::array; @@ -160,7 +160,7 @@ class AtlasBetheHeitlerApprox { /// Checks if an input is valid for the parameterization /// /// @param x pathlength in terms of the radiation length - constexpr bool validXOverX0(ActsScalar x) const { + constexpr bool validXOverX0(double x) const { if (m_clampToRange) { return true; } else { @@ -172,7 +172,7 @@ class AtlasBetheHeitlerApprox { /// that the sum of all weights is 1 /// /// @param x pathlength in terms of the radiation length - auto mixture(ActsScalar x) const { + auto mixture(double x) const { using Array = boost::container::static_vector; @@ -181,9 +181,9 @@ class AtlasBetheHeitlerApprox { } // Build a polynom - auto poly = [](ActsScalar xx, - const std::array &coeffs) { - ActsScalar sum{0.}; + auto poly = [](double xx, + const std::array &coeffs) { + double sum{0.}; for (const auto c : coeffs) { sum = xx * sum + c; } @@ -195,7 +195,7 @@ class AtlasBetheHeitlerApprox { auto make_mixture = [&](const Data &data, double xx, bool transform) { // Value initialization should garanuee that all is initialized to zero Array ret(NComponents); - ActsScalar weight_sum = 0; + double weight_sum = 0; for (int i = 0; i < NComponents; ++i) { // These transformations must be applied to the data according to ATHENA // (TrkGaussianSumFilter/src/GsfCombinedMaterialEffects.cxx:79) diff --git a/Core/include/Acts/TrackFitting/GainMatrixSmoother.hpp b/Core/include/Acts/TrackFitting/GainMatrixSmoother.hpp index cf5b372f487..5adc8340cfe 100644 --- a/Core/include/Acts/TrackFitting/GainMatrixSmoother.hpp +++ b/Core/include/Acts/TrackFitting/GainMatrixSmoother.hpp @@ -10,7 +10,6 @@ #include "Acts/EventData/MultiTrajectory.hpp" #include "Acts/Geometry/GeometryContext.hpp" -#include "Acts/TrackFitting/KalmanFitterError.hpp" #include "Acts/Utilities/Delegate.hpp" #include "Acts/Utilities/Logger.hpp" #include "Acts/Utilities/Result.hpp" diff --git a/Core/include/Acts/TrackFitting/GainMatrixUpdater.hpp b/Core/include/Acts/TrackFitting/GainMatrixUpdater.hpp index 0ac45a79b1d..9d8ae5a0d03 100644 --- a/Core/include/Acts/TrackFitting/GainMatrixUpdater.hpp +++ b/Core/include/Acts/TrackFitting/GainMatrixUpdater.hpp @@ -80,7 +80,7 @@ class GainMatrixUpdater { // shape later trackState.effectiveCalibrated().data(), trackState.effectiveCalibratedCovariance().data(), - trackState.boundSubspaceIndices(), + trackState.projectorSubspaceIndices(), trackState.predicted(), trackState.predictedCovariance(), trackState.filtered(), diff --git a/Core/include/Acts/TrackFitting/GaussianSumFitter.hpp b/Core/include/Acts/TrackFitting/GaussianSumFitter.hpp index f6c990a696d..4efcd82e4c4 100644 --- a/Core/include/Acts/TrackFitting/GaussianSumFitter.hpp +++ b/Core/include/Acts/TrackFitting/GaussianSumFitter.hpp @@ -14,6 +14,7 @@ #include "Acts/Propagator/Navigator.hpp" #include "Acts/Propagator/StandardAborters.hpp" #include "Acts/Surfaces/BoundaryTolerance.hpp" +#include "Acts/TrackFitting/GsfError.hpp" #include "Acts/TrackFitting/GsfOptions.hpp" #include "Acts/TrackFitting/detail/GsfActor.hpp" #include "Acts/Utilities/Helpers.hpp" @@ -217,7 +218,7 @@ struct GaussianSumFitter { .closest() .status(); - if (intersectionStatusStartSurface != Intersection3D::Status::onSurface) { + if (intersectionStatusStartSurface != IntersectionStatus::onSurface) { ACTS_DEBUG( "Surface intersection of start parameters WITH bound-check failed"); } diff --git a/Core/include/Acts/TrackFitting/GlobalChiSquareFitter.hpp b/Core/include/Acts/TrackFitting/GlobalChiSquareFitter.hpp index 8442071a23f..dc0bc221e9a 100644 --- a/Core/include/Acts/TrackFitting/GlobalChiSquareFitter.hpp +++ b/Core/include/Acts/TrackFitting/GlobalChiSquareFitter.hpp @@ -251,7 +251,7 @@ struct ScatteringProperties { /// @param invCovarianceMaterial_ The inverse covariance of the material. /// @param materialIsValid_ A boolean flag indicating whether the material is valid. ScatteringProperties(const BoundVector& scatteringAngles_, - const ActsScalar invCovarianceMaterial_, + const double invCovarianceMaterial_, const bool materialIsValid_) : m_scatteringAngles(scatteringAngles_), m_invCovarianceMaterial(invCovarianceMaterial_), @@ -264,7 +264,7 @@ struct ScatteringProperties { BoundVector& scatteringAngles() { return m_scatteringAngles; } // Accessor for the inverse covariance of the material. - ActsScalar invCovarianceMaterial() const { return m_invCovarianceMaterial; } + double invCovarianceMaterial() const { return m_invCovarianceMaterial; } // Accessor for the material validity flag. bool materialIsValid() const { return m_materialIsValid; } @@ -276,7 +276,7 @@ struct ScatteringProperties { /// Inverse covariance of the material. Compute with e.g. the Highland /// formula. - ActsScalar m_invCovarianceMaterial; + double m_invCovarianceMaterial; /// Flag indicating whether the material is valid. Commonly vacuum and zero /// thickness material will be ignored. @@ -423,7 +423,7 @@ void addMeasurementToGx2fSums(Gx2fSystem& extendedSystem, trackState.template calibrated(); const ActsMatrix projector = - trackState.projector().template topLeftCorner(); + trackState.template projectorSubspaceHelper().projector(); const Eigen::MatrixXd projJacobian = projector * extendedJacobian; @@ -503,7 +503,7 @@ void addMaterialToGx2fSums( "No scattering angles found for material surface."); } - const ActsScalar sinThetaLoc = std::sin(trackState.smoothed()[eBoundTheta]); + const double sinThetaLoc = std::sin(trackState.smoothed()[eBoundTheta]); // The position, where we need to insert the values in aMatrix and bVector const std::size_t deltaPosition = eBoundSize + 2 * nMaterialsHandled; @@ -511,7 +511,7 @@ void addMaterialToGx2fSums( const BoundVector& scatteringAngles = scatteringMapId->second.scatteringAngles(); - const ActsScalar invCov = scatteringMapId->second.invCovarianceMaterial(); + const double invCov = scatteringMapId->second.invCovarianceMaterial(); // Phi contribution extendedSystem.aMatrix()(deltaPosition, deltaPosition) += @@ -1408,9 +1408,9 @@ class Gx2Fitter { if ((gx2fOptions.relChi2changeCutOff != 0) && (nUpdate > 0) && (std::abs(extendedSystem.chi2() / oldChi2sum - 1) < gx2fOptions.relChi2changeCutOff)) { - ACTS_INFO("Abort with relChi2changeCutOff after " - << nUpdate + 1 << "/" << gx2fOptions.nUpdateMax - << " iterations."); + ACTS_DEBUG("Abort with relChi2changeCutOff after " + << nUpdate + 1 << "/" << gx2fOptions.nUpdateMax + << " iterations."); updateGx2fCovarianceParams(fullCovariancePredicted, extendedSystem); break; } diff --git a/Core/include/Acts/TrackFitting/GsfOptions.hpp b/Core/include/Acts/TrackFitting/GsfOptions.hpp index 4840b6b6184..88fb902daff 100644 --- a/Core/include/Acts/TrackFitting/GsfOptions.hpp +++ b/Core/include/Acts/TrackFitting/GsfOptions.hpp @@ -29,7 +29,7 @@ enum class ComponentMergeMethod { eMean, eMaxWeight }; /// /// Encapsulates a component of a Gaussian mixture as used by the GSF struct GsfComponent { - ActsScalar weight = 0; + double weight = 0; BoundVector boundPars = BoundVector::Zero(); BoundSquareMatrix boundCov = BoundSquareMatrix::Identity(); }; diff --git a/Core/include/Acts/TrackFitting/MbfSmoother.hpp b/Core/include/Acts/TrackFitting/MbfSmoother.hpp index 02066a642e7..be7a8c12311 100644 --- a/Core/include/Acts/TrackFitting/MbfSmoother.hpp +++ b/Core/include/Acts/TrackFitting/MbfSmoother.hpp @@ -87,9 +87,6 @@ class MbfSmoother { /// Internal track state representation for the smoother. /// @note This allows us to move parts of the implementation into the .cpp struct InternalTrackState final { - using Projector = - typename TrackStateTraits::Projector; using Jacobian = typename TrackStateTraits::Covariance; @@ -105,14 +102,14 @@ class MbfSmoother { // This is used to build a covariance matrix view in the .cpp file const double* calibrated{nullptr}; const double* calibratedCovariance{nullptr}; - Projector projector; + BoundSubspaceIndices projector; template explicit Measurement(TrackStateProxy ts) : calibratedSize(ts.calibratedSize()), calibrated(ts.effectiveCalibrated().data()), calibratedCovariance(ts.effectiveCalibratedCovariance().data()), - projector(ts.projector()) {} + projector(ts.projectorSubspaceIndices()) {} }; Jacobian jacobian; diff --git a/Core/include/Acts/TrackFitting/detail/GainMatrixUpdaterImpl.hpp b/Core/include/Acts/TrackFitting/detail/GainMatrixUpdaterImpl.hpp index 0dce3c2ba21..0437ca551a3 100644 --- a/Core/include/Acts/TrackFitting/detail/GainMatrixUpdaterImpl.hpp +++ b/Core/include/Acts/TrackFitting/detail/GainMatrixUpdaterImpl.hpp @@ -35,7 +35,7 @@ std::tuple GainMatrixUpdater::visitMeasurementImpl( ACTS_VERBOSE("Calibrated measurement: " << calibrated.transpose()); ACTS_VERBOSE("Calibrated measurement covariance:\n" << calibratedCovariance); - std::span validSubspaceIndices( + std::span validSubspaceIndices( trackState.projector.begin(), trackState.projector.begin() + kMeasurementSize); FixedBoundSubspaceHelper subspaceHelper( diff --git a/Core/include/Acts/TrackFitting/detail/GsfActor.hpp b/Core/include/Acts/TrackFitting/detail/GsfActor.hpp index 92c5529d319..6d5ac68d8b9 100644 --- a/Core/include/Acts/TrackFitting/detail/GsfActor.hpp +++ b/Core/include/Acts/TrackFitting/detail/GsfActor.hpp @@ -12,14 +12,9 @@ #include "Acts/EventData/MultiComponentTrackParameters.hpp" #include "Acts/EventData/MultiTrajectory.hpp" #include "Acts/EventData/MultiTrajectoryHelpers.hpp" -#include "Acts/MagneticField/MagneticFieldProvider.hpp" -#include "Acts/Material/ISurfaceMaterial.hpp" -#include "Acts/Surfaces/CylinderSurface.hpp" +#include "Acts/Propagator/detail/PointwiseMaterialInteraction.hpp" #include "Acts/Surfaces/Surface.hpp" -#include "Acts/TrackFitting/BetheHeitlerApprox.hpp" -#include "Acts/TrackFitting/GsfError.hpp" #include "Acts/TrackFitting/GsfOptions.hpp" -#include "Acts/TrackFitting/KalmanFitter.hpp" #include "Acts/TrackFitting/detail/GsfComponentMerging.hpp" #include "Acts/TrackFitting/detail/GsfUtils.hpp" #include "Acts/TrackFitting/detail/KalmanUpdateHelpers.hpp" @@ -28,7 +23,6 @@ #include #include -#include namespace Acts::detail { @@ -53,8 +47,8 @@ struct GsfResult { std::size_t measurementHoles = 0; std::size_t processedStates = 0; - std::vector visitedSurfaces; - std::vector surfacesVisitedBwdAgain; + std::vector visitedSurfaces; + std::vector surfacesVisitedBwdAgain; /// Statistics about material encounterings Updatable nInvalidBetheHeitler; @@ -74,7 +68,7 @@ struct GsfActor { /// Enforce default construction GsfActor() = default; - using ComponentCache = Acts::GsfComponent; + using ComponentCache = GsfComponent; /// Broadcast the result_type using result_type = GsfResult; @@ -189,7 +183,7 @@ struct GsfActor { // All components must have status "on surface". It is however possible, // that currentSurface is nullptr and all components are "on surface" (e.g., // for surfaces excluded from the navigation) - using Status [[maybe_unused]] = Acts::Intersection3D::Status; + using Status [[maybe_unused]] = IntersectionStatus; assert(std::all_of( stepperComponents.begin(), stepperComponents.end(), [](const auto& cmp) { return cmp.status() == Status::onSurface; })); @@ -484,7 +478,7 @@ struct GsfActor { // we set ignored components to missed, so we can remove them after // the loop if (tmpStates.weights.at(idx) < m_cfg.weightCutoff) { - cmp.status() = Intersection3D::Status::missed; + cmp.status() = IntersectionStatus::unreachable; continue; } @@ -534,9 +528,9 @@ struct GsfActor { state.geoContext, freeParams.template segment<3>(eFreePos0), freeParams.template segment<3>(eFreeDir0)); cmp.pathAccumulated() = state.stepping.pathAccumulated; - cmp.jacobian() = Acts::BoundMatrix::Identity(); - cmp.derivative() = Acts::FreeVector::Zero(); - cmp.jacTransport() = Acts::FreeMatrix::Identity(); + cmp.jacobian() = BoundMatrix::Identity(); + cmp.derivative() = FreeVector::Zero(); + cmp.jacTransport() = FreeMatrix::Identity(); } } @@ -574,8 +568,7 @@ struct GsfActor { // If at least one component is no outlier, we consider the whole thing // as a measurementState - if (trackStateProxy.typeFlags().test( - Acts::TrackStateFlag::MeasurementFlag)) { + if (trackStateProxy.typeFlags().test(TrackStateFlag::MeasurementFlag)) { is_valid_measurement = true; } @@ -621,7 +614,7 @@ struct GsfActor { stepper.particleHypothesis(state.stepping)); // Return success - return Acts::Result::success(); + return Result::success(); } template & options) { + void setOptions(const GsfOptions& options) { m_cfg.maxComponents = options.maxComponents; m_cfg.extensions = options.extensions; m_cfg.abortOnError = options.abortOnError; diff --git a/Core/include/Acts/TrackFitting/detail/GsfUtils.hpp b/Core/include/Acts/TrackFitting/detail/GsfUtils.hpp index 501208b7e09..574a69e8f71 100644 --- a/Core/include/Acts/TrackFitting/detail/GsfUtils.hpp +++ b/Core/include/Acts/TrackFitting/detail/GsfUtils.hpp @@ -13,6 +13,7 @@ #include "Acts/EventData/MultiComponentTrackParameters.hpp" #include "Acts/EventData/MultiTrajectory.hpp" #include "Acts/EventData/TrackParameters.hpp" +#include "Acts/EventData/Types.hpp" #include "Acts/Utilities/Logger.hpp" #include @@ -150,13 +151,11 @@ class ScopedGsfInfoPrinterAndChecker { } }; -ActsScalar calculateDeterminant( +double calculateDeterminant( const double *fullCalibratedCovariance, TrackStateTraits::Covariance predictedCovariance, - TrackStateTraits::Projector - projector, - unsigned int calibratedSize); + BoundSubspaceIndices projector, unsigned int calibratedSize); /// Reweight the components according to `R. Frühwirth, "Track fitting /// with non-Gaussian noise"`. See also the implementation in Athena at @@ -190,7 +189,8 @@ void computePosteriorWeights( .template calibratedCovariance< MultiTrajectoryTraits::MeasurementSizeMax>() .data(), - state.predictedCovariance(), state.projector(), state.calibratedSize()); + state.predictedCovariance(), state.projectorSubspaceIndices(), + state.calibratedSize()); const auto factor = std::sqrt(1. / detR) * safeExp(-0.5 * chi2); diff --git a/Core/include/Acts/TrackFitting/detail/SymmetricKlDistanceMatrix.hpp b/Core/include/Acts/TrackFitting/detail/SymmetricKlDistanceMatrix.hpp index f7fcfbd871e..e243840f5b9 100644 --- a/Core/include/Acts/TrackFitting/detail/SymmetricKlDistanceMatrix.hpp +++ b/Core/include/Acts/TrackFitting/detail/SymmetricKlDistanceMatrix.hpp @@ -66,7 +66,7 @@ auto mergeComponents(const component_t &a, const component_t &b, /// @brief Class representing a symmetric distance matrix class SymmetricKLDistanceMatrix { - using Array = Eigen::Array; + using Array = Eigen::Array; using Mask = Eigen::Array; Array m_distances; @@ -127,7 +127,7 @@ class SymmetricKLDistanceMatrix { } auto minDistancePair() const { - auto min = std::numeric_limits::max(); + auto min = std::numeric_limits::max(); std::size_t idx = 0; for (auto i = 0l; i < m_distances.size(); ++i) { diff --git a/Core/include/Acts/Utilities/Axis.hpp b/Core/include/Acts/Utilities/Axis.hpp index f843d0e7f92..758a8c2ec3c 100644 --- a/Core/include/Acts/Utilities/Axis.hpp +++ b/Core/include/Acts/Utilities/Axis.hpp @@ -97,7 +97,7 @@ class NeighborHoodIndices { /// This class provides some basic functionality for calculating bin indices /// for a given equidistant binning. template -class Axis final : public IAxis { +class Axis : public IAxis { public: static constexpr AxisType type = AxisType::Equidistant; @@ -109,7 +109,7 @@ class Axis final : public IAxis { /// /// Divide the range \f$[\text{xmin},\text{xmax})\f$ into \f$\text{nBins}\f$ /// equidistant bins. - Axis(ActsScalar xmin, ActsScalar xmax, std::size_t nBins) + Axis(double xmin, double xmax, std::size_t nBins) : m_min(xmin), m_max(xmax), m_width((xmax - xmin) / nBins), @@ -124,7 +124,7 @@ class Axis final : public IAxis { /// /// Divide the range \f$[\text{xmin},\text{xmax})\f$ into \f$\text{nBins}\f$ /// equidistant bins. - Axis(AxisBoundaryTypeTag typeTag, ActsScalar xmin, ActsScalar xmax, + Axis(AxisBoundaryTypeTag typeTag, double xmin, double xmax, std::size_t nBins) : Axis(xmin, xmax, nBins) { static_cast(typeTag); @@ -306,7 +306,7 @@ class Axis final : public IAxis { /// bin with lower bound @c l and upper bound @c u. /// @note Bin indices start at @c 1. The underflow bin has the index @c 0 /// while the index nBins + 1 indicates the overflow bin . - std::size_t getBin(ActsScalar x) const { + std::size_t getBin(double x) const { return wrapBin( static_cast(std::floor((x - getMin()) / getBinWidth()) + 1)); } @@ -314,7 +314,7 @@ class Axis final : public IAxis { /// @brief get bin width /// /// @return constant width for all bins - ActsScalar getBinWidth(std::size_t /*bin*/ = 0) const { return m_width; } + double getBinWidth(std::size_t /*bin*/ = 0) const { return m_width; } /// @brief get lower bound of bin /// @@ -326,7 +326,7 @@ class Axis final : public IAxis { /// /// @note Bin intervals have a closed lower bound, i.e. the lower boundary /// belongs to the bin with the given bin index. - ActsScalar getBinLowerBound(std::size_t bin) const { + double getBinLowerBound(std::size_t bin) const { return getMin() + (bin - 1) * getBinWidth(); } @@ -340,7 +340,7 @@ class Axis final : public IAxis { /// /// @note Bin intervals have an open upper bound, i.e. the upper boundary /// does @b not belong to the bin with the given bin index. - ActsScalar getBinUpperBound(std::size_t bin) const { + double getBinUpperBound(std::size_t bin) const { return getMin() + bin * getBinWidth(); } @@ -351,19 +351,19 @@ class Axis final : public IAxis { /// /// @pre @c bin must be a valid bin index (excluding under-/overflow bins), /// i.e. \f$1 \le \text{bin} \le \text{nBins}\f$ - ActsScalar getBinCenter(std::size_t bin) const { + double getBinCenter(std::size_t bin) const { return getMin() + (bin - 0.5) * getBinWidth(); } /// @brief get maximum of binning range /// /// @return maximum of binning range - ActsScalar getMax() const override { return m_max; } + double getMax() const override { return m_max; } /// @brief get minimum of binning range /// /// @return minimum of binning range - ActsScalar getMin() const override { return m_min; } + double getMin() const override { return m_min; } /// @brief get total number of bins /// @@ -377,12 +377,12 @@ class Axis final : public IAxis { /// /// @post If @c true is returned, the bin containing the given value is a /// valid bin, i.e. it is neither the underflow nor the overflow bin. - bool isInside(ActsScalar x) const { return (m_min <= x) && (x < m_max); } + bool isInside(double x) const { return (m_min <= x) && (x < m_max); } /// @brief Return a vector of bin edges /// @return Vector which contains the bin edges - std::vector getBinEdges() const override { - std::vector binEdges; + std::vector getBinEdges() const override { + std::vector binEdges; for (std::size_t i = 1; i <= m_bins; i++) { binEdges.push_back(getBinLowerBound(i)); } @@ -403,11 +403,11 @@ class Axis final : public IAxis { private: /// minimum of binning range - ActsScalar m_min{}; + double m_min{}; /// maximum of binning range - ActsScalar m_max{}; + double m_max{}; /// constant bin width - ActsScalar m_width{}; + double m_width{}; /// number of bins (excluding under-/overflow bins) std::size_t m_bins{}; }; @@ -417,7 +417,7 @@ class Axis final : public IAxis { /// This class provides some basic functionality for calculating bin indices /// for a given binning with variable bin sizes. template -class Axis final : public IAxis { +class Axis : public IAxis { public: static constexpr AxisType type = AxisType::Variable; @@ -428,7 +428,7 @@ class Axis final : public IAxis { /// Create a binning structure with @c nBins variable-sized bins from the /// given bin boundaries. @c nBins is given by the number of bin edges /// reduced by one. - explicit Axis(std::vector binEdges) + explicit Axis(std::vector binEdges) : m_binEdges(std::move(binEdges)) {} /// @param [in] typeTag boundary type tag @@ -439,7 +439,7 @@ class Axis final : public IAxis { /// Create a binning structure with @c nBins variable-sized bins from the /// given bin boundaries. @c nBins is given by the number of bin edges /// reduced by one. - Axis(AxisBoundaryTypeTag typeTag, std::vector binEdges) + Axis(AxisBoundaryTypeTag typeTag, std::vector binEdges) : Axis(std::move(binEdges)) { static_cast(typeTag); } @@ -618,7 +618,7 @@ class Axis final : public IAxis { /// bin with lower bound @c l and upper bound @c u. /// @note Bin indices start at @c 1. The underflow bin has the index @c 0 /// while the index nBins + 1 indicates the overflow bin . - std::size_t getBin(ActsScalar x) const { + std::size_t getBin(double x) const { const auto it = std::upper_bound(std::begin(m_binEdges), std::end(m_binEdges), x); return wrapBin(std::distance(std::begin(m_binEdges), it)); @@ -631,7 +631,7 @@ class Axis final : public IAxis { /// /// @pre @c bin must be a valid bin index (excluding under-/overflow bins), /// i.e. \f$1 \le \text{bin} \le \text{nBins}\f$ - ActsScalar getBinWidth(std::size_t bin) const { + double getBinWidth(std::size_t bin) const { return m_binEdges.at(bin) - m_binEdges.at(bin - 1); } @@ -645,7 +645,7 @@ class Axis final : public IAxis { /// /// @note Bin intervals have a closed lower bound, i.e. the lower boundary /// belongs to the bin with the given bin index. - ActsScalar getBinLowerBound(std::size_t bin) const { + double getBinLowerBound(std::size_t bin) const { return m_binEdges.at(bin - 1); } @@ -659,9 +659,7 @@ class Axis final : public IAxis { /// /// @note Bin intervals have an open upper bound, i.e. the upper boundary /// does @b not belong to the bin with the given bin index. - ActsScalar getBinUpperBound(std::size_t bin) const { - return m_binEdges.at(bin); - } + double getBinUpperBound(std::size_t bin) const { return m_binEdges.at(bin); } /// @brief get bin center /// @@ -670,19 +668,19 @@ class Axis final : public IAxis { /// /// @pre @c bin must be a valid bin index (excluding under-/overflow bins), /// i.e. \f$1 \le \text{bin} \le \text{nBins}\f$ - ActsScalar getBinCenter(std::size_t bin) const { + double getBinCenter(std::size_t bin) const { return 0.5 * (getBinLowerBound(bin) + getBinUpperBound(bin)); } /// @brief get maximum of binning range /// /// @return maximum of binning range - ActsScalar getMax() const override { return m_binEdges.back(); } + double getMax() const override { return m_binEdges.back(); } /// @brief get minimum of binning range /// /// @return minimum of binning range - ActsScalar getMin() const override { return m_binEdges.front(); } + double getMin() const override { return m_binEdges.front(); } /// @brief get total number of bins /// @@ -696,13 +694,13 @@ class Axis final : public IAxis { /// /// @post If @c true is returned, the bin containing the given value is a /// valid bin, i.e. it is neither the underflow nor the overflow bin. - bool isInside(ActsScalar x) const { + bool isInside(double x) const { return (m_binEdges.front() <= x) && (x < m_binEdges.back()); } /// @brief Return a vector of bin edges /// @return Vector which contains the bin edges - std::vector getBinEdges() const override { return m_binEdges; } + std::vector getBinEdges() const override { return m_binEdges; } friend std::ostream& operator<<(std::ostream& os, const Axis& axis) { os << "Axis("; @@ -719,6 +717,6 @@ class Axis final : public IAxis { private: /// vector of bin edges (sorted in ascending order) - std::vector m_binEdges; + std::vector m_binEdges; }; } // namespace Acts diff --git a/Core/include/Acts/Utilities/AxisFwd.hpp b/Core/include/Acts/Utilities/AxisFwd.hpp index fefa980cbfd..ce31ff3f7b6 100644 --- a/Core/include/Acts/Utilities/AxisFwd.hpp +++ b/Core/include/Acts/Utilities/AxisFwd.hpp @@ -86,18 +86,18 @@ inline std::ostream& operator<<(std::ostream& os, AxisType type) { template class Axis; -Axis(ActsScalar min, ActsScalar max, +Axis(double min, double max, std::size_t bins) -> Axis; template -Axis(AxisBoundaryTypeTag /*bdt*/, ActsScalar min, ActsScalar max, +Axis(AxisBoundaryTypeTag /*bdt*/, double min, double max, std::size_t bins) -> Axis; -Axis(std::vector bins) +Axis(std::vector bins) -> Axis; template Axis(AxisBoundaryTypeTag /*bdt*/, - std::vector bins) -> Axis; + std::vector bins) -> Axis; } // namespace Acts diff --git a/Core/include/Acts/Utilities/Grid.hpp b/Core/include/Acts/Utilities/Grid.hpp index f6c5f9ddaf9..317fb3b123e 100644 --- a/Core/include/Acts/Utilities/Grid.hpp +++ b/Core/include/Acts/Utilities/Grid.hpp @@ -85,7 +85,7 @@ class Grid final : public IGrid { /// constant reference type to values stored using const_reference = const value_type&; /// type for points in d-dimensional grid space - using point_t = std::array; + using point_t = std::array; /// index type using local bin indices along each axis using index_t = std::array; /// global iterator type @@ -240,7 +240,7 @@ class Grid final : public IGrid { /// /// @pre All local bin indices must be a valid index for the corresponding /// axis (excluding the under-/overflow bins for each axis). - std::array binCenter(const index_t& localBins) const { + std::array binCenter(const index_t& localBins) const { return detail::grid_helper::getBinCenter(localBins, m_axes); } @@ -411,19 +411,19 @@ class Grid final : public IGrid { /// /// @note This function is available only if the following conditions are /// fulfilled: - /// - Given @c U and @c V of value type @c T as well as two @c ActsScalar + /// - Given @c U and @c V of value type @c T as well as two @c double /// @c a and @c b, then the following must be a valid expression a * U + b /// * V yielding an object which is (implicitly) convertible to @c T. /// - @c Point must represent a d-dimensional position and support /// coordinate access using @c operator[] which should return a @c - /// ActsScalar (or a value which is implicitly convertible). Coordinate + /// double (or a value which is implicitly convertible). Coordinate /// indices must start at 0. /// @note Bin values are interpreted as being the field values at the /// lower-left corner of the corresponding hyper-box. template T interpolate(const Point& point) const - requires(Concepts::interpolatable, - std::array>) + requires(Concepts::interpolatable, + std::array>) { // there are 2^DIM corner points used during the interpolation constexpr std::size_t nCorners = 1 << DIM; diff --git a/Core/include/Acts/Utilities/GridAccessHelpers.hpp b/Core/include/Acts/Utilities/GridAccessHelpers.hpp index 20755d01ff6..fbaf7f3acbd 100644 --- a/Core/include/Acts/Utilities/GridAccessHelpers.hpp +++ b/Core/include/Acts/Utilities/GridAccessHelpers.hpp @@ -110,7 +110,7 @@ class IBoundToGridLocal { }; template -class Affine3Transformed final : public IGlobalToGridLocal { +class Affine3Transformed : public IGlobalToGridLocal { public: using grid_local_t = typename global_to_grid_local_t::grid_local_t; @@ -142,9 +142,9 @@ class Affine3Transformed final : public IGlobalToGridLocal { /// position /// @tparam ...Args template -class GlobalSubspace final : public IGlobalToGridLocal { +class GlobalSubspace : public IGlobalToGridLocal { public: - using grid_local_t = std::array; + using grid_local_t = std::array; /// Assert that size has to be bigger than 0 static_assert(sizeof...(Args) > 0, @@ -179,9 +179,9 @@ class GlobalSubspace final : public IGlobalToGridLocal { // The bound to grid local transformation, if only access of a subspace // is requested template -class LocalSubspace final : public IBoundToGridLocal { +class LocalSubspace : public IBoundToGridLocal { public: - using grid_local_t = std::array; + using grid_local_t = std::array; /// Assert that the accessors are unique static_assert(sizeof...(Args) == 1 || sizeof...(Args) == 2, @@ -214,15 +214,15 @@ class LocalSubspace final : public IBoundToGridLocal { class BoundCylinderToZPhi final : public IBoundToGridLocal { public: - ActsScalar radius = 1.; - ActsScalar shift = 0.; + double radius = 1.; + double shift = 0.; /// Constructor with arguments /// @param r the radius /// @param z the shift - BoundCylinderToZPhi(ActsScalar r, ActsScalar z) : radius(r), shift(z) {} + BoundCylinderToZPhi(double r, double z) : radius(r), shift(z) {} - std::array toGridLocal(const Vector2& local) const { + std::array toGridLocal(const Vector2& local) const { return {local[1u] + shift, local[0u] / radius}; } @@ -232,25 +232,25 @@ class BoundCylinderToZPhi final : public IBoundToGridLocal { // Definition of bound (on surface) to grid local representation delegate // 1 dimensional local grid using BoundToGridLocal1DimDelegate = - OwningDelegate(const Vector2&), + OwningDelegate(const Vector2&), GridAccess::IBoundToGridLocal>; // Definition of global to grid local representation delegate // 1 dimensional local grid using GlobalToGridLocal1DimDelegate = - OwningDelegate(const Vector3&), + OwningDelegate(const Vector3&), GridAccess::IGlobalToGridLocal>; // Definition of bound (on surface) to grid local representation delegate // 2 dimensional local grid using BoundToGridLocal2DimDelegate = - OwningDelegate(const Vector2&), + OwningDelegate(const Vector2&), GridAccess::IBoundToGridLocal>; // Definition of global to grid local representation delegate // 2 dimensional local grid using GlobalToGridLocal2DimDelegate = - OwningDelegate(const Vector3&), + OwningDelegate(const Vector3&), GridAccess::IGlobalToGridLocal>; } // namespace GridAccess diff --git a/Core/include/Acts/Utilities/GridAxisGenerators.hpp b/Core/include/Acts/Utilities/GridAxisGenerators.hpp index 18e6a1cdd2e..170108d2316 100644 --- a/Core/include/Acts/Utilities/GridAxisGenerators.hpp +++ b/Core/include/Acts/Utilities/GridAxisGenerators.hpp @@ -38,7 +38,7 @@ struct Eq { using grid_type = Acts::Grid>; - std::array range = {}; + std::array range = {}; std::size_t nBins = 0u; /// Call operator that generates the Axis @@ -66,7 +66,7 @@ struct Var { template using grid_type = Acts::Grid>; - std::vector edges = {}; + std::vector edges = {}; /// Call operator that generates the Axis return_type operator()() const { @@ -98,9 +98,9 @@ struct EqEq { Acts::Grid, Acts::Axis>; - std::array range0 = {}; + std::array range0 = {}; std::size_t nBins0 = 0u; - std::array range1 = {}; + std::array range1 = {}; std::size_t nBins1 = 1u; /// Call operator that generates the Axis @@ -151,9 +151,9 @@ struct EqVar { Acts::Grid, Acts::Axis>; - std::array range = {}; + std::array range = {}; std::size_t nBins = 0u; - std::vector edges = {}; + std::vector edges = {}; /// Call operator that generates the Axis return_type operator()() const { @@ -201,8 +201,8 @@ struct VarEq { using grid_type = Acts::Grid, Acts::Axis>; - std::vector edges = {}; - std::array range = {}; + std::vector edges = {}; + std::array range = {}; std::size_t nBins = 0u; /// Call operator that generates the Axis @@ -250,8 +250,8 @@ struct VarVar { using grid_type = Acts::Grid, Acts::Axis>; - std::vector edges0 = {}; - std::vector edges1 = {}; + std::vector edges0 = {}; + std::vector edges1 = {}; /// Call operator that generates the Axis return_type operator()() const { diff --git a/Core/include/Acts/Utilities/Helpers.hpp b/Core/include/Acts/Utilities/Helpers.hpp index 4bf9d1c89c3..44bf23d9157 100644 --- a/Core/include/Acts/Utilities/Helpers.hpp +++ b/Core/include/Acts/Utilities/Helpers.hpp @@ -175,10 +175,10 @@ T clampValue(U value) { /// /// @return [ range, medium ] in an tuple template -std::tuple range_medium(const T& tseries) { +std::tuple range_medium(const T& tseries) { auto [minIt, maxIt] = std::ranges::minmax_element(tseries); typename T::value_type range = (*maxIt - *minIt); - ActsScalar medium = static_cast((*maxIt + *minIt) * 0.5); + double medium = static_cast((*maxIt + *minIt) * 0.5); return {range, medium}; } @@ -204,4 +204,21 @@ bool rangeContainsValue(const R& range, const T& value) { return std::ranges::find(range, value) != std::ranges::end(range); } +/// Helper struct that can turn a set of lambdas into a single entity with +/// overloaded call operator. This can be useful for example in a std::visit +/// call. +/// ```cpp +/// std::visit(overloaded{ +/// [](const int& i) { std::cout << "int: " << i << std::endl; }, +/// [](const std::string& s) { std::cout << "string: " << s << std::endl; }, +/// }, variant); +/// ``` +template +struct overloaded : Ts... { + using Ts::operator()...; +}; + +template +overloaded(Ts...) -> overloaded; + } // namespace Acts diff --git a/Core/include/Acts/Utilities/IAxis.hpp b/Core/include/Acts/Utilities/IAxis.hpp index e279b83ed1a..09c9fbd3a56 100644 --- a/Core/include/Acts/Utilities/IAxis.hpp +++ b/Core/include/Acts/Utilities/IAxis.hpp @@ -41,17 +41,17 @@ class IAxis { /// @brief Return a vector of bin edges /// @return Vector which contains the bin edges - virtual std::vector getBinEdges() const = 0; + virtual std::vector getBinEdges() const = 0; /// @brief get minimum of binning range /// /// @return minimum of binning range - virtual ActsScalar getMin() const = 0; + virtual double getMin() const = 0; /// @brief get maximum of binning range /// /// @return maximum of binning range - virtual ActsScalar getMax() const = 0; + virtual double getMax() const = 0; /// @brief get total number of bins /// diff --git a/Core/include/Acts/Utilities/Intersection.hpp b/Core/include/Acts/Utilities/Intersection.hpp index 6276538ed5e..1f7ee6d28b0 100644 --- a/Core/include/Acts/Utilities/Intersection.hpp +++ b/Core/include/Acts/Utilities/Intersection.hpp @@ -9,7 +9,6 @@ #pragma once #include "Acts/Definitions/Algebra.hpp" -#include "Acts/Definitions/Tolerance.hpp" #include "Acts/Utilities/Logger.hpp" #include @@ -24,7 +23,6 @@ namespace Acts { /// Status enum enum class IntersectionStatus : int { - missed = 0, unreachable = 0, reachable = 1, onSurface = 2 @@ -47,8 +45,6 @@ class Intersection { public: /// Position type using Position = ActsVector; - /// Status enum - using Status = IntersectionStatus; /// Constructor with arguments /// @@ -56,20 +52,22 @@ class Intersection { /// @param pathLength is the path length to the intersection /// @param status is an enum indicating the status of the intersection constexpr Intersection(const Position& position, double pathLength, - Status status) + IntersectionStatus status) : m_position(position), m_pathLength(pathLength), m_status(status) {} /// Returns whether the intersection was successful or not - constexpr bool isValid() const { return m_status != Status::missed; } + constexpr bool isValid() const { + return m_status != IntersectionStatus::unreachable; + } /// Returns the position of the interseciton constexpr const Position& position() const { return m_position; } /// Returns the path length to the interseciton - constexpr ActsScalar pathLength() const { return m_pathLength; } + constexpr double pathLength() const { return m_pathLength; } /// Returns the intersection status enum - constexpr Status status() const { return m_status; } + constexpr IntersectionStatus status() const { return m_status; } /// Static factory to creae an invalid instesection constexpr static Intersection invalid() { return Intersection(); } @@ -87,12 +85,12 @@ class Intersection { /// be first. constexpr static bool closestOrder(const Intersection& aIntersection, const Intersection& bIntersection) { - if ((aIntersection.status() == Status::unreachable) && - (bIntersection.status() != Status::unreachable)) { + if ((aIntersection.status() == IntersectionStatus::unreachable) && + (bIntersection.status() != IntersectionStatus::unreachable)) { return false; } - if ((aIntersection.status() != Status::unreachable) && - (bIntersection.status() == Status::unreachable)) { + if ((aIntersection.status() != IntersectionStatus::unreachable) && + (bIntersection.status() == IntersectionStatus::unreachable)) { return true; } // both are reachable or onSurface now @@ -115,9 +113,9 @@ class Intersection { /// Position of the intersection Position m_position = Position::Zero(); /// Signed path length to the intersection (if valid) - ActsScalar m_pathLength = std::numeric_limits::infinity(); + double m_pathLength = std::numeric_limits::infinity(); /// The Status of the intersection - Status m_status = Status::unreachable; + IntersectionStatus m_status = IntersectionStatus::unreachable; constexpr Intersection() = default; }; @@ -156,12 +154,10 @@ class ObjectIntersection { } /// Returns the path length to the interseciton - constexpr ActsScalar pathLength() const { - return m_intersection.pathLength(); - } + constexpr double pathLength() const { return m_intersection.pathLength(); } /// Returns the status of the interseciton - constexpr Intersection3D::Status status() const { + constexpr IntersectionStatus status() const { return m_intersection.status(); } diff --git a/Core/include/Acts/Utilities/JacobianHelpers.hpp b/Core/include/Acts/Utilities/JacobianHelpers.hpp index b3b51b510fa..eace94fd096 100644 --- a/Core/include/Acts/Utilities/JacobianHelpers.hpp +++ b/Core/include/Acts/Utilities/JacobianHelpers.hpp @@ -53,7 +53,7 @@ inline ActsMatrix<2, 3> freeToSphericalDirectionJacobian( const Vector3& direction) { auto [cosPhi, sinPhi, cosTheta, sinTheta] = VectorHelpers::evaluateTrigonomics(direction); - ActsScalar invSinTheta = 1. / sinTheta; + double invSinTheta = 1. / sinTheta; // clang-format off ActsMatrix<2, 3> jacobian; diff --git a/Core/include/Acts/Utilities/Ray.hpp b/Core/include/Acts/Utilities/Ray.hpp index 3ec972847ff..6b6ad1940ae 100644 --- a/Core/include/Acts/Utilities/Ray.hpp +++ b/Core/include/Acts/Utilities/Ray.hpp @@ -78,7 +78,7 @@ std::ostream& operator<<(std::ostream& os, const Ray& ray) { return os; } -using Ray3D = Ray; +using Ray3D = Ray; } // namespace Acts diff --git a/Core/include/Acts/Utilities/SpacePointUtility.hpp b/Core/include/Acts/Utilities/SpacePointUtility.hpp index c995bfd3c36..f95ca4521f7 100644 --- a/Core/include/Acts/Utilities/SpacePointUtility.hpp +++ b/Core/include/Acts/Utilities/SpacePointUtility.hpp @@ -75,8 +75,7 @@ class SpacePointUtility { /// @param par local position /// @param cov local covariance /// @return vectors of the global coordinates and covariance of the SourceLink - std::tuple, Vector2, - std::optional> + std::tuple, Vector2, std::optional> globalCoords(const GeometryContext& gctx, const SourceLink& slink, const SourceLinkSurfaceAccessor& surfaceAccessor, const BoundVector& par, const BoundSquareMatrix& cov) const; diff --git a/Core/include/Acts/Utilities/StringHelpers.hpp b/Core/include/Acts/Utilities/StringHelpers.hpp index e77b317eb0d..16c4965e937 100644 --- a/Core/include/Acts/Utilities/StringHelpers.hpp +++ b/Core/include/Acts/Utilities/StringHelpers.hpp @@ -104,10 +104,10 @@ inline std::string toString(const Acts::Transform3& transform, return sout.str(); } -/// Print out a vector of ActsScalar +/// Print out a vector of double /// @param pVector The vector to print /// @param precision Numeric output precision -inline std::string toString(const std::vector& pVector, +inline std::string toString(const std::vector& pVector, int precision = 4) { std::ostringstream sout; sout << std::setiosflags(std::ios::fixed) << std::setprecision(precision); diff --git a/Core/include/Acts/Utilities/TrackHelpers.hpp b/Core/include/Acts/Utilities/TrackHelpers.hpp index 20cc1be8621..2e40c6b4988 100644 --- a/Core/include/Acts/Utilities/TrackHelpers.hpp +++ b/Core/include/Acts/Utilities/TrackHelpers.hpp @@ -8,11 +8,15 @@ #pragma once +#include "Acts/Definitions/Algebra.hpp" #include "Acts/Definitions/Tolerance.hpp" +#include "Acts/Definitions/TrackParametrization.hpp" +#include "Acts/EventData/MeasurementHelpers.hpp" #include "Acts/EventData/MultiTrajectoryHelpers.hpp" #include "Acts/EventData/TrackContainerFrontendConcept.hpp" #include "Acts/EventData/TrackParameters.hpp" #include "Acts/EventData/TrackProxyConcept.hpp" +#include "Acts/EventData/TrackStateProxyConcept.hpp" #include "Acts/EventData/TrackStateType.hpp" #include "Acts/Geometry/GeometryContext.hpp" #include "Acts/Propagator/StandardAborters.hpp" @@ -493,6 +497,219 @@ void trimTrack(track_proxy_t track, bool trimHoles, bool trimOutliers, trimTrackBack(track, trimHoles, trimOutliers, trimMaterial); } +/// Helper function to calculate the predicted residual and its covariance +/// @tparam nMeasurementDim the dimension of the measurement +/// @tparam track_state_proxy_t the track state proxy type +/// @param trackState the track state to calculate the residual from +/// @return a pair of the residual and its covariance +template +std::pair, ActsSquareMatrix> +calculatePredictedResidual(track_state_proxy_t trackState) { + using MeasurementVector = ActsVector; + using MeasurementMatrix = ActsSquareMatrix; + + if (!trackState.hasPredicted()) { + throw std::invalid_argument("track state has no predicted parameters"); + } + if (!trackState.hasCalibrated()) { + throw std::invalid_argument("track state has no calibrated parameters"); + } + + auto subspaceHelper = + trackState.template fixedBoundSubspaceHelper(); + + auto measurement = trackState.calibrated(); + auto measurementCovariance = trackState.calibratedCovariance(); + MeasurementVector predicted = + subspaceHelper.projectVector(trackState.predicted()); + MeasurementMatrix predictedCovariance = + subspaceHelper.projectMatrix(trackState.predictedCovariance()); + + MeasurementVector residual = measurement - predicted; + MeasurementMatrix residualCovariance = + measurementCovariance + predictedCovariance; + + return std::pair(residual, residualCovariance); +} + +/// Helper function to calculate the filtered residual and its covariance +/// @tparam nMeasurementDim the dimension of the measurement +/// @tparam track_state_proxy_t the track state proxy type +/// @param trackState the track state to calculate the residual from +/// @return a pair of the residual and its covariance +template +std::pair, ActsSquareMatrix> +calculateFilteredResidual(track_state_proxy_t trackState) { + using MeasurementVector = ActsVector; + using MeasurementMatrix = ActsSquareMatrix; + + if (!trackState.hasFiltered()) { + throw std::invalid_argument("track state has no filtered parameters"); + } + if (!trackState.hasCalibrated()) { + throw std::invalid_argument("track state has no calibrated parameters"); + } + + auto subspaceHelper = + trackState.template fixedBoundSubspaceHelper(); + + auto measurement = trackState.calibrated(); + auto measurementCovariance = trackState.calibratedCovariance(); + MeasurementVector filtered = + subspaceHelper.projectVector(trackState.filtered()); + MeasurementMatrix filteredCovariance = + subspaceHelper.projectMatrix(trackState.filteredCovariance()); + + MeasurementVector residual = measurement - filtered; + MeasurementMatrix residualCovariance = + measurementCovariance + filteredCovariance; + + return std::pair(residual, residualCovariance); +} + +/// Helper function to calculate the smoothed residual and its covariance +/// @tparam nMeasurementDim the dimension of the measurement +/// @tparam track_state_proxy_t the track state proxy type +/// @param trackState the track state to calculate the residual from +/// @return a pair of the residual and its covariance +template +std::pair, ActsSquareMatrix> +calculateSmoothedResidual(track_state_proxy_t trackState) { + using MeasurementVector = ActsVector; + using MeasurementMatrix = ActsSquareMatrix; + + if (!trackState.hasSmoothed()) { + throw std::invalid_argument("track state has no smoothed parameters"); + } + if (!trackState.hasCalibrated()) { + throw std::invalid_argument("track state has no calibrated parameters"); + } + + auto subspaceHelper = + trackState.template fixedBoundSubspaceHelper(); + + auto measurement = trackState.calibrated(); + auto measurementCovariance = trackState.calibratedCovariance(); + MeasurementVector smoothed = + subspaceHelper.projectVector(trackState.smoothed()); + MeasurementMatrix smoothedCovariance = + subspaceHelper.projectMatrix(trackState.smoothedCovariance()); + + MeasurementVector residual = measurement - smoothed; + MeasurementMatrix residualCovariance = + measurementCovariance + smoothedCovariance; + + return std::pair(residual, residualCovariance); +} + +/// Helper function to calculate the predicted chi2 +/// @tparam track_state_proxy_t the track state proxy type +/// @param trackState the track state to calculate the chi2 from +/// @return the chi2 +template +double calculatePredictedChi2(track_state_proxy_t trackState) { + if (!trackState.hasPredicted()) { + throw std::invalid_argument("track state has no predicted parameters"); + } + if (!trackState.hasCalibrated()) { + throw std::invalid_argument("track state has no calibrated parameters"); + } + + return visit_measurement( + trackState.calibratedSize(), + [&](std::integral_constant) { + auto [residual, residualCovariance] = + calculatePredictedResidual(trackState); + + return residual.transpose() * residualCovariance.inverse() * residual; + }); +} + +/// Helper function to calculate the filtered chi2 +/// @tparam track_state_proxy_t the track state proxy type +/// @param trackState the track state to calculate the chi2 from +/// @return the chi2 +template +double calculateFilteredChi2(track_state_proxy_t trackState) { + if (!trackState.hasFiltered()) { + throw std::invalid_argument("track state has no filtered parameters"); + } + if (!trackState.hasCalibrated()) { + throw std::invalid_argument("track state has no calibrated parameters"); + } + + return visit_measurement( + trackState.calibratedSize(), + [&](std::integral_constant) { + auto [residual, residualCovariance] = + calculateFilteredResidual(trackState); + + return residual.transpose() * residualCovariance.inverse() * residual; + }); +} + +/// Helper function to calculate the smoothed chi2 +/// @tparam track_state_proxy_t the track state proxy type +/// @param trackState the track state to calculate the chi2 from +/// @return the chi2 +template +double calculateSmoothedChi2(track_state_proxy_t trackState) { + if (!trackState.hasSmoothed()) { + throw std::invalid_argument("track state has no smoothed parameters"); + } + if (!trackState.hasCalibrated()) { + throw std::invalid_argument("track state has no calibrated parameters"); + } + + return visit_measurement( + trackState.calibratedSize(), + [&](std::integral_constant) { + auto [residual, residualCovariance] = + calculateSmoothedResidual(trackState); + + return residual.transpose() * residualCovariance.inverse() * residual; + }); +} + +/// Helper function to calculate the unbiased track parameters and their +/// covariance (i.e. fitted track parameters with this measurement removed) +/// using Eq.(12a)-Eq.(12c) of NIMA 262, 444 (1987) +/// @tparam track_state_proxy_t the track state proxy type +/// @param trackState the track state to calculate the unbiased parameters from +/// @return a pair of the unbiased parameters and their covariance +template +std::pair calculateUnbiasedParametersCovariance( + track_state_proxy_t trackState) { + if (!trackState.hasSmoothed()) { + throw std::invalid_argument("track state has no smoothed parameters"); + } + if (!trackState.hasCalibrated()) { + throw std::invalid_argument("track state has no calibrated parameters"); + } + + return visit_measurement( + trackState.calibratedSize(), + [&](std::integral_constant) { + FixedBoundSubspaceHelper subspaceHelper = + trackState.template projectorSubspaceHelper(); + + // TODO use subspace helper for projection instead + auto H = subspaceHelper.projector(); + auto s = trackState.smoothed(); + auto C = trackState.smoothedCovariance(); + auto m = trackState.template calibrated(); + auto V = trackState.template calibratedCovariance(); + auto K = + (C * H.transpose() * (H * C * H.transpose() - V).inverse()).eval(); + BoundVector unbiasedParamsVec = s + K * (m - H * s); + BoundMatrix unbiasedParamsCov = C - K * H * C; + return std::make_pair(unbiasedParamsVec, unbiasedParamsCov); + }); +} + } // namespace Acts namespace std { diff --git a/Core/include/Acts/Utilities/VectorHelpers.hpp b/Core/include/Acts/Utilities/VectorHelpers.hpp index 8f09a6d0591..bec3e874cf9 100644 --- a/Core/include/Acts/Utilities/VectorHelpers.hpp +++ b/Core/include/Acts/Utilities/VectorHelpers.hpp @@ -125,19 +125,19 @@ double eta(const Eigen::MatrixBase& v) noexcept { /// @param direction for this evaluatoin /// /// @return cos(phi), sin(phi), cos(theta), sin(theta), 1/sin(theta) -inline std::array evaluateTrigonomics(const Vector3& direction) { - const ActsScalar x = direction(0); // == cos(phi) * sin(theta) - const ActsScalar y = direction(1); // == sin(phi) * sin(theta) - const ActsScalar z = direction(2); // == cos(theta) +inline std::array evaluateTrigonomics(const Vector3& direction) { + const double x = direction(0); // == cos(phi) * sin(theta) + const double y = direction(1); // == sin(phi) * sin(theta) + const double z = direction(2); // == cos(theta) // can be turned into cosine/sine - const ActsScalar cosTheta = z; - const ActsScalar sinTheta = std::sqrt(1 - z * z); + const double cosTheta = z; + const double sinTheta = std::sqrt(1 - z * z); assert(sinTheta != 0 && "VectorHelpers: Vector is parallel to the z-axis " "which leads to division by zero"); - const ActsScalar invSinTheta = 1. / sinTheta; - const ActsScalar cosPhi = x * invSinTheta; - const ActsScalar sinPhi = y * invSinTheta; + const double invSinTheta = 1. / sinTheta; + const double cosPhi = x * invSinTheta; + const double sinPhi = y * invSinTheta; return {cosPhi, sinPhi, cosTheta, sinTheta}; } diff --git a/Core/include/Acts/Utilities/detail/grid_helper.hpp b/Core/include/Acts/Utilities/detail/grid_helper.hpp index efc0f0a70cf..287a9f69a08 100644 --- a/Core/include/Acts/Utilities/detail/grid_helper.hpp +++ b/Core/include/Acts/Utilities/detail/grid_helper.hpp @@ -162,7 +162,7 @@ template struct grid_helper_impl { template static void getBinCenter( - std::array& center, + std::array& center, const std::array& localIndices, const std::tuple& axes) { center.at(N) = std::get(axes).getBinCenter(localIndices.at(N)); @@ -203,7 +203,7 @@ struct grid_helper_impl { template static void getLowerLeftBinEdge( - std::array& llEdge, + std::array& llEdge, const std::array& localIndices, const std::tuple& axes) { llEdge.at(N) = std::get(axes).getBinLowerBound(localIndices.at(N)); @@ -235,7 +235,7 @@ struct grid_helper_impl { template static void getUpperRightBinEdge( - std::array& urEdge, + std::array& urEdge, const std::array& localIndices, const std::tuple& axes) { urEdge.at(N) = std::get(axes).getBinUpperBound(localIndices.at(N)); @@ -252,21 +252,21 @@ struct grid_helper_impl { template static void getMin(const std::tuple& axes, - std::array& minArray) { + std::array& minArray) { minArray[N] = std::get(axes).getMin(); grid_helper_impl::getMin(axes, minArray); } template static void getMax(const std::tuple& axes, - std::array& maxArray) { + std::array& maxArray) { maxArray[N] = std::get(axes).getMax(); grid_helper_impl::getMax(axes, maxArray); } template static void getWidth(const std::tuple& axes, - std::array& widthArray) { + std::array& widthArray) { widthArray[N] = std::get(axes).getBinWidth(); grid_helper_impl::getWidth(axes, widthArray); } @@ -328,7 +328,7 @@ template <> struct grid_helper_impl<0u> { template static void getBinCenter( - std::array& center, + std::array& center, const std::array& localIndices, const std::tuple& axes) { center.at(0u) = std::get<0u>(axes).getBinCenter(localIndices.at(0u)); @@ -361,7 +361,7 @@ struct grid_helper_impl<0u> { template static void getLowerLeftBinEdge( - std::array& llEdge, + std::array& llEdge, const std::array& localIndices, const std::tuple& axes) { llEdge.at(0u) = std::get<0u>(axes).getBinLowerBound(localIndices.at(0u)); @@ -389,7 +389,7 @@ struct grid_helper_impl<0u> { template static void getUpperRightBinEdge( - std::array& urEdge, + std::array& urEdge, const std::array& localIndices, const std::tuple& axes) { urEdge.at(0u) = std::get<0u>(axes).getBinUpperBound(localIndices.at(0u)); @@ -404,19 +404,19 @@ struct grid_helper_impl<0u> { template static void getMin(const std::tuple& axes, - std::array& minArray) { + std::array& minArray) { minArray[0u] = std::get<0u>(axes).getMin(); } template static void getMax(const std::tuple& axes, - std::array& maxArray) { + std::array& maxArray) { maxArray[0u] = std::get<0u>(axes).getMax(); } template static void getWidth(const std::tuple& axes, - std::array& widthArray) { + std::array& widthArray) { widthArray[0u] = std::get<0u>(axes).getBinWidth(); } @@ -518,10 +518,10 @@ struct grid_helper { /// @pre @c localIndices must only contain valid bin indices (i.e. excluding /// under-/overflow bins). template - static std::array getBinCenter( + static std::array getBinCenter( const std::array& localIndices, const std::tuple& axes) { - std::array center{}; + std::array center{}; constexpr std::size_t MAX = sizeof...(Axes) - 1; grid_helper_impl::getBinCenter(center, localIndices, axes); @@ -608,10 +608,10 @@ struct grid_helper { /// @pre @c localIndices must only contain valid bin indices (excluding /// underflow bins). template - static std::array getLowerLeftBinEdge( + static std::array getLowerLeftBinEdge( const std::array& localIndices, const std::tuple& axes) { - std::array llEdge{}; + std::array llEdge{}; constexpr std::size_t MAX = sizeof...(Axes) - 1; grid_helper_impl::getLowerLeftBinEdge(llEdge, localIndices, axes); @@ -682,10 +682,10 @@ struct grid_helper { /// @pre @c localIndices must only contain valid bin indices (excluding /// overflow bins). template - static std::array getUpperRightBinEdge( + static std::array getUpperRightBinEdge( const std::array& localIndices, const std::tuple& axes) { - std::array urEdge{}; + std::array urEdge{}; constexpr std::size_t MAX = sizeof...(Axes) - 1; grid_helper_impl::getUpperRightBinEdge(urEdge, localIndices, axes); @@ -722,9 +722,9 @@ struct grid_helper { /// @param [in] axes actual axis objects spanning the grid /// @return array returning the minima of all given axes template - static std::array getMin( + static std::array getMin( const std::tuple& axes) { - std::array minArray{}; + std::array minArray{}; grid_helper_impl::getMin(axes, minArray); return minArray; } @@ -735,9 +735,9 @@ struct grid_helper { /// @param [in] axes actual axis objects spanning the grid /// @return array returning the maxima of all given axes template - static std::array getMax( + static std::array getMax( const std::tuple& axes) { - std::array maxArray{}; + std::array maxArray{}; grid_helper_impl::getMax(axes, maxArray); return maxArray; } @@ -748,9 +748,9 @@ struct grid_helper { /// @param [in] axes actual axis objects spanning the grid /// @return array returning the maxima of all given axes template - static std::array getWidth( + static std::array getWidth( const std::tuple& axes) { - std::array widthArray{}; + std::array widthArray{}; grid_helper_impl::getWidth(axes, widthArray); return widthArray; } diff --git a/Core/include/Acts/Vertexing/HelicalTrackLinearizer.hpp b/Core/include/Acts/Vertexing/HelicalTrackLinearizer.hpp index fa1eef6d50a..0257d8ec730 100644 --- a/Core/include/Acts/Vertexing/HelicalTrackLinearizer.hpp +++ b/Core/include/Acts/Vertexing/HelicalTrackLinearizer.hpp @@ -53,7 +53,7 @@ class HelicalTrackLinearizer { /// Tolerance determining how close we need to get to the Perigee surface to /// reach it during propagation - ActsScalar targetTolerance = 1e-12; + double targetTolerance = 1e-12; }; /// @brief Constructor diff --git a/Core/include/Acts/Vertexing/NumericalTrackLinearizer.hpp b/Core/include/Acts/Vertexing/NumericalTrackLinearizer.hpp index 00d5cddf989..e9beca46f36 100644 --- a/Core/include/Acts/Vertexing/NumericalTrackLinearizer.hpp +++ b/Core/include/Acts/Vertexing/NumericalTrackLinearizer.hpp @@ -79,11 +79,11 @@ class NumericalTrackLinearizer { /// Tolerance determining how close we need to get to a surface to /// reach it during propagation - ActsScalar targetTolerance = 1e-12; + double targetTolerance = 1e-12; /// Setting size of the perturbation delta for calculation of numerical /// derivatives (i.e., f'(x) ~ (f(x+delta) - f(x)) / delta) - ActsScalar delta = 1e-8; + double delta = 1e-8; }; /// @brief Constructor diff --git a/Core/include/Acts/Vertexing/SingleSeedVertexFinder.hpp b/Core/include/Acts/Vertexing/SingleSeedVertexFinder.hpp index cc5bdf20289..cd05eb4eb0a 100644 --- a/Core/include/Acts/Vertexing/SingleSeedVertexFinder.hpp +++ b/Core/include/Acts/Vertexing/SingleSeedVertexFinder.hpp @@ -39,47 +39,47 @@ class SingleSeedVertexFinder { struct Config { /// maximum deviation in phi between the near and middle spacepoints or /// middle and far spacepoints - Acts::ActsScalar maxPhideviation = 0.08; + double maxPhideviation = 0.08; /// maximum deviation in X-Y between the first 2 spacepoints and the last 2 /// spacepoints - Acts::ActsScalar maxXYdeviation = 0.08; + double maxXYdeviation = 0.08; /// maximum deviation in 3D between the first 2 spacepoints and the last 2 /// spacepoints - Acts::ActsScalar maxXYZdeviation = 0.08; + double maxXYZdeviation = 0.08; /// minimum angle between Z axis and a triplet, effectively removing /// triplets with large |eta| - Acts::ActsScalar minTheta = 1.; + double minTheta = 1.; /// thresholds for near, middle, and far spacepoints - Acts::ActsScalar rMinNear = 20.f * Acts::UnitConstants::mm; - Acts::ActsScalar rMaxNear = 60.f * Acts::UnitConstants::mm; - Acts::ActsScalar rMinMiddle = 150.f * Acts::UnitConstants::mm; - Acts::ActsScalar rMaxMiddle = 190.f * Acts::UnitConstants::mm; - Acts::ActsScalar rMinFar = 280.f * Acts::UnitConstants::mm; - Acts::ActsScalar rMaxFar = 320.f * Acts::UnitConstants::mm; + double rMinNear = 20.f * Acts::UnitConstants::mm; + double rMaxNear = 60.f * Acts::UnitConstants::mm; + double rMinMiddle = 150.f * Acts::UnitConstants::mm; + double rMaxMiddle = 190.f * Acts::UnitConstants::mm; + double rMinFar = 280.f * Acts::UnitConstants::mm; + double rMaxFar = 320.f * Acts::UnitConstants::mm; /// number of phi slices, at least 3 to avoid duplicities /// it should be less than 2*pi/maxPhideviation in order not to loop over /// triplets that will be rejected by maxPhideviation anyway std::uint32_t numPhiSlices = 60; /// use only a fraction of available phi slices to speed up calculations; - Acts::ActsScalar useFracPhiSlices = 0.5; + double useFracPhiSlices = 0.5; /// number of z slices std::uint32_t numZSlices = 150; /// use only a fraction of available z slices to speed up calculations; - Acts::ActsScalar useFracZSlices = 0.5; + double useFracZSlices = 0.5; /// maximum |z| to consider, z slices will be done within the range /// (-maxAbsZ,maxAbsZ) /// values of maxAbsZ, maxZPosition, rMaxFar, and minTheta should be /// set reasonably with respect to each other - Acts::ActsScalar maxAbsZ = 450. * Acts::UnitConstants::mm; + double maxAbsZ = 450. * Acts::UnitConstants::mm; /// maximum Z position of the vertex at the point closest to the Z axis - Acts::ActsScalar maxZPosition = 200.f * Acts::UnitConstants::mm; + double maxZPosition = 200.f * Acts::UnitConstants::mm; /// maximum R position of the vertex at the point closest to the Z axis - Acts::ActsScalar maxRPosition = 10.f * Acts::UnitConstants::mm; + double maxRPosition = 10.f * Acts::UnitConstants::mm; /// chi^2 minimalization will happen with respect to "planes" or "rays" std::string minimalizeWRT = "planes"; @@ -88,9 +88,9 @@ class SingleSeedVertexFinder { /// chi^2 std::uint32_t maxIterations = 20; /// each iteration, discard this fraction of triplets with the largest chi^2 - Acts::ActsScalar removeFraction = 0.10; + double removeFraction = 0.10; /// if the vertex estimation moves less than this, stop iterations - Acts::ActsScalar minVtxShift = 0.3f * Acts::UnitConstants::mm; + double minVtxShift = 0.3f * Acts::UnitConstants::mm; }; /// Const access to the config @@ -126,11 +126,11 @@ class SingleSeedVertexFinder { /// @brief Struct to store sorted spacepoints for each layer (near, middle, and far), for each slice of phi, and for each slice of z struct SortedSpacepoints { SortedSpacepoints(const int phiSize, const int zSize) { - std::vector> helper = {}; - std::vector>> - helperZ(zSize, helper); - std::vector>>> + std::vector> helper = {}; + std::vector>> helperZ( + zSize, helper); + std::vector< + std::vector>>> helperPhi(phiSize, helperZ); sortedSP.fill(helperPhi); } @@ -140,8 +140,9 @@ class SingleSeedVertexFinder { /// @param phi Index of the phi slice /// @param z Index of the z slice /// @return Non-const vector of spacepoints - inline std::vector>& addSP( - int layer, int phi, int z) { + inline std::vector>& addSP(int layer, + int phi, + int z) { return sortedSP[layer][phi][z]; } @@ -150,13 +151,13 @@ class SingleSeedVertexFinder { /// @param phi Index of the phi slice /// @param z Index of the z slice /// @return Const vector of spacepoints - inline const std::vector>& - getSP(int layer, int phi, int z) const { + inline const std::vector>& getSP( + int layer, int phi, int z) const { return sortedSP[layer][phi][z]; } - std::array>>>, + std::array>>>, 3> sortedSP; }; @@ -187,7 +188,7 @@ class SingleSeedVertexFinder { /// @brief Calculates equation of the plane (alpha*x + beta*y + gamma*z + delta = 0), given the three points /// @param triplet A single triplet (with 3 spacepoints) /// @return A pair of {{alpha,beta,gamma},delta} - static std::pair makePlaneFromTriplet( + static std::pair makePlaneFromTriplet( const Triplet& triplet); /// @brief Find a point (=the vertex) that has minimum chi^2 with respect to all planes defined by the triplets diff --git a/Core/include/Acts/Vertexing/SingleSeedVertexFinder.ipp b/Core/include/Acts/Vertexing/SingleSeedVertexFinder.ipp index 83b13d37d57..6dd6a588898 100644 --- a/Core/include/Acts/Vertexing/SingleSeedVertexFinder.ipp +++ b/Core/include/Acts/Vertexing/SingleSeedVertexFinder.ipp @@ -85,7 +85,7 @@ Acts::SingleSeedVertexFinder::sortSpacepoints( for (const auto& sp : spacepoints) { // phi will be saved for later - Acts::ActsScalar phi = detail::radian_pos(std::atan2(sp.y(), sp.x())); + double phi = detail::radian_pos(std::atan2(sp.y(), sp.x())); std::uint32_t phislice = static_cast( phi / (2 * std::numbers::pi) * m_cfg.numPhiSlices); if (phislice >= m_cfg.numPhiSlices) { @@ -144,12 +144,12 @@ Acts::SingleSeedVertexFinder::findTriplets( Acts::Vector2 vecB = {vecA[1], -vecA[0]}; vecB /= std::tan(m_cfg.maxXYZdeviation); Acts::Vector2 posR = Acts::Vector2(-m_cfg.maxZPosition, 0.) + vecA + vecB; - Acts::ActsScalar R = vecA.norm() / std::sin(m_cfg.maxXYZdeviation); - Acts::ActsScalar constB = -2. * posR[0]; - Acts::ActsScalar constC = - posR[0] * posR[0] + - (posR[1] - m_cfg.rMaxNear) * (posR[1] - m_cfg.rMaxNear) - R * R; - Acts::ActsScalar maxZMiddle = + double R = vecA.norm() / std::sin(m_cfg.maxXYZdeviation); + double constB = -2. * posR[0]; + double constC = posR[0] * posR[0] + + (posR[1] - m_cfg.rMaxNear) * (posR[1] - m_cfg.rMaxNear) - + R * R; + double maxZMiddle = -1. * (-constB - sqrt(constB * constB - 4. * constC)) / 2.; if (maxZMiddle <= 0) { ACTS_WARNING( @@ -160,14 +160,14 @@ Acts::SingleSeedVertexFinder::findTriplets( } // save some constant values for later - Acts::ActsScalar rNearRatio[2] = {m_cfg.rMinNear / m_cfg.rMaxMiddle, - m_cfg.rMaxNear / m_cfg.rMinMiddle}; - Acts::ActsScalar rMiddle[2] = {m_cfg.rMaxMiddle, m_cfg.rMinMiddle}; - Acts::ActsScalar rFarDelta[2] = { + double rNearRatio[2] = {m_cfg.rMinNear / m_cfg.rMaxMiddle, + m_cfg.rMaxNear / m_cfg.rMinMiddle}; + double rMiddle[2] = {m_cfg.rMaxMiddle, m_cfg.rMinMiddle}; + double rFarDelta[2] = { m_cfg.rMaxFar - m_cfg.rMinMiddle, m_cfg.rMinFar - m_cfg.rMaxMiddle, }; - Acts::ActsScalar zBinLength = 2. * m_cfg.maxAbsZ / m_cfg.numZSlices; + double zBinLength = 2. * m_cfg.maxAbsZ / m_cfg.numZSlices; // limits in terms of slice numbers std::uint32_t limitMiddleSliceFrom = @@ -190,25 +190,24 @@ Acts::SingleSeedVertexFinder::findTriplets( // calculate limits for near spacepoints, assuming the middle spacepoints // are within some boundaries bool isLessFrom = (middleZ <= limitAbsZSliceFrom); - Acts::ActsScalar deltaZfrom = - (middleZ - limitAbsZSliceFrom - 1) * zBinLength; - Acts::ActsScalar angleZfrom = + double deltaZfrom = (middleZ - limitAbsZSliceFrom - 1) * zBinLength; + double angleZfrom = std::atan2(rMiddle[isLessFrom], deltaZfrom) + m_cfg.maxXYZdeviation; std::uint32_t nearZFrom = 0; - if (angleZfrom < std::numbers::pi_v) { - Acts::ActsScalar new_deltaZfrom = + if (angleZfrom < std::numbers::pi) { + double new_deltaZfrom = rMiddle[isLessFrom] / std::tan(angleZfrom) / zBinLength; nearZFrom = static_cast(std::max( new_deltaZfrom * rNearRatio[isLessFrom] + limitAbsZSliceFrom, 0.)); } bool isLessTo = (middleZ < limitAbsZSliceTo); - Acts::ActsScalar deltaZto = (middleZ - limitAbsZSliceTo + 1) * zBinLength; - Acts::ActsScalar angleZto = + double deltaZto = (middleZ - limitAbsZSliceTo + 1) * zBinLength; + double angleZto = std::atan2(rMiddle[!isLessTo], deltaZto) - m_cfg.maxXYZdeviation; std::uint32_t nearZTo = m_cfg.numZSlices; if (angleZto > 0) { - Acts::ActsScalar new_deltaZto = + double new_deltaZto = rMiddle[!isLessTo] / std::tan(angleZto) / zBinLength; nearZTo = static_cast(std::max( new_deltaZto * rNearRatio[!isLessTo] + limitAbsZSliceTo, 0.)); @@ -222,12 +221,11 @@ Acts::SingleSeedVertexFinder::findTriplets( // spacepoints are within some boundaries bool isMiddleLess = (middleZ <= nearZ); - Acts::ActsScalar delta2Zfrom = (middleZ - nearZ - 1) * zBinLength; - Acts::ActsScalar angle2Zfrom = - std::atan2(rFarDelta[isMiddleLess], delta2Zfrom) + - m_cfg.maxXYZdeviation; + double delta2Zfrom = (middleZ - nearZ - 1) * zBinLength; + double angle2Zfrom = std::atan2(rFarDelta[isMiddleLess], delta2Zfrom) + + m_cfg.maxXYZdeviation; std::uint32_t farZFrom = 0; - if (angle2Zfrom < std::numbers::pi_v) { + if (angle2Zfrom < std::numbers::pi) { farZFrom = static_cast(std::max( (rFarDelta[isMiddleLess] / std::tan(angle2Zfrom) / zBinLength) + middleZ, @@ -238,10 +236,9 @@ Acts::SingleSeedVertexFinder::findTriplets( } isMiddleLess = (middleZ < nearZ); - Acts::ActsScalar delta2Zto = (middleZ - nearZ + 1) * zBinLength; - Acts::ActsScalar angle2Zto = - std::atan2(rFarDelta[!isMiddleLess], delta2Zto) - - m_cfg.maxXYZdeviation; + double delta2Zto = (middleZ - nearZ + 1) * zBinLength; + double angle2Zto = std::atan2(rFarDelta[!isMiddleLess], delta2Zto) - + m_cfg.maxXYZdeviation; std::uint32_t farZTo = m_cfg.numZSlices; if (angle2Zto > 0) { farZTo = static_cast(std::max( @@ -282,13 +279,13 @@ Acts::SingleSeedVertexFinder::findTriplets( // for all near spacepoints in this slice for (const auto& nearSP : sortedSpacepoints.getSP(0, nearPhi, nearZ)) { - Acts::ActsScalar phiA = nearSP.second; + double phiA = nearSP.second; // for all middle spacepoints in this slice for (const auto& middleSP : sortedSpacepoints.getSP(1, middlePhi, middleZ)) { - Acts::ActsScalar phiB = middleSP.second; - Acts::ActsScalar deltaPhiAB = detail::difference_periodic( + double phiB = middleSP.second; + double deltaPhiAB = detail::difference_periodic( phiA, phiB, 2 * std::numbers::pi); if (std::abs(deltaPhiAB) > m_cfg.maxPhideviation) { continue; @@ -297,10 +294,9 @@ Acts::SingleSeedVertexFinder::findTriplets( // for all far spacepoints in this slice for (const auto& farSP : sortedSpacepoints.getSP(2, farPhi, farZ)) { - Acts::ActsScalar phiC = farSP.second; - Acts::ActsScalar deltaPhiBC = detail::difference_periodic( - phiB, phiC, - static_cast(2 * std::numbers::pi)); + double phiC = farSP.second; + double deltaPhiBC = detail::difference_periodic( + phiB, phiC, 2 * std::numbers::pi); if (std::abs(deltaPhiBC) > m_cfg.maxPhideviation) { continue; } @@ -328,14 +324,14 @@ template bool Acts::SingleSeedVertexFinder::tripletValidationAndUpdate( Acts::SingleSeedVertexFinder::Triplet& triplet) const { // slope for near+middle spacepoints - Acts::ActsScalar alpha1 = + double alpha1 = std::atan2(triplet.a.y() - triplet.b.y(), triplet.a.x() - triplet.b.x()); // slope for middle+far spacepoints - Acts::ActsScalar alpha2 = + double alpha2 = std::atan2(triplet.b.y() - triplet.c.y(), triplet.b.x() - triplet.c.x()); // these two slopes shouldn't be too different - Acts::ActsScalar deltaAlpha = detail::difference_periodic( - alpha1, alpha2, static_cast(2 * std::numbers::pi)); + double deltaAlpha = + detail::difference_periodic(alpha1, alpha2, 2 * std::numbers::pi); if (std::abs(deltaAlpha) > m_cfg.maxXYdeviation) { return false; } @@ -347,8 +343,8 @@ bool Acts::SingleSeedVertexFinder::tripletValidationAndUpdate( Acts::Vector3 bc{triplet.b.x() - triplet.c.x(), triplet.b.y() - triplet.c.y(), triplet.b.z() - triplet.c.z()}; // dot product of these two - Acts::ActsScalar cosTheta = (ab.dot(bc)) / (ab.norm() * bc.norm()); - Acts::ActsScalar theta = std::acos(cosTheta); + double cosTheta = (ab.dot(bc)) / (ab.norm() * bc.norm()); + double theta = std::acos(cosTheta); if (theta > m_cfg.maxXYZdeviation) { return false; } @@ -359,21 +355,21 @@ bool Acts::SingleSeedVertexFinder::tripletValidationAndUpdate( const Acts::Vector3& direction = ray.dir(); // norm to z-axis and to the ray Acts::Vector3 norm{-1. * direction[1], 1. * direction[0], 0}; - Acts::ActsScalar norm_size = norm.norm(); + double norm_size = norm.norm(); - Acts::ActsScalar tanTheta = norm_size / direction[2]; + double tanTheta = norm_size / direction[2]; if (std::abs(tanTheta) < std::tan(m_cfg.minTheta)) { return false; } // nearest distance from the ray to z-axis - Acts::ActsScalar dist = std::abs(startPoint.dot(norm)) / norm_size; + double dist = std::abs(startPoint.dot(norm)) / norm_size; if (dist > m_cfg.maxRPosition) { return false; } // z coordinate of the nearest distance from the ray to z-axis - Acts::ActsScalar zDist = + double zDist = direction.cross(norm).dot(startPoint) / (norm_size * norm_size); if (std::abs(zDist) > m_cfg.maxZPosition) { return false; @@ -388,7 +384,7 @@ bool Acts::SingleSeedVertexFinder::tripletValidationAndUpdate( } template -std::pair +std::pair Acts::SingleSeedVertexFinder::makePlaneFromTriplet( const Acts::SingleSeedVertexFinder::Triplet& triplet) { Acts::Vector3 a{triplet.a.x(), triplet.a.y(), triplet.a.z()}; @@ -399,7 +395,7 @@ Acts::SingleSeedVertexFinder::makePlaneFromTriplet( // vector (alpha,beta,gamma) normalized to unity for convenience Acts::Vector3 abg = ba.cross(ca).normalized(); - Acts::ActsScalar delta = -1. * abg.dot(a); + double delta = -1. * abg.dot(a); // plane (alpha*x + beta*y + gamma*z + delta = 0), split to {{alpha, beta, // gamma}, delta} for convenience @@ -423,8 +419,7 @@ Acts::SingleSeedVertexFinder::findClosestPointFromPlanes( Acts::Vector3 vtxPrev{m_cfg.rMaxFar, m_cfg.rMaxFar, m_cfg.maxAbsZ}; // (alpha-beta-gamma, delta), distance - std::vector< - std::pair, Acts::ActsScalar>> + std::vector, double>> tripletsWithPlanes; tripletsWithPlanes.reserve(triplets.size()); @@ -462,7 +457,7 @@ Acts::SingleSeedVertexFinder::findClosestPointFromPlanes( for (auto& triplet : tripletsWithPlanes) { const auto& abg = triplet.first.first; const auto& delta = triplet.first.second; - Acts::ActsScalar distance = std::abs(abg.dot(vtx) + delta); + double distance = std::abs(abg.dot(vtx) + delta); triplet.second = distance; } @@ -527,8 +522,7 @@ Acts::SingleSeedVertexFinder::findClosestPointFromRays( Acts::Vector3 vtxPrev{m_cfg.rMaxFar, m_cfg.rMaxFar, m_cfg.maxAbsZ}; // (startPoint, direction), distance - std::vector< - std::pair, Acts::ActsScalar>> + std::vector, double>> tripletsWithRays; tripletsWithRays.reserve(triplets.size()); @@ -568,7 +562,7 @@ Acts::SingleSeedVertexFinder::findClosestPointFromRays( for (auto& triplet : tripletsWithRays) { const auto& startPoint = triplet.first.first; const auto& direction = triplet.first.second; - Acts::ActsScalar distance = (vtx - startPoint).cross(direction).norm(); + double distance = (vtx - startPoint).cross(direction).norm(); triplet.second = distance; } diff --git a/Core/include/Acts/Vertexing/Vertex.hpp b/Core/include/Acts/Vertexing/Vertex.hpp index d656c7a199f..453fe34a9e0 100644 --- a/Core/include/Acts/Vertexing/Vertex.hpp +++ b/Core/include/Acts/Vertexing/Vertex.hpp @@ -50,7 +50,7 @@ class Vertex { Vector3 position() const; /// @return Returns time - ActsScalar time() const; + double time() const; /// @return Returns 4-position const Vector4& fullPosition() const; @@ -86,7 +86,7 @@ class Vertex { /// @brief Sets time /// /// @param time The time - void setTime(ActsScalar time); + void setTime(double time); /// @brief Sets 3x3 covariance /// diff --git a/Core/src/Detector/IndexedRootVolumeFinderBuilder.cpp b/Core/src/Detector/IndexedRootVolumeFinderBuilder.cpp index 0493750b9a3..ae1bee83e5d 100644 --- a/Core/src/Detector/IndexedRootVolumeFinderBuilder.cpp +++ b/Core/src/Detector/IndexedRootVolumeFinderBuilder.cpp @@ -21,15 +21,15 @@ void fillGridIndices2D( const Acts::GeometryContext& gctx, Grid2D& grid, const std::vector>& rootVolumes, - const std::array, 2u>& boundaries, + const std::array, 2u>& boundaries, const std::array& casts) { // Brute force loop over all bins & all volumes for (const auto [ic0, c0] : Acts::enumerate(boundaries[0u])) { if (ic0 > 0) { - Acts::ActsScalar v0 = 0.5 * (c0 + boundaries[0u][ic0 - 1]); + double v0 = 0.5 * (c0 + boundaries[0u][ic0 - 1]); for (const auto [ic1, c1] : Acts::enumerate(boundaries[1u])) { if (ic1 > 0) { - Acts::ActsScalar v1 = 0.5 * (c1 + boundaries[1u][ic1 - 1]); + double v1 = 0.5 * (c1 + boundaries[1u][ic1 - 1]); if (casts == std::array{Acts::BinningValue::binZ, Acts::BinningValue::binR}) { @@ -74,8 +74,7 @@ Acts::Experimental::IndexedRootVolumeFinderBuilder::construct( auto casts = std::array{m_casts[0u], m_casts[1u]}; - auto boundaries = - std::array, 2u>{rzphis[1], rzphis[0]}; + auto boundaries = std::array, 2u>{rzphis[1], rzphis[0]}; fillGridIndices2D(gctx, grid, rootVolumes, boundaries, casts); using IndexedDetectorVolumesImpl = diff --git a/Core/src/Detector/LayerStructureBuilder.cpp b/Core/src/Detector/LayerStructureBuilder.cpp index 94766a80d0d..76092582eea 100644 --- a/Core/src/Detector/LayerStructureBuilder.cpp +++ b/Core/src/Detector/LayerStructureBuilder.cpp @@ -48,8 +48,8 @@ void adaptBinningRange(std::vector& pBinning, const Acts::Extent& extent) { for (auto& pb : pBinning) { // Starting values - Acts::ActsScalar vmin = pb.edges.front(); - Acts::ActsScalar vmax = pb.edges.back(); + double vmin = pb.edges.front(); + double vmax = pb.edges.back(); // Get the number of bins std::size_t nBins = pb.bins(); // Check if extent overwrites that @@ -61,7 +61,7 @@ void adaptBinningRange(std::vector& pBinning, } // Possibly update the edges if (pb.axisType == Acts::AxisType::Equidistant) { - Acts::ActsScalar binWidth = (vmax - vmin) / nBins; + double binWidth = (vmax - vmin) / nBins; // Fill the edges pb.edges = {vmin}; pb.edges.resize(nBins + 1); diff --git a/Core/src/Detector/ProtoDetector.cpp b/Core/src/Detector/ProtoDetector.cpp index e305dc9052c..a1ec0009c57 100644 --- a/Core/src/Detector/ProtoDetector.cpp +++ b/Core/src/Detector/ProtoDetector.cpp @@ -99,13 +99,13 @@ void Acts::ProtoVolume::harmonize(bool legacy) { borders.push_back(static_cast(fVolume.extent.min(binValue))); for (unsigned int iv = 1; iv < cts.constituentVolumes.size(); ++iv) { auto& lv = cts.constituentVolumes[iv - 1u]; - ActsScalar zero = lv.extent.min(binValue); - ActsScalar low = lv.extent.max(binValue); + double zero = lv.extent.min(binValue); + double low = lv.extent.max(binValue); auto& hv = cts.constituentVolumes[iv]; - ActsScalar high = hv.extent.min(binValue); - ActsScalar mid = 0.5 * (low + high); - ActsScalar max = hv.extent.max(binValue); + double high = hv.extent.min(binValue); + double mid = 0.5 * (low + high); + double max = hv.extent.max(binValue); lv.extent.set(binValue, zero, mid); hv.extent.set(binValue, mid, max); borders.push_back(mid); @@ -118,7 +118,7 @@ void Acts::ProtoVolume::harmonize(bool legacy) { std::vector boundaries = {}; // New container vector std::vector updatedConstituents; - ActsScalar containerMin = extent.min(binValue); + double containerMin = extent.min(binValue); if (fVolume.extent.min(binValue) > containerMin) { ProtoVolume gap; gap.name = name + "-gap-" + std::to_string(gaps++); @@ -133,9 +133,9 @@ void Acts::ProtoVolume::harmonize(bool legacy) { updatedConstituents.push_back(lv); borders.push_back(static_cast(lv.extent.min(binValue))); // check if a gap to the next is needed - ActsScalar low = lv.extent.max(binValue); + double low = lv.extent.max(binValue); auto& hv = cts.constituentVolumes[iv]; - ActsScalar high = hv.extent.min(binValue); + double high = hv.extent.min(binValue); if (high > low) { ProtoVolume gap; gap.name = name + "-gap-" + std::to_string(gaps++); @@ -144,11 +144,11 @@ void Acts::ProtoVolume::harmonize(bool legacy) { borders.push_back(static_cast(low)); } } - ActsScalar constituentsMax = lVolume.extent.max(binValue); + double constituentsMax = lVolume.extent.max(binValue); updatedConstituents.push_back(lVolume); borders.push_back(static_cast(constituentsMax)); // Check the container min/max setting - ActsScalar containerMax = extent.max(binValue); + double containerMax = extent.max(binValue); if (constituentsMax < containerMax) { ProtoVolume gap; gap.name = name + "-gap-" + std::to_string(gaps++); diff --git a/Core/src/Detector/VolumeStructureBuilder.cpp b/Core/src/Detector/VolumeStructureBuilder.cpp index e63a13d5039..9103164ad58 100644 --- a/Core/src/Detector/VolumeStructureBuilder.cpp +++ b/Core/src/Detector/VolumeStructureBuilder.cpp @@ -50,7 +50,7 @@ Acts::Experimental::VolumeStructureBuilder::construct( // The transform from the extent auto eTransform = Transform3::Identity(); - std::vector boundValues = m_cfg.boundValues; + std::vector boundValues = m_cfg.boundValues; // This code dispatches into the dedicated volume types switch (m_cfg.boundsType) { @@ -64,8 +64,8 @@ Acts::Experimental::VolumeStructureBuilder::construct( "object. It needs at least 5 parameters, while " + std::to_string(boundValues.size()) + " where given"); } - auto bArray = toArray( - boundValues); + auto bArray = + toArray(boundValues); volumeBounds = std::make_unique(bArray); } break; case VolumeBounds::BoundsType::eCuboid: { @@ -144,7 +144,7 @@ Acts::Experimental::VolumeStructureBuilder::construct( } // Check if phi has been constraint, otherwise fill it with full coverage if (boundValues.size() == 3u) { - boundValues.push_back(std::numbers::pi_v); + boundValues.push_back(std::numbers::pi); boundValues.push_back(0.); } ACTS_VERBOSE(" - cylindrical shape with [iR, oR, hZ, sPhi, mPhi] = " diff --git a/Core/src/Detector/detail/BlueprintHelper.cpp b/Core/src/Detector/detail/BlueprintHelper.cpp index bf440c61acc..b0167188021 100644 --- a/Core/src/Detector/detail/BlueprintHelper.cpp +++ b/Core/src/Detector/detail/BlueprintHelper.cpp @@ -122,7 +122,7 @@ void Acts::Experimental::detail::BlueprintHelper::fillGapsCylindrical( unsigned int igap = 0; for (auto& child : node.children) { auto [neg, pos] = endPointsXYZ(*child, bVal); - ActsScalar gapSpan = (neg - negC).norm(); + double gapSpan = (neg - negC).norm(); if (gapSpan > s_onSurfaceTolerance) { // Fill a gap node auto gapName = node.name + "_gap_" + std::to_string(igap); @@ -131,7 +131,7 @@ void Acts::Experimental::detail::BlueprintHelper::fillGapsCylindrical( gapTransform.pretranslate(0.5 * (neg + negC)); auto gap = std::make_unique( gapName, gapTransform, VolumeBounds::eCylinder, - std::vector{cInnerR, cOuterR, 0.5 * gapSpan}); + std::vector{cInnerR, cOuterR, 0.5 * gapSpan}); gaps.push_back(std::move(gap)); ++igap; } @@ -139,7 +139,7 @@ void Acts::Experimental::detail::BlueprintHelper::fillGapsCylindrical( negC = pos; } // Check if a last one needs to be filled - ActsScalar gapSpan = (negC - posC).norm(); + double gapSpan = (negC - posC).norm(); if (gapSpan > s_onSurfaceTolerance) { // Fill a gap node auto gapName = node.name + "_gap_" + std::to_string(igap); @@ -148,7 +148,7 @@ void Acts::Experimental::detail::BlueprintHelper::fillGapsCylindrical( gapTransform.pretranslate(0.5 * (negC + posC)); auto gap = std::make_unique( gapName, gapTransform, VolumeBounds::eCylinder, - std::vector{cInnerR, cOuterR, 0.5 * gapSpan}); + std::vector{cInnerR, cOuterR, 0.5 * gapSpan}); gaps.push_back(std::move(gap)); } @@ -163,14 +163,13 @@ void Acts::Experimental::detail::BlueprintHelper::fillGapsCylindrical( } // Fill the gaps in R unsigned int igap = 0; - ActsScalar lastR = cInnerR; + double lastR = cInnerR; for (auto& child : node.children) { - ActsScalar iR = child->boundaryValues[0]; + double iR = child->boundaryValues[0]; if (std::abs(iR - lastR) > s_onSurfaceTolerance) { auto gap = std::make_unique( node.name + "_gap_" + std::to_string(igap), node.transform, - VolumeBounds::eCylinder, - std::vector{lastR, iR, cHalfZ}); + VolumeBounds::eCylinder, std::vector{lastR, iR, cHalfZ}); gaps.push_back(std::move(gap)); ++igap; } @@ -181,8 +180,7 @@ void Acts::Experimental::detail::BlueprintHelper::fillGapsCylindrical( if (std::abs(lastR - cOuterR) > s_onSurfaceTolerance) { auto gap = std::make_unique( node.name + "_gap_" + std::to_string(igap), node.transform, - VolumeBounds::eCylinder, - std::vector{lastR, cOuterR, cHalfZ}); + VolumeBounds::eCylinder, std::vector{lastR, cOuterR, cHalfZ}); gaps.push_back(std::move(gap)); } } else { @@ -237,14 +235,14 @@ void Acts::Experimental::detail::BlueprintHelper::fillGapsCuboidal( unsigned int igap = 0; for (auto& child : node.children) { auto [neg, pos] = endPointsXYZ(*child, binVal); - ActsScalar gapSpan = (neg - negC).norm(); + double gapSpan = (neg - negC).norm(); if (gapSpan > s_onSurfaceTolerance) { // Fill a gap node auto gapName = node.name + "_gap_" + std::to_string(igap); auto gapTransform = Transform3::Identity(); gapTransform.rotate(node.transform.rotation()); gapTransform.pretranslate(0.5 * (neg + negC)); - std::vector gapBounds{0, 0, 0}; + std::vector gapBounds{0, 0, 0}; gapBounds[toUnderlying(binVal)] = 0.5 * gapSpan; for (auto bv : allowedBinVals) { if (bv != binVal) { @@ -260,14 +258,14 @@ void Acts::Experimental::detail::BlueprintHelper::fillGapsCuboidal( negC = pos; } // Check if a last one needs to be filled - ActsScalar gapSpan = (negC - posC).norm(); + double gapSpan = (negC - posC).norm(); if (gapSpan > s_onSurfaceTolerance) { // Fill a gap node auto gapName = node.name + "_gap_" + std::to_string(igap); auto gapTransform = Transform3::Identity(); gapTransform.rotate(node.transform.rotation()); gapTransform.pretranslate(0.5 * (negC + posC)); - std::vector gapBounds{0, 0, 0}; + std::vector gapBounds{0, 0, 0}; gapBounds[toUnderlying(binVal)] = 0.5 * gapSpan; for (auto bv : allowedBinVals) { if (bv != binVal) { diff --git a/Core/src/Detector/detail/CuboidalDetectorHelper.cpp b/Core/src/Detector/detail/CuboidalDetectorHelper.cpp index ac2acd2482a..cda12f02de2 100644 --- a/Core/src/Detector/detail/CuboidalDetectorHelper.cpp +++ b/Core/src/Detector/detail/CuboidalDetectorHelper.cpp @@ -53,8 +53,8 @@ Acts::Experimental::detail::CuboidalDetectorHelper::connect( auto [sIndex, fIndex] = portalSets[toUnderlying(bValue)]; // Log the merge splits, i.e. the boundaries of the volumes - std::array, 3u> mergeSplits; - std::array mergeHalfLengths = { + std::array, 3u> mergeSplits; + std::array mergeHalfLengths = { 0., 0., 0., @@ -72,7 +72,7 @@ Acts::Experimental::detail::CuboidalDetectorHelper::connect( // Things that can be done without a loop be first/last check // Estimate the merge parameters: the scalar and the transform - using MergeParameters = std::tuple; + using MergeParameters = std::tuple; std::map mergeParameters; auto& firstVolume = volumes.front(); auto& lastVolume = volumes.back(); @@ -93,8 +93,8 @@ Acts::Experimental::detail::CuboidalDetectorHelper::connect( ->surface() .transform(gctx) .rotation(); - ActsScalar stepDown = firstBoundValues[toUnderlying(bValue)]; - ActsScalar stepUp = lastBoundValues[toUnderlying(bValue)]; + double stepDown = firstBoundValues[toUnderlying(bValue)]; + double stepUp = lastBoundValues[toUnderlying(bValue)]; // Take translation from first and last volume auto translationF = firstVolume->portalPtrs()[index] ->surface() @@ -113,7 +113,7 @@ Acts::Experimental::detail::CuboidalDetectorHelper::connect( portalTransform.prerotate(rotation); portalTransform.pretranslate(translation); // The half length to be kept - ActsScalar keepHalfLength = + double keepHalfLength = firstBoundValues[toUnderlying(counterPart(mergeValue))]; mergeParameters[index] = MergeParameters(keepHalfLength, portalTransform); } @@ -183,7 +183,7 @@ Acts::Experimental::detail::CuboidalDetectorHelper::connect( } // The stitch boundaries for portal pointing - std::vector stitchBoundaries; + std::vector stitchBoundaries; stitchBoundaries.push_back(-mergeHalfLengths[im]); for (auto step : mergeSplits[im]) { stitchBoundaries.push_back(stitchBoundaries.back() + step); @@ -322,7 +322,7 @@ Acts::Experimental::detail::CuboidalDetectorHelper::connect( return dShell; } -std::array, 3u> +std::array, 3u> Acts::Experimental::detail::CuboidalDetectorHelper::xyzBoundaries( [[maybe_unused]] const GeometryContext& gctx, [[maybe_unused]] const std::vector< @@ -332,16 +332,16 @@ Acts::Experimental::detail::CuboidalDetectorHelper::xyzBoundaries( ACTS_LOCAL_LOGGER(getDefaultLogger("CuboidalDetectorHelper", logLevel)); // The return boundaries - std::array, 3u> boundaries; + std::array, 3u> boundaries; // The map for collecting - std::array, 3u> valueMaps; + std::array, 3u> valueMaps; auto& xMap = valueMaps[0u]; auto& yMap = valueMaps[1u]; auto& zMap = valueMaps[2u]; - auto fillMap = [&](std::map& map, - const std::array& values) { + auto fillMap = [&](std::map& map, + const std::array& values) { for (auto v : values) { // This will insert v with a value of 0 if it doesn't exist ++map[v]; @@ -353,18 +353,18 @@ Acts::Experimental::detail::CuboidalDetectorHelper::xyzBoundaries( if (v->volumeBounds().type() == Acts::VolumeBounds::BoundsType::eCuboid) { auto bValues = v->volumeBounds().values(); // The min/max values - ActsScalar halfX = bValues[CuboidVolumeBounds::BoundValues::eHalfLengthX]; - ActsScalar halfY = bValues[CuboidVolumeBounds::BoundValues::eHalfLengthY]; - ActsScalar halfZ = bValues[CuboidVolumeBounds::BoundValues::eHalfLengthZ]; + double halfX = bValues[CuboidVolumeBounds::BoundValues::eHalfLengthX]; + double halfY = bValues[CuboidVolumeBounds::BoundValues::eHalfLengthY]; + double halfZ = bValues[CuboidVolumeBounds::BoundValues::eHalfLengthZ]; // Get the transform @todo use a center of gravity of the detector auto translation = v->transform(gctx).translation(); // The min/max values - ActsScalar xMin = translation.x() - halfX; - ActsScalar xMax = translation.x() + halfX; - ActsScalar yMin = translation.y() - halfY; - ActsScalar yMax = translation.y() + halfY; - ActsScalar zMin = translation.z() - halfZ; - ActsScalar zMax = translation.z() + halfZ; + double xMin = translation.x() - halfX; + double xMax = translation.x() + halfX; + double yMin = translation.y() - halfY; + double yMax = translation.y() + halfY; + double zMin = translation.z() - halfZ; + double zMax = translation.z() + halfZ; // Fill the maps fillMap(xMap, {xMin, xMax}); fillMap(yMap, {yMin, yMax}); diff --git a/Core/src/Detector/detail/CylindricalDetectorHelper.cpp b/Core/src/Detector/detail/CylindricalDetectorHelper.cpp index 499d28c0785..545e0947797 100644 --- a/Core/src/Detector/detail/CylindricalDetectorHelper.cpp +++ b/Core/src/Detector/detail/CylindricalDetectorHelper.cpp @@ -80,9 +80,8 @@ namespace { /// /// @return a new portal replacement object Acts::Experimental::PortalReplacement createDiscReplacement( - const Acts::Transform3& transform, - const std::vector& rBoundaries, - const std::vector& phiBoundaries, unsigned int index, + const Acts::Transform3& transform, const std::vector& rBoundaries, + const std::vector& phiBoundaries, unsigned int index, Acts::Direction dir) { // Autodetector stitch value Acts::BinningValue stitchValue = phiBoundaries.size() == 2u @@ -117,9 +116,9 @@ Acts::Experimental::PortalReplacement createDiscReplacement( /// /// @return a new portal replacement object Acts::Experimental::PortalReplacement createCylinderReplacement( - const Acts::Transform3& transform, Acts::ActsScalar r, - const std::vector& zBoundaries, - const std::vector& phiBoundaries, unsigned int index, + const Acts::Transform3& transform, double r, + const std::vector& zBoundaries, + const std::vector& phiBoundaries, unsigned int index, Acts::Direction dir) { // Autodetector stitch value Acts::BinningValue stitchValue = phiBoundaries.size() == 2u @@ -155,9 +154,8 @@ Acts::Experimental::PortalReplacement createCylinderReplacement( /// @return a new portal replacement object Acts::Experimental::PortalReplacement createSectorReplacement( const Acts::GeometryContext& gctx, const Acts::Vector3& volumeCenter, - const Acts::Surface& refSurface, - const std::vector& boundaries, Acts::BinningValue binning, - unsigned int index, Acts::Direction dir) { + const Acts::Surface& refSurface, const std::vector& boundaries, + Acts::BinningValue binning, unsigned int index, Acts::Direction dir) { // Get a reference transform const auto& refTransform = refSurface.transform(gctx); auto refRotation = refTransform.rotation(); @@ -176,7 +174,7 @@ Acts::Experimental::PortalReplacement createSectorReplacement( Acts::Vector3 pCenter = volumeCenter + medium * refRotation.col(1u); transform.pretranslate(pCenter); // Create the halflength - Acts::ActsScalar halfX = + double halfX = 0.5 * (boundValues[Acts::RectangleBounds::BoundValues::eMaxX] - boundValues[Acts::RectangleBounds::BoundValues::eMinX]); // New joint bounds @@ -187,12 +185,12 @@ Acts::Experimental::PortalReplacement createSectorReplacement( // Center R calculation, using projection onto vector const auto& surfaceCenter = refSurface.center(gctx); Acts::Vector3 centerDiffs = (surfaceCenter - volumeCenter); - Acts::ActsScalar centerR = centerDiffs.dot(refRotation.col(2)); + double centerR = centerDiffs.dot(refRotation.col(2)); // New joint center Acts::Vector3 pCenter = volumeCenter + centerR * refRotation.col(2); transform.pretranslate(pCenter); // New joint bounds - Acts::ActsScalar halfY = + double halfY = 0.5 * (boundValues[Acts::RectangleBounds::BoundValues::eMaxY] - boundValues[Acts::RectangleBounds::BoundValues::eMinY]); bounds = std::make_unique(0.5 * range, halfY); @@ -318,7 +316,7 @@ Acts::Experimental::detail::CylindricalDetectorHelper::connectInR( DetectorComponent::PortalContainer dShell; // Innermost volume boundaries - std::vector rBoundaries = {}; + std::vector rBoundaries = {}; auto refValues = volumes[0u]->volumeBounds().values(); // Reference boundary values @@ -329,9 +327,9 @@ Acts::Experimental::detail::CylindricalDetectorHelper::connectInR( bool connectR = selectedOnly.empty() || rangeContainsValue(selectedOnly, 2u); // Get phi sector and average phi - ActsScalar phiSector = + double phiSector = refValues[CylinderVolumeBounds::BoundValues::eHalfPhiSector]; - ActsScalar avgPhi = refValues[CylinderVolumeBounds::BoundValues::eAveragePhi]; + double avgPhi = refValues[CylinderVolumeBounds::BoundValues::eAveragePhi]; // Fuse the cylinders for (unsigned int iv = 1; iv < volumes.size(); ++iv) { @@ -481,7 +479,7 @@ Acts::Experimental::detail::CylindricalDetectorHelper::connectInZ( auto addZboundary3D = [&](const Experimental::DetectorVolume& volume, int side) -> void { const auto boundValues = volume.volumeBounds().values(); - ActsScalar halflengthZ = + double halflengthZ = boundValues[CylinderVolumeBounds::BoundValues::eHalfLengthZ]; zBoundaries3D.push_back(volume.transform(gctx).translation() + side * halflengthZ * rotation.col(2)); @@ -534,11 +532,10 @@ Acts::Experimental::detail::CylindricalDetectorHelper::connectInZ( << toString(combinedCenter)); // Evaluate the series of z boundaries - std::vector zBoundaries = {}; + std::vector zBoundaries = {}; for (const auto& zb3D : zBoundaries3D) { auto proj3D = (zb3D - combinedCenter).dot(rotation.col(2)); - ActsScalar zBoundary = - std::copysign((zb3D - combinedCenter).norm(), proj3D); + double zBoundary = std::copysign((zb3D - combinedCenter).norm(), proj3D); zBoundaries.push_back(zBoundary); } @@ -551,11 +548,11 @@ Acts::Experimental::detail::CylindricalDetectorHelper::connectInZ( const auto refValues = refVolume->volumeBounds().values(); // Get phi sector and average phi - ActsScalar minR = refValues[CylinderVolumeBounds::BoundValues::eMinR]; - ActsScalar maxR = refValues[CylinderVolumeBounds::BoundValues::eMaxR]; - ActsScalar phiSector = + double minR = refValues[CylinderVolumeBounds::BoundValues::eMinR]; + double maxR = refValues[CylinderVolumeBounds::BoundValues::eMaxR]; + double phiSector = refValues[CylinderVolumeBounds::BoundValues::eHalfPhiSector]; - ActsScalar avgPhi = refValues[CylinderVolumeBounds::BoundValues::eAveragePhi]; + double avgPhi = refValues[CylinderVolumeBounds::BoundValues::eAveragePhi]; // Check if inner cylinder and sectors are present by the number of portals std::size_t nPortals = volumes[volumes.size() - 1u]->portals().size(); @@ -569,7 +566,7 @@ Acts::Experimental::detail::CylindricalDetectorHelper::connectInZ( // Disc assignments are forward for negative disc, backward for positive std::vector cylinderDirs = {Acts::Direction::Backward}; // Cylinder radii - std::vector cylinderR = {maxR}; + std::vector cylinderR = {maxR}; if (innerPresent) { ACTS_VERBOSE("Inner surface present, tube geometry detected."); cylinderDirs.push_back(Direction::Forward); @@ -657,7 +654,7 @@ Acts::Experimental::detail::CylindricalDetectorHelper::connectInPhi( // Sector offset unsigned int iSecOffset = innerPresent ? 4u : 3u; - std::vector phiBoundaries = {}; + std::vector phiBoundaries = {}; auto refValues = volumes[0u]->volumeBounds().values(); phiBoundaries.push_back( refValues[CylinderVolumeBounds::BoundValues::eAveragePhi] - @@ -679,10 +676,10 @@ Acts::Experimental::detail::CylindricalDetectorHelper::connectInPhi( // The current values auto curValues = volumes[iv]->volumeBounds().values(); // Bail out if they do not match - ActsScalar lowPhi = + double lowPhi = curValues[CylinderVolumeBounds::BoundValues::eAveragePhi] - curValues[CylinderVolumeBounds::BoundValues::eHalfPhiSector]; - ActsScalar highPhi = + double highPhi = curValues[CylinderVolumeBounds::BoundValues::eAveragePhi] + curValues[CylinderVolumeBounds::BoundValues::eHalfPhiSector]; // Check phi attachment @@ -816,12 +813,11 @@ Acts::Experimental::detail::CylindricalDetectorHelper::wrapInZR( "cylinder volume."); } // We need a new cylinder spanning over the entire inner tube - ActsScalar hlZ = cylVolBounds->get( + double hlZ = cylVolBounds->get( Acts::CylinderVolumeBounds::BoundValues::eHalfLengthZ); - ActsScalar HlZ = ccylVolBounds->get( + double HlZ = ccylVolBounds->get( Acts::CutoutCylinderVolumeBounds::BoundValues::eHalfLengthZ); - ActsScalar innerR = - cylVolBounds->get(CylinderVolumeBounds::BoundValues::eMinR); + double innerR = cylVolBounds->get(CylinderVolumeBounds::BoundValues::eMinR); // Create the inner replacement std::vector pReplacements; pReplacements.push_back(createCylinderReplacement( @@ -1112,17 +1108,15 @@ Acts::Experimental::detail::CylindricalDetectorHelper::wrapInZR( // Inner Container portal auto& centralSegment = innerContainer[3u]; auto centralValues = centralSegment->surface().bounds().values(); - ActsScalar centralHalfLengthZ = + double centralHalfLengthZ = centralValues[CylinderBounds::BoundValues::eHalfLengthZ]; // The two segments auto& nSegment = wrappingVolume->portalPtrs()[6u]; auto nValues = nSegment->surface().bounds().values(); - ActsScalar nHalfLengthZ = - nValues[CylinderBounds::BoundValues::eHalfLengthZ]; + double nHalfLengthZ = nValues[CylinderBounds::BoundValues::eHalfLengthZ]; auto& pSegment = wrappingVolume->portalPtrs()[7u]; auto pValues = pSegment->surface().bounds().values(); - ActsScalar pHalfLengthZ = - pValues[CylinderBounds::BoundValues::eHalfLengthZ]; + double pHalfLengthZ = pValues[CylinderBounds::BoundValues::eHalfLengthZ]; auto sideVolumes = PortalHelper::stripSideVolumes({innerContainer}, {3u}, {3u}, logLevel); @@ -1131,8 +1125,8 @@ Acts::Experimental::detail::CylindricalDetectorHelper::wrapInZR( std::vector> innerVolumes = { wrappingVolume->getSharedPtr()}; - std::vector zBoundaries = { - -centralHalfLengthZ - 2 * nHalfLengthZ, centralHalfLengthZ}; + std::vector zBoundaries = {-centralHalfLengthZ - 2 * nHalfLengthZ, + centralHalfLengthZ}; // Loop over side volume and register the z boundaries for (auto& svs : sideVolumes) { for (auto& v : svs.second) { @@ -1142,7 +1136,7 @@ Acts::Experimental::detail::CylindricalDetectorHelper::wrapInZR( throw std::invalid_argument( "CylindricalDetectorHelper: side volume must be a cylinder."); } - ActsScalar hlZ = + double hlZ = cylVolBounds->get(CylinderVolumeBounds::BoundValues::eHalfLengthZ); zBoundaries.push_back(zBoundaries.back() + 2 * hlZ); innerVolumes.push_back(v); diff --git a/Core/src/Detector/detail/DetectorVolumeConsistency.cpp b/Core/src/Detector/detail/DetectorVolumeConsistency.cpp index 1d9cae71402..999fe5fe6a8 100644 --- a/Core/src/Detector/detail/DetectorVolumeConsistency.cpp +++ b/Core/src/Detector/detail/DetectorVolumeConsistency.cpp @@ -35,12 +35,12 @@ void Acts::Experimental::detail::DetectorVolumeConsistency:: } } -std::vector +std::vector Acts::Experimental::detail::DetectorVolumeConsistency::checkCenterAlignment( const GeometryContext& gctx, const std::vector>& volumes, BinningValue axisValue) { - std::vector distances = {}; + std::vector distances = {}; // First it needs to surfive the rotation check checkRotationAlignment(gctx, volumes); diff --git a/Core/src/Detector/detail/PortalHelper.cpp b/Core/src/Detector/detail/PortalHelper.cpp index 72d4d8ac7f1..a24b74308cf 100644 --- a/Core/src/Detector/detail/PortalHelper.cpp +++ b/Core/src/Detector/detail/PortalHelper.cpp @@ -35,7 +35,7 @@ void Acts::Experimental::detail::PortalHelper::attachExternalNavigationDelegate( void Acts::Experimental::detail::PortalHelper::attachDetectorVolumesUpdater( const GeometryContext& gctx, Portal& portal, const std::vector>& volumes, - const Direction& direction, const std::vector& boundaries, + const Direction& direction, const std::vector& boundaries, const BinningValue& binning) { // Check if the boundaries need a transform const auto pTransform = portal.surface().transform(gctx); diff --git a/Core/src/Detector/detail/SupportSurfacesHelper.cpp b/Core/src/Detector/detail/SupportSurfacesHelper.cpp index 62916abe39c..1d06294e6a3 100644 --- a/Core/src/Detector/detail/SupportSurfacesHelper.cpp +++ b/Core/src/Detector/detail/SupportSurfacesHelper.cpp @@ -36,17 +36,17 @@ operator()(const Extent& lExtent) const { } // Min / Max z with clearances adapted - ActsScalar minZ = lExtent.min(BinningValue::binZ) + std::abs(zClearance[0u]); - ActsScalar maxZ = lExtent.max(BinningValue::binZ) - std::abs(zClearance[1u]); + double minZ = lExtent.min(BinningValue::binZ) + std::abs(zClearance[0u]); + double maxZ = lExtent.max(BinningValue::binZ) - std::abs(zClearance[1u]); // Phi sector - ActsScalar hPhiSector = std::numbers::pi_v; - ActsScalar avgPhi = 0.; + double hPhiSector = std::numbers::pi; + double avgPhi = 0.; if (lExtent.constrains(BinningValue::binPhi)) { // Min / Max phi with clearances adapted - ActsScalar minPhi = + double minPhi = lExtent.min(BinningValue::binPhi) + std::abs(phiClearance[0u]); - ActsScalar maxPhi = + double maxPhi = lExtent.max(BinningValue::binPhi) - std::abs(phiClearance[1u]); hPhiSector = 0.5 * (maxPhi - minPhi); avgPhi = 0.5 * (minPhi + maxPhi); @@ -58,8 +58,8 @@ operator()(const Extent& lExtent) const { } // The Radius estimation - ActsScalar r = rOffset < 0 ? lExtent.min(BinningValue::binR) + rOffset - : lExtent.max(BinningValue::binR) + rOffset; + double r = rOffset < 0 ? lExtent.min(BinningValue::binR) + rOffset + : lExtent.max(BinningValue::binR) + rOffset; if (rOffset == 0.) { r = lExtent.medium(BinningValue::binR); } @@ -80,25 +80,25 @@ Acts::Experimental::detail::SupportSurfacesHelper::DiscSupport::operator()( } // Min / Max r with clearances adapted - ActsScalar minR = lExtent.min(BinningValue::binR) + std::abs(rClearance[0u]); - ActsScalar maxR = lExtent.max(BinningValue::binR) - std::abs(rClearance[1u]); + double minR = lExtent.min(BinningValue::binR) + std::abs(rClearance[0u]); + double maxR = lExtent.max(BinningValue::binR) - std::abs(rClearance[1u]); // Phi sector - ActsScalar hPhiSector = std::numbers::pi_v; - ActsScalar avgPhi = 0.; + double hPhiSector = std::numbers::pi; + double avgPhi = 0.; if (lExtent.constrains(BinningValue::binPhi)) { // Min / Max phi with clearances adapted - ActsScalar minPhi = + double minPhi = lExtent.min(BinningValue::binPhi) + std::abs(phiClearance[0u]); - ActsScalar maxPhi = + double maxPhi = lExtent.max(BinningValue::binPhi) - std::abs(phiClearance[1u]); hPhiSector = 0.5 * (maxPhi - minPhi); avgPhi = 0.5 * (minPhi + maxPhi); } // The z position estimate - ActsScalar z = zOffset < 0 ? lExtent.min(BinningValue::binZ) + zOffset - : lExtent.max(BinningValue::binZ) + zOffset; + double z = zOffset < 0 ? lExtent.min(BinningValue::binZ) + zOffset + : lExtent.max(BinningValue::binZ) + zOffset; if (zOffset == 0.) { z = lExtent.medium(BinningValue::binZ); } @@ -131,12 +131,12 @@ operator()(const Extent& lExtent) const { } // Make the rectangular shape - ActsScalar minX = lExtent.min(locals[0]) + std::abs(loc0Clearance[0u]); - ActsScalar maxX = lExtent.max(locals[0]) - std::abs(loc0Clearance[1u]); - ActsScalar minY = lExtent.min(locals[1]) + std::abs(loc1Clearance[0u]); - ActsScalar maxY = lExtent.max(locals[1]) - std::abs(loc1Clearance[1u]); + double minX = lExtent.min(locals[0]) + std::abs(loc0Clearance[0u]); + double maxX = lExtent.max(locals[0]) - std::abs(loc0Clearance[1u]); + double minY = lExtent.min(locals[1]) + std::abs(loc1Clearance[0u]); + double maxY = lExtent.max(locals[1]) - std::abs(loc1Clearance[1u]); - ActsScalar gPlacement = lExtent.medium(pPlacement) + pOffset; + double gPlacement = lExtent.medium(pPlacement) + pOffset; Vector3 placement = Vector3::Zero(); placement[toUnderlying(pPlacement)] = gPlacement; @@ -166,7 +166,7 @@ Acts::Experimental::detail::SupportSurfacesHelper::cylindricalSupport( "surface type is not a cylinder."); } - std::array bounds = {}; + std::array bounds = {}; std::copy_n(values.begin(), 6u, bounds.begin()); // Return vector for generated surfaces @@ -177,28 +177,27 @@ Acts::Experimental::detail::SupportSurfacesHelper::cylindricalSupport( transform, std::make_shared(bounds))); } else { // Split into n(splits) planar surfaces, prep work: - ActsScalar r = bounds[0u]; - ActsScalar halfZ = bounds[1u]; - ActsScalar minPhi = bounds[3u] - bounds[2u]; - ActsScalar maxPhi = bounds[3u] + bounds[2u]; - ActsScalar dHalfPhi = (maxPhi - minPhi) / (2 * splits); - ActsScalar cosPhiHalf = std::cos(dHalfPhi); - ActsScalar sinPhiHalf = std::sin(dHalfPhi); - ActsScalar planeR = r * cosPhiHalf; - ActsScalar planeHalfX = r * sinPhiHalf; - ActsScalar planeZ = transform.translation().z(); + double r = bounds[0u]; + double halfZ = bounds[1u]; + double minPhi = bounds[3u] - bounds[2u]; + double maxPhi = bounds[3u] + bounds[2u]; + double dHalfPhi = (maxPhi - minPhi) / (2 * splits); + double cosPhiHalf = std::cos(dHalfPhi); + double sinPhiHalf = std::sin(dHalfPhi); + double planeR = r * cosPhiHalf; + double planeHalfX = r * sinPhiHalf; + double planeZ = transform.translation().z(); auto sRectangle = std::make_shared(planeHalfX, halfZ); // Now create the Trapezoids for (unsigned int iphi = 0; iphi < splits; ++iphi) { // Get the moduleTransform - ActsScalar phi = - -std::numbers::pi_v + (2 * iphi + 1) * dHalfPhi; - ActsScalar cosPhi = std::cos(phi); - ActsScalar sinPhi = std::sin(phi); - ActsScalar planeX = planeR * cosPhi; - ActsScalar planeY = planeR * sinPhi; + double phi = -std::numbers::pi + (2 * iphi + 1) * dHalfPhi; + double cosPhi = std::cos(phi); + double sinPhi = std::sin(phi); + double planeX = planeR * cosPhi; + double planeY = planeR * sinPhi; Acts::Vector3 planeCenter(planeX, planeY, planeZ); Acts::Vector3 planeAxisZ(cosPhi, sinPhi, 0.); @@ -241,7 +240,7 @@ Acts::Experimental::detail::SupportSurfacesHelper::discSupport( "surface type is not a disc."); } - std::array bounds = {}; + std::array bounds = {}; std::copy_n(values.begin(), 4u, bounds.begin()); // Return vector for generated surfaces @@ -252,33 +251,31 @@ Acts::Experimental::detail::SupportSurfacesHelper::discSupport( transform, std::make_shared(bounds))); } else { // Split into n(splits) planar surfaces in phi, prep work: - ActsScalar minR = bounds[0u]; - ActsScalar maxR = bounds[1u]; - ActsScalar minPhi = bounds[3u] - bounds[2u]; - ActsScalar maxPhi = bounds[3u] + bounds[2u]; - ActsScalar dHalfPhi = (maxPhi - minPhi) / (2 * splits); - ActsScalar cosPhiHalf = std::cos(dHalfPhi); - ActsScalar sinPhiHalf = std::sin(dHalfPhi); - ActsScalar maxLocY = maxR * cosPhiHalf; - ActsScalar minLocY = minR * cosPhiHalf; - ActsScalar hR = 0.5 * (maxLocY + minLocY); - ActsScalar hY = 0.5 * (maxLocY - minLocY); - ActsScalar hXminY = minR * sinPhiHalf; - ActsScalar hXmaxY = maxR * sinPhiHalf; + double minR = bounds[0u]; + double maxR = bounds[1u]; + double minPhi = bounds[3u] - bounds[2u]; + double maxPhi = bounds[3u] + bounds[2u]; + double dHalfPhi = (maxPhi - minPhi) / (2 * splits); + double cosPhiHalf = std::cos(dHalfPhi); + double sinPhiHalf = std::sin(dHalfPhi); + double maxLocY = maxR * cosPhiHalf; + double minLocY = minR * cosPhiHalf; + double hR = 0.5 * (maxLocY + minLocY); + double hY = 0.5 * (maxLocY - minLocY); + double hXminY = minR * sinPhiHalf; + double hXmaxY = maxR * sinPhiHalf; // Split trapezoid auto sTrapezoid = std::make_shared(hXminY, hXmaxY, hY); Vector3 zAxis = transform.rotation().col(2); - ActsScalar zPosition = transform.translation().z(); + double zPosition = transform.translation().z(); // Now create the Trapezoids for (unsigned int iphi = 0; iphi < splits; ++iphi) { // Create the split module transform - ActsScalar phi = - -std::numbers::pi_v + (2 * iphi + 1) * dHalfPhi; + double phi = -std::numbers::pi + (2 * iphi + 1) * dHalfPhi; auto sTransform = Transform3( Translation3(hR * std::cos(phi), hR * std::sin(phi), zPosition) * - AngleAxis3(phi - static_cast(std::numbers::pi / 2.), - zAxis)); + AngleAxis3(phi - std::numbers::pi / 2., zAxis)); // Place it dSupport.push_back( Surface::makeShared(sTransform, sTrapezoid)); @@ -307,7 +304,7 @@ Acts::Experimental::detail::SupportSurfacesHelper::rectangularSupport( "surface type is not a plane."); } - std::array bounds = {}; + std::array bounds = {}; std::copy_n(values.begin(), 4u, bounds.begin()); return {Surface::makeShared( diff --git a/Core/src/EventData/CorrectedTransformationFreeToBound.cpp b/Core/src/EventData/CorrectedTransformationFreeToBound.cpp index ebeb73c00ba..405fea01e3b 100644 --- a/Core/src/EventData/CorrectedTransformationFreeToBound.cpp +++ b/Core/src/EventData/CorrectedTransformationFreeToBound.cpp @@ -25,9 +25,8 @@ #include #include -Acts::FreeToBoundCorrection::FreeToBoundCorrection(bool apply_, - ActsScalar alpha_, - ActsScalar beta_) +Acts::FreeToBoundCorrection::FreeToBoundCorrection(bool apply_, double alpha_, + double beta_) : apply(apply_), alpha(alpha_), beta(beta_) {} Acts::FreeToBoundCorrection::FreeToBoundCorrection(bool apply_) @@ -38,8 +37,8 @@ Acts::FreeToBoundCorrection::operator bool() const { } Acts::detail::CorrectedFreeToBoundTransformer::CorrectedFreeToBoundTransformer( - ActsScalar alpha, ActsScalar beta, ActsScalar cosIncidentAngleMinCutoff, - ActsScalar cosIncidentAngleMaxCutoff) + double alpha, double beta, double cosIncidentAngleMinCutoff, + double cosIncidentAngleMaxCutoff) : m_alpha(alpha), m_beta(beta), m_cosIncidentAngleMinCutoff(cosIncidentAngleMinCutoff), @@ -63,7 +62,7 @@ Acts::detail::CorrectedFreeToBoundTransformer::operator()( Vector3 dir = freeParams.segment<3>(eFreeDir0); Vector3 normal = surface.normal(geoContext, freeParams.segment<3>(eFreePos0), dir); - ActsScalar absCosIncidenceAng = std::abs(dir.dot(normal)); + double absCosIncidenceAng = std::abs(dir.dot(normal)); // No correction if the incidentAngle is small enough (not necessary ) or too // large (correction could be invalid). Fall back to nominal free to bound // transformation @@ -78,7 +77,7 @@ Acts::detail::CorrectedFreeToBoundTransformer::operator()( std::size_t sampleSize = 2 * eFreeSize + 1; // The sampled free parameters, the weight for measurement W_m and weight for // covariance, W_c - std::vector> sampledFreeParams; + std::vector> sampledFreeParams; sampledFreeParams.reserve(sampleSize); // Initialize the covariance sqrt root matrix @@ -99,11 +98,11 @@ Acts::detail::CorrectedFreeToBoundTransformer::operator()( covSqrt = U * D; // Define kappa = alpha*alpha*N - ActsScalar kappa = m_alpha * m_alpha * static_cast(eFreeSize); + double kappa = m_alpha * m_alpha * static_cast(eFreeSize); // lambda = alpha*alpha*N - N - ActsScalar lambda = kappa - static_cast(eFreeSize); + double lambda = kappa - static_cast(eFreeSize); // gamma = sqrt(labmda + N) - ActsScalar gamma = std::sqrt(kappa); + double gamma = std::sqrt(kappa); // Sample the free parameters // 1. the nominal parameter @@ -125,7 +124,7 @@ Acts::detail::CorrectedFreeToBoundTransformer::operator()( // The transformed bound parameters and weight for each sampled free // parameters - std::vector> transformedBoundParams; + std::vector> transformedBoundParams; // 1. The nominal one // The sampled free parameters, the weight for measurement W_m and weight for diff --git a/Core/src/EventData/PrintParameters.cpp b/Core/src/EventData/PrintParameters.cpp index 01d62694c66..a076ea17027 100644 --- a/Core/src/EventData/PrintParameters.cpp +++ b/Core/src/EventData/PrintParameters.cpp @@ -188,8 +188,7 @@ void Acts::detail::printFreeParameters(std::ostream& os, void Acts::detail::printMeasurement(std::ostream& os, BoundIndices size, const std::uint8_t* indices, - const ActsScalar* params, - const ActsScalar* cov) { + const double* params, const double* cov) { auto s = static_cast(size); printParametersCovariance(os, makeBoundNames(), indices, ParametersMap(params, s), CovarianceMap(cov, s, s)); @@ -197,8 +196,7 @@ void Acts::detail::printMeasurement(std::ostream& os, BoundIndices size, void Acts::detail::printMeasurement(std::ostream& os, FreeIndices size, const std::uint8_t* indices, - const ActsScalar* params, - const ActsScalar* cov) { + const double* params, const double* cov) { auto s = static_cast(size); printParametersCovariance(os, makeFreeNames(), indices, ParametersMap(params, s), CovarianceMap(cov, s, s)); diff --git a/Core/src/EventData/TransformationHelpers.cpp b/Core/src/EventData/TransformationHelpers.cpp index 90014814073..ea6dcf061d1 100644 --- a/Core/src/EventData/TransformationHelpers.cpp +++ b/Core/src/EventData/TransformationHelpers.cpp @@ -42,7 +42,7 @@ Acts::FreeVector Acts::transformBoundToFreeParameters( Acts::Result Acts::transformFreeToBoundParameters( const FreeVector& freeParams, const Surface& surface, - const GeometryContext& geoCtx, ActsScalar tolerance) { + const GeometryContext& geoCtx, double tolerance) { // initialize the bound vector BoundVector bp = BoundVector::Zero(); // convert global to local position on the surface @@ -65,10 +65,9 @@ Acts::Result Acts::transformFreeToBoundParameters( } Acts::Result Acts::transformFreeToBoundParameters( - const Acts::Vector3& position, ActsScalar time, - const Acts::Vector3& direction, ActsScalar qOverP, - const Acts::Surface& surface, const Acts::GeometryContext& geoCtx, - ActsScalar tolerance) { + const Acts::Vector3& position, double time, const Acts::Vector3& direction, + double qOverP, const Acts::Surface& surface, + const Acts::GeometryContext& geoCtx, double tolerance) { // initialize the bound vector BoundVector bp = BoundVector::Zero(); // convert global to local position on the surface @@ -88,8 +87,10 @@ Acts::Result Acts::transformFreeToBoundParameters( return Result::success(bp); } -Acts::BoundVector Acts::transformFreeToCurvilinearParameters( - ActsScalar time, ActsScalar phi, ActsScalar theta, ActsScalar qOverP) { +Acts::BoundVector Acts::transformFreeToCurvilinearParameters(double time, + double phi, + double theta, + double qOverP) { BoundVector bp = BoundVector::Zero(); // local coordinates are zero by construction bp[eBoundTime] = time; @@ -100,7 +101,7 @@ Acts::BoundVector Acts::transformFreeToCurvilinearParameters( } Acts::BoundVector Acts::transformFreeToCurvilinearParameters( - ActsScalar time, const Vector3& direction, ActsScalar qOverP) { + double time, const Vector3& direction, double qOverP) { BoundVector bp = BoundVector::Zero(); // local coordinates are zero by construction bp[eBoundTime] = time; diff --git a/Core/src/EventData/VectorMultiTrajectory.cpp b/Core/src/EventData/VectorMultiTrajectory.cpp index 66629d65f12..f25d64db4c5 100644 --- a/Core/src/EventData/VectorMultiTrajectory.cpp +++ b/Core/src/EventData/VectorMultiTrajectory.cpp @@ -212,6 +212,7 @@ void VectorMultiTrajectory::unset_impl(TrackStatePropMask target, case PM::Calibrated: m_measOffset[istate] = kInvalid; m_measCovOffset[istate] = kInvalid; + m_index[istate].measdim = kInvalid; break; default: throw std::domain_error{"Unable to unset this component"}; diff --git a/Core/src/EventData/VectorTrackContainer.cpp b/Core/src/EventData/VectorTrackContainer.cpp index dc7cca761d1..5be40fae6c8 100644 --- a/Core/src/EventData/VectorTrackContainer.cpp +++ b/Core/src/EventData/VectorTrackContainer.cpp @@ -167,4 +167,8 @@ void VectorTrackContainer::clear() { } } +std::size_t VectorTrackContainer::size() const { + return m_tipIndex.size(); +} + } // namespace Acts diff --git a/Core/src/Geometry/CompositePortalLink.cpp b/Core/src/Geometry/CompositePortalLink.cpp index d8010bbbce2..108db95c192 100644 --- a/Core/src/Geometry/CompositePortalLink.cpp +++ b/Core/src/Geometry/CompositePortalLink.cpp @@ -228,9 +228,9 @@ std::unique_ptr CompositePortalLink::makeGrid( const auto& bounds = dynamic_cast(child->surface().bounds()); Transform3 ltransform = itransform * child->surface().transform(gctx); - ActsScalar hlZ = bounds.get(CylinderBounds::eHalfLengthZ); - ActsScalar minZ = ltransform.translation()[eZ] - hlZ; - ActsScalar maxZ = ltransform.translation()[eZ] + hlZ; + double hlZ = bounds.get(CylinderBounds::eHalfLengthZ); + double minZ = ltransform.translation()[eZ] - hlZ; + double maxZ = ltransform.translation()[eZ] + hlZ; if (i == 0) { edges.push_back(minZ); } diff --git a/Core/src/Geometry/ConeVolumeBounds.cpp b/Core/src/Geometry/ConeVolumeBounds.cpp index 31339ca4779..ebc1262c1b8 100644 --- a/Core/src/Geometry/ConeVolumeBounds.cpp +++ b/Core/src/Geometry/ConeVolumeBounds.cpp @@ -30,10 +30,10 @@ #include namespace Acts { -ConeVolumeBounds::ConeVolumeBounds( - ActsScalar innerAlpha, ActsScalar innerOffsetZ, ActsScalar outerAlpha, - ActsScalar outerOffsetZ, ActsScalar halflengthZ, ActsScalar averagePhi, - ActsScalar halfPhiSector) noexcept(false) +ConeVolumeBounds::ConeVolumeBounds(double innerAlpha, double innerOffsetZ, + double outerAlpha, double outerOffsetZ, + double halflengthZ, double averagePhi, + double halfPhiSector) noexcept(false) : VolumeBounds(), m_values() { m_values[eInnerAlpha] = innerAlpha; m_values[eInnerOffsetZ] = innerOffsetZ; @@ -46,10 +46,10 @@ ConeVolumeBounds::ConeVolumeBounds( checkConsistency(); } -ConeVolumeBounds::ConeVolumeBounds(ActsScalar cylinderR, ActsScalar alpha, - ActsScalar offsetZ, ActsScalar halflengthZ, - ActsScalar averagePhi, - ActsScalar halfPhiSector) noexcept(false) +ConeVolumeBounds::ConeVolumeBounds(double cylinderR, double alpha, + double offsetZ, double halflengthZ, + double averagePhi, + double halfPhiSector) noexcept(false) : VolumeBounds(), m_values() { m_values[eInnerAlpha] = 0.; m_values[eInnerOffsetZ] = 0.; @@ -60,11 +60,11 @@ ConeVolumeBounds::ConeVolumeBounds(ActsScalar cylinderR, ActsScalar alpha, m_values[eHalfPhiSector] = halfPhiSector; // Cone parameters - ActsScalar tanAlpha = std::tan(alpha); - ActsScalar zmin = offsetZ - halflengthZ; - ActsScalar zmax = offsetZ + halflengthZ; - ActsScalar rmin = std::abs(zmin) * tanAlpha; - ActsScalar rmax = std::abs(zmax) * tanAlpha; + double tanAlpha = std::tan(alpha); + double zmin = offsetZ - halflengthZ; + double zmax = offsetZ + halflengthZ; + double rmin = std::abs(zmin) * tanAlpha; + double rmax = std::abs(zmax) * tanAlpha; if (rmin >= cylinderR) { // Cylindrical cut-out of a cone @@ -192,36 +192,35 @@ void ConeVolumeBounds::checkConsistency() noexcept(false) { } } -bool ConeVolumeBounds::inside(const Vector3& pos, ActsScalar tol) const { - ActsScalar z = pos.z(); - ActsScalar zmin = z + tol; - ActsScalar zmax = z - tol; +bool ConeVolumeBounds::inside(const Vector3& pos, double tol) const { + double z = pos.z(); + double zmin = z + tol; + double zmax = z - tol; // Quick check outside z if (zmin < -get(eHalfLengthZ) || zmax > get(eHalfLengthZ)) { return false; } - ActsScalar r = VectorHelpers::perp(pos); + double r = VectorHelpers::perp(pos); if (std::abs(get(eHalfPhiSector) - std::numbers::pi) > s_onSurfaceTolerance) { // need to check the phi sector - approximate phi tolerance - ActsScalar phitol = tol / r; - ActsScalar phi = VectorHelpers::phi(pos); - ActsScalar phimin = phi - phitol; - ActsScalar phimax = phi + phitol; + double phitol = tol / r; + double phi = VectorHelpers::phi(pos); + double phimin = phi - phitol; + double phimax = phi + phitol; if (phimin < get(eAveragePhi) - get(eHalfPhiSector) || phimax > get(eAveragePhi) + get(eHalfPhiSector)) { return false; } } // We are within phi sector check box r quickly - ActsScalar rmin = r + tol; - ActsScalar rmax = r - tol; + double rmin = r + tol; + double rmax = r - tol; if (rmin > innerRmax() && rmax < outerRmin()) { return true; } // Finally we need to check the cone if (m_innerConeBounds != nullptr) { - ActsScalar innerConeR = - m_innerConeBounds->r(std::abs(z + get(eInnerOffsetZ))); + double innerConeR = m_innerConeBounds->r(std::abs(z + get(eInnerOffsetZ))); if (innerConeR > rmin) { return false; } @@ -230,8 +229,7 @@ bool ConeVolumeBounds::inside(const Vector3& pos, ActsScalar tol) const { } // And the outer cone if (m_outerConeBounds != nullptr) { - ActsScalar outerConeR = - m_outerConeBounds->r(std::abs(z + get(eOuterOffsetZ))); + double outerConeR = m_outerConeBounds->r(std::abs(z + get(eOuterOffsetZ))); if (outerConeR < rmax) { return false; } @@ -245,8 +243,8 @@ void ConeVolumeBounds::buildSurfaceBounds() { // Build inner cone or inner cylinder if (get(eInnerAlpha) > s_epsilon) { m_innerTanAlpha = std::tan(get(eInnerAlpha)); - ActsScalar innerZmin = get(eInnerOffsetZ) - get(eHalfLengthZ); - ActsScalar innerZmax = get(eInnerOffsetZ) + get(eHalfLengthZ); + double innerZmin = get(eInnerOffsetZ) - get(eHalfLengthZ); + double innerZmax = get(eInnerOffsetZ) + get(eHalfLengthZ); m_innerRmin = std::abs(innerZmin) * m_innerTanAlpha; m_innerRmax = std::abs(innerZmax) * m_innerTanAlpha; m_innerConeBounds = @@ -259,8 +257,8 @@ void ConeVolumeBounds::buildSurfaceBounds() { if (get(eOuterAlpha) > s_epsilon) { m_outerTanAlpha = std::tan(get(eOuterAlpha)); - ActsScalar outerZmin = get(eOuterOffsetZ) - get(eHalfLengthZ); - ActsScalar outerZmax = get(eOuterOffsetZ) + get(eHalfLengthZ); + double outerZmin = get(eOuterOffsetZ) - get(eHalfLengthZ); + double outerZmax = get(eOuterOffsetZ) + get(eHalfLengthZ); m_outerRmin = std::abs(outerZmin) * m_outerTanAlpha; m_outerRmax = std::abs(outerZmax) * m_outerTanAlpha; m_outerConeBounds = @@ -312,32 +310,32 @@ Volume::BoundingBox ConeVolumeBounds::boundingBox(const Transform3* trf, return trf == nullptr ? box : box.transformed(*trf); } -ActsScalar ConeVolumeBounds::innerRmin() const { +double ConeVolumeBounds::innerRmin() const { return m_innerRmin; } -ActsScalar ConeVolumeBounds::innerRmax() const { +double ConeVolumeBounds::innerRmax() const { return m_innerRmax; } -ActsScalar ConeVolumeBounds::innerTanAlpha() const { +double ConeVolumeBounds::innerTanAlpha() const { return m_innerTanAlpha; } -ActsScalar ConeVolumeBounds::outerRmin() const { +double ConeVolumeBounds::outerRmin() const { return m_outerRmin; } -ActsScalar ConeVolumeBounds::outerRmax() const { +double ConeVolumeBounds::outerRmax() const { return m_outerRmax; } -ActsScalar ConeVolumeBounds::outerTanAlpha() const { +double ConeVolumeBounds::outerTanAlpha() const { return m_outerTanAlpha; } -std::vector ConeVolumeBounds::values() const { - std::vector valvector; +std::vector ConeVolumeBounds::values() const { + std::vector valvector; valvector.insert(valvector.begin(), m_values.begin(), m_values.end()); return valvector; } diff --git a/Core/src/Geometry/CuboidVolumeBounds.cpp b/Core/src/Geometry/CuboidVolumeBounds.cpp index 64b0b67f8d7..be2443c9691 100644 --- a/Core/src/Geometry/CuboidVolumeBounds.cpp +++ b/Core/src/Geometry/CuboidVolumeBounds.cpp @@ -18,15 +18,13 @@ namespace Acts { -CuboidVolumeBounds::CuboidVolumeBounds(ActsScalar halex, ActsScalar haley, - ActsScalar halez) +CuboidVolumeBounds::CuboidVolumeBounds(double halex, double haley, double halez) : VolumeBounds(), m_values({halex, haley, halez}) { checkConsistency(); buildSurfaceBounds(); } -CuboidVolumeBounds::CuboidVolumeBounds( - const std::array& values) +CuboidVolumeBounds::CuboidVolumeBounds(const std::array& values) : m_values(values) { checkConsistency(); buildSurfaceBounds(); @@ -102,7 +100,7 @@ void CuboidVolumeBounds::buildSurfaceBounds() { get(eHalfLengthX)); } -ActsScalar CuboidVolumeBounds::binningBorder(BinningValue bValue) const { +double CuboidVolumeBounds::binningBorder(BinningValue bValue) const { if (bValue <= BinningValue::binZ) { return m_values[toUnderlying(bValue)]; } @@ -115,14 +113,14 @@ ActsScalar CuboidVolumeBounds::binningBorder(BinningValue bValue) const { return 0.0; } -bool CuboidVolumeBounds::inside(const Vector3& pos, ActsScalar tol) const { +bool CuboidVolumeBounds::inside(const Vector3& pos, double tol) const { return (std::abs(pos.x()) <= get(eHalfLengthX) + tol && std::abs(pos.y()) <= get(eHalfLengthY) + tol && std::abs(pos.z()) <= get(eHalfLengthZ) + tol); } -std::vector CuboidVolumeBounds::values() const { - std::vector valvector; +std::vector CuboidVolumeBounds::values() const { + std::vector valvector; valvector.insert(valvector.begin(), m_values.begin(), m_values.end()); return valvector; } @@ -135,13 +133,13 @@ void CuboidVolumeBounds::checkConsistency() noexcept(false) { } } -void CuboidVolumeBounds::set(BoundValues bValue, ActsScalar value) { +void CuboidVolumeBounds::set(BoundValues bValue, double value) { set({{bValue, value}}); } void CuboidVolumeBounds::set( - std::initializer_list> keyValues) { - std::array previous = m_values; + std::initializer_list> keyValues) { + std::array previous = m_values; for (const auto& [key, value] : keyValues) { m_values[key] = value; } diff --git a/Core/src/Geometry/CylinderVolumeBounds.cpp b/Core/src/Geometry/CylinderVolumeBounds.cpp index b4f8084a4c0..1e3bba1d67f 100644 --- a/Core/src/Geometry/CylinderVolumeBounds.cpp +++ b/Core/src/Geometry/CylinderVolumeBounds.cpp @@ -26,11 +26,10 @@ namespace Acts { -CylinderVolumeBounds::CylinderVolumeBounds(ActsScalar rmin, ActsScalar rmax, - ActsScalar halfz, ActsScalar halfphi, - ActsScalar avgphi, - ActsScalar bevelMinZ, - ActsScalar bevelMaxZ) +CylinderVolumeBounds::CylinderVolumeBounds(double rmin, double rmax, + double halfz, double halfphi, + double avgphi, double bevelMinZ, + double bevelMaxZ) : m_values() { m_values[eMinR] = rmin; m_values[eMaxR] = rmax; @@ -44,16 +43,16 @@ CylinderVolumeBounds::CylinderVolumeBounds(ActsScalar rmin, ActsScalar rmax, } CylinderVolumeBounds::CylinderVolumeBounds( - const std::array& values) + const std::array& values) : m_values(values) { checkConsistency(); buildSurfaceBounds(); } CylinderVolumeBounds::CylinderVolumeBounds(const CylinderBounds& cBounds, - ActsScalar thickness) + double thickness) : VolumeBounds() { - ActsScalar cR = cBounds.get(CylinderBounds::eR); + double cR = cBounds.get(CylinderBounds::eR); if (thickness <= 0. || (cR - 0.5 * thickness) < 0.) { throw(std::invalid_argument( "CylinderVolumeBounds: invalid extrusion thickness.")); @@ -69,7 +68,7 @@ CylinderVolumeBounds::CylinderVolumeBounds(const CylinderBounds& cBounds, } CylinderVolumeBounds::CylinderVolumeBounds(const RadialBounds& rBounds, - ActsScalar thickness) + double thickness) : VolumeBounds() { if (thickness <= 0.) { throw(std::invalid_argument( @@ -93,11 +92,11 @@ std::vector CylinderVolumeBounds::orientedSurfaces( Translation3 vMinZ(0., 0., -get(eHalfLengthZ)); Translation3 vMaxZ(0., 0., get(eHalfLengthZ)); // Set up transform for beveled edges if they are defined - ActsScalar bevelMinZ = get(eBevelMinZ); - ActsScalar bevelMaxZ = get(eBevelMaxZ); + double bevelMinZ = get(eBevelMinZ); + double bevelMaxZ = get(eBevelMaxZ); Transform3 transMinZ, transMaxZ; if (bevelMinZ != 0.) { - ActsScalar sy = 1 - 1 / std::cos(bevelMinZ); + double sy = 1 - 1 / std::cos(bevelMinZ); transMinZ = transform * vMinZ * Eigen::AngleAxisd(-bevelMinZ, Eigen::Vector3d(1., 0., 0.)) * Eigen::Scaling(1., 1. + sy, 1.); @@ -105,7 +104,7 @@ std::vector CylinderVolumeBounds::orientedSurfaces( transMinZ = transform * vMinZ; } if (bevelMaxZ != 0.) { - ActsScalar sy = 1 - 1 / std::cos(bevelMaxZ); + double sy = 1 - 1 / std::cos(bevelMaxZ); transMaxZ = transform * vMaxZ * Eigen::AngleAxisd(bevelMaxZ, Eigen::Vector3d(1., 0., 0.)) * Eigen::Scaling(1., 1. + sy, 1.); @@ -195,7 +194,7 @@ std::ostream& CylinderVolumeBounds::toStream(std::ostream& os) const { Volume::BoundingBox CylinderVolumeBounds::boundingBox( const Transform3* trf, const Vector3& envelope, const Volume* entity) const { - ActsScalar xmax = 0, xmin = 0, ymax = 0, ymin = 0; + double xmax = 0, xmin = 0, ymax = 0, ymin = 0; xmax = get(eMaxR); if (get(eHalfPhiSector) > std::numbers::pi / 2.) { @@ -219,10 +218,10 @@ Volume::BoundingBox CylinderVolumeBounds::boundingBox( return trf == nullptr ? box : box.transformed(*trf); } -bool CylinderVolumeBounds::inside(const Vector3& pos, ActsScalar tol) const { +bool CylinderVolumeBounds::inside(const Vector3& pos, double tol) const { using VectorHelpers::perp; using VectorHelpers::phi; - ActsScalar ros = perp(pos); + double ros = perp(pos); bool insidePhi = cos(phi(pos)) >= cos(get(eHalfPhiSector)) - tol; bool insideR = insidePhi ? ((ros >= get(eMinR) - tol) && (ros <= get(eMaxR) + tol)) @@ -241,7 +240,7 @@ Vector3 CylinderVolumeBounds::binningOffset(BinningValue bValue) return VolumeBounds::binningOffset(bValue); } -ActsScalar CylinderVolumeBounds::binningBorder(BinningValue bValue) const { +double CylinderVolumeBounds::binningBorder(BinningValue bValue) const { if (bValue == Acts::BinningValue::binR) { return 0.5 * (get(eMaxR) - get(eMinR)); } @@ -251,8 +250,8 @@ ActsScalar CylinderVolumeBounds::binningBorder(BinningValue bValue) const { return VolumeBounds::binningBorder(bValue); } -std::vector CylinderVolumeBounds::values() const { - std::vector valvector; +std::vector CylinderVolumeBounds::values() const { + std::vector valvector; valvector.insert(valvector.begin(), m_values.begin(), m_values.end()); return valvector; } @@ -291,13 +290,13 @@ void CylinderVolumeBounds::checkConsistency() { } } -void CylinderVolumeBounds::set(BoundValues bValue, ActsScalar value) { +void CylinderVolumeBounds::set(BoundValues bValue, double value) { set({{bValue, value}}); } void CylinderVolumeBounds::set( - std::initializer_list> keyValues) { - std::array previous = m_values; + std::initializer_list> keyValues) { + std::array previous = m_values; for (const auto& [key, value] : keyValues) { m_values[key] = value; } diff --git a/Core/src/Geometry/CylinderVolumeBuilder.cpp b/Core/src/Geometry/CylinderVolumeBuilder.cpp index 47de379d9be..4f99a77eabd 100644 --- a/Core/src/Geometry/CylinderVolumeBuilder.cpp +++ b/Core/src/Geometry/CylinderVolumeBuilder.cpp @@ -171,7 +171,7 @@ Acts::CylinderVolumeBuilder::trackingVolume( } std::string layerConfiguration = "|"; - if (wConfig.nVolumeConfig) { + if (wConfig.nVolumeConfig.present) { // negative layers are present ACTS_VERBOSE("Negative layers are present: rmin, rmax | zmin, zmax = " << wConfig.nVolumeConfig.toString()); @@ -185,7 +185,7 @@ Acts::CylinderVolumeBuilder::trackingVolume( // add to the string output layerConfiguration += " Negative Endcap |"; } - if (wConfig.cVolumeConfig) { + if (wConfig.cVolumeConfig.present) { // central layers are present ACTS_VERBOSE("Central layers are present: rmin, rmax | zmin, zmax = " << wConfig.cVolumeConfig.toString()); @@ -199,7 +199,7 @@ Acts::CylinderVolumeBuilder::trackingVolume( // add to the string output layerConfiguration += " Barrel |"; } - if (wConfig.pVolumeConfig) { + if (wConfig.pVolumeConfig.present) { // positive layers are present ACTS_VERBOSE("Positive layers are present: rmin, rmax | zmin, zmax = " << wConfig.pVolumeConfig.toString()); @@ -226,7 +226,7 @@ Acts::CylinderVolumeBuilder::trackingVolume( << '\n' << wConfig.toString()); // now let's understand the wrapping if needed - if (wConfig.existingVolumeConfig) { + if (wConfig.existingVolumeConfig.present) { wConfig.wrapInsertAttach(); ACTS_VERBOSE("Configuration after wrapping, insertion, attachment " << '\n' @@ -242,7 +242,7 @@ Acts::CylinderVolumeBuilder::trackingVolume( auto tvHelper = m_cfg.trackingVolumeHelper; // the barrel is always created auto barrel = - wConfig.cVolumeConfig + wConfig.cVolumeConfig.present ? tvHelper->createTrackingVolume( gctx, wConfig.cVolumeConfig.layers, wConfig.cVolumeConfig.volumes, m_cfg.volumeMaterial, @@ -258,7 +258,7 @@ Acts::CylinderVolumeBuilder::trackingVolume( [&](VolumeConfig& centralConfig, VolumeConfig& endcapConfig, const std::string& endcapName) -> MutableTrackingVolumePtr { // No config - no volume - if (!endcapConfig) { + if (!endcapConfig.present) { return nullptr; } // Check for ring layout @@ -478,7 +478,7 @@ Acts::CylinderVolumeBuilder::trackingVolume( if (existingVolumeCp) { // Check if gaps are needed std::vector existingContainer; - if (wConfig.fGapVolumeConfig) { + if (wConfig.fGapVolumeConfig.present) { // create the gap volume auto fGap = tvHelper->createGapTrackingVolume( gctx, wConfig.cVolumeConfig.volumes, m_cfg.volumeMaterial, @@ -489,7 +489,7 @@ Acts::CylinderVolumeBuilder::trackingVolume( existingContainer.push_back(fGap); } existingContainer.push_back(existingVolumeCp); - if (wConfig.sGapVolumeConfig) { + if (wConfig.sGapVolumeConfig.present) { // create the gap volume auto sGap = tvHelper->createGapTrackingVolume( gctx, wConfig.cVolumeConfig.volumes, m_cfg.volumeMaterial, diff --git a/Core/src/Geometry/CylinderVolumeHelper.cpp b/Core/src/Geometry/CylinderVolumeHelper.cpp index f5b244983ef..77d9dcaee8f 100644 --- a/Core/src/Geometry/CylinderVolumeHelper.cpp +++ b/Core/src/Geometry/CylinderVolumeHelper.cpp @@ -638,7 +638,7 @@ bool Acts::CylinderVolumeHelper::interGlueTrackingVolume( std::const_pointer_cast(*(++tVolIter)); // re-evalueate rGlueMin - ActsScalar rGlueR = + double rGlueR = 0.5 * (tVol1->volumeBounds() .values()[CylinderVolumeBounds::BoundValues::eMaxR] + tVol2->volumeBounds() diff --git a/Core/src/Geometry/CylinderVolumeStack.cpp b/Core/src/Geometry/CylinderVolumeStack.cpp index 5dd0949ac79..5350c3e764e 100644 --- a/Core/src/Geometry/CylinderVolumeStack.cpp +++ b/Core/src/Geometry/CylinderVolumeStack.cpp @@ -40,23 +40,23 @@ struct CylinderVolumeStack::VolumeTuple { updatedBounds = std::make_shared(*bounds); } - ActsScalar midZ() const { return localTransform.translation()[eZ]; } - ActsScalar halfLengthZ() const { + double midZ() const { return localTransform.translation()[eZ]; } + double halfLengthZ() const { return updatedBounds->get(CylinderVolumeBounds::eHalfLengthZ); } - ActsScalar minZ() const { return midZ() - halfLengthZ(); } - ActsScalar maxZ() const { return midZ() + halfLengthZ(); } + double minZ() const { return midZ() - halfLengthZ(); } + double maxZ() const { return midZ() + halfLengthZ(); } - ActsScalar minR() const { + double minR() const { return updatedBounds->get(CylinderVolumeBounds::eMinR); } - ActsScalar maxR() const { + double maxR() const { return updatedBounds->get(CylinderVolumeBounds::eMaxR); } - ActsScalar midR() const { return (minR() + maxR()) / 2.0; } + double midR() const { return (minR() + maxR()) / 2.0; } void set(std::initializer_list< - std::pair> + std::pair> keyValues) { updatedBounds->set(keyValues); } @@ -204,11 +204,11 @@ void CylinderVolumeStack::initializeOuterVolume(BinningValue direction, ACTS_DEBUG("*** Volume configuration after final z sorting:"); printVolumeSequence(volumeTuples, logger, Acts::Logging::DEBUG); - ActsScalar minZ = volumeTuples.front().minZ(); - ActsScalar maxZ = volumeTuples.back().maxZ(); + double minZ = volumeTuples.front().minZ(); + double maxZ = volumeTuples.back().maxZ(); - ActsScalar midZ = (minZ + maxZ) / 2.0; - ActsScalar hlZ = (maxZ - minZ) / 2.0; + double midZ = (minZ + maxZ) / 2.0; + double hlZ = (maxZ - minZ) / 2.0; m_transform = m_groupTransform * Translation3{0, 0, midZ}; @@ -261,11 +261,11 @@ void CylinderVolumeStack::initializeOuterVolume(BinningValue direction, ACTS_DEBUG("*** Volume configuration after final r sorting:"); printVolumeSequence(volumeTuples, logger, Acts::Logging::DEBUG); - ActsScalar minR = volumeTuples.front().minR(); - ActsScalar maxR = volumeTuples.back().maxR(); + double minR = volumeTuples.front().minR(); + double maxR = volumeTuples.back().maxR(); - ActsScalar midZ = (minZ + maxZ) / 2.0; - ActsScalar hlZ = (maxZ - minZ) / 2.0; + double midZ = (minZ + maxZ) / 2.0; + double hlZ = (maxZ - minZ) / 2.0; m_transform = m_groupTransform * Translation3{0, 0, midZ}; @@ -349,7 +349,7 @@ CylinderVolumeStack::checkOverlapAndAttachInZ( if (std::abs(a.maxZ() - b.minZ()) < tolerance) { ACTS_VERBOSE("No gap between volumes, no attachment needed"); } else { - ActsScalar gapWidth = b.minZ() - a.maxZ(); + double gapWidth = b.minZ() - a.maxZ(); ACTS_VERBOSE("Gap width: " << gapWidth); ACTS_VERBOSE("Synchronizing bounds in z with strategy: " << strategy); @@ -357,8 +357,8 @@ CylinderVolumeStack::checkOverlapAndAttachInZ( case AttachmentStrategy::Midpoint: { ACTS_VERBOSE(" -> Strategy: Expand both volumes to midpoint"); - ActsScalar aZMidNew = (a.minZ() + a.maxZ()) / 2.0 + gapWidth / 4.0; - ActsScalar aHlZNew = a.halfLengthZ() + gapWidth / 4.0; + double aZMidNew = (a.minZ() + a.maxZ()) / 2.0 + gapWidth / 4.0; + double aHlZNew = a.halfLengthZ() + gapWidth / 4.0; ACTS_VERBOSE(" - New halflength for first volume: " << aHlZNew); ACTS_VERBOSE(" - New bounds for first volume: [" << (aZMidNew - aHlZNew) << " <- " << aZMidNew << " -> " @@ -368,8 +368,8 @@ CylinderVolumeStack::checkOverlapAndAttachInZ( "Volume shrunk"); assert(aHlZNew >= a.halfLengthZ() && "Volume shrunk"); - ActsScalar bZMidNew = (b.minZ() + b.maxZ()) / 2.0 - gapWidth / 4.0; - ActsScalar bHlZNew = b.halfLengthZ() + gapWidth / 4.0; + double bZMidNew = (b.minZ() + b.maxZ()) / 2.0 - gapWidth / 4.0; + double bHlZNew = b.halfLengthZ() + gapWidth / 4.0; ACTS_VERBOSE(" - New halflength for second volume: " << bHlZNew); ACTS_VERBOSE(" - New bounds for second volume: [" << (bZMidNew - bHlZNew) << " <- " << bZMidNew << " -> " @@ -391,8 +391,8 @@ CylinderVolumeStack::checkOverlapAndAttachInZ( } case AttachmentStrategy::First: { ACTS_VERBOSE(" -> Strategy: Expand first volume"); - ActsScalar aZMidNew = (a.minZ() + b.minZ()) / 2.0; - ActsScalar aHlZNew = (b.minZ() - a.minZ()) / 2.0; + double aZMidNew = (a.minZ() + b.minZ()) / 2.0; + double aHlZNew = (b.minZ() - a.minZ()) / 2.0; ACTS_VERBOSE(" - Gap width: " << gapWidth); ACTS_VERBOSE(" - New bounds for first volume: [" << (aZMidNew - aHlZNew) << " <- " << aZMidNew << " -> " @@ -410,8 +410,8 @@ CylinderVolumeStack::checkOverlapAndAttachInZ( } case AttachmentStrategy::Second: { ACTS_VERBOSE(" -> Strategy: Expand second volume"); - ActsScalar bZMidNew = (a.maxZ() + b.maxZ()) / 2.0; - ActsScalar bHlZNew = (b.maxZ() - a.maxZ()) / 2.0; + double bZMidNew = (a.maxZ() + b.maxZ()) / 2.0; + double bHlZNew = (b.maxZ() - a.maxZ()) / 2.0; ACTS_VERBOSE(" - New halflength for second volume: " << bHlZNew); ACTS_VERBOSE(" - New bounds for second volume: [" << (bZMidNew - bHlZNew) << " <- " << bZMidNew << " -> " @@ -428,14 +428,14 @@ CylinderVolumeStack::checkOverlapAndAttachInZ( } case AttachmentStrategy::Gap: { ACTS_VERBOSE(" -> Strategy: Create a gap volume"); - ActsScalar gapHlZ = (b.minZ() - a.maxZ()) / 2.0; - ActsScalar gapMidZ = (b.minZ() + a.maxZ()) / 2.0; + double gapHlZ = (b.minZ() - a.maxZ()) / 2.0; + double gapMidZ = (b.minZ() + a.maxZ()) / 2.0; ACTS_VERBOSE(" - Gap half length: " << gapHlZ << " at z: " << gapMidZ); - ActsScalar minR = std::min(a.minR(), b.minR()); - ActsScalar maxR = std::max(a.maxR(), b.maxR()); + double minR = std::min(a.minR(), b.minR()); + double maxR = std::max(a.maxR(), b.maxR()); Transform3 gapLocalTransform{Translation3{0, 0, gapMidZ}}; Transform3 gapGlobalTransform = m_groupTransform * gapLocalTransform; @@ -483,7 +483,7 @@ CylinderVolumeStack::checkOverlapAndAttachInR( if (std::abs(a.maxR() - b.minR()) < tolerance) { ACTS_VERBOSE("No gap between volumes, no attachment needed"); } else { - ActsScalar gapWidth = b.minR() - a.maxR(); + double gapWidth = b.minR() - a.maxR(); ACTS_VERBOSE("Gap width: " << gapWidth); ACTS_VERBOSE("Synchronizing bounds in r with strategy: " << strategy); @@ -592,9 +592,9 @@ void CylinderVolumeStack::checkVolumeAlignment( } } -std::pair CylinderVolumeStack::synchronizeRBounds( +std::pair CylinderVolumeStack::synchronizeRBounds( std::vector& volumes, const Logger& logger) { - const ActsScalar minR = + const double minR = std::min_element(volumes.begin(), volumes.end(), [](const auto& a, const auto& b) { return a.bounds->get(CylinderVolumeBounds::eMinR) < @@ -602,7 +602,7 @@ std::pair CylinderVolumeStack::synchronizeRBounds( }) ->bounds->get(CylinderVolumeBounds::eMinR); - const ActsScalar maxR = + const double maxR = std::max_element(volumes.begin(), volumes.end(), [](const auto& a, const auto& b) { return a.bounds->get(CylinderVolumeBounds::eMaxR) < @@ -621,21 +621,21 @@ std::pair CylinderVolumeStack::synchronizeRBounds( return {minR, maxR}; } -std::pair CylinderVolumeStack::synchronizeZBounds( +std::pair CylinderVolumeStack::synchronizeZBounds( std::vector& volumes, const Logger& logger) { - const ActsScalar minZ = std::min_element(volumes.begin(), volumes.end(), - [](const auto& a, const auto& b) { - return a.minZ() < b.minZ(); - }) - ->minZ(); - - const ActsScalar maxZ = std::max_element(volumes.begin(), volumes.end(), - [](const auto& a, const auto& b) { - return a.maxZ() < b.maxZ(); - }) - ->maxZ(); - const ActsScalar midZ = (minZ + maxZ) / 2.0; - const ActsScalar hlZ = (maxZ - minZ) / 2.0; + const double minZ = std::min_element(volumes.begin(), volumes.end(), + [](const auto& a, const auto& b) { + return a.minZ() < b.minZ(); + }) + ->minZ(); + + const double maxZ = std::max_element(volumes.begin(), volumes.end(), + [](const auto& a, const auto& b) { + return a.maxZ() < b.maxZ(); + }) + ->maxZ(); + const double midZ = (minZ + maxZ) / 2.0; + const double hlZ = (maxZ - minZ) / 2.0; ACTS_DEBUG("Found overall z bounds: [ " << minZ << " <- " << midZ << " -> " << maxZ << " ]"); const Transform3 transform{Translation3{0, 0, midZ}}; @@ -703,19 +703,19 @@ void CylinderVolumeStack::update(std::shared_ptr volbounds, checkNoPhiOrBevel(*cylBounds, logger); - const ActsScalar newMinR = newVolume.minR(); - const ActsScalar newMaxR = newVolume.maxR(); - const ActsScalar newMinZ = newVolume.minZ(); - const ActsScalar newMaxZ = newVolume.maxZ(); - const ActsScalar newMidZ = newVolume.midZ(); - const ActsScalar newHlZ = newVolume.halfLengthZ(); + const double newMinR = newVolume.minR(); + const double newMaxR = newVolume.maxR(); + const double newMinZ = newVolume.minZ(); + const double newMaxZ = newVolume.maxZ(); + const double newMidZ = newVolume.midZ(); + const double newHlZ = newVolume.halfLengthZ(); - const ActsScalar oldMinR = oldVolume.minR(); - const ActsScalar oldMaxR = oldVolume.maxR(); - const ActsScalar oldMinZ = oldVolume.minZ(); - const ActsScalar oldMaxZ = oldVolume.maxZ(); - const ActsScalar oldMidZ = oldVolume.midZ(); - const ActsScalar oldHlZ = oldVolume.halfLengthZ(); + const double oldMinR = oldVolume.minR(); + const double oldMaxR = oldVolume.maxR(); + const double oldMinZ = oldVolume.minZ(); + const double oldMaxZ = oldVolume.maxZ(); + const double oldMidZ = oldVolume.midZ(); + const double oldHlZ = oldVolume.halfLengthZ(); ACTS_VERBOSE("Previous bounds are: z: [ " << oldMinZ << " <- " << oldMidZ << " -> " << oldMaxZ << " ] (" @@ -727,9 +727,7 @@ void CylinderVolumeStack::update(std::shared_ptr volbounds, << " ]"); constexpr auto tolerance = s_onSurfaceTolerance; - auto same = [](ActsScalar a, ActsScalar b) { - return std::abs(a - b) < tolerance; - }; + auto same = [](double a, double b) { return std::abs(a - b) < tolerance; }; if (!same(newMinZ, oldMinZ) && newMinZ > oldMinZ) { ACTS_ERROR("Shrinking the stack size in z is not supported: " @@ -796,9 +794,9 @@ void CylinderVolumeStack::update(std::shared_ptr volbounds, ACTS_VERBOSE("Expanding first volume to new z bounds"); auto& first = volumeTuples.front(); - ActsScalar newMinZFirst = newVolume.minZ(); - ActsScalar newMidZFirst = (newMinZFirst + first.maxZ()) / 2.0; - ActsScalar newHlZFirst = (first.maxZ() - newMinZFirst) / 2.0; + double newMinZFirst = newVolume.minZ(); + double newMidZFirst = (newMinZFirst + first.maxZ()) / 2.0; + double newHlZFirst = (first.maxZ() - newMinZFirst) / 2.0; ACTS_VERBOSE(" -> first z: [ " << newMinZFirst << " <- " << newMidZFirst << " -> " @@ -813,9 +811,9 @@ void CylinderVolumeStack::update(std::shared_ptr volbounds, ACTS_VERBOSE("Expanding last volume to new z bounds"); auto& last = volumeTuples.back(); - ActsScalar newMaxZLast = newVolume.maxZ(); - ActsScalar newMidZLast = (last.minZ() + newMaxZLast) / 2.0; - ActsScalar newHlZLast = (newMaxZLast - last.minZ()) / 2.0; + double newMaxZLast = newVolume.maxZ(); + double newMidZLast = (last.minZ() + newMaxZLast) / 2.0; + double newHlZLast = (newMaxZLast - last.minZ()) / 2.0; ACTS_VERBOSE(" -> last z: [ " << last.minZ() << " <- " << newMidZLast << " -> " << newMaxZLast @@ -837,10 +835,10 @@ void CylinderVolumeStack::update(std::shared_ptr volbounds, }; if (!same(newMinZ, oldMinZ) && newMinZ < oldMinZ) { - ActsScalar gap1MinZ = newVolume.minZ(); - ActsScalar gap1MaxZ = oldVolume.minZ(); - ActsScalar gap1HlZ = (gap1MaxZ - gap1MinZ) / 2.0; - ActsScalar gap1PZ = (gap1MaxZ + gap1MinZ) / 2.0; + double gap1MinZ = newVolume.minZ(); + double gap1MaxZ = oldVolume.minZ(); + double gap1HlZ = (gap1MaxZ - gap1MinZ) / 2.0; + double gap1PZ = (gap1MaxZ + gap1MinZ) / 2.0; // // check if we need a new gap volume or reuse an existing one auto& candidate = volumeTuples.front(); @@ -875,10 +873,10 @@ void CylinderVolumeStack::update(std::shared_ptr volbounds, } if (!same(newMaxZ, oldMaxZ) && newMaxZ > oldMaxZ) { - ActsScalar gap2MinZ = oldVolume.maxZ(); - ActsScalar gap2MaxZ = newVolume.maxZ(); - ActsScalar gap2HlZ = (gap2MaxZ - gap2MinZ) / 2.0; - ActsScalar gap2PZ = (gap2MaxZ + gap2MinZ) / 2.0; + double gap2MinZ = oldVolume.maxZ(); + double gap2MaxZ = newVolume.maxZ(); + double gap2HlZ = (gap2MaxZ - gap2MinZ) / 2.0; + double gap2PZ = (gap2MaxZ + gap2MinZ) / 2.0; // check if we need a new gap volume or reuse an existing one auto& candidate = volumeTuples.back(); diff --git a/Core/src/Geometry/Extent.cpp b/Core/src/Geometry/Extent.cpp index bd50d8536ef..8dfc33c1203 100644 --- a/Core/src/Geometry/Extent.cpp +++ b/Core/src/Geometry/Extent.cpp @@ -20,13 +20,13 @@ Acts::Extent::Extent(const ExtentEnvelope& envelope) : m_constrains(0), m_envelope(envelope) { m_range[toUnderlying(BinningValue::binR)] = - Range1D(0., std::numeric_limits::max()); - m_range[toUnderlying(BinningValue::binPhi)] = Range1D( - -std::numbers::pi_v, std::numbers::pi_v); + Range1D(0., std::numeric_limits::max()); + m_range[toUnderlying(BinningValue::binPhi)] = + Range1D(-std::numbers::pi, std::numbers::pi); m_range[toUnderlying(BinningValue::binRPhi)] = - Range1D(0., std::numeric_limits::max()); + Range1D(0., std::numeric_limits::max()); m_range[toUnderlying(BinningValue::binMag)] = - Range1D(0., std::numeric_limits::max()); + Range1D(0., std::numeric_limits::max()); } void Acts::Extent::extend(const Vector3& vtx, @@ -34,14 +34,14 @@ void Acts::Extent::extend(const Vector3& vtx, bool applyEnv, bool fillHistograms) { for (auto bValue : bValues) { // Get the casted value given the binning value description - ActsScalar cValue = VectorHelpers::cast(vtx, bValue); + double cValue = VectorHelpers::cast(vtx, bValue); if (fillHistograms) { m_valueHistograms[toUnderlying(bValue)].push_back(cValue); } // Apply envelope as suggested - ActsScalar lEnv = applyEnv ? m_envelope[bValue][0] : 0.; - ActsScalar hEnv = applyEnv ? m_envelope[bValue][1] : 0.; - ActsScalar mValue = cValue - lEnv; + double lEnv = applyEnv ? m_envelope[bValue][0] : 0.; + double hEnv = applyEnv ? m_envelope[bValue][1] : 0.; + double mValue = cValue - lEnv; // Special protection for radial value if (bValue == BinningValue::binR && mValue < 0.) { mValue = std::max(mValue, 0.); @@ -61,8 +61,8 @@ void Acts::Extent::extend(const Extent& rhs, for (auto bValue : bValues) { // The value is constraint, envelope can be optional if (rhs.constrains(bValue)) { - ActsScalar lEnv = applyEnv ? m_envelope[bValue][0] : 0.; - ActsScalar hEnv = applyEnv ? m_envelope[bValue][1] : 0.; + double lEnv = applyEnv ? m_envelope[bValue][0] : 0.; + double hEnv = applyEnv ? m_envelope[bValue][1] : 0.; if (constrains(bValue)) { m_range[toUnderlying(bValue)].expand( rhs.range()[toUnderlying(bValue)].min() - lEnv, @@ -95,17 +95,17 @@ void Acts::Extent::addConstrain(const Acts::Extent& rhs, } } -void Acts::Extent::set(BinningValue bValue, ActsScalar min, ActsScalar max) { - ActsScalar minval = min; +void Acts::Extent::set(BinningValue bValue, double min, double max) { + double minval = min; if (bValue == BinningValue::binR && minval < 0.) { minval = 0.; } - m_range[toUnderlying(bValue)] = Range1D{minval, max}; + m_range[toUnderlying(bValue)] = Range1D{minval, max}; m_constrains.set(toUnderlying(bValue)); } -void Acts::Extent::setMin(BinningValue bValue, ActsScalar min) { - ActsScalar minval = min; +void Acts::Extent::setMin(BinningValue bValue, double min) { + double minval = min; if (bValue == BinningValue::binR && minval < 0.) { minval = 0.; } @@ -113,7 +113,7 @@ void Acts::Extent::setMin(BinningValue bValue, ActsScalar min) { m_constrains.set(toUnderlying(bValue)); } -void Acts::Extent::setMax(BinningValue bValue, ActsScalar max) { +void Acts::Extent::setMax(BinningValue bValue, double max) { m_range[toUnderlying(bValue)].setMax(0u, max); m_constrains.set(toUnderlying(bValue)); } @@ -126,7 +126,7 @@ bool Acts::Extent::contains(const Vector3& vtx) const { Extent checkExtent; for (const auto& bv : allBinningValues()) { if (constrains(bv)) { - ActsScalar vtxVal = VectorHelpers::cast(vtx, bv); + double vtxVal = VectorHelpers::cast(vtx, bv); checkExtent.set(bv, vtxVal, vtxVal); } } diff --git a/Core/src/Geometry/GridPortalLink.cpp b/Core/src/Geometry/GridPortalLink.cpp index 632289d9dc3..ae6168e11cf 100644 --- a/Core/src/Geometry/GridPortalLink.cpp +++ b/Core/src/Geometry/GridPortalLink.cpp @@ -24,20 +24,19 @@ std::unique_ptr GridPortalLink::make( dynamic_cast(surface.get()); cylinder != nullptr) { if (direction == BinningValue::binRPhi) { - ActsScalar r = cylinder->bounds().get(CylinderBounds::eR); + double r = cylinder->bounds().get(CylinderBounds::eR); if (cylinder->bounds().coversFullAzimuth()) { grid = GridPortalLink::make( surface, direction, Axis{AxisClosed, -std::numbers::pi * r, std::numbers::pi * r, 1}); } else { - ActsScalar hlPhi = - cylinder->bounds().get(CylinderBounds::eHalfPhiSector); + double hlPhi = cylinder->bounds().get(CylinderBounds::eHalfPhiSector); grid = GridPortalLink::make(surface, direction, Axis{AxisBound, -hlPhi * r, hlPhi * r, 1}); } } else if (direction == BinningValue::binZ) { - ActsScalar hlZ = cylinder->bounds().get(CylinderBounds::eHalfLengthZ); + double hlZ = cylinder->bounds().get(CylinderBounds::eHalfLengthZ); grid = GridPortalLink::make(surface, direction, Axis{AxisBound, -hlZ, hlZ, 1}); } else { @@ -47,8 +46,8 @@ std::unique_ptr GridPortalLink::make( disc != nullptr) { const auto& bounds = dynamic_cast(disc->bounds()); if (direction == BinningValue::binR) { - ActsScalar minR = bounds.get(RadialBounds::eMinR); - ActsScalar maxR = bounds.get(RadialBounds::eMaxR); + double minR = bounds.get(RadialBounds::eMinR); + double maxR = bounds.get(RadialBounds::eMaxR); grid = GridPortalLink::make(surface, direction, Axis{AxisBound, minR, maxR, 1}); } else if (direction == BinningValue::binPhi) { @@ -57,7 +56,7 @@ std::unique_ptr GridPortalLink::make( surface, direction, Axis{AxisClosed, -std::numbers::pi, std::numbers::pi, 1}); } else { - ActsScalar hlPhi = bounds.get(RadialBounds::eHalfPhiSector); + double hlPhi = bounds.get(RadialBounds::eHalfPhiSector); grid = GridPortalLink::make(surface, direction, Axis{AxisBound, -hlPhi, hlPhi, 1}); } @@ -90,7 +89,7 @@ void GridPortalLink::checkConsistency(const CylinderSurface& cyl) const { auto same = [](auto a, auto b) { return std::abs(a - b) < tolerance; }; auto checkZ = [&cyl, same](const IAxis& axis) { - ActsScalar hlZ = cyl.bounds().get(CylinderBounds::eHalfLengthZ); + double hlZ = cyl.bounds().get(CylinderBounds::eHalfLengthZ); if (!same(axis.getMin(), -hlZ) || !same(axis.getMax(), hlZ)) { throw std::invalid_argument( "GridPortalLink: CylinderBounds: invalid length setup: " + @@ -100,9 +99,9 @@ void GridPortalLink::checkConsistency(const CylinderSurface& cyl) const { } }; auto checkRPhi = [&cyl, same](const IAxis& axis) { - ActsScalar hlPhi = cyl.bounds().get(CylinderBounds::eHalfPhiSector); - ActsScalar r = cyl.bounds().get(CylinderBounds::eR); - if (ActsScalar hlRPhi = r * hlPhi; + double hlPhi = cyl.bounds().get(CylinderBounds::eHalfPhiSector); + double r = cyl.bounds().get(CylinderBounds::eR); + if (double hlRPhi = r * hlPhi; !same(axis.getMin(), -hlRPhi) || !same(axis.getMax(), hlRPhi)) { throw std::invalid_argument( "GridPortalLink: CylinderBounds: invalid phi sector setup: axes " @@ -157,8 +156,8 @@ void GridPortalLink::checkConsistency(const DiscSurface& disc) const { } auto checkR = [&bounds, same](const IAxis& axis) { - ActsScalar minR = bounds->get(RadialBounds::eMinR); - ActsScalar maxR = bounds->get(RadialBounds::eMaxR); + double minR = bounds->get(RadialBounds::eMinR); + double maxR = bounds->get(RadialBounds::eMaxR); if (!same(axis.getMin(), minR) || !same(axis.getMax(), maxR)) { throw std::invalid_argument( "GridPortalLink: DiscBounds: invalid radius setup."); @@ -166,7 +165,7 @@ void GridPortalLink::checkConsistency(const DiscSurface& disc) const { }; auto checkPhi = [&bounds, same](const IAxis& axis) { - ActsScalar hlPhi = bounds->get(RadialBounds::eHalfPhiSector); + double hlPhi = bounds->get(RadialBounds::eHalfPhiSector); if (!same(axis.getMin(), -hlPhi) || !same(axis.getMax(), hlPhi)) { throw std::invalid_argument( "GridPortalLink: DiscBounds: invalid phi sector setup."); @@ -322,7 +321,7 @@ std::unique_ptr GridPortalLink::extendTo2dImpl( if (direction() == BinningValue::binRPhi) { const auto& axisRPhi = *grid().axes().front(); // 1D direction is binRPhi, so add a Z axis - ActsScalar hlZ = surface->bounds().get(CylinderBounds::eHalfLengthZ); + double hlZ = surface->bounds().get(CylinderBounds::eHalfLengthZ); auto grid = axisRPhi.visit([&](const auto& axis0) { Axis axisZ{AxisBound, -hlZ, hlZ, 1}; @@ -340,9 +339,9 @@ std::unique_ptr GridPortalLink::extendTo2dImpl( } else { const auto& axisZ = *grid().axes().front(); // 1D direction is binZ, so add an rPhi axis - ActsScalar r = surface->bounds().get(CylinderBounds::eR); - ActsScalar hlPhi = surface->bounds().get(CylinderBounds::eHalfPhiSector); - ActsScalar hlRPhi = r * hlPhi; + double r = surface->bounds().get(CylinderBounds::eR); + double hlPhi = surface->bounds().get(CylinderBounds::eHalfPhiSector); + double hlRPhi = r * hlPhi; auto makeGrid = [&](auto bdt) { auto grid = axisZ.visit([&](const auto& axis1) { @@ -379,7 +378,7 @@ std::unique_ptr GridPortalLink::extendTo2dImpl( if (direction() == BinningValue::binR) { const auto& axisR = *grid().axes().front(); // 1D direction is binR, so add a phi axis - ActsScalar hlPhi = bounds->get(RadialBounds::eHalfPhiSector); + double hlPhi = bounds->get(RadialBounds::eHalfPhiSector); auto makeGrid = [&](auto bdt) { auto grid = axisR.visit([&](const auto& axis0) { @@ -403,8 +402,8 @@ std::unique_ptr GridPortalLink::extendTo2dImpl( } else { const auto& axisPhi = *grid().axes().front(); // 1D direction is binPhi, so add an R axis - ActsScalar rMin = bounds->get(RadialBounds::eMinR); - ActsScalar rMax = bounds->get(RadialBounds::eMaxR); + double rMin = bounds->get(RadialBounds::eMinR); + double rMax = bounds->get(RadialBounds::eMaxR); auto grid = axisPhi.visit([&](const auto& axis1) { Axis axisR{AxisBound, rMin, rMax, 1}; diff --git a/Core/src/Geometry/GridPortalLinkMerging.cpp b/Core/src/Geometry/GridPortalLinkMerging.cpp index 1a828e71176..f475822876b 100644 --- a/Core/src/Geometry/GridPortalLinkMerging.cpp +++ b/Core/src/Geometry/GridPortalLinkMerging.cpp @@ -88,14 +88,14 @@ std::unique_ptr makeGrid( std::unique_ptr mergeVariable( const std::shared_ptr& mergedSurface, const IAxis& axisA, - const IAxis& axisB, ActsScalar /*tolerance*/, BinningValue direction, + const IAxis& axisB, double /*tolerance*/, BinningValue direction, const Logger& logger, const IAxis* otherAxis, bool prepend) { ACTS_VERBOSE("Variable merge: direction is " << direction); ACTS_VERBOSE("~> axis a: " << axisA); ACTS_VERBOSE("~> axis b: " << axisB); - std::vector binEdges; + std::vector binEdges; binEdges.reserve(axisA.getNBins() + axisB.getNBins() + 1); @@ -107,23 +107,23 @@ std::unique_ptr mergeVariable( } else { ACTS_VERBOSE("Performing symmetrized merge"); - ActsScalar halfWidth = + double halfWidth = (axisA.getMax() - axisA.getMin() + axisB.getMax() - axisB.getMin()) / 2.0; ACTS_VERBOSE(" ~> half width: " << halfWidth); - ActsScalar shift = axisA.getMax() - halfWidth; + double shift = axisA.getMax() - halfWidth; ACTS_VERBOSE(" ~> shift: " << shift); std::ranges::transform(edgesA, std::back_inserter(binEdges), - [&](ActsScalar edge) { return edge + shift; }); + [&](double edge) { return edge + shift; }); } - ActsScalar stitchPoint = binEdges.back(); + double stitchPoint = binEdges.back(); auto edgesB = axisB.getBinEdges(); std::transform( std::next(edgesB.begin()), edgesB.end(), std::back_inserter(binEdges), - [&](ActsScalar edge) { return edge - axisB.getMin() + stitchPoint; }); + [&](double edge) { return edge - axisB.getMin() + stitchPoint; }); return makeGrid(mergedSurface, direction, logger, std::tuple{std::move(binEdges)}, otherAxis, prepend); @@ -131,25 +131,25 @@ std::unique_ptr mergeVariable( std::unique_ptr mergeEquidistant( const std::shared_ptr& mergedSurface, const IAxis& axisA, - const IAxis& axisB, ActsScalar tolerance, BinningValue direction, + const IAxis& axisB, double tolerance, BinningValue direction, const Logger& logger, const IAxis* otherAxis, bool prepend) { ACTS_VERBOSE("===> potentially equidistant merge: checking bin widths"); ACTS_VERBOSE("~> axis a: " << axisA); ACTS_VERBOSE("~> axis b: " << axisB); - ActsScalar binsWidthA = (axisA.getMax() - axisA.getMin()) / - static_cast(axisA.getNBins()); - ActsScalar binsWidthB = (axisB.getMax() - axisB.getMin()) / - static_cast(axisB.getNBins()); + double binsWidthA = + (axisA.getMax() - axisA.getMin()) / static_cast(axisA.getNBins()); + double binsWidthB = + (axisB.getMax() - axisB.getMin()) / static_cast(axisB.getNBins()); ACTS_VERBOSE(" ~> binWidths: " << binsWidthA << " vs " << binsWidthB); if (std::abs(binsWidthA - binsWidthB) < tolerance) { ACTS_VERBOSE("==> binWidths same: " << binsWidthA); - ActsScalar min = std::numeric_limits::signaling_NaN(); - ActsScalar max = std::numeric_limits::signaling_NaN(); + double min = std::numeric_limits::signaling_NaN(); + double max = std::numeric_limits::signaling_NaN(); if (direction == BinningValue::binR) { ACTS_VERBOSE("Performing asymmetric merge"); @@ -158,7 +158,7 @@ std::unique_ptr mergeEquidistant( } else { ACTS_VERBOSE("Performing symmetrized merge"); - ActsScalar halfWidth = + double halfWidth = (axisA.getMax() - axisA.getMin() + axisB.getMax() - axisB.getMin()) / 2.0; @@ -183,7 +183,7 @@ std::unique_ptr mergeEquidistant( std::unique_ptr colinearMerge( const std::shared_ptr& mergedSurface, const IAxis& axisA, - const IAxis& axisB, ActsScalar tolerance, BinningValue direction, + const IAxis& axisB, double tolerance, BinningValue direction, const Logger& logger, const IAxis* otherAxis, bool prepend) { AxisType aType = axisA.getType(); AxisType bType = axisB.getType(); diff --git a/Core/src/Geometry/KDTreeTrackingGeometryBuilder.cpp b/Core/src/Geometry/KDTreeTrackingGeometryBuilder.cpp index 75e2d50d4fa..c0a45763372 100644 --- a/Core/src/Geometry/KDTreeTrackingGeometryBuilder.cpp +++ b/Core/src/Geometry/KDTreeTrackingGeometryBuilder.cpp @@ -45,16 +45,16 @@ std::unique_ptr Acts::KDTreeTrackingGeometryBuilder::trackingGeometry( const GeometryContext& gctx) const { using MeasuredSurface = - std::pair, std::shared_ptr>; + std::pair, std::shared_ptr>; // Prepare all the surfaces std::vector surfacesMeasured; surfacesMeasured.reserve(m_cfg.surfaces.size()); for (auto& s : m_cfg.surfaces) { auto ext = s->polyhedronRepresentation(gctx, 1u).extent(); - surfacesMeasured.push_back(MeasuredSurface{ - std::array{ext.medium(BinningValue::binZ), - ext.medium(BinningValue::binR)}, - s}); + surfacesMeasured.push_back( + MeasuredSurface{std::array{ext.medium(BinningValue::binZ), + ext.medium(BinningValue::binR)}, + s}); } // Create the KDTree @@ -157,7 +157,7 @@ Acts::KDTreeTrackingGeometryBuilder::translateLayer( auto& its = plVolume.internal.value(); // Try to pull from the kd tree - RangeXD<2u, ActsScalar> zrRange; + RangeXD<2u, double> zrRange; zrRange[0u] = plVolume.extent.range(Acts::BinningValue::binZ); zrRange[1u] = plVolume.extent.range(Acts::BinningValue::binR); diff --git a/Core/src/Geometry/LayerCreator.cpp b/Core/src/Geometry/LayerCreator.cpp index 632274c671f..e24ff8e0661 100644 --- a/Core/src/Geometry/LayerCreator.cpp +++ b/Core/src/Geometry/LayerCreator.cpp @@ -407,8 +407,7 @@ Acts::MutableLayerPtr Acts::LayerCreator::planeLayer( } // create the layer and push it back - std::shared_ptr pBounds( - new RectangleBounds(layerHalf1, layerHalf2)); + auto pBounds = std::make_shared(layerHalf1, layerHalf2); // create the layer MutableLayerPtr pLayer = diff --git a/Core/src/Geometry/TrapezoidVolumeBounds.cpp b/Core/src/Geometry/TrapezoidVolumeBounds.cpp index 96d682a35dc..f03af8c85c0 100644 --- a/Core/src/Geometry/TrapezoidVolumeBounds.cpp +++ b/Core/src/Geometry/TrapezoidVolumeBounds.cpp @@ -23,9 +23,8 @@ namespace Acts { -TrapezoidVolumeBounds::TrapezoidVolumeBounds(ActsScalar minhalex, - ActsScalar maxhalex, - ActsScalar haley, ActsScalar halez) +TrapezoidVolumeBounds::TrapezoidVolumeBounds(double minhalex, double maxhalex, + double haley, double halez) : VolumeBounds() { m_values[eHalfLengthXnegY] = minhalex; m_values[eHalfLengthXposY] = maxhalex; @@ -37,9 +36,9 @@ TrapezoidVolumeBounds::TrapezoidVolumeBounds(ActsScalar minhalex, buildSurfaceBounds(); } -TrapezoidVolumeBounds::TrapezoidVolumeBounds(ActsScalar minhalex, - ActsScalar haley, ActsScalar halez, - ActsScalar alpha, ActsScalar beta) +TrapezoidVolumeBounds::TrapezoidVolumeBounds(double minhalex, double haley, + double halez, double alpha, + double beta) : VolumeBounds() { m_values[eHalfLengthXnegY] = minhalex; m_values[eHalfLengthY] = haley; @@ -47,8 +46,8 @@ TrapezoidVolumeBounds::TrapezoidVolumeBounds(ActsScalar minhalex, m_values[eAlpha] = alpha; m_values[eBeta] = beta; // now calculate the remaining max half X - ActsScalar gamma = (alpha > beta) ? (alpha - std::numbers::pi / 2.) - : (beta - std::numbers::pi / 2.); + double gamma = (alpha > beta) ? (alpha - std::numbers::pi / 2.) + : (beta - std::numbers::pi / 2.); m_values[eHalfLengthXposY] = minhalex + (2. * haley) * tan(gamma); checkConsistency(); @@ -78,9 +77,9 @@ std::vector TrapezoidVolumeBounds::orientedSurfaces( oSurfaces.push_back( OrientedSurface{std::move(sf), Direction::OppositeNormal}); - ActsScalar poshOffset = get(eHalfLengthY) / std::tan(get(eAlpha)); - ActsScalar neghOffset = get(eHalfLengthY) / std::tan(get(eBeta)); - ActsScalar topShift = poshOffset + neghOffset; + double poshOffset = get(eHalfLengthY) / std::tan(get(eAlpha)); + double neghOffset = get(eHalfLengthY) / std::tan(get(eBeta)); + double topShift = poshOffset + neghOffset; // Face surfaces yz // (3) - At point B, attached to beta opening angle @@ -141,7 +140,7 @@ void TrapezoidVolumeBounds::buildSurfaceBounds() { get(eHalfLengthZ), get(eHalfLengthXposY)); } -bool TrapezoidVolumeBounds::inside(const Vector3& pos, ActsScalar tol) const { +bool TrapezoidVolumeBounds::inside(const Vector3& pos, double tol) const { if (std::abs(pos.z()) > get(eHalfLengthZ) + tol) { return false; } @@ -168,10 +167,10 @@ std::ostream& TrapezoidVolumeBounds::toStream(std::ostream& os) const { Volume::BoundingBox TrapezoidVolumeBounds::boundingBox( const Transform3* trf, const Vector3& envelope, const Volume* entity) const { - ActsScalar minx = get(eHalfLengthXnegY); - ActsScalar maxx = get(eHalfLengthXposY); - ActsScalar haley = get(eHalfLengthY); - ActsScalar halez = get(eHalfLengthZ); + double minx = get(eHalfLengthXnegY); + double maxx = get(eHalfLengthXposY); + double haley = get(eHalfLengthY); + double halez = get(eHalfLengthZ); std::array vertices = {{{-minx, -haley, -halez}, {+minx, -haley, -halez}, @@ -199,8 +198,8 @@ Volume::BoundingBox TrapezoidVolumeBounds::boundingBox( return {entity, vmin - envelope, vmax + envelope}; } -std::vector TrapezoidVolumeBounds::values() const { - std::vector valvector; +std::vector TrapezoidVolumeBounds::values() const { + std::vector valvector; valvector.insert(valvector.begin(), m_values.begin(), m_values.end()); return valvector; } diff --git a/Core/src/Geometry/Volume.cpp b/Core/src/Geometry/Volume.cpp index 97a026b039f..7aac6f8b9d6 100644 --- a/Core/src/Geometry/Volume.cpp +++ b/Core/src/Geometry/Volume.cpp @@ -55,7 +55,7 @@ Volume& Volume::operator=(const Volume& vol) { return *this; } -bool Volume::inside(const Vector3& gpos, ActsScalar tol) const { +bool Volume::inside(const Vector3& gpos, double tol) const { Vector3 posInVolFrame((transform().inverse()) * gpos); return (volumeBounds()).inside(posInVolFrame, tol); } diff --git a/Core/src/Material/BinnedSurfaceMaterial.cpp b/Core/src/Material/BinnedSurfaceMaterial.cpp index 0113e89a6e3..aae46bd02d7 100644 --- a/Core/src/Material/BinnedSurfaceMaterial.cpp +++ b/Core/src/Material/BinnedSurfaceMaterial.cpp @@ -29,11 +29,10 @@ Acts::BinnedSurfaceMaterial::BinnedSurfaceMaterial( m_binUtility(binUtility), m_fullMaterial(std::move(fullProperties)) {} -Acts::BinnedSurfaceMaterial& Acts::BinnedSurfaceMaterial::operator*=( - double scale) { +Acts::BinnedSurfaceMaterial& Acts::BinnedSurfaceMaterial::scale(double factor) { for (auto& materialVector : m_fullMaterial) { for (auto& materialBin : materialVector) { - materialBin.scaleThickness(scale); + materialBin.scaleThickness(factor); } } return (*this); diff --git a/Core/src/Material/HomogeneousSurfaceMaterial.cpp b/Core/src/Material/HomogeneousSurfaceMaterial.cpp index ec56cfd4c81..c3bef1f9de3 100644 --- a/Core/src/Material/HomogeneousSurfaceMaterial.cpp +++ b/Core/src/Material/HomogeneousSurfaceMaterial.cpp @@ -12,20 +12,33 @@ #include -Acts::HomogeneousSurfaceMaterial::HomogeneousSurfaceMaterial( - const MaterialSlab& full, double splitFactor, Acts::MappingType mappingType) +namespace Acts { + +HomogeneousSurfaceMaterial::HomogeneousSurfaceMaterial(const MaterialSlab& full, + double splitFactor, + MappingType mappingType) : ISurfaceMaterial(splitFactor, mappingType), m_fullMaterial(full) {} -Acts::HomogeneousSurfaceMaterial& Acts::HomogeneousSurfaceMaterial::operator*=( - double scale) { - m_fullMaterial.scaleThickness(scale); - return (*this); +HomogeneousSurfaceMaterial& HomogeneousSurfaceMaterial::scale(double factor) { + m_fullMaterial.scaleThickness(factor); + return *this; +} + +const MaterialSlab& HomogeneousSurfaceMaterial::materialSlab( + const Vector2& /*lp*/) const { + return m_fullMaterial; } -std::ostream& Acts::HomogeneousSurfaceMaterial::toStream( - std::ostream& sl) const { - sl << "Acts::HomogeneousSurfaceMaterial : " << std::endl; +const MaterialSlab& HomogeneousSurfaceMaterial::materialSlab( + const Vector3& /*gp*/) const { + return m_fullMaterial; +} + +std::ostream& HomogeneousSurfaceMaterial::toStream(std::ostream& sl) const { + sl << "HomogeneousSurfaceMaterial : " << std::endl; sl << " - fullMaterial : " << m_fullMaterial << std::endl; sl << " - split factor : " << m_splitFactor << std::endl; return sl; } + +} // namespace Acts diff --git a/Core/src/Material/HomogeneousVolumeMaterial.cpp b/Core/src/Material/HomogeneousVolumeMaterial.cpp index 574859bb648..a5ea578f0ce 100644 --- a/Core/src/Material/HomogeneousVolumeMaterial.cpp +++ b/Core/src/Material/HomogeneousVolumeMaterial.cpp @@ -12,13 +12,20 @@ #include -Acts::HomogeneousVolumeMaterial::HomogeneousVolumeMaterial( - const Material& material) +namespace Acts { + +HomogeneousVolumeMaterial::HomogeneousVolumeMaterial(const Material& material) : m_material(material) {} -std::ostream& Acts::HomogeneousVolumeMaterial::toStream( - std::ostream& sl) const { - sl << "Acts::HomogeneousVolumeMaterial : " << std::endl; +const Material HomogeneousVolumeMaterial::material( + const Vector3& /*position*/) const { + return m_material; +} + +std::ostream& HomogeneousVolumeMaterial::toStream(std::ostream& sl) const { + sl << "HomogeneousVolumeMaterial : " << std::endl; sl << " - material : " << m_material << std::endl; return sl; } + +} // namespace Acts diff --git a/Core/src/Material/Material.cpp b/Core/src/Material/Material.cpp index dd8c1e5cca1..29d9502fde9 100644 --- a/Core/src/Material/Material.cpp +++ b/Core/src/Material/Material.cpp @@ -13,6 +13,8 @@ #include #include +namespace Acts { + namespace { enum MaterialClassificationNumberIndices { eRadiationLength = 0, @@ -23,12 +25,12 @@ enum MaterialClassificationNumberIndices { }; // Avogadro constant -constexpr double kAvogadro = 6.02214076e23 / Acts::UnitConstants::mol; +constexpr double kAvogadro = 6.02214076e23 / UnitConstants::mol; } // namespace -Acts::Material Acts::Material::fromMassDensity(float x0, float l0, float ar, - float z, float massRho) { - using namespace Acts::UnitLiterals; +Material Material::fromMassDensity(float x0, float l0, float ar, float z, + float massRho) { + using namespace UnitLiterals; Material mat; mat.m_x0 = x0; @@ -51,8 +53,8 @@ Acts::Material Acts::Material::fromMassDensity(float x0, float l0, float ar, return mat; } -Acts::Material Acts::Material::fromMolarDensity(float x0, float l0, float ar, - float z, float molarRho) { +Material Material::fromMolarDensity(float x0, float l0, float ar, float z, + float molarRho) { Material mat; mat.m_x0 = x0; mat.m_l0 = l0; @@ -62,15 +64,15 @@ Acts::Material Acts::Material::fromMolarDensity(float x0, float l0, float ar, return mat; } -Acts::Material::Material(const ParametersVector& parameters) +Material::Material(const ParametersVector& parameters) : m_x0(parameters[eRadiationLength]), m_l0(parameters[eInteractionLength]), m_ar(parameters[eRelativeAtomicMass]), m_z(parameters[eNuclearCharge]), m_molarRho(parameters[eMolarDensity]) {} -float Acts::Material::massDensity() const { - using namespace Acts::UnitLiterals; +float Material::massDensity() const { + using namespace UnitLiterals; // perform computations in double precision to avoid loss of precision const double atomicMass = static_cast(m_ar) * 1_u; @@ -78,14 +80,14 @@ float Acts::Material::massDensity() const { return atomicMass * numberDensity; } -float Acts::Material::meanExcitationEnergy() const { - using namespace Acts::UnitLiterals; +float Material::meanExcitationEnergy() const { + using namespace UnitLiterals; // use approximative computation as defined in ATL-SOFT-PUB-2008-003 return 16_eV * std::pow(m_z, 0.9f); } -Acts::Material::ParametersVector Acts::Material::parameters() const { +Material::ParametersVector Material::parameters() const { ParametersVector parameters; parameters[eRadiationLength] = m_x0; parameters[eInteractionLength] = m_l0; @@ -95,7 +97,7 @@ Acts::Material::ParametersVector Acts::Material::parameters() const { return parameters; } -std::ostream& Acts::operator<<(std::ostream& os, const Material& material) { +std::ostream& operator<<(std::ostream& os, const Material& material) { if (!material.isValid()) { os << "vacuum"; } else { @@ -107,3 +109,5 @@ std::ostream& Acts::operator<<(std::ostream& os, const Material& material) { } return os; } + +} // namespace Acts diff --git a/Core/src/Material/MaterialInteractionAssignment.cpp b/Core/src/Material/MaterialInteractionAssignment.cpp index 8d4b4b0ac60..32e93bcef1a 100644 --- a/Core/src/Material/MaterialInteractionAssignment.cpp +++ b/Core/src/Material/MaterialInteractionAssignment.cpp @@ -49,7 +49,7 @@ Acts::MaterialInteractionAssignment::assign( // Walk along the sorted intersections auto [cSurface, cPosition, cDirection] = intersectedSurfaces[is]; - ActsScalar cDistance = (cPosition - materialInteraction.position).norm(); + double cDistance = (cPosition - materialInteraction.position).norm(); // Peak forward to check if you have a closer intersection while ( @@ -57,9 +57,9 @@ Acts::MaterialInteractionAssignment::assign( (((intersectedSurfaces[is + 1]).position - materialInteraction.position) .norm() < cDistance)) { // Recalculate the new distance - ActsScalar nDistance = ((intersectedSurfaces[is + 1]).position - - materialInteraction.position) - .norm(); + double nDistance = ((intersectedSurfaces[is + 1]).position - + materialInteraction.position) + .norm(); ++is; cDistance = nDistance; } @@ -68,8 +68,7 @@ Acts::MaterialInteractionAssignment::assign( auto [surface, position, direction] = intersectedSurfaces[is]; // Calculate the path correction - ActsScalar pathCorrection = - surface->pathCorrection(gctx, position, direction); + double pathCorrection = surface->pathCorrection(gctx, position, direction); // A local veta veto kicked in GeometryIdentifier intersectionID = surface->geometryId(); diff --git a/Core/src/Material/MaterialSlab.cpp b/Core/src/Material/MaterialSlab.cpp index acfd7064936..4fad731c6c1 100644 --- a/Core/src/Material/MaterialSlab.cpp +++ b/Core/src/Material/MaterialSlab.cpp @@ -11,7 +11,6 @@ #include "Acts/Material/detail/AverageMaterials.hpp" #include -#include #include #include diff --git a/Core/src/Navigation/NavigationStream.cpp b/Core/src/Navigation/NavigationStream.cpp index c36eed12bbe..3ea28dd748c 100644 --- a/Core/src/Navigation/NavigationStream.cpp +++ b/Core/src/Navigation/NavigationStream.cpp @@ -18,7 +18,7 @@ namespace Acts { bool NavigationStream::initialize(const GeometryContext& gctx, const QueryPoint& queryPoint, const BoundaryTolerance& cTolerance, - ActsScalar onSurfaceTolerance) { + double onSurfaceTolerance) { // Position and direction from the query point const Vector3& position = queryPoint.position; const Vector3& direction = queryPoint.direction; @@ -95,7 +95,7 @@ bool NavigationStream::initialize(const GeometryContext& gctx, bool NavigationStream::update(const GeometryContext& gctx, const QueryPoint& queryPoint, - ActsScalar onSurfaceTolerance) { + double onSurfaceTolerance) { // Loop over the (currently valid) candidates and update for (; m_currentIndex < m_candidates.size(); ++m_currentIndex) { // Get the candidate, and resolve the tuple diff --git a/Core/src/Propagator/SympyStepper.cpp b/Core/src/Propagator/SympyStepper.cpp index a33e1f567bb..d55c073a851 100644 --- a/Core/src/Propagator/SympyStepper.cpp +++ b/Core/src/Propagator/SympyStepper.cpp @@ -144,7 +144,8 @@ Result SympyStepper::stepImpl( double errorEstimate = 0.; while (true) { - nStepTrials++; + ++nStepTrials; + ++state.statistics.nAttemptedSteps; // For details about the factor 4 see ATL-SOFT-PUB-2009-001 Result res = @@ -164,6 +165,8 @@ Result SympyStepper::stepImpl( break; } + ++state.statistics.nRejectedSteps; + const double stepSizeScaling = calcStepSizeScaling(errorEstimate); h *= stepSizeScaling; @@ -186,6 +189,13 @@ Result SympyStepper::stepImpl( ++state.nSteps; state.nStepTrials += nStepTrials; + ++state.statistics.nSuccessfulSteps; + if (stepDirection != Direction::fromScalarZeroAsPositive(initialH)) { + ++state.statistics.nReverseSteps; + } + state.statistics.pathLength += h; + state.statistics.absolutePathLength += std::abs(h); + const double stepSizeScaling = calcStepSizeScaling(errorEstimate); const double nextAccuracy = std::abs(h * stepSizeScaling); const double previousAccuracy = std::abs(state.stepSize.accuracy()); diff --git a/Core/src/Seeding/EstimateTrackParamsFromSeed.cpp b/Core/src/Seeding/EstimateTrackParamsFromSeed.cpp index 055691bbb2f..6d11d82e124 100644 --- a/Core/src/Seeding/EstimateTrackParamsFromSeed.cpp +++ b/Core/src/Seeding/EstimateTrackParamsFromSeed.cpp @@ -9,6 +9,7 @@ #include "Acts/Seeding/EstimateTrackParamsFromSeed.hpp" #include "Acts/Definitions/TrackParametrization.hpp" +#include "Acts/Utilities/MathHelpers.hpp" #include @@ -47,27 +48,27 @@ Acts::FreeVector Acts::estimateTrackParamsFromSeed(const Vector3& sp0, Vector2 circleCenter; circleCenter(0) = 0.5 * local1(0); - ActsScalar deltaX21 = local2(0) - local1(0); - ActsScalar sumX21 = local2(0) + local1(0); + double deltaX21 = local2(0) - local1(0); + double sumX21 = local2(0) + local1(0); // straight line connecting the two points // y = a * x + c (we don't care about c right now) // we simply need the slope // we compute 1./a since this is what we need for the following computation - ActsScalar ia = deltaX21 / local2(1); + double ia = deltaX21 / local2(1); // Perpendicular line is then y = -1/a *x + b // we can evaluate b given we know a already by imposing // the line passes through P = (0.5 * (x2 + x1), 0.5 * y2) - ActsScalar b = 0.5 * (local2(1) + ia * sumX21); + double b = 0.5 * (local2(1) + ia * sumX21); circleCenter(1) = -ia * circleCenter(0) + b; // Radius is a signed distance between circleCenter and first sp, which is at // (0, 0) in the new frame. Sign depends on the slope a (positive vs negative) int sign = ia > 0 ? -1 : 1; - const ActsScalar R = circleCenter.norm(); - ActsScalar invTanTheta = + const double R = circleCenter.norm(); + double invTanTheta = local2.z() / (2 * R * std::asin(local2.head<2>().norm() / (2 * R))); // The momentum direction in the new frame (the center of the circle has the // coordinate (-1.*A/(2*B), 1./(2*B))) - ActsScalar A = -circleCenter(0) / circleCenter(1); + double A = -circleCenter(0) / circleCenter(1); Vector3 transDirection(1., A, fastHypot(1, A) * invTanTheta); // Transform it back to the original frame Vector3 direction = rotation * transDirection.normalized(); @@ -83,7 +84,7 @@ Acts::FreeVector Acts::estimateTrackParamsFromSeed(const Vector3& sp0, // The estimated q/pt in [GeV/c]^-1 (note that the pt is the projection of // momentum on the transverse plane of the new frame) - ActsScalar qOverPt = sign / (bField.norm() * R); + double qOverPt = sign / (bField.norm() * R); // The estimated q/p in [GeV/c]^-1 params[eFreeQOverP] = qOverPt / fastHypot(1., invTanTheta); diff --git a/Core/src/Surfaces/AnnulusBounds.cpp b/Core/src/Surfaces/AnnulusBounds.cpp index 34c7b5c468b..593184816ac 100644 --- a/Core/src/Surfaces/AnnulusBounds.cpp +++ b/Core/src/Surfaces/AnnulusBounds.cpp @@ -107,11 +107,11 @@ std::vector Acts::AnnulusBounds::vertices( if (quarterSegments > 0u) { using VectorHelpers::phi; - ActsScalar phiMinInner = phi(m_inRightStripXY - m_moduleOrigin); - ActsScalar phiMaxInner = phi(m_inLeftStripXY - m_moduleOrigin); + double phiMinInner = phi(m_inRightStripXY - m_moduleOrigin); + double phiMaxInner = phi(m_inLeftStripXY - m_moduleOrigin); - ActsScalar phiMinOuter = phi(m_outRightStripXY - m_moduleOrigin); - ActsScalar phiMaxOuter = phi(m_outLeftStripXY - m_moduleOrigin); + double phiMinOuter = phi(m_outRightStripXY - m_moduleOrigin); + double phiMaxOuter = phi(m_outLeftStripXY - m_moduleOrigin); // Inner bow from phi_min -> phi_max (needs to be reversed) std::vector rvertices = @@ -355,10 +355,7 @@ Acts::Vector2 Acts::AnnulusBounds::closestOnSegment( // weighted scalar product of line to point and segment line auto u = ((p - a).transpose() * weight * n).value() / f; // clamp to [0, 1], convert to point - return std::min(std::max(u, static_cast(0)), - static_cast(1)) * - n + - a; + return std::min(std::max(u, 0.), 1.) * n + a; } double Acts::AnnulusBounds::squaredNorm(const Vector2& v, @@ -367,7 +364,7 @@ double Acts::AnnulusBounds::squaredNorm(const Vector2& v, } Acts::Vector2 Acts::AnnulusBounds::moduleOrigin() const { - return Eigen::Rotation2D(get(eAveragePhi)) * m_moduleOrigin; + return Eigen::Rotation2D(get(eAveragePhi)) * m_moduleOrigin; } // Ostream operator overload diff --git a/Core/src/Surfaces/ConeSurface.cpp b/Core/src/Surfaces/ConeSurface.cpp index b6d04e87e06..5dddd1527bf 100644 --- a/Core/src/Surfaces/ConeSurface.cpp +++ b/Core/src/Surfaces/ConeSurface.cpp @@ -189,8 +189,8 @@ Acts::Polyhedron Acts::ConeSurface::polyhedronRepresentation( std::vector vertices; std::vector faces; std::vector triangularMesh; - ActsScalar minZ = bounds().get(ConeBounds::eMinZ); - ActsScalar maxZ = bounds().get(ConeBounds::eMaxZ); + double minZ = bounds().get(ConeBounds::eMinZ); + double maxZ = bounds().get(ConeBounds::eMaxZ); if (minZ == -std::numeric_limits::infinity() || maxZ == std::numeric_limits::infinity()) { @@ -208,15 +208,15 @@ Acts::Polyhedron Acts::ConeSurface::polyhedronRepresentation( } // Cone parameters - ActsScalar hPhiSec = bounds().get(ConeBounds::eHalfPhiSector); - ActsScalar avgPhi = bounds().get(ConeBounds::eAveragePhi); - std::vector refPhi = {}; - if (bool fullCone = (hPhiSec == std::numbers::pi_v); !fullCone) { + double hPhiSec = bounds().get(ConeBounds::eHalfPhiSector); + double avgPhi = bounds().get(ConeBounds::eAveragePhi); + std::vector refPhi = {}; + if (bool fullCone = (hPhiSec == std::numbers::pi); !fullCone) { refPhi = {avgPhi}; } // Add the cone sizes - std::vector coneSides; + std::vector coneSides; if (std::abs(minZ) > s_onSurfaceTolerance) { coneSides.push_back(minZ); } @@ -284,7 +284,7 @@ Acts::detail::RealQuadraticEquation Acts::ConeSurface::intersectionSolver( Acts::SurfaceMultiIntersection Acts::ConeSurface::intersect( const GeometryContext& gctx, const Vector3& position, const Vector3& direction, const BoundaryTolerance& boundaryTolerance, - ActsScalar tolerance) const { + double tolerance) const { // Solve the quadratic equation auto qe = intersectionSolver(gctx, position, direction); @@ -295,23 +295,23 @@ Acts::SurfaceMultiIntersection Acts::ConeSurface::intersect( // Check the validity of the first solution Vector3 solution1 = position + qe.first * direction; - Intersection3D::Status status1 = std::abs(qe.first) < std::abs(tolerance) - ? Intersection3D::Status::onSurface - : Intersection3D::Status::reachable; + IntersectionStatus status1 = std::abs(qe.first) < std::abs(tolerance) + ? IntersectionStatus::onSurface + : IntersectionStatus::reachable; if (!boundaryTolerance.isInfinite() && !isOnSurface(gctx, solution1, direction, boundaryTolerance)) { - status1 = Intersection3D::Status::missed; + status1 = IntersectionStatus::unreachable; } // Check the validity of the second solution Vector3 solution2 = position + qe.first * direction; - Intersection3D::Status status2 = std::abs(qe.second) < std::abs(tolerance) - ? Intersection3D::Status::onSurface - : Intersection3D::Status::reachable; + IntersectionStatus status2 = std::abs(qe.second) < std::abs(tolerance) + ? IntersectionStatus::onSurface + : IntersectionStatus::reachable; if (!boundaryTolerance.isInfinite() && !isOnSurface(gctx, solution2, direction, boundaryTolerance)) { - status2 = Intersection3D::Status::missed; + status2 = IntersectionStatus::unreachable; } const auto& tf = transform(gctx); diff --git a/Core/src/Surfaces/CylinderBounds.cpp b/Core/src/Surfaces/CylinderBounds.cpp index 82f809c6c5b..c538b5c170b 100644 --- a/Core/src/Surfaces/CylinderBounds.cpp +++ b/Core/src/Surfaces/CylinderBounds.cpp @@ -112,9 +112,9 @@ std::vector Acts::CylinderBounds::circleVertices( double avgPhi = get(eAveragePhi); double halfPhi = get(eHalfPhiSector); - std::vector phiRef = {}; + std::vector phiRef = {}; if (bool fullCylinder = coversFullAzimuth(); fullCylinder) { - phiRef = {static_cast(avgPhi)}; + phiRef = {avgPhi}; } // Write the two bows/circles on either side @@ -127,13 +127,13 @@ std::vector Acts::CylinderBounds::circleVertices( vertices.insert(vertices.end(), svertices.begin(), svertices.end()); } - ActsScalar bevelMinZ = get(eBevelMinZ); - ActsScalar bevelMaxZ = get(eBevelMaxZ); + double bevelMinZ = get(eBevelMinZ); + double bevelMaxZ = get(eBevelMaxZ); // Modify the vertices position if bevel is defined if ((bevelMinZ != 0. || bevelMaxZ != 0.) && vertices.size() % 2 == 0) { auto halfWay = vertices.end() - vertices.size() / 2; - ActsScalar mult{1}; + double mult{1}; auto invTransform = transform.inverse(); auto func = [&mult, &transform, &invTransform](Vector3& v) { v = invTransform * v; diff --git a/Core/src/Surfaces/CylinderSurface.cpp b/Core/src/Surfaces/CylinderSurface.cpp index 4b3cd2db7be..23bb74e49f8 100644 --- a/Core/src/Surfaces/CylinderSurface.cpp +++ b/Core/src/Surfaces/CylinderSurface.cpp @@ -230,7 +230,7 @@ Acts::detail::RealQuadraticEquation Acts::CylinderSurface::intersectionSolver( Acts::SurfaceMultiIntersection Acts::CylinderSurface::intersect( const GeometryContext& gctx, const Vector3& position, const Vector3& direction, const BoundaryTolerance& boundaryTolerance, - ActsScalar tolerance) const { + double tolerance) const { const auto& gctxTransform = transform(gctx); // Solve the quadratic equation @@ -243,14 +243,13 @@ Acts::SurfaceMultiIntersection Acts::CylinderSurface::intersect( // Check the validity of the first solution Vector3 solution1 = position + qe.first * direction; - Intersection3D::Status status1 = std::abs(qe.first) < std::abs(tolerance) - ? Intersection3D::Status::onSurface - : Intersection3D::Status::reachable; + IntersectionStatus status1 = std::abs(qe.first) < std::abs(tolerance) + ? IntersectionStatus::onSurface + : IntersectionStatus::reachable; // Helper method for boundary check - auto boundaryCheck = - [&](const Vector3& solution, - Intersection3D::Status status) -> Intersection3D::Status { + auto boundaryCheck = [&](const Vector3& solution, + IntersectionStatus status) -> IntersectionStatus { // No check to be done, return current status if (boundaryTolerance.isInfinite()) { return status; @@ -267,11 +266,11 @@ Acts::SurfaceMultiIntersection Acts::CylinderSurface::intersect( double modifiedTolerance = tolerance + absoluteBound->tolerance1; double hZ = cBounds.get(CylinderBounds::eHalfLengthZ) + modifiedTolerance; return std::abs(cZ) < std::abs(hZ) ? status - : Intersection3D::Status::missed; + : IntersectionStatus::unreachable; } return isOnSurface(gctx, solution, direction, boundaryTolerance) ? status - : Intersection3D::Status::missed; + : IntersectionStatus::unreachable; }; // Check first solution for boundary compatibility status1 = boundaryCheck(solution1, status1); @@ -282,9 +281,9 @@ Acts::SurfaceMultiIntersection Acts::CylinderSurface::intersect( } // Check the validity of the second solution Vector3 solution2 = position + qe.second * direction; - Intersection3D::Status status2 = std::abs(qe.second) < std::abs(tolerance) - ? Intersection3D::Status::onSurface - : Intersection3D::Status::reachable; + IntersectionStatus status2 = std::abs(qe.second) < std::abs(tolerance) + ? IntersectionStatus::onSurface + : IntersectionStatus::reachable; // Check first solution for boundary compatibility status2 = boundaryCheck(solution2, status2); Intersection3D second(solution2, qe.second, status2); @@ -430,7 +429,7 @@ Acts::CylinderSurface::mergedWith(const CylinderSurface& other, "CylinderSurface::merge: surfaces have different radii"); } - ActsScalar r = bounds().get(CylinderBounds::eR); + double r = bounds().get(CylinderBounds::eR); // no translation in x/z is allowed Vector3 translation = otherLocal.translation(); @@ -444,20 +443,20 @@ Acts::CylinderSurface::mergedWith(const CylinderSurface& other, "CylinderSurface::merge: surfaces have relative translation in x/y"); } - ActsScalar hlZ = bounds().get(CylinderBounds::eHalfLengthZ); - ActsScalar minZ = -hlZ; - ActsScalar maxZ = hlZ; + double hlZ = bounds().get(CylinderBounds::eHalfLengthZ); + double minZ = -hlZ; + double maxZ = hlZ; - ActsScalar zShift = translation[2]; - ActsScalar otherHlZ = other.bounds().get(CylinderBounds::eHalfLengthZ); - ActsScalar otherMinZ = -otherHlZ + zShift; - ActsScalar otherMaxZ = otherHlZ + zShift; + double zShift = translation[2]; + double otherHlZ = other.bounds().get(CylinderBounds::eHalfLengthZ); + double otherMinZ = -otherHlZ + zShift; + double otherMaxZ = otherHlZ + zShift; - ActsScalar hlPhi = bounds().get(CylinderBounds::eHalfPhiSector); - ActsScalar avgPhi = bounds().get(CylinderBounds::eAveragePhi); + double hlPhi = bounds().get(CylinderBounds::eHalfPhiSector); + double avgPhi = bounds().get(CylinderBounds::eAveragePhi); - ActsScalar otherHlPhi = other.bounds().get(CylinderBounds::eHalfPhiSector); - ActsScalar otherAvgPhi = other.bounds().get(CylinderBounds::eAveragePhi); + double otherHlPhi = other.bounds().get(CylinderBounds::eHalfPhiSector); + double otherAvgPhi = other.bounds().get(CylinderBounds::eAveragePhi); if (direction == Acts::BinningValue::binZ) { // z shift must match the bounds @@ -491,10 +490,10 @@ Acts::CylinderSurface::mergedWith(const CylinderSurface& other, "different phi sectors"); } - ActsScalar newMaxZ = std::max(maxZ, otherMaxZ); - ActsScalar newMinZ = std::min(minZ, otherMinZ); - ActsScalar newHlZ = (newMaxZ - newMinZ) / 2.0; - ActsScalar newMidZ = (newMaxZ + newMinZ) / 2.0; + double newMaxZ = std::max(maxZ, otherMaxZ); + double newMinZ = std::min(minZ, otherMinZ); + double newHlZ = (newMaxZ - newMinZ) / 2.0; + double newMidZ = (newMaxZ + newMinZ) / 2.0; ACTS_VERBOSE("merged: [" << newMinZ << ", " << newMaxZ << "] ~> " << newMidZ << " +- " << newHlZ); @@ -526,7 +525,7 @@ Acts::CylinderSurface::mergedWith(const CylinderSurface& other, // Figure out signed relative rotation Vector2 rotatedX = otherLocal.linear().col(eX).head<2>(); - ActsScalar zrotation = std::atan2(rotatedX[1], rotatedX[0]); + double zrotation = std::atan2(rotatedX[1], rotatedX[0]); ACTS_VERBOSE("this: [" << avgPhi / 1_degree << " +- " << hlPhi / 1_degree << "]"); @@ -535,7 +534,7 @@ Acts::CylinderSurface::mergedWith(const CylinderSurface& other, ACTS_VERBOSE("Relative rotation around local z: " << zrotation / 1_degree); - ActsScalar prevOtherAvgPhi = otherAvgPhi; + double prevOtherAvgPhi = otherAvgPhi; otherAvgPhi = detail::radian_sym(otherAvgPhi + zrotation); ACTS_VERBOSE("~> local other average phi: " << otherAvgPhi / 1_degree diff --git a/Core/src/Surfaces/DiscSurface.cpp b/Core/src/Surfaces/DiscSurface.cpp index da1aa2b54bc..ac3c188fd7d 100644 --- a/Core/src/Surfaces/DiscSurface.cpp +++ b/Core/src/Surfaces/DiscSurface.cpp @@ -278,7 +278,7 @@ Acts::FreeToBoundMatrix Acts::DiscSurface::freeToBoundJacobian( Acts::SurfaceMultiIntersection Acts::DiscSurface::intersect( const GeometryContext& gctx, const Vector3& position, const Vector3& direction, const BoundaryTolerance& boundaryTolerance, - ActsScalar tolerance) const { + double tolerance) const { // Get the contextual transform auto gctxTransform = transform(gctx); // Use the intersection helper for planar surfaces @@ -286,7 +286,7 @@ Acts::SurfaceMultiIntersection Acts::DiscSurface::intersect( PlanarHelper::intersect(gctxTransform, position, direction, tolerance); auto status = intersection.status(); // Evaluate boundary check if requested (and reachable) - if (intersection.status() != Intersection3D::Status::unreachable && + if (intersection.status() != IntersectionStatus::unreachable && m_bounds != nullptr && !boundaryTolerance.isInfinite()) { // Built-in local to global for speed reasons const auto& tMatrix = gctxTransform.matrix(); @@ -297,11 +297,11 @@ Acts::SurfaceMultiIntersection Acts::DiscSurface::intersect( double modifiedTolerance = tolerance + absoluteBound->tolerance0; if (!m_bounds->insideRadialBounds(VectorHelpers::perp(lcartesian), modifiedTolerance)) { - status = Intersection3D::Status::missed; + status = IntersectionStatus::unreachable; } } else if (!insideBounds(localCartesianToPolar(lcartesian), boundaryTolerance)) { - status = Intersection3D::Status::missed; + status = IntersectionStatus::unreachable; } } return {{Intersection3D(intersection.position(), intersection.pathLength(), @@ -425,25 +425,25 @@ Acts::DiscSurface::mergedWith(const DiscSurface& other, BinningValue direction, "DiscSurface::merge: surfaces have bounds other than radial"); } - ActsScalar minR = bounds->get(RadialBounds::eMinR); - ActsScalar maxR = bounds->get(RadialBounds::eMaxR); + double minR = bounds->get(RadialBounds::eMinR); + double maxR = bounds->get(RadialBounds::eMaxR); - ActsScalar hlPhi = bounds->get(RadialBounds::eHalfPhiSector); - ActsScalar avgPhi = bounds->get(RadialBounds::eAveragePhi); - ActsScalar minPhi = detail::radian_sym(-hlPhi + avgPhi); - ActsScalar maxPhi = detail::radian_sym(hlPhi + avgPhi); + double hlPhi = bounds->get(RadialBounds::eHalfPhiSector); + double avgPhi = bounds->get(RadialBounds::eAveragePhi); + double minPhi = detail::radian_sym(-hlPhi + avgPhi); + double maxPhi = detail::radian_sym(hlPhi + avgPhi); ACTS_VERBOSE(" this: r = [" << minR << ", " << maxR << "]"); ACTS_VERBOSE(" phi = [" << minPhi / 1_degree << ", " << maxPhi / 1_degree << "] ~> " << avgPhi / 1_degree << " +- " << hlPhi / 1_degree); - ActsScalar otherMinR = otherBounds->get(RadialBounds::eMinR); - ActsScalar otherMaxR = otherBounds->get(RadialBounds::eMaxR); - ActsScalar otherAvgPhi = otherBounds->get(RadialBounds::eAveragePhi); - ActsScalar otherHlPhi = otherBounds->get(RadialBounds::eHalfPhiSector); - ActsScalar otherMinPhi = detail::radian_sym(-otherHlPhi + otherAvgPhi); - ActsScalar otherMaxPhi = detail::radian_sym(otherHlPhi + otherAvgPhi); + double otherMinR = otherBounds->get(RadialBounds::eMinR); + double otherMaxR = otherBounds->get(RadialBounds::eMaxR); + double otherAvgPhi = otherBounds->get(RadialBounds::eAveragePhi); + double otherHlPhi = otherBounds->get(RadialBounds::eHalfPhiSector); + double otherMinPhi = detail::radian_sym(-otherHlPhi + otherAvgPhi); + double otherMaxPhi = detail::radian_sym(otherHlPhi + otherAvgPhi); ACTS_VERBOSE("other: r = [" << otherMinR << ", " << otherMaxR << "]"); ACTS_VERBOSE(" phi = [" << otherMinPhi / 1_degree << ", " @@ -481,8 +481,8 @@ Acts::DiscSurface::mergedWith(const DiscSurface& other, BinningValue direction, "DiscSurface::merge: surfaces have different half phi sector"); } - ActsScalar newMinR = std::min(minR, otherMinR); - ActsScalar newMaxR = std::max(maxR, otherMaxR); + double newMinR = std::min(minR, otherMinR); + double newMaxR = std::max(maxR, otherMaxR); ACTS_VERBOSE(" new: r = [" << newMinR << ", " << newMaxR << "]"); auto newBounds = @@ -502,7 +502,7 @@ Acts::DiscSurface::mergedWith(const DiscSurface& other, BinningValue direction, // Figure out signed relative rotation Vector2 rotatedX = otherLocal.linear().col(eX).head<2>(); - ActsScalar zrotation = std::atan2(rotatedX[1], rotatedX[0]); + double zrotation = std::atan2(rotatedX[1], rotatedX[0]); ACTS_VERBOSE("this: [" << avgPhi / 1_degree << " +- " << hlPhi / 1_degree << "]"); @@ -511,7 +511,7 @@ Acts::DiscSurface::mergedWith(const DiscSurface& other, BinningValue direction, ACTS_VERBOSE("Relative rotation around local z: " << zrotation / 1_degree); - ActsScalar prevOtherAvgPhi = otherAvgPhi; + double prevOtherAvgPhi = otherAvgPhi; otherAvgPhi = detail::radian_sym(otherAvgPhi + zrotation); ACTS_VERBOSE("~> local other average phi: " << otherAvgPhi / 1_degree diff --git a/Core/src/Surfaces/IntersectionHelper2D.cpp b/Core/src/Surfaces/IntersectionHelper2D.cpp index 1053021034f..458a54a2262 100644 --- a/Core/src/Surfaces/IntersectionHelper2D.cpp +++ b/Core/src/Surfaces/IntersectionHelper2D.cpp @@ -17,11 +17,11 @@ Acts::Intersection2D Acts::detail::IntersectionHelper2D::intersectSegment( const Vector2& s0, const Vector2& s1, const Vector2& origin, const Vector2& dir, bool boundCheck) { - using Line = Eigen::ParametrizedLine; - using Plane = Eigen::Hyperplane; + using Line = Eigen::ParametrizedLine; + using Plane = Eigen::Hyperplane; Vector2 edge(s1 - s0); - ActsScalar det = edge.x() * dir.y() - edge.y() * dir.x(); + double det = edge.x() * dir.y() - edge.y() * dir.x(); if (std::abs(det) < s_epsilon) { return Intersection2D::invalid(); } @@ -30,19 +30,18 @@ Acts::Intersection2D Acts::detail::IntersectionHelper2D::intersectSegment( auto d = line.intersectionParameter(Plane::Through(s0, s1)); Vector2 intersection(origin + d * dir); - Intersection2D::Status status = Intersection2D::Status::reachable; + IntersectionStatus status = IntersectionStatus::reachable; if (boundCheck) { auto edgeToSol = intersection - s0; if (edgeToSol.dot(edge) < 0. || edgeToSol.norm() > (edge).norm()) { - status = Intersection2D::Status::unreachable; + status = IntersectionStatus::unreachable; } } return Intersection2D(intersection, d, status); } std::array -Acts::detail::IntersectionHelper2D::intersectEllipse(ActsScalar Rx, - ActsScalar Ry, +Acts::detail::IntersectionHelper2D::intersectEllipse(double Rx, double Ry, const Vector2& origin, const Vector2& dir) { auto createSolution = @@ -51,65 +50,65 @@ Acts::detail::IntersectionHelper2D::intersectEllipse(ActsScalar Rx, Vector2 toSolD(sol - origin); Vector2 toAltD(alt - origin); - ActsScalar solD = std::copysign(toSolD.norm(), toSolD.dot(dir)); - ActsScalar altD = std::copysign(toAltD.norm(), toAltD.dot(dir)); + double solD = std::copysign(toSolD.norm(), toSolD.dot(dir)); + double altD = std::copysign(toAltD.norm(), toAltD.dot(dir)); if (std::abs(solD) < std::abs(altD)) { - return {Intersection2D(sol, solD, Intersection2D::Status::reachable), - Intersection2D(alt, altD, Intersection2D::Status::reachable)}; + return {Intersection2D(sol, solD, IntersectionStatus::reachable), + Intersection2D(alt, altD, IntersectionStatus::reachable)}; } - return {Intersection2D(alt, altD, Intersection2D::Status::reachable), - Intersection2D(sol, solD, Intersection2D::Status::reachable)}; + return {Intersection2D(alt, altD, IntersectionStatus::reachable), + Intersection2D(sol, solD, IntersectionStatus::reachable)}; }; // Special cases first if (std::abs(dir.x()) < s_epsilon) { - ActsScalar solx = origin.x(); - ActsScalar D = 1. - solx * solx / (Rx * Rx); + double solx = origin.x(); + double D = 1. - solx * solx / (Rx * Rx); if (D > 0.) { - ActsScalar sqrtD = std::sqrt(D); + double sqrtD = std::sqrt(D); Vector2 sol(solx, Ry * sqrtD); Vector2 alt(solx, -Ry * sqrtD); return createSolution(sol, alt); } else if (std::abs(D) < s_epsilon) { return {Intersection2D(Vector2(solx, 0.), -origin.y(), - Intersection2D::Status::reachable), + IntersectionStatus::reachable), Intersection2D::invalid()}; } return {Intersection2D::invalid(), Intersection2D::invalid()}; } else if (std::abs(dir.y()) < s_epsilon) { - ActsScalar soly = origin.y(); - ActsScalar D = 1. - soly * soly / (Ry * Ry); + double soly = origin.y(); + double D = 1. - soly * soly / (Ry * Ry); if (D > 0.) { - ActsScalar sqrtD = std::sqrt(D); + double sqrtD = std::sqrt(D); Vector2 sol(Rx * sqrtD, soly); Vector2 alt(-Rx * sqrtD, soly); return createSolution(sol, alt); } else if (std::abs(D) < s_epsilon) { return {Intersection2D(Vector2(0., soly), -origin.x(), - Intersection2D::Status::reachable), + IntersectionStatus::reachable), Intersection2D::invalid()}; } return {Intersection2D::invalid(), Intersection2D::invalid()}; } // General solution - ActsScalar k = dir.y() / dir.x(); - ActsScalar d = origin.y() - k * origin.x(); - ActsScalar Ry2 = Ry * Ry; - ActsScalar alpha = 1. / (Rx * Rx) + k * k / Ry2; - ActsScalar beta = 2. * k * d / Ry2; - ActsScalar gamma = d * d / Ry2 - 1; + double k = dir.y() / dir.x(); + double d = origin.y() - k * origin.x(); + double Ry2 = Ry * Ry; + double alpha = 1. / (Rx * Rx) + k * k / Ry2; + double beta = 2. * k * d / Ry2; + double gamma = d * d / Ry2 - 1; Acts::detail::RealQuadraticEquation solver(alpha, beta, gamma); if (solver.solutions == 1) { - ActsScalar x = solver.first; + double x = solver.first; Vector2 sol(x, k * x + d); Vector2 toSolD(sol - origin); - ActsScalar solD = std::copysign(toSolD.norm(), toSolD.dot(dir)); - return {Intersection2D(sol, solD, Intersection2D::Status::reachable), + double solD = std::copysign(toSolD.norm(), toSolD.dot(dir)); + return {Intersection2D(sol, solD, IntersectionStatus::reachable), Intersection2D::invalid()}; } else if (solver.solutions > 1) { - ActsScalar x0 = solver.first; - ActsScalar x1 = solver.second; + double x0 = solver.first; + double x1 = solver.second; Vector2 sol(x0, k * x0 + d); Vector2 alt(x1, k * x1 + d); return createSolution(sol, alt); @@ -118,12 +117,12 @@ Acts::detail::IntersectionHelper2D::intersectEllipse(ActsScalar Rx, } Acts::Intersection2D Acts::detail::IntersectionHelper2D::intersectCircleSegment( - ActsScalar R, ActsScalar phiMin, ActsScalar phiMax, const Vector2& origin, + double R, double phiMin, double phiMax, const Vector2& origin, const Vector2& dir) { auto intersections = intersectCircle(R, origin, dir); for (const auto& candidate : intersections) { if (candidate.pathLength() > 0.) { - ActsScalar phi = Acts::VectorHelpers::phi(candidate.position()); + double phi = Acts::VectorHelpers::phi(candidate.position()); if (phi > phiMin && phi < phiMax) { return candidate; } diff --git a/Core/src/Surfaces/LineSurface.cpp b/Core/src/Surfaces/LineSurface.cpp index f67fe038aa9..166a36bf630 100644 --- a/Core/src/Surfaces/LineSurface.cpp +++ b/Core/src/Surfaces/LineSurface.cpp @@ -149,7 +149,7 @@ const Acts::SurfaceBounds& Acts::LineSurface::bounds() const { Acts::SurfaceMultiIntersection Acts::LineSurface::intersect( const GeometryContext& gctx, const Vector3& position, const Vector3& direction, const BoundaryTolerance& boundaryTolerance, - ActsScalar tolerance) const { + double tolerance) const { // The nomenclature is following the header file and doxygen documentation const Vector3& ma = position; @@ -174,9 +174,9 @@ Acts::SurfaceMultiIntersection Acts::LineSurface::intersect( double u = (mab.dot(ea) - mab.dot(eb) * eaTeb) / denom; // Check if we are on the surface already - Intersection3D::Status status = std::abs(u) > std::abs(tolerance) - ? Intersection3D::Status::reachable - : Intersection3D::Status::onSurface; + IntersectionStatus status = std::abs(u) > std::abs(tolerance) + ? IntersectionStatus::reachable + : IntersectionStatus::onSurface; Vector3 result = ma + u * ea; // Evaluate the boundary check if requested // m_bounds == nullptr prevents unnecessary calculations for PerigeeSurface @@ -185,7 +185,7 @@ Acts::SurfaceMultiIntersection Acts::LineSurface::intersect( double cZ = vecLocal.dot(eb); double cR = (vecLocal - cZ * eb).norm(); if (!m_bounds->inside({cR, cZ}, boundaryTolerance)) { - status = Intersection3D::Status::missed; + status = IntersectionStatus::unreachable; } } diff --git a/Core/src/Surfaces/PlaneSurface.cpp b/Core/src/Surfaces/PlaneSurface.cpp index 658920e6686..b4ebb77956c 100644 --- a/Core/src/Surfaces/PlaneSurface.cpp +++ b/Core/src/Surfaces/PlaneSurface.cpp @@ -160,7 +160,7 @@ double Acts::PlaneSurface::pathCorrection(const GeometryContext& gctx, Acts::SurfaceMultiIntersection Acts::PlaneSurface::intersect( const GeometryContext& gctx, const Vector3& position, const Vector3& direction, const BoundaryTolerance& boundaryTolerance, - ActsScalar tolerance) const { + double tolerance) const { // Get the contextual transform const auto& gctxTransform = transform(gctx); // Use the intersection helper for planar surfaces @@ -168,14 +168,14 @@ Acts::SurfaceMultiIntersection Acts::PlaneSurface::intersect( PlanarHelper::intersect(gctxTransform, position, direction, tolerance); auto status = intersection.status(); // Evaluate boundary check if requested (and reachable) - if (intersection.status() != Intersection3D::Status::unreachable) { + if (intersection.status() != IntersectionStatus::unreachable) { // Built-in local to global for speed reasons const auto& tMatrix = gctxTransform.matrix(); // Create the reference vector in local const Vector3 vecLocal(intersection.position() - tMatrix.block<3, 1>(0, 3)); if (!insideBounds(tMatrix.block<3, 2>(0, 0).transpose() * vecLocal, boundaryTolerance)) { - status = Intersection3D::Status::missed; + status = IntersectionStatus::unreachable; } } return {{Intersection3D(intersection.position(), intersection.pathLength(), diff --git a/Core/src/Surfaces/Surface.cpp b/Core/src/Surfaces/Surface.cpp index cadef176cda..0fbfe6bc982 100644 --- a/Core/src/Surfaces/Surface.cpp +++ b/Core/src/Surfaces/Surface.cpp @@ -314,7 +314,7 @@ Acts::FreeToPathMatrix Acts::Surface::freeToPathDerivative( // The measurement frame z axis const Vector3 refZAxis = rframe.col(2); // Cosine of angle between momentum direction and measurement frame z axis - const ActsScalar dz = refZAxis.dot(direction); + const double dz = refZAxis.dot(direction); // Initialize the derivative FreeToPathMatrix freeToPath = FreeToPathMatrix::Zero(); freeToPath.segment<3>(eFreePos0) = -1.0 * refZAxis.transpose() / dz; diff --git a/Core/src/Surfaces/detail/AnnulusBoundsHelper.cpp b/Core/src/Surfaces/detail/AnnulusBoundsHelper.cpp index 47cb4e2e9a6..b46bfaf5b8a 100644 --- a/Core/src/Surfaces/detail/AnnulusBoundsHelper.cpp +++ b/Core/src/Surfaces/detail/AnnulusBoundsHelper.cpp @@ -16,7 +16,7 @@ std::tuple, Acts::Transform3> Acts::detail::AnnulusBoundsHelper::create(const Transform3& transform, - ActsScalar rMin, ActsScalar rMax, + double rMin, double rMax, std::vector vertices) { using Line2D = Eigen::Hyperplane; diff --git a/Core/src/Surfaces/detail/MergeHelper.cpp b/Core/src/Surfaces/detail/MergeHelper.cpp index 414e5761686..ca394efd4e8 100644 --- a/Core/src/Surfaces/detail/MergeHelper.cpp +++ b/Core/src/Surfaces/detail/MergeHelper.cpp @@ -12,9 +12,10 @@ namespace Acts::detail { -std::tuple mergedPhiSector( - ActsScalar hlPhi1, ActsScalar avgPhi1, ActsScalar hlPhi2, - ActsScalar avgPhi2, const Logger& logger, ActsScalar tolerance) { +std::tuple mergedPhiSector(double hlPhi1, double avgPhi1, + double hlPhi2, double avgPhi2, + const Logger& logger, + double tolerance) { using namespace Acts::UnitLiterals; if (std::abs(hlPhi1 - std::numbers::pi / 2.) < tolerance && @@ -33,8 +34,8 @@ std::tuple mergedPhiSector( "Phi sectors cover half a circle but are not opposite"); } - ActsScalar newAvgPhi = detail::radian_sym(avgPhi1 + std::numbers::pi / 2.); - ActsScalar newHlPhi = std::numbers::pi; + double newAvgPhi = detail::radian_sym(avgPhi1 + std::numbers::pi / 2.); + double newHlPhi = std::numbers::pi; ACTS_VERBOSE("merged: [" << detail::radian_sym(newAvgPhi - newHlPhi) / 1_degree << ", " << detail::radian_sym(newAvgPhi + newHlPhi) / 1_degree @@ -43,27 +44,27 @@ std::tuple mergedPhiSector( return {newHlPhi, newAvgPhi, false}; } - ActsScalar minPhi1 = detail::radian_sym(-hlPhi1 + avgPhi1); - ActsScalar maxPhi1 = detail::radian_sym(hlPhi1 + avgPhi1); + double minPhi1 = detail::radian_sym(-hlPhi1 + avgPhi1); + double maxPhi1 = detail::radian_sym(hlPhi1 + avgPhi1); ACTS_VERBOSE("one: [" << minPhi1 / 1_degree << ", " << maxPhi1 / 1_degree << "] ~> " << avgPhi1 / 1_degree << " +- " << hlPhi1 / 1_degree); - ActsScalar maxPhi2 = detail::radian_sym(hlPhi2 + avgPhi2); - ActsScalar minPhi2 = detail::radian_sym(-hlPhi2 + avgPhi2); + double maxPhi2 = detail::radian_sym(hlPhi2 + avgPhi2); + double minPhi2 = detail::radian_sym(-hlPhi2 + avgPhi2); ACTS_VERBOSE("two: [" << minPhi2 / 1_degree << ", " << maxPhi2 / 1_degree << "] ~> " << avgPhi2 / 1_degree << " +- " << hlPhi2 / 1_degree); ACTS_VERBOSE("Checking for CCW or CW ordering"); - auto same = [tolerance](ActsScalar a, ActsScalar b) { + auto same = [tolerance](double a, double b) { return std::abs(a - b) < tolerance; }; - ActsScalar newMaxPhi{}, newMinPhi{}; - ActsScalar newHlPhi = hlPhi1 + hlPhi2; + double newMaxPhi{}, newMinPhi{}; + double newHlPhi = hlPhi1 + hlPhi2; bool reversed = false; if (same(minPhi1, maxPhi2)) { @@ -81,7 +82,7 @@ std::tuple mergedPhiSector( throw std::invalid_argument("Phi ranges are incompatible"); } - ActsScalar newAvgPhi = detail::radian_sym(newMinPhi + newHlPhi); + double newAvgPhi = detail::radian_sym(newMinPhi + newHlPhi); ACTS_VERBOSE("merged: [" << newMinPhi / 1_degree << ", " << newMaxPhi / 1_degree << "] ~> " diff --git a/Core/src/Surfaces/detail/VerticesHelper.cpp b/Core/src/Surfaces/detail/VerticesHelper.cpp index e97d75d45bf..98a00deb142 100644 --- a/Core/src/Surfaces/detail/VerticesHelper.cpp +++ b/Core/src/Surfaces/detail/VerticesHelper.cpp @@ -13,9 +13,9 @@ #include #include -std::vector Acts::detail::VerticesHelper::phiSegments( - ActsScalar phiMin, ActsScalar phiMax, - const std::vector& phiRefs, unsigned int quarterSegments) { +std::vector Acts::detail::VerticesHelper::phiSegments( + double phiMin, double phiMax, const std::vector& phiRefs, + unsigned int quarterSegments) { // Check that the phi range is valid if (phiMin > phiMax) { throw std::invalid_argument( @@ -24,7 +24,7 @@ std::vector Acts::detail::VerticesHelper::phiSegments( } // First check that no reference phi is outside the range - for (ActsScalar phiRef : phiRefs) { + for (double phiRef : phiRefs) { if (phiRef < phiMin || phiRef > phiMax) { throw std::invalid_argument( "VerticesHelper::phiSegments ... Reference phi is outside the range " @@ -36,16 +36,16 @@ std::vector Acts::detail::VerticesHelper::phiSegments( "VerticesHelper::phiSegments ... Number of segments must be larger " "than 0."); } - std::vector phiSegments = {phiMin, phiMax}; + std::vector phiSegments = {phiMin, phiMax}; // Minimum approximation for a circle need // - if the circle is closed the last point is given twice for (unsigned int i = 0; i < 4 * quarterSegments + 1; ++i) { - ActsScalar phiExt = + double phiExt = -std::numbers::pi + i * 2 * std::numbers::pi / (4 * quarterSegments); if (phiExt > phiMin && phiExt < phiMax && - std::ranges::none_of(phiSegments, [&phiExt](ActsScalar phi) { + std::ranges::none_of(phiSegments, [&phiExt](double phi) { return std::abs(phi - phiExt) < - std::numeric_limits::epsilon(); + std::numeric_limits::epsilon(); })) { phiSegments.push_back(phiExt); } @@ -53,9 +53,9 @@ std::vector Acts::detail::VerticesHelper::phiSegments( // Add the reference phis for (const auto& phiRef : phiRefs) { if (phiRef > phiMin && phiRef < phiMax) { - if (std::ranges::none_of(phiSegments, [&phiRef](ActsScalar phi) { + if (std::ranges::none_of(phiSegments, [&phiRef](double phi) { return std::abs(phi - phiRef) < - std::numeric_limits::epsilon(); + std::numeric_limits::epsilon(); })) { phiSegments.push_back(phiRef); } @@ -68,9 +68,8 @@ std::vector Acts::detail::VerticesHelper::phiSegments( } std::vector Acts::detail::VerticesHelper::ellipsoidVertices( - ActsScalar innerRx, ActsScalar innerRy, ActsScalar outerRx, - ActsScalar outerRy, ActsScalar avgPhi, ActsScalar halfPhi, - unsigned int quarterSegments) { + double innerRx, double innerRy, double outerRx, double outerRy, + double avgPhi, double halfPhi, unsigned int quarterSegments) { // List of vertices counter-clockwise starting at smallest phi w.r.t center, // for both inner/outer ring/segment std::vector rvertices; // return vertices @@ -80,7 +79,7 @@ std::vector Acts::detail::VerticesHelper::ellipsoidVertices( bool innerExists = (innerRx > 0. && innerRy > 0.); bool closed = std::abs(halfPhi - std::numbers::pi) < s_onSurfaceTolerance; - std::vector refPhi = {}; + std::vector refPhi = {}; if (avgPhi != 0.) { refPhi.push_back(avgPhi); } @@ -113,20 +112,20 @@ std::vector Acts::detail::VerticesHelper::ellipsoidVertices( } std::vector Acts::detail::VerticesHelper::circularVertices( - ActsScalar innerR, ActsScalar outerR, ActsScalar avgPhi, ActsScalar halfPhi, + double innerR, double outerR, double avgPhi, double halfPhi, unsigned int quarterSegments) { return ellipsoidVertices(innerR, innerR, outerR, outerR, avgPhi, halfPhi, quarterSegments); } bool Acts::detail::VerticesHelper::onHyperPlane( - const std::vector& vertices, ActsScalar tolerance) { + const std::vector& vertices, double tolerance) { // Obvious always on one surface if (vertices.size() < 4) { return true; } // Create the hyperplane - auto hyperPlane = Eigen::Hyperplane::Through( + auto hyperPlane = Eigen::Hyperplane::Through( vertices[0], vertices[1], vertices[2]); for (std::size_t ip = 3; ip < vertices.size(); ++ip) { if (hyperPlane.absDistance(vertices[ip]) > tolerance) { diff --git a/Core/src/TrackFinding/GbtsConnector.cpp b/Core/src/TrackFinding/GbtsConnector.cpp index d947894871c..69e0f7919e5 100644 --- a/Core/src/TrackFinding/GbtsConnector.cpp +++ b/Core/src/TrackFinding/GbtsConnector.cpp @@ -9,7 +9,6 @@ // TODO: update to C++17 style #include "Acts/TrackFinding/GbtsConnector.hpp" -#include #include #include #include @@ -34,7 +33,7 @@ GbtsConnector::GbtsConnector(std::ifstream &inFile) { inFile >> lIdx >> stage >> src >> dst >> height >> width >> nEntries; - GbtsConnection *pC = new GbtsConnection(src, dst); + auto pC = std::make_unique(src, dst); int dummy{}; @@ -47,19 +46,17 @@ GbtsConnector::GbtsConnector(std::ifstream &inFile) { int vol_id = src / 1000; if (vol_id == 13 || vol_id == 12 || vol_id == 14) { - delete pC; continue; } vol_id = dst / 1000; if (vol_id == 13 || vol_id == 12 || vol_id == 14) { - delete pC; continue; } auto &connections = m_connMap[stage]; - connections.push_back(pC); + connections.push_back(std::move(pC)); } // re-arrange the connection stages @@ -69,7 +66,9 @@ GbtsConnector::GbtsConnector(std::ifstream &inFile) { std::map> newConnMap; for (const auto &[_, value] : m_connMap) { - std::ranges::copy(value, std::back_inserter(lConns)); + for (const auto &conn : value) { + lConns.push_back(conn.get()); + } } int stageCounter = 0; @@ -172,12 +171,4 @@ GbtsConnector::GbtsConnector(std::ifstream &inFile) { newConnMap.clear(); } -GbtsConnector::~GbtsConnector() { - m_layerGroups.clear(); - for (const auto &[_, connections] : m_connMap) { - for (auto *conn : connections) { - delete conn; - } - } -} } // namespace Acts diff --git a/Core/src/TrackFinding/MeasurementSelector.cpp b/Core/src/TrackFinding/MeasurementSelector.cpp index 2a3c0e2d390..676cf8074ff 100644 --- a/Core/src/TrackFinding/MeasurementSelector.cpp +++ b/Core/src/TrackFinding/MeasurementSelector.cpp @@ -9,7 +9,6 @@ #include "Acts/TrackFinding/MeasurementSelector.hpp" #include "Acts/Definitions/Algebra.hpp" -#include "Acts/Definitions/TrackParametrization.hpp" #include "Acts/EventData/MeasurementHelpers.hpp" #include "Acts/EventData/SubspaceHelpers.hpp" #include "Acts/EventData/Types.hpp" @@ -19,6 +18,8 @@ #include #include #include +#include +#include namespace Acts { @@ -99,7 +100,7 @@ double MeasurementSelector::calculateChi2( using ParametersVector = ActsVector; - std::span validSubspaceIndices( + std::span validSubspaceIndices( projector.begin(), projector.begin() + kMeasurementSize); FixedBoundSubspaceHelper subspaceHelper( validSubspaceIndices); diff --git a/Core/src/TrackFitting/GsfUtils.cpp b/Core/src/TrackFitting/GsfUtils.cpp index ae5b47ca700..8ff52f2c1b6 100644 --- a/Core/src/TrackFitting/GsfUtils.cpp +++ b/Core/src/TrackFitting/GsfUtils.cpp @@ -9,27 +9,34 @@ #include "Acts/TrackFitting/detail/GsfUtils.hpp" #include "Acts/EventData/MeasurementHelpers.hpp" +#include "Acts/EventData/SubspaceHelpers.hpp" +#include "Acts/EventData/Types.hpp" #include +#include +#include namespace Acts::detail { using TrackStateTraits = TrackStateTraits; -ActsScalar calculateDeterminant( - const double* fullCalibratedCovariance, - TrackStateTraits::Covariance predictedCovariance, - TrackStateTraits::Projector projector, unsigned int calibratedSize) { +double calculateDeterminant(const double* fullCalibratedCovariance, + TrackStateTraits::Covariance predictedCovariance, + BoundSubspaceIndices projector, + unsigned int calibratedSize) { return visit_measurement(calibratedSize, [&](auto N) { constexpr std::size_t kMeasurementSize = decltype(N)::value; + std::span validSubspaceIndices( + projector.begin(), projector.begin() + kMeasurementSize); + FixedBoundSubspaceHelper subspaceHelper( + validSubspaceIndices); typename Acts::TrackStateTraits< kMeasurementSize, true>::CalibratedCovariance calibratedCovariance{ fullCalibratedCovariance}; - const auto H = - projector.template topLeftCorner().eval(); + const auto H = subspaceHelper.projector(); return (H * predictedCovariance * H.transpose() + calibratedCovariance) .determinant(); diff --git a/Core/src/TrackFitting/MbfSmoother.cpp b/Core/src/TrackFitting/MbfSmoother.cpp index 2614834aadb..9b300989e90 100644 --- a/Core/src/TrackFitting/MbfSmoother.cpp +++ b/Core/src/TrackFitting/MbfSmoother.cpp @@ -10,6 +10,8 @@ #include "Acts/EventData/TrackParameterHelpers.hpp" +#include + namespace Acts { void MbfSmoother::calculateSmoothed(InternalTrackState& ts, @@ -42,23 +44,25 @@ void MbfSmoother::visitMeasurement(const InternalTrackState& ts, visit_measurement(measurement.calibratedSize, [&](auto N) -> void { constexpr std::size_t kMeasurementSize = decltype(N)::value; + std::span validSubspaceIndices( + measurement.projector.begin(), + measurement.projector.begin() + kMeasurementSize); + FixedBoundSubspaceHelper subspaceHelper( + validSubspaceIndices); - using MeasurementMatrix = - Eigen::Matrix; + using ProjectorMatrix = Eigen::Matrix; using CovarianceMatrix = - Eigen::Matrix; + Eigen::Matrix; using KalmanGainMatrix = - Eigen::Matrix; + Eigen::Matrix; typename TrackStateTraits::Calibrated calibrated{ measurement.calibrated}; typename TrackStateTraits::CalibratedCovariance calibratedCovariance{measurement.calibratedCovariance}; - // Measurement matrix - const MeasurementMatrix H = - measurement.projector - .template topLeftCorner(); + // Projector matrix + const ProjectorMatrix H = subspaceHelper.projector(); // Residual covariance const CovarianceMatrix S = @@ -71,12 +75,12 @@ void MbfSmoother::visitMeasurement(const InternalTrackState& ts, const KalmanGainMatrix K = (ts.predictedCovariance * H.transpose() * SInv); const Acts::BoundMatrix CHat = (Acts::BoundMatrix::Identity() - K * H); - const Eigen::Matrix y = + const Eigen::Matrix y = (calibrated - H * ts.predicted); const Acts::BoundMatrix bigLambdaTilde = (H.transpose() * SInv * H + CHat.transpose() * bigLambdaHat * CHat); - const Eigen::Matrix smallLambdaTilde = + const Eigen::Matrix smallLambdaTilde = (-H.transpose() * SInv * y + CHat.transpose() * smallLambdaHat); bigLambdaHat = F.transpose() * bigLambdaTilde * F; diff --git a/Core/src/Utilities/Intersection.cpp b/Core/src/Utilities/Intersection.cpp index 23378f0b381..8a99870b282 100644 --- a/Core/src/Utilities/Intersection.cpp +++ b/Core/src/Utilities/Intersection.cpp @@ -8,6 +8,8 @@ #include "Acts/Utilities/Intersection.hpp" +#include "Acts/Definitions/Tolerance.hpp" + namespace Acts { bool detail::checkPathLength(double pathLength, double nearLimit, diff --git a/Core/src/Utilities/SpacePointUtility.cpp b/Core/src/Utilities/SpacePointUtility.cpp index 7018db37830..32470e1ebb9 100644 --- a/Core/src/Utilities/SpacePointUtility.cpp +++ b/Core/src/Utilities/SpacePointUtility.cpp @@ -51,8 +51,7 @@ Result SpacePointUtility::differenceOfMeasurementsChecked( return Result::success(diffTheta2 + diffPhi2); } -std::tuple, Vector2, - std::optional> +std::tuple, Vector2, std::optional> SpacePointUtility::globalCoords( const GeometryContext& gctx, const SourceLink& slink, const SourceLinkSurfaceAccessor& surfaceAccessor, const BoundVector& par, @@ -93,8 +92,8 @@ SpacePointUtility::globalCoords( // optionally set time // TODO the current condition of checking the covariance is not optional but // should do for now - std::optional globalTime = par[eBoundTime]; - std::optional tcov = cov(eBoundTime, eBoundTime); + std::optional globalTime = par[eBoundTime]; + std::optional tcov = cov(eBoundTime, eBoundTime); if (tcov.value() <= 0) { globalTime = std::nullopt; tcov = std::nullopt; diff --git a/Core/src/Vertexing/HelicalTrackLinearizer.cpp b/Core/src/Vertexing/HelicalTrackLinearizer.cpp index 9d529745559..e42bc9d0aad 100644 --- a/Core/src/Vertexing/HelicalTrackLinearizer.cpp +++ b/Core/src/Vertexing/HelicalTrackLinearizer.cpp @@ -68,40 +68,40 @@ Acts::HelicalTrackLinearizer::linearizeTrack( // Extracting Perigee parameters and compute functions of them for later // usage - ActsScalar d0 = paramsAtPCA(BoundIndices::eBoundLoc0); + double d0 = paramsAtPCA(BoundIndices::eBoundLoc0); - ActsScalar phi = paramsAtPCA(BoundIndices::eBoundPhi); - ActsScalar sinPhi = std::sin(phi); - ActsScalar cosPhi = std::cos(phi); + double phi = paramsAtPCA(BoundIndices::eBoundPhi); + double sinPhi = std::sin(phi); + double cosPhi = std::cos(phi); - ActsScalar theta = paramsAtPCA(BoundIndices::eBoundTheta); - ActsScalar sinTheta = std::sin(theta); - ActsScalar tanTheta = std::tan(theta); + double theta = paramsAtPCA(BoundIndices::eBoundTheta); + double sinTheta = std::sin(theta); + double tanTheta = std::tan(theta); // q over p - ActsScalar qOvP = paramsAtPCA(BoundIndices::eBoundQOverP); + double qOvP = paramsAtPCA(BoundIndices::eBoundQOverP); // Rest mass - ActsScalar m0 = params.particleHypothesis().mass(); + double m0 = params.particleHypothesis().mass(); // Momentum - ActsScalar p = params.particleHypothesis().extractMomentum(qOvP); + double p = params.particleHypothesis().extractMomentum(qOvP); // Speed in units of c - ActsScalar beta = p / fastHypot(p, m0); + double beta = p / fastHypot(p, m0); // Transverse speed (i.e., speed in the x-y plane) - ActsScalar betaT = beta * sinTheta; + double betaT = beta * sinTheta; // Momentum direction at the PCA Vector3 momentumAtPCA(phi, theta, qOvP); // Particle charge - ActsScalar absoluteCharge = params.particleHypothesis().absoluteCharge(); + double absoluteCharge = params.particleHypothesis().absoluteCharge(); // get the z-component of the B-field at the PCA auto field = m_cfg.bField->getField(VectorHelpers::position(pca), fieldCache); if (!field.ok()) { return field.error(); } - ActsScalar Bz = (*field)[eZ]; + double Bz = (*field)[eZ]; // Complete Jacobian (consists of positionJacobian and momentumJacobian) ActsMatrix completeJacobian = @@ -142,24 +142,24 @@ Acts::HelicalTrackLinearizer::linearizeTrack( completeJacobian(eBoundTime, eLinPhi) = -d0 / betaT; } else { // Helix radius - ActsScalar rho = sinTheta * (1. / qOvP) / Bz; + double rho = sinTheta * (1. / qOvP) / Bz; // Sign of helix radius - ActsScalar h = (rho < 0.) ? -1 : 1; + double h = (rho < 0.) ? -1 : 1; // Quantities from Eq. 5.34 in Ref. (1) (see .hpp) - ActsScalar X = pca(0) - perigeeSurface.center(gctx).x() + rho * sinPhi; - ActsScalar Y = pca(1) - perigeeSurface.center(gctx).y() - rho * cosPhi; - ActsScalar S2 = (X * X + Y * Y); + double X = pca(0) - perigeeSurface.center(gctx).x() + rho * sinPhi; + double Y = pca(1) - perigeeSurface.center(gctx).y() - rho * cosPhi; + double S2 = (X * X + Y * Y); // S is the 2D distance from the helix center to the reference point // in the x-y plane - ActsScalar S = std::sqrt(S2); + double S = std::sqrt(S2); - ActsScalar XoverS2 = X / S2; - ActsScalar YoverS2 = Y / S2; - ActsScalar rhoCotTheta = rho / tanTheta; - ActsScalar rhoOverBetaT = rho / betaT; + double XoverS2 = X / S2; + double YoverS2 = Y / S2; + double rhoCotTheta = rho / tanTheta; + double rhoOverBetaT = rho / betaT; // Absolute value of rho over S - ActsScalar absRhoOverS = h * rho / S; + double absRhoOverS = h * rho / S; // Derivatives can be found in Eq. 5.36 in Ref. (1) // Since we propagated to the PCA (point P in Ref. (1)), the points diff --git a/Core/src/Vertexing/ImpactPointEstimator.cpp b/Core/src/Vertexing/ImpactPointEstimator.cpp index 3caac09b57b..df9f75fd9fa 100644 --- a/Core/src/Vertexing/ImpactPointEstimator.cpp +++ b/Core/src/Vertexing/ImpactPointEstimator.cpp @@ -193,7 +193,7 @@ Result> getDistanceAndMomentumImpl( Vector3 positionOnTrack = trkParams.position(gctx); // Distance between positionOnTrack and the 3D PCA - ActsScalar distanceToPca = + double distanceToPca = (vtxPos.template head<3>() - positionOnTrack).dot(momDirStraightTrack); // 3D PCA @@ -204,11 +204,11 @@ Result> getDistanceAndMomentumImpl( // Track time at positionOnTrack double timeOnTrack = trkParams.parameters()[BoundIndices::eBoundTime]; - ActsScalar m0 = trkParams.particleHypothesis().mass(); - ActsScalar p = trkParams.particleHypothesis().extractMomentum(qOvP); + double m0 = trkParams.particleHypothesis().mass(); + double p = trkParams.particleHypothesis().extractMomentum(qOvP); // Speed in units of c - ActsScalar beta = p / fastHypot(p, m0); + double beta = p / fastHypot(p, m0); pcaStraightTrack[3] = timeOnTrack + distanceToPca / beta; } @@ -279,11 +279,11 @@ Result> getDistanceAndMomentumImpl( // Time at the 2D PCA P double tP = trkParams.parameters()[BoundIndices::eBoundTime]; - ActsScalar m0 = trkParams.particleHypothesis().mass(); - ActsScalar p = trkParams.particleHypothesis().extractMomentum(qOvP); + double m0 = trkParams.particleHypothesis().mass(); + double p = trkParams.particleHypothesis().extractMomentum(qOvP); // Speed in units of c - ActsScalar beta = p / fastHypot(p, m0); + double beta = p / fastHypot(p, m0); pca[3] = tP - rho / (beta * sinTheta) * (phi - phiP); } diff --git a/Core/src/Vertexing/NumericalTrackLinearizer.cpp b/Core/src/Vertexing/NumericalTrackLinearizer.cpp index ca9af5825e4..c7928a23258 100644 --- a/Core/src/Vertexing/NumericalTrackLinearizer.cpp +++ b/Core/src/Vertexing/NumericalTrackLinearizer.cpp @@ -78,10 +78,10 @@ Acts::NumericalTrackLinearizer::linearizeTrack( // Fill "paramVec", "pca", and "momentumAtPCA" { Vector3 globalCoords = endParams.position(gctx); - ActsScalar globalTime = endParams.time(); - ActsScalar phi = perigeeParams(BoundIndices::eBoundPhi); - ActsScalar theta = perigeeParams(BoundIndices::eBoundTheta); - ActsScalar qOvP = perigeeParams(BoundIndices::eBoundQOverP); + double globalTime = endParams.time(); + double phi = perigeeParams(BoundIndices::eBoundPhi); + double theta = perigeeParams(BoundIndices::eBoundTheta); + double qOvP = perigeeParams(BoundIndices::eBoundQOverP); paramVec << globalCoords, globalTime, phi, theta, qOvP; pca << globalCoords, globalTime; diff --git a/Core/src/Vertexing/Vertex.cpp b/Core/src/Vertexing/Vertex.cpp index 0a8eda8c279..7c2c54cc7ac 100644 --- a/Core/src/Vertexing/Vertex.cpp +++ b/Core/src/Vertexing/Vertex.cpp @@ -37,7 +37,7 @@ Vector3 Vertex::position() const { return VectorHelpers::position(m_position); } -ActsScalar Vertex::time() const { +double Vertex::time() const { return m_position[eTime]; } @@ -85,7 +85,7 @@ void Vertex::setFullPosition(const Vector4& fullPosition) { m_position = fullPosition; } -void Vertex::setTime(ActsScalar time) { +void Vertex::setTime(double time) { m_position[eTime] = time; } diff --git a/Examples/Algorithms/Digitization/include/ActsExamples/Digitization/GeometricConfig.hpp b/Examples/Algorithms/Digitization/include/ActsExamples/Digitization/GeometricConfig.hpp index 6b4348e20f6..5df64bc4326 100644 --- a/Examples/Algorithms/Digitization/include/ActsExamples/Digitization/GeometricConfig.hpp +++ b/Examples/Algorithms/Digitization/include/ActsExamples/Digitization/GeometricConfig.hpp @@ -58,10 +58,10 @@ struct GeometricConfig { bool strip = false; /// The variances for this digitization - std::map> varianceMap = {}; + std::map> varianceMap = {}; /// Charge generation (configurable via the chargeSmearer) - Acts::ActsScalar charge(Acts::ActsScalar path, RandomEngine &rng) const { + double charge(double path, RandomEngine &rng) const { if (!chargeSmearer) { return path; } @@ -82,9 +82,8 @@ struct GeometricConfig { /// @param cmins is the cluster minimum in the different dimensions /// /// @return a vector of variances for the cluster - std::vector variances( - const std::array &csizes, - const std::array &cmins) const; + std::vector variances(const std::array &csizes, + const std::array &cmins) const; /// Drift generation (currently not implemented) /// Takes as an argument the position, and a random engine diff --git a/Examples/Algorithms/Digitization/include/ActsExamples/Digitization/MeasurementCreation.hpp b/Examples/Algorithms/Digitization/include/ActsExamples/Digitization/MeasurementCreation.hpp index 667e0c9f4c3..ce139065e20 100644 --- a/Examples/Algorithms/Digitization/include/ActsExamples/Digitization/MeasurementCreation.hpp +++ b/Examples/Algorithms/Digitization/include/ActsExamples/Digitization/MeasurementCreation.hpp @@ -26,8 +26,8 @@ namespace ActsExamples { /// Is public as it is also used by the I/O system struct DigitizedParameters { std::vector indices = {}; - std::vector values = {}; - std::vector variances = {}; + std::vector values = {}; + std::vector variances = {}; Cluster cluster; }; diff --git a/Examples/Algorithms/Digitization/include/ActsExamples/Digitization/ModuleClusters.hpp b/Examples/Algorithms/Digitization/include/ActsExamples/Digitization/ModuleClusters.hpp index 452111db2eb..b93d6980ced 100644 --- a/Examples/Algorithms/Digitization/include/ActsExamples/Digitization/ModuleClusters.hpp +++ b/Examples/Algorithms/Digitization/include/ActsExamples/Digitization/ModuleClusters.hpp @@ -27,8 +27,8 @@ struct DigitizedParameters; struct ModuleValue { std::vector paramIndices = {}; - std::vector paramValues = {}; - std::vector paramVariances = {}; + std::vector paramValues = {}; + std::vector paramVariances = {}; std::variant value; std::set sources = {}; Acts::Ccl::Label label = {Acts::Ccl::NO_LABEL}; diff --git a/Examples/Algorithms/Digitization/src/DigitizationAlgorithm.cpp b/Examples/Algorithms/Digitization/src/DigitizationAlgorithm.cpp index 07019be74ca..08b19b34ba1 100644 --- a/Examples/Algorithms/Digitization/src/DigitizationAlgorithm.cpp +++ b/Examples/Algorithms/Digitization/src/DigitizationAlgorithm.cpp @@ -317,7 +317,7 @@ DigitizedParameters DigitizationAlgorithm::localParameters( const auto& binningData = geoCfg.segmentation.binningData(); - Acts::ActsScalar totalWeight = 0.; + double totalWeight = 0.; Acts::Vector2 m(0., 0.); std::size_t b0min = std::numeric_limits::max(); std::size_t b0max = 0; @@ -326,8 +326,7 @@ DigitizedParameters DigitizationAlgorithm::localParameters( // Combine the channels for (const auto& ch : channels) { auto bin = ch.bin; - Acts::ActsScalar charge = - geoCfg.digital ? 1. : geoCfg.charge(ch.activation, rng); + double charge = geoCfg.digital ? 1. : geoCfg.charge(ch.activation, rng); if (geoCfg.digital || charge > geoCfg.threshold) { totalWeight += charge; std::size_t b0 = bin[0]; diff --git a/Examples/Algorithms/Digitization/src/DigitizationConfig.cpp b/Examples/Algorithms/Digitization/src/DigitizationConfig.cpp index 8c23ba729d1..232ae598cc7 100644 --- a/Examples/Algorithms/Digitization/src/DigitizationConfig.cpp +++ b/Examples/Algorithms/Digitization/src/DigitizationConfig.cpp @@ -10,12 +10,12 @@ namespace ActsExamples { -std::vector GeometricConfig::variances( +std::vector GeometricConfig::variances( const std::array& csizes, const std::array& cmins) const { - std::vector rVariances; + std::vector rVariances; for (const auto& bIndex : indices) { - Acts::ActsScalar var = 0.; + double var = 0.; if (varianceMap.contains(bIndex)) { // Try to find the variance for this cluster size std::size_t lsize = diff --git a/Examples/Algorithms/Digitization/src/DigitizationConfigurator.cpp b/Examples/Algorithms/Digitization/src/DigitizationConfigurator.cpp index bbf6ec7583b..8542b2fdd5b 100644 --- a/Examples/Algorithms/Digitization/src/DigitizationConfigurator.cpp +++ b/Examples/Algorithms/Digitization/src/DigitizationConfigurator.cpp @@ -82,8 +82,8 @@ void ActsExamples::DigitizationConfigurator::operator()( case Acts::SurfaceBounds::eRectangle: { if (inputSegmentation.binningData()[0].binvalue == Acts::BinningValue::binX) { - Acts::ActsScalar minX = boundValues[Acts::RectangleBounds::eMinX]; - Acts::ActsScalar maxX = boundValues[Acts::RectangleBounds::eMaxX]; + double minX = boundValues[Acts::RectangleBounds::eMinX]; + double maxX = boundValues[Acts::RectangleBounds::eMaxX]; unsigned int nBins = static_cast(std::round( (maxX - minX) / inputSegmentation.binningData()[0].step)); outputSegmentation += Acts::BinUtility( @@ -95,8 +95,8 @@ void ActsExamples::DigitizationConfigurator::operator()( inputSegmentation.dimensions() == 2) { unsigned int accessBin = inputSegmentation.dimensions() == 2 ? 1 : 0; - Acts::ActsScalar minY = boundValues[Acts::RectangleBounds::eMinY]; - Acts::ActsScalar maxY = boundValues[Acts::RectangleBounds::eMaxY]; + double minY = boundValues[Acts::RectangleBounds::eMinY]; + double maxY = boundValues[Acts::RectangleBounds::eMaxY]; unsigned int nBins = static_cast( std::round((maxY - minY) / inputSegmentation.binningData()[accessBin].step)); @@ -110,7 +110,7 @@ void ActsExamples::DigitizationConfigurator::operator()( case Acts::SurfaceBounds::eTrapezoid: { if (inputSegmentation.binningData()[0].binvalue == Acts::BinningValue::binX) { - Acts::ActsScalar maxX = std::max( + double maxX = std::max( boundValues[Acts::TrapezoidBounds::eHalfLengthXnegY], boundValues[Acts::TrapezoidBounds::eHalfLengthXposY]); unsigned int nBins = static_cast(std::round( @@ -124,8 +124,7 @@ void ActsExamples::DigitizationConfigurator::operator()( inputSegmentation.dimensions() == 2) { unsigned int accessBin = inputSegmentation.dimensions() == 2 ? 1 : 0; - Acts::ActsScalar maxY = - boundValues[Acts::TrapezoidBounds::eHalfLengthY]; + double maxY = boundValues[Acts::TrapezoidBounds::eHalfLengthY]; unsigned int nBins = static_cast( std::round((2 * maxY) / inputSegmentation.binningData()[accessBin].step)); @@ -139,8 +138,8 @@ void ActsExamples::DigitizationConfigurator::operator()( case Acts::SurfaceBounds::eAnnulus: { if (inputSegmentation.binningData()[0].binvalue == Acts::BinningValue::binR) { - Acts::ActsScalar minR = boundValues[Acts::AnnulusBounds::eMinR]; - Acts::ActsScalar maxR = boundValues[Acts::AnnulusBounds::eMaxR]; + double minR = boundValues[Acts::AnnulusBounds::eMinR]; + double maxR = boundValues[Acts::AnnulusBounds::eMaxR]; unsigned int nBins = static_cast(std::round( (maxR - minR) / inputSegmentation.binningData()[0].step)); outputSegmentation += Acts::BinUtility( @@ -152,11 +151,10 @@ void ActsExamples::DigitizationConfigurator::operator()( inputSegmentation.dimensions() == 2) { unsigned int accessBin = inputSegmentation.dimensions() == 2 ? 1 : 0; - Acts::ActsScalar averagePhi = - boundValues[Acts::AnnulusBounds::eAveragePhi]; - Acts::ActsScalar minPhi = + double averagePhi = boundValues[Acts::AnnulusBounds::eAveragePhi]; + double minPhi = averagePhi - boundValues[Acts::AnnulusBounds::eMinPhiRel]; - Acts::ActsScalar maxPhi = + double maxPhi = averagePhi + boundValues[Acts::AnnulusBounds::eMaxPhiRel]; unsigned int nBins = static_cast( std::round((maxPhi - minPhi) / @@ -170,10 +168,8 @@ void ActsExamples::DigitizationConfigurator::operator()( // The module is a Disc Trapezoid case Acts::SurfaceBounds::eDiscTrapezoid: { - Acts::ActsScalar minR = - boundValues[Acts::DiscTrapezoidBounds::eMinR]; - Acts::ActsScalar maxR = - boundValues[Acts::DiscTrapezoidBounds::eMaxR]; + double minR = boundValues[Acts::DiscTrapezoidBounds::eMinR]; + double maxR = boundValues[Acts::DiscTrapezoidBounds::eMaxR]; if (inputSegmentation.binningData()[0].binvalue == Acts::BinningValue::binR) { @@ -188,16 +184,16 @@ void ActsExamples::DigitizationConfigurator::operator()( inputSegmentation.dimensions() == 2) { unsigned int accessBin = inputSegmentation.dimensions() == 2 ? 1 : 0; - Acts::ActsScalar hxMinR = + double hxMinR = boundValues[Acts::DiscTrapezoidBounds::eHalfLengthXminR]; - Acts::ActsScalar hxMaxR = + double hxMaxR = boundValues[Acts::DiscTrapezoidBounds::eHalfLengthXmaxR]; - Acts::ActsScalar averagePhi = + double averagePhi = boundValues[Acts::DiscTrapezoidBounds::eAveragePhi]; - Acts::ActsScalar alphaMinR = std::atan2(minR, hxMinR); - Acts::ActsScalar alphaMaxR = std::atan2(maxR, hxMaxR); - Acts::ActsScalar alpha = std::max(alphaMinR, alphaMaxR); + double alphaMinR = std::atan2(minR, hxMinR); + double alphaMaxR = std::atan2(maxR, hxMaxR); + double alpha = std::max(alphaMinR, alphaMaxR); unsigned int nBins = static_cast(std::round( 2 * alpha / inputSegmentation.binningData()[accessBin].step)); outputSegmentation += Acts::BinUtility( @@ -211,8 +207,8 @@ void ActsExamples::DigitizationConfigurator::operator()( case Acts::SurfaceBounds::eDisc: { if (inputSegmentation.binningData()[0].binvalue == Acts::BinningValue::binR) { - Acts::ActsScalar minR = boundValues[Acts::RadialBounds::eMinR]; - Acts::ActsScalar maxR = boundValues[Acts::RadialBounds::eMaxR]; + double minR = boundValues[Acts::RadialBounds::eMinR]; + double maxR = boundValues[Acts::RadialBounds::eMaxR]; unsigned int nBins = static_cast(std::round( (maxR - minR) / inputSegmentation.binningData()[0].step)); outputSegmentation += Acts::BinUtility( @@ -225,12 +221,11 @@ void ActsExamples::DigitizationConfigurator::operator()( unsigned int accessBin = inputSegmentation.dimensions() == 2 ? 1 : 0; - Acts::ActsScalar averagePhi = - boundValues[Acts::RadialBounds::eAveragePhi]; - Acts::ActsScalar halfPhiSector = + double averagePhi = boundValues[Acts::RadialBounds::eAveragePhi]; + double halfPhiSector = boundValues[Acts::RadialBounds::eHalfPhiSector]; - Acts::ActsScalar minPhi = averagePhi - halfPhiSector; - Acts::ActsScalar maxPhi = averagePhi + halfPhiSector; + double minPhi = averagePhi - halfPhiSector; + double maxPhi = averagePhi + halfPhiSector; unsigned int nBins = static_cast( std::round((maxPhi - minPhi) / diff --git a/Examples/Algorithms/Digitization/src/ModuleClusters.cpp b/Examples/Algorithms/Digitization/src/ModuleClusters.cpp index fbe7bb2a901..d8c456c427c 100644 --- a/Examples/Algorithms/Digitization/src/ModuleClusters.cpp +++ b/Examples/Algorithms/Digitization/src/ModuleClusters.cpp @@ -186,12 +186,12 @@ std::vector> ModuleClusters::mergeParameters( for (ModuleValue& thisval : thisvec) { // Loop over non-geometric dimensions for (auto k : nonGeoEntries(thisval.paramIndices)) { - Acts::ActsScalar p_i = thisval.paramValues.at(k); - Acts::ActsScalar p_j = values.at(j).paramValues.at(k); - Acts::ActsScalar v_i = thisval.paramVariances.at(k); - Acts::ActsScalar v_j = values.at(j).paramVariances.at(k); + double p_i = thisval.paramValues.at(k); + double p_j = values.at(j).paramValues.at(k); + double v_i = thisval.paramVariances.at(k); + double v_j = values.at(j).paramVariances.at(k); - Acts::ActsScalar left = 0, right = 0; + double left = 0, right = 0; if (p_i < p_j) { left = p_i + m_nsigma * std::sqrt(v_i); right = p_j - m_nsigma * std::sqrt(v_j); @@ -225,9 +225,9 @@ std::vector> ModuleClusters::mergeParameters( ModuleValue ModuleClusters::squash(std::vector& values) { ModuleValue mval; - Acts::ActsScalar tot = 0; - Acts::ActsScalar tot2 = 0; - std::vector weights; + double tot = 0; + double tot2 = 0; + std::vector weights; // First, start by computing cell weights for (ModuleValue& other : values) { @@ -253,9 +253,8 @@ ModuleValue ModuleClusters::squash(std::vector& values) { mval.paramValues.push_back(0); mval.paramVariances.push_back(0); } - Acts::ActsScalar f = weights.at(i) / (tot > 0 ? tot : 1); - Acts::ActsScalar f2 = - weights.at(i) * weights.at(i) / (tot2 > 0 ? tot2 : 1); + double f = weights.at(i) / (tot > 0 ? tot : 1); + double f2 = weights.at(i) * weights.at(i) / (tot2 > 0 ? tot2 : 1); mval.paramValues.at(j) += f * other.paramValues.at(j); mval.paramVariances.at(j) += f2 * other.paramVariances.at(j); } diff --git a/Examples/Algorithms/Geant4/include/ActsExamples/DDG4/DDG4DetectorConstruction.hpp b/Examples/Algorithms/Geant4/include/ActsExamples/DDG4/DDG4DetectorConstruction.hpp index 529a3725980..6706b5c20e4 100644 --- a/Examples/Algorithms/Geant4/include/ActsExamples/DDG4/DDG4DetectorConstruction.hpp +++ b/Examples/Algorithms/Geant4/include/ActsExamples/DDG4/DDG4DetectorConstruction.hpp @@ -20,18 +20,17 @@ class G4VPhysicalVolume; namespace dd4hep { class Detector; } + namespace ActsExamples { -namespace DD4hep { struct DD4hepDetector; -} /// Construct the Geant4 detector from a DD4hep description. class DDG4DetectorConstruction final : public G4VUserDetectorConstruction { public: DDG4DetectorConstruction( - std::shared_ptr detector, - std::vector> regionCreators = {}); + std::shared_ptr detector, + std::vector> regionCreators = {}); ~DDG4DetectorConstruction() final; /// Convert the stored DD4hep detector to a Geant4 description. @@ -45,9 +44,9 @@ class DDG4DetectorConstruction final : public G4VUserDetectorConstruction { private: /// The Acts DD4hep detector instance - std::shared_ptr m_detector; + std::shared_ptr m_detector; /// Region creators - std::vector> m_regionCreators; + std::vector> m_regionCreators; /// The world volume G4VPhysicalVolume* m_world = nullptr; @@ -56,20 +55,20 @@ class DDG4DetectorConstruction final : public G4VUserDetectorConstruction { }; class DDG4DetectorConstructionFactory final - : public DetectorConstructionFactory { + : public Geant4::DetectorConstructionFactory { public: DDG4DetectorConstructionFactory( - std::shared_ptr detector, - std::vector> regionCreators = {}); + std::shared_ptr detector, + std::vector> regionCreators = {}); ~DDG4DetectorConstructionFactory() final; std::unique_ptr factorize() const override; private: /// The Acts DD4hep detector instance - std::shared_ptr m_detector; + std::shared_ptr m_detector; /// Region creators - std::vector> m_regionCreators; + std::vector> m_regionCreators; }; } // namespace ActsExamples diff --git a/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/DetectorConstructionFactory.hpp b/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/DetectorConstructionFactory.hpp index a0f5b3e41cd..16cb2c3eae6 100644 --- a/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/DetectorConstructionFactory.hpp +++ b/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/DetectorConstructionFactory.hpp @@ -12,7 +12,7 @@ #include -namespace ActsExamples { +namespace ActsExamples::Geant4 { /// Silly Geant4 will destroy the detector construction after the run manager is /// destructed. This class works around it by factorizing a factory. @@ -23,4 +23,4 @@ class DetectorConstructionFactory { virtual std::unique_ptr factorize() const = 0; }; -} // namespace ActsExamples +} // namespace ActsExamples::Geant4 diff --git a/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/EventStore.hpp b/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/EventStore.hpp index a46512ce299..7ca1775b81a 100644 --- a/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/EventStore.hpp +++ b/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/EventStore.hpp @@ -21,8 +21,10 @@ #include "G4Types.hh" namespace ActsExamples { - class WhiteBoard; +} + +namespace ActsExamples::Geant4 { /// Common event store for all Geant4 related sub algorithms struct EventStore { @@ -80,4 +82,4 @@ struct EventStore { std::unordered_map subparticleMap; }; -} // namespace ActsExamples +} // namespace ActsExamples::Geant4 diff --git a/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/GdmlDetectorConstruction.hpp b/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/GdmlDetectorConstruction.hpp index 24924bd7867..69156e94e06 100644 --- a/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/GdmlDetectorConstruction.hpp +++ b/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/GdmlDetectorConstruction.hpp @@ -26,7 +26,7 @@ class GdmlDetectorConstruction final : public G4VUserDetectorConstruction { /// @param regionCreators are the region creators GdmlDetectorConstruction( std::string path, - std::vector> regionCreators = {}); + std::vector> regionCreators = {}); /// Read the file and parse it to construct the Geant4 description /// @@ -38,17 +38,17 @@ class GdmlDetectorConstruction final : public G4VUserDetectorConstruction { /// Path to the Gdml file std::string m_path; /// Region creators - std::vector> m_regionCreators; + std::vector> m_regionCreators; /// Cached world volume G4VPhysicalVolume* m_world = nullptr; }; class GdmlDetectorConstructionFactory final - : public DetectorConstructionFactory { + : public Geant4::DetectorConstructionFactory { public: GdmlDetectorConstructionFactory( std::string path, - std::vector> regionCreators = {}); + std::vector> regionCreators = {}); std::unique_ptr factorize() const override; @@ -56,7 +56,7 @@ class GdmlDetectorConstructionFactory final /// Path to the Gdml file std::string m_path; /// Region creators - std::vector> m_regionCreators; + std::vector> m_regionCreators; }; } // namespace ActsExamples diff --git a/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/Geant4Manager.hpp b/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/Geant4Manager.hpp index c3db1c3f2fe..bdf9ab7bb82 100644 --- a/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/Geant4Manager.hpp +++ b/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/Geant4Manager.hpp @@ -18,8 +18,10 @@ class G4VUserPhysicsList; namespace ActsExamples { -class PhysicsListFactory; class Geant4Manager; +namespace Geant4 { +class PhysicsListFactory; +} /// Manages the life time of G4RunManager and G4VUserPhysicsList. /// @@ -75,12 +77,14 @@ class Geant4Manager { /// Registers a named physics list factory to the manager for easy /// instantiation when needed. void registerPhysicsListFactory( - std::string name, std::shared_ptr physicsListFactory); + std::string name, + std::shared_ptr physicsListFactory); std::unique_ptr createPhysicsList( const std::string &name) const; /// Get the current list of physics list factories. - const std::unordered_map> & + const std::unordered_map> & getPhysicsListFactories() const; private: @@ -89,7 +93,7 @@ class Geant4Manager { bool m_created = false; std::weak_ptr m_handle; - std::unordered_map> + std::unordered_map> m_physicsListFactories; }; diff --git a/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/Geant4Simulation.hpp b/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/Geant4Simulation.hpp index f735dcd3859..88f526fff4f 100644 --- a/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/Geant4Simulation.hpp +++ b/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/Geant4Simulation.hpp @@ -39,14 +39,15 @@ class MagneticFieldProvider; class Volume; } // namespace Acts -class G4VUserDetectorConstruction; - namespace ActsExamples { +struct Geant4Handle; +namespace Geant4 { class DetectorConstructionFactory; class SensitiveSurfaceMapper; struct EventStore; -struct Geant4Handle; +class RegionCreator; +} // namespace Geant4 /// Abstracts common Geant4 Acts algorithm behaviour. class Geant4SimulationBase : public IAlgorithm { @@ -61,7 +62,8 @@ class Geant4SimulationBase : public IAlgorithm { /// Detector construction object. /// G4RunManager will take care of deletion - std::shared_ptr detectorConstructionFactory; + std::shared_ptr + detectorConstructionFactory; /// Optional Geant4 instance overwrite. std::shared_ptr geant4Handle; @@ -91,11 +93,11 @@ class Geant4SimulationBase : public IAlgorithm { G4RunManager& runManager() const; - EventStore& eventStore() const; + Geant4::EventStore& eventStore() const; std::unique_ptr m_logger; - std::shared_ptr m_eventStore; + std::shared_ptr m_eventStore; int m_geant4Level{}; @@ -122,8 +124,8 @@ class Geant4Simulation final : public Geant4SimulationBase { std::string outputParticles = "particles_simulated"; /// The ACTS sensitive surfaces in a mapper, used for hit creation - std::shared_ptr sensitiveSurfaceMapper = - nullptr; + std::shared_ptr + sensitiveSurfaceMapper = nullptr; /// The ACTS Magnetic field provider std::shared_ptr magneticField = nullptr; diff --git a/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/MagneticFieldWrapper.hpp b/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/MagneticFieldWrapper.hpp index a73663fb503..7581d5b6cf5 100644 --- a/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/MagneticFieldWrapper.hpp +++ b/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/MagneticFieldWrapper.hpp @@ -18,7 +18,7 @@ namespace Acts { class MagneticFieldProvider; } -namespace ActsExamples { +namespace ActsExamples::Geant4 { /// A magnetic field wrapper for the Acts magnetic field /// to be used with Geant4. @@ -58,4 +58,4 @@ class MagneticFieldWrapper : public G4MagneticField { std::unique_ptr m_logger; }; -} // namespace ActsExamples +} // namespace ActsExamples::Geant4 diff --git a/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/MaterialPhysicsList.hpp b/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/MaterialPhysicsList.hpp index 9cfb45d0453..924c1b54e59 100644 --- a/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/MaterialPhysicsList.hpp +++ b/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/MaterialPhysicsList.hpp @@ -12,11 +12,10 @@ #include #include -#include #include -namespace ActsExamples { +namespace ActsExamples::Geant4 { /// @class MaterialPhysicsList /// @@ -57,4 +56,4 @@ class MaterialPhysicsList final : public G4VUserPhysicsList { std::unique_ptr m_logger; }; -} // namespace ActsExamples +} // namespace ActsExamples::Geant4 diff --git a/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/MaterialSteppingAction.hpp b/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/MaterialSteppingAction.hpp index 8b21c41a7ce..23ccb88764e 100644 --- a/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/MaterialSteppingAction.hpp +++ b/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/MaterialSteppingAction.hpp @@ -19,7 +19,7 @@ class G4Step; -namespace ActsExamples { +namespace ActsExamples::Geant4 { /// @class MaterialSteppingAction /// @@ -66,4 +66,4 @@ class MaterialSteppingAction final : public G4UserSteppingAction { std::unique_ptr m_logger; }; -} // namespace ActsExamples +} // namespace ActsExamples::Geant4 diff --git a/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/ParticleKillAction.hpp b/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/ParticleKillAction.hpp index 4eb45d4f6ec..fe15a2d185c 100644 --- a/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/ParticleKillAction.hpp +++ b/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/ParticleKillAction.hpp @@ -22,7 +22,7 @@ namespace Acts { class Volume; } // namespace Acts -namespace ActsExamples { +namespace ActsExamples::Geant4 { /// A G4SteppingAction that is called for every step in the simulation process. /// @@ -67,4 +67,4 @@ class ParticleKillAction : public G4UserSteppingAction { std::unique_ptr m_logger; }; -} // namespace ActsExamples +} // namespace ActsExamples::Geant4 diff --git a/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/ParticleTrackingAction.hpp b/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/ParticleTrackingAction.hpp index acf07ec75dc..4ff1d413f34 100644 --- a/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/ParticleTrackingAction.hpp +++ b/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/ParticleTrackingAction.hpp @@ -9,7 +9,6 @@ #pragma once #include "Acts/Utilities/Logger.hpp" -#include "ActsExamples/EventData/SimHit.hpp" #include "ActsExamples/EventData/SimParticle.hpp" #include "ActsExamples/Geant4/EventStore.hpp" @@ -22,7 +21,7 @@ class G4Track; -namespace ActsExamples { +namespace ActsExamples::Geant4 { /// The G4UserTrackingAction that is called for every track in /// the simulation process. @@ -82,4 +81,4 @@ class ParticleTrackingAction : public G4UserTrackingAction { std::unique_ptr m_logger; }; -} // namespace ActsExamples +} // namespace ActsExamples::Geant4 diff --git a/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/PhysicsListFactory.hpp b/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/PhysicsListFactory.hpp index 6bbc39b4f04..e248beaffd4 100644 --- a/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/PhysicsListFactory.hpp +++ b/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/PhysicsListFactory.hpp @@ -13,7 +13,7 @@ class G4VUserPhysicsList; -namespace ActsExamples { +namespace ActsExamples::Geant4 { /// A factory around G4VUserPhysicsList which allows on demand instantiation. class PhysicsListFactory { @@ -36,4 +36,4 @@ class PhysicsListFactoryFunction final : public PhysicsListFactory { Function m_function; }; -} // namespace ActsExamples +} // namespace ActsExamples::Geant4 diff --git a/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/RegionCreator.hpp b/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/RegionCreator.hpp index b141948ec90..5327e4f37eb 100644 --- a/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/RegionCreator.hpp +++ b/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/RegionCreator.hpp @@ -13,7 +13,7 @@ #include #include -namespace ActsExamples { +namespace ActsExamples::Geant4 { /// Geant4 Region Creator /// @@ -49,7 +49,7 @@ class RegionCreator { Acts::Logging::Level level); /// Construct the region - void Construct(); + void construct(); /// Readonly access to the configuration const Config& config() const { return m_cfg; } @@ -68,4 +68,4 @@ class RegionCreator { std::unique_ptr m_logger; }; -} // namespace ActsExamples +} // namespace ActsExamples::Geant4 diff --git a/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/SensitiveSteppingAction.hpp b/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/SensitiveSteppingAction.hpp index 664522349df..d415e77e940 100644 --- a/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/SensitiveSteppingAction.hpp +++ b/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/SensitiveSteppingAction.hpp @@ -23,7 +23,7 @@ namespace Acts { class Surface; } -namespace ActsExamples { +namespace ActsExamples::Geant4 { /// The G4SteppingAction that is called for every step in /// the simulation process. @@ -83,4 +83,4 @@ class SensitiveSteppingAction : public G4UserSteppingAction { m_surfaceMapping; }; -} // namespace ActsExamples +} // namespace ActsExamples::Geant4 diff --git a/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/SensitiveSurfaceMapper.hpp b/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/SensitiveSurfaceMapper.hpp index 60f86d0d4e3..7614635ff93 100644 --- a/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/SensitiveSurfaceMapper.hpp +++ b/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/SensitiveSurfaceMapper.hpp @@ -12,7 +12,6 @@ #include "Acts/Geometry/GeometryContext.hpp" #include "Acts/Geometry/GeometryIdentifier.hpp" #include "Acts/Geometry/TrackingGeometry.hpp" -#include "Acts/Utilities/GridAccessHelpers.hpp" #include "Acts/Utilities/Logger.hpp" #include @@ -26,7 +25,7 @@ namespace Acts { class Surface; } -namespace ActsExamples { +namespace ActsExamples::Geant4 { struct SensitiveCandidatesBase { /// Get the sensitive surfaces for a given position @@ -148,4 +147,4 @@ class SensitiveSurfaceMapper { std::unique_ptr m_logger; }; -} // namespace ActsExamples +} // namespace ActsExamples::Geant4 diff --git a/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/SimParticleTranslation.hpp b/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/SimParticleTranslation.hpp index 8a20f91ae39..5b43102d812 100644 --- a/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/SimParticleTranslation.hpp +++ b/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/SimParticleTranslation.hpp @@ -20,7 +20,7 @@ class G4Event; -namespace ActsExamples { +namespace ActsExamples::Geant4 { /// @class SimParticleTranslation /// @@ -81,4 +81,4 @@ class SimParticleTranslation final : public G4VUserPrimaryGeneratorAction { std::unique_ptr m_logger; }; -} // namespace ActsExamples +} // namespace ActsExamples::Geant4 diff --git a/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/SteppingActionList.hpp b/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/SteppingActionList.hpp index b4a6d7e5d68..807417cf1f4 100644 --- a/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/SteppingActionList.hpp +++ b/Examples/Algorithms/Geant4/include/ActsExamples/Geant4/SteppingActionList.hpp @@ -8,17 +8,12 @@ #pragma once -#include "Acts/Utilities/Logger.hpp" -#include "ActsExamples/EventData/SimHit.hpp" -#include "ActsExamples/EventData/SimParticle.hpp" - #include -#include -#include +#include #include -namespace ActsExamples { +namespace ActsExamples::Geant4 { /// Geant4 only allows one user action of each type. This simple wrapper /// dispatches multiple actions to Geant4. @@ -42,4 +37,4 @@ class SteppingActionList : public G4UserSteppingAction { Config m_cfg; }; -} // namespace ActsExamples +} // namespace ActsExamples::Geant4 diff --git a/Examples/Algorithms/Geant4/include/ActsExamples/GeoModelG4/GeoModelDetectorConstruction.hpp b/Examples/Algorithms/Geant4/include/ActsExamples/GeoModelG4/GeoModelDetectorConstruction.hpp index a919d2866b0..d3070bbc590 100644 --- a/Examples/Algorithms/Geant4/include/ActsExamples/GeoModelG4/GeoModelDetectorConstruction.hpp +++ b/Examples/Algorithms/Geant4/include/ActsExamples/GeoModelG4/GeoModelDetectorConstruction.hpp @@ -12,8 +12,6 @@ #include "ActsExamples/Geant4/DetectorConstructionFactory.hpp" #include "ActsExamples/Geant4/RegionCreator.hpp" -#include - #include class G4VPhysicalVolume; @@ -27,7 +25,7 @@ class GeoModelDetectorConstruction final : public G4VUserDetectorConstruction { /// @param regionCreators are the region creators GeoModelDetectorConstruction( const Acts::GeoModelTree& geoModelTree, - std::vector> regionCreators = {}); + std::vector> regionCreators = {}); /// Read the file and parse it to construct the Geant4 description /// @@ -39,17 +37,17 @@ class GeoModelDetectorConstruction final : public G4VUserDetectorConstruction { /// The GeoModel tree Acts::GeoModelTree m_geoModelTree; /// Region creators - std::vector> m_regionCreators; + std::vector> m_regionCreators; /// The world volume G4VPhysicalVolume* m_g4World = nullptr; }; class GeoModelDetectorConstructionFactory final - : public DetectorConstructionFactory { + : public Geant4::DetectorConstructionFactory { public: GeoModelDetectorConstructionFactory( const Acts::GeoModelTree& geoModelTree, - std::vector> regionCreators = {}); + std::vector> regionCreators = {}); std::unique_ptr factorize() const override; @@ -57,7 +55,7 @@ class GeoModelDetectorConstructionFactory final /// The GeoModel tree Acts::GeoModelTree m_geoModelTree; /// Region creators - std::vector> m_regionCreators; + std::vector> m_regionCreators; }; } // namespace ActsExamples diff --git a/Examples/Algorithms/Geant4/include/ActsExamples/TelescopeDetector/TelescopeG4DetectorConstruction.hpp b/Examples/Algorithms/Geant4/include/ActsExamples/TelescopeDetector/TelescopeG4DetectorConstruction.hpp index 66fc363fe53..dba44638152 100644 --- a/Examples/Algorithms/Geant4/include/ActsExamples/TelescopeDetector/TelescopeG4DetectorConstruction.hpp +++ b/Examples/Algorithms/Geant4/include/ActsExamples/TelescopeDetector/TelescopeG4DetectorConstruction.hpp @@ -17,14 +17,14 @@ class G4VPhysicalVolume; class G4LogicalVolume; -namespace ActsExamples::Telescope { +namespace ActsExamples { class TelescopeG4DetectorConstruction final : public G4VUserDetectorConstruction { public: TelescopeG4DetectorConstruction( const TelescopeDetector::Config& cfg, - std::vector> regionCreators = {}); + std::vector> regionCreators = {}); G4VPhysicalVolume* Construct() final; @@ -32,17 +32,17 @@ class TelescopeG4DetectorConstruction final /// The configuration of the telescope detector TelescopeDetector::Config m_cfg; /// Region creators - std::vector> m_regionCreators; + std::vector> m_regionCreators; /// The world volume G4VPhysicalVolume* m_world{}; }; class TelescopeG4DetectorConstructionFactory final - : public DetectorConstructionFactory { + : public Geant4::DetectorConstructionFactory { public: TelescopeG4DetectorConstructionFactory( const TelescopeDetector::Config& cfg, - std::vector> regionCreators = {}); + std::vector> regionCreators = {}); std::unique_ptr factorize() const override; @@ -50,7 +50,7 @@ class TelescopeG4DetectorConstructionFactory final /// The configuration of the telescope detector TelescopeDetector::Config m_cfg; /// Region creators - std::vector> m_regionCreators; + std::vector> m_regionCreators; }; -} // namespace ActsExamples::Telescope +} // namespace ActsExamples diff --git a/Examples/Algorithms/Geant4/src/DDG4DetectorConstruction.cpp b/Examples/Algorithms/Geant4/src/DDG4DetectorConstruction.cpp index ae6a4609180..1b24da8f273 100644 --- a/Examples/Algorithms/Geant4/src/DDG4DetectorConstruction.cpp +++ b/Examples/Algorithms/Geant4/src/DDG4DetectorConstruction.cpp @@ -22,22 +22,23 @@ class G4VPhysicalVolume; -ActsExamples::DDG4DetectorConstruction::DDG4DetectorConstruction( - std::shared_ptr detector, - std::vector> regionCreators) +namespace ActsExamples { + +DDG4DetectorConstruction::DDG4DetectorConstruction( + std::shared_ptr detector, + std::vector> regionCreators) : G4VUserDetectorConstruction(), m_detector(std::move(detector)), m_regionCreators(std::move(regionCreators)) {} -ActsExamples::DDG4DetectorConstruction::~DDG4DetectorConstruction() = default; +DDG4DetectorConstruction::~DDG4DetectorConstruction() = default; -dd4hep::Detector& ActsExamples::DDG4DetectorConstruction::dd4hepDetector() - const { +dd4hep::Detector& DDG4DetectorConstruction::dd4hepDetector() const { return m_detector->geometryService->detector(); } // See DD4hep::Simulation::Geant4DetectorConstruction::Construct() -G4VPhysicalVolume* ActsExamples::DDG4DetectorConstruction::Construct() { +G4VPhysicalVolume* DDG4DetectorConstruction::Construct() { if (m_world == nullptr) { dd4hep::sim::Geant4Mapping& g4map = dd4hep::sim::Geant4Mapping::instance(); auto conv = dd4hep::sim::Geant4Converter(dd4hepDetector(), @@ -52,23 +53,24 @@ G4VPhysicalVolume* ActsExamples::DDG4DetectorConstruction::Construct() { // Create regions for (const auto& regionCreator : m_regionCreators) { - regionCreator->Construct(); + regionCreator->construct(); } } return m_world; } -ActsExamples::DDG4DetectorConstructionFactory::DDG4DetectorConstructionFactory( - std::shared_ptr detector, - std::vector> regionCreators) +DDG4DetectorConstructionFactory::DDG4DetectorConstructionFactory( + std::shared_ptr detector, + std::vector> regionCreators) : m_detector(std::move(detector)), m_regionCreators(std::move(regionCreators)) {} -ActsExamples::DDG4DetectorConstructionFactory:: - ~DDG4DetectorConstructionFactory() = default; +DDG4DetectorConstructionFactory::~DDG4DetectorConstructionFactory() = default; std::unique_ptr -ActsExamples::DDG4DetectorConstructionFactory::factorize() const { +DDG4DetectorConstructionFactory::factorize() const { return std::make_unique(m_detector, m_regionCreators); } + +} // namespace ActsExamples diff --git a/Examples/Algorithms/Geant4/src/GdmlDetectorConstruction.cpp b/Examples/Algorithms/Geant4/src/GdmlDetectorConstruction.cpp index 5a10933bb3f..242597ac175 100644 --- a/Examples/Algorithms/Geant4/src/GdmlDetectorConstruction.cpp +++ b/Examples/Algorithms/Geant4/src/GdmlDetectorConstruction.cpp @@ -18,7 +18,7 @@ using namespace ActsExamples; GdmlDetectorConstruction::GdmlDetectorConstruction( std::string path, - std::vector> regionCreators) + std::vector> regionCreators) : G4VUserDetectorConstruction(), m_path(std::move(path)), m_regionCreators(std::move(regionCreators)) {} @@ -32,7 +32,7 @@ G4VPhysicalVolume* GdmlDetectorConstruction::Construct() { // Create regions for (const auto& regionCreator : m_regionCreators) { - regionCreator->Construct(); + regionCreator->construct(); } } return m_world; @@ -40,7 +40,7 @@ G4VPhysicalVolume* GdmlDetectorConstruction::Construct() { GdmlDetectorConstructionFactory::GdmlDetectorConstructionFactory( std::string path, - std::vector> regionCreators) + std::vector> regionCreators) : m_path(std::move(path)), m_regionCreators(std::move(regionCreators)) {} std::unique_ptr diff --git a/Examples/Algorithms/Geant4/src/Geant4Manager.cpp b/Examples/Algorithms/Geant4/src/Geant4Manager.cpp index fb981704561..13e7428ac60 100644 --- a/Examples/Algorithms/Geant4/src/Geant4Manager.cpp +++ b/Examples/Algorithms/Geant4/src/Geant4Manager.cpp @@ -109,7 +109,8 @@ std::shared_ptr Geant4Manager::createHandle( } void Geant4Manager::registerPhysicsListFactory( - std::string name, std::shared_ptr physicsListFactory) { + std::string name, + std::shared_ptr physicsListFactory) { if (m_physicsListFactories.contains(name)) { throw std::invalid_argument("name already mapped"); } @@ -126,22 +127,23 @@ std::unique_ptr Geant4Manager::createPhysicsList( return it->second->factorize(); } -const std::unordered_map>& +const std::unordered_map>& Geant4Manager::getPhysicsListFactories() const { return m_physicsListFactories; } Geant4Manager::Geant4Manager() { registerPhysicsListFactory( - "FTFP_BERT", std::make_shared( + "FTFP_BERT", std::make_shared( []() { return std::make_unique(); })); registerPhysicsListFactory( - "FTFP_BERT_ATL", std::make_shared( + "FTFP_BERT_ATL", std::make_shared( []() { return std::make_unique(); })); - registerPhysicsListFactory("MaterialPhysicsList", - std::make_shared([]() { - return std::make_unique(); - })); + registerPhysicsListFactory( + "MaterialPhysicsList", + std::make_shared( + []() { return std::make_unique(); })); } Geant4Manager::~Geant4Manager() = default; diff --git a/Examples/Algorithms/Geant4/src/Geant4Simulation.cpp b/Examples/Algorithms/Geant4/src/Geant4Simulation.cpp index 795ddad78fa..bbc5c533e5c 100644 --- a/Examples/Algorithms/Geant4/src/Geant4Simulation.cpp +++ b/Examples/Algorithms/Geant4/src/Geant4Simulation.cpp @@ -28,7 +28,6 @@ #include "ActsExamples/Geant4/SimParticleTranslation.hpp" #include "ActsExamples/Geant4/SteppingActionList.hpp" -#include #include #include @@ -47,22 +46,24 @@ #include #include -ActsExamples::Geant4SimulationBase::Geant4SimulationBase( - const Config& cfg, std::string name, Acts::Logging::Level level) +namespace ActsExamples { + +Geant4SimulationBase::Geant4SimulationBase(const Config& cfg, std::string name, + Acts::Logging::Level level) : IAlgorithm(std::move(name), level) { if (cfg.inputParticles.empty()) { throw std::invalid_argument("Missing input particle collection"); } - if (!cfg.detectorConstructionFactory) { + if (cfg.detectorConstructionFactory == nullptr) { throw std::invalid_argument("Missing detector construction factory"); } - if (!cfg.randomNumbers) { + if (cfg.randomNumbers == nullptr) { throw std::invalid_argument("Missing random numbers"); } m_logger = Acts::getDefaultLogger("Geant4", level); - m_eventStore = std::make_shared(); + m_eventStore = std::make_shared(); // tweak logging // If we are in VERBOSE mode, set the verbose level in Geant4 to 2. @@ -70,9 +71,9 @@ ActsExamples::Geant4SimulationBase::Geant4SimulationBase( m_geant4Level = logger().level() == Acts::Logging::VERBOSE ? 2 : 0; } -ActsExamples::Geant4SimulationBase::~Geant4SimulationBase() = default; +Geant4SimulationBase::~Geant4SimulationBase() = default; -void ActsExamples::Geant4SimulationBase::commonInitialization() { +void Geant4SimulationBase::commonInitialization() { // Set the detector construction { // Clear detector construction if it exists @@ -89,24 +90,22 @@ void ActsExamples::Geant4SimulationBase::commonInitialization() { m_geant4Instance->tweakLogging(m_geant4Level); } -G4RunManager& ActsExamples::Geant4SimulationBase::runManager() const { +G4RunManager& Geant4SimulationBase::runManager() const { return *m_geant4Instance->runManager.get(); } -ActsExamples::EventStore& ActsExamples::Geant4SimulationBase::eventStore() - const { +Geant4::EventStore& Geant4SimulationBase::eventStore() const { return *m_eventStore; } -ActsExamples::ProcessCode ActsExamples::Geant4SimulationBase::initialize() { +ProcessCode Geant4SimulationBase::initialize() { // Initialize the Geant4 run manager runManager().Initialize(); - return ActsExamples::ProcessCode::SUCCESS; + return ProcessCode::SUCCESS; } -ActsExamples::ProcessCode ActsExamples::Geant4SimulationBase::execute( - const ActsExamples::AlgorithmContext& ctx) const { +ProcessCode Geant4SimulationBase::execute(const AlgorithmContext& ctx) const { // Ensure exclusive access to the Geant4 run manager std::lock_guard guard(m_geant4Instance->mutex); @@ -114,7 +113,7 @@ ActsExamples::ProcessCode ActsExamples::Geant4SimulationBase::execute( G4Random::setTheSeed(config().randomNumbers->generateSeed(ctx)); // Get and reset event registry state - eventStore() = EventStore{}; + eventStore() = Geant4::EventStore{}; // Register the current event store to the registry // this will allow access from the User*Actions @@ -153,16 +152,15 @@ ActsExamples::ProcessCode ActsExamples::Geant4SimulationBase::execute( "Step merging: max hits per hit: " << eventStore().maxStepsForHit); } - return ActsExamples::ProcessCode::SUCCESS; + return ProcessCode::SUCCESS; } -std::shared_ptr -ActsExamples::Geant4SimulationBase::geant4Handle() const { +std::shared_ptr Geant4SimulationBase::geant4Handle() const { return m_geant4Instance; } -ActsExamples::Geant4Simulation::Geant4Simulation(const Config& cfg, - Acts::Logging::Level level) +Geant4Simulation::Geant4Simulation(const Config& cfg, + Acts::Logging::Level level) : Geant4SimulationBase(cfg, "Geant4Simulation", level), m_cfg(cfg) { m_geant4Instance = m_cfg.geant4Handle @@ -180,10 +178,10 @@ ActsExamples::Geant4Simulation::Geant4Simulation(const Config& cfg, if (runManager().GetUserPrimaryGeneratorAction() != nullptr) { delete runManager().GetUserPrimaryGeneratorAction(); } - SimParticleTranslation::Config prCfg; + Geant4::SimParticleTranslation::Config prCfg; prCfg.eventStore = m_eventStore; // G4RunManager will take care of deletion - auto primaryGeneratorAction = new SimParticleTranslation( + auto primaryGeneratorAction = new Geant4::SimParticleTranslation( prCfg, m_logger->cloneWithSuffix("SimParticleTranslation")); // Set the primary generator action runManager().SetUserAction(primaryGeneratorAction); @@ -195,48 +193,49 @@ ActsExamples::Geant4Simulation::Geant4Simulation(const Config& cfg, if (runManager().GetUserTrackingAction() != nullptr) { delete runManager().GetUserTrackingAction(); } - ParticleTrackingAction::Config trackingCfg; + Geant4::ParticleTrackingAction::Config trackingCfg; trackingCfg.eventStore = m_eventStore; trackingCfg.keepParticlesWithoutHits = cfg.keepParticlesWithoutHits; // G4RunManager will take care of deletion - auto trackingAction = new ParticleTrackingAction( + auto trackingAction = new Geant4::ParticleTrackingAction( trackingCfg, m_logger->cloneWithSuffix("ParticleTracking")); runManager().SetUserAction(trackingAction); } // Stepping actions - SensitiveSteppingAction* sensitiveSteppingActionAccess = nullptr; + Geant4::SensitiveSteppingAction* sensitiveSteppingActionAccess = nullptr; { // Clear stepping action if it exists if (runManager().GetUserSteppingAction() != nullptr) { delete runManager().GetUserSteppingAction(); } - ParticleKillAction::Config particleKillCfg; + Geant4::ParticleKillAction::Config particleKillCfg; particleKillCfg.eventStore = m_eventStore; particleKillCfg.volume = cfg.killVolume; particleKillCfg.maxTime = cfg.killAfterTime; particleKillCfg.secondaries = cfg.killSecondaries; - SensitiveSteppingAction::Config stepCfg; + Geant4::SensitiveSteppingAction::Config stepCfg; stepCfg.eventStore = m_eventStore; stepCfg.charged = true; stepCfg.neutral = cfg.recordHitsOfNeutrals; stepCfg.primary = true; stepCfg.secondary = cfg.recordHitsOfSecondaries; - SteppingActionList::Config steppingCfg; - steppingCfg.actions.push_back(std::make_unique( + Geant4::SteppingActionList::Config steppingCfg; + steppingCfg.actions.push_back(std::make_unique( particleKillCfg, m_logger->cloneWithSuffix("Killer"))); - auto sensitiveSteppingAction = std::make_unique( - stepCfg, m_logger->cloneWithSuffix("SensitiveStepping")); + auto sensitiveSteppingAction = + std::make_unique( + stepCfg, m_logger->cloneWithSuffix("SensitiveStepping")); sensitiveSteppingActionAccess = sensitiveSteppingAction.get(); steppingCfg.actions.push_back(std::move(sensitiveSteppingAction)); // G4RunManager will take care of deletion - auto steppingAction = new SteppingActionList(steppingCfg); + auto steppingAction = new Geant4::SteppingActionList(steppingCfg); runManager().SetUserAction(steppingAction); } @@ -251,9 +250,10 @@ ActsExamples::Geant4Simulation::Geant4Simulation(const Config& cfg, if (cfg.magneticField) { ACTS_INFO("Setting ACTS configured field to Geant4."); - MagneticFieldWrapper::Config g4FieldCfg; + Geant4::MagneticFieldWrapper::Config g4FieldCfg; g4FieldCfg.magneticField = cfg.magneticField; - m_magneticField = std::make_unique(g4FieldCfg); + m_magneticField = + std::make_unique(g4FieldCfg); // Set the field or the G4Field manager m_fieldManager = std::make_unique(); @@ -266,7 +266,7 @@ ActsExamples::Geant4Simulation::Geant4Simulation(const Config& cfg, // ACTS sensitive surfaces are provided, so hit creation is turned on if (cfg.sensitiveSurfaceMapper != nullptr) { - SensitiveSurfaceMapper::State sState; + Geant4::SensitiveSurfaceMapper::State sState; ACTS_INFO( "Remapping selected volumes from Geant4 to Acts::Surface::GeometryID"); cfg.sensitiveSurfaceMapper->remapSensitiveNames( @@ -288,10 +288,9 @@ ActsExamples::Geant4Simulation::Geant4Simulation(const Config& cfg, m_outputParticles.initialize(cfg.outputParticles); } -ActsExamples::Geant4Simulation::~Geant4Simulation() = default; +Geant4Simulation::~Geant4Simulation() = default; -ActsExamples::ProcessCode ActsExamples::Geant4Simulation::execute( - const ActsExamples::AlgorithmContext& ctx) const { +ProcessCode Geant4Simulation::execute(const AlgorithmContext& ctx) const { auto ret = Geant4SimulationBase::execute(ctx); if (ret != ProcessCode::SUCCESS) { return ret; @@ -313,18 +312,18 @@ ActsExamples::ProcessCode ActsExamples::Geant4Simulation::execute( ctx, SimHitContainer(eventStore().hits.begin(), eventStore().hits.end())); #endif - return ActsExamples::ProcessCode::SUCCESS; + return ProcessCode::SUCCESS; } -ActsExamples::Geant4MaterialRecording::Geant4MaterialRecording( - const Config& cfg, Acts::Logging::Level level) +Geant4MaterialRecording::Geant4MaterialRecording(const Config& cfg, + Acts::Logging::Level level) : Geant4SimulationBase(cfg, "Geant4Simulation", level), m_cfg(cfg) { auto physicsListName = "MaterialPhysicsList"; m_geant4Instance = m_cfg.geant4Handle ? m_cfg.geant4Handle : Geant4Manager::instance().createHandle( - std::make_unique( + std::make_unique( m_logger->cloneWithSuffix("MaterialPhysicsList")), physicsListName); if (m_geant4Instance->physicsListName != physicsListName) { @@ -340,14 +339,14 @@ ActsExamples::Geant4MaterialRecording::Geant4MaterialRecording( delete runManager().GetUserPrimaryGeneratorAction(); } - SimParticleTranslation::Config prCfg; + Geant4::SimParticleTranslation::Config prCfg; prCfg.eventStore = m_eventStore; prCfg.forcedPdgCode = 0; prCfg.forcedCharge = 0.; prCfg.forcedMass = 0.; // G4RunManager will take care of deletion - auto primaryGeneratorAction = new SimParticleTranslation( + auto primaryGeneratorAction = new Geant4::SimParticleTranslation( prCfg, m_logger->cloneWithSuffix("SimParticleTranslation")); // Set the primary generator action runManager().SetUserAction(primaryGeneratorAction); @@ -359,11 +358,11 @@ ActsExamples::Geant4MaterialRecording::Geant4MaterialRecording( if (runManager().GetUserTrackingAction() != nullptr) { delete runManager().GetUserTrackingAction(); } - ParticleTrackingAction::Config trackingCfg; + Geant4::ParticleTrackingAction::Config trackingCfg; trackingCfg.eventStore = m_eventStore; trackingCfg.keepParticlesWithoutHits = true; // G4RunManager will take care of deletion - auto trackingAction = new ParticleTrackingAction( + auto trackingAction = new Geant4::ParticleTrackingAction( trackingCfg, m_logger->cloneWithSuffix("ParticleTracking")); runManager().SetUserAction(trackingAction); } @@ -374,11 +373,11 @@ ActsExamples::Geant4MaterialRecording::Geant4MaterialRecording( if (runManager().GetUserSteppingAction() != nullptr) { delete runManager().GetUserSteppingAction(); } - MaterialSteppingAction::Config steppingCfg; + Geant4::MaterialSteppingAction::Config steppingCfg; steppingCfg.eventStore = m_eventStore; steppingCfg.excludeMaterials = m_cfg.excludeMaterials; // G4RunManager will take care of deletion - auto steppingAction = new MaterialSteppingAction( + auto steppingAction = new Geant4::MaterialSteppingAction( steppingCfg, m_logger->cloneWithSuffix("MaterialSteppingAction")); runManager().SetUserAction(steppingAction); } @@ -389,10 +388,10 @@ ActsExamples::Geant4MaterialRecording::Geant4MaterialRecording( m_outputMaterialTracks.initialize(cfg.outputMaterialTracks); } -ActsExamples::Geant4MaterialRecording::~Geant4MaterialRecording() = default; +Geant4MaterialRecording::~Geant4MaterialRecording() = default; -ActsExamples::ProcessCode ActsExamples::Geant4MaterialRecording::execute( - const ActsExamples::AlgorithmContext& ctx) const { +ProcessCode Geant4MaterialRecording::execute( + const AlgorithmContext& ctx) const { const auto ret = Geant4SimulationBase::execute(ctx); if (ret != ProcessCode::SUCCESS) { return ret; @@ -402,5 +401,7 @@ ActsExamples::ProcessCode ActsExamples::Geant4MaterialRecording::execute( m_outputMaterialTracks( ctx, decltype(eventStore().materialTracks)(eventStore().materialTracks)); - return ActsExamples::ProcessCode::SUCCESS; + return ProcessCode::SUCCESS; } + +} // namespace ActsExamples diff --git a/Examples/Algorithms/Geant4/src/GeoModelDetectorConstruction.cpp b/Examples/Algorithms/Geant4/src/GeoModelDetectorConstruction.cpp index c3ad0eea6de..8d33622714b 100644 --- a/Examples/Algorithms/Geant4/src/GeoModelDetectorConstruction.cpp +++ b/Examples/Algorithms/Geant4/src/GeoModelDetectorConstruction.cpp @@ -21,7 +21,7 @@ using namespace ActsExamples; GeoModelDetectorConstruction::GeoModelDetectorConstruction( const Acts::GeoModelTree& geoModelTree, - std::vector> regionCreators) + std::vector> regionCreators) : G4VUserDetectorConstruction(), m_geoModelTree(geoModelTree), m_regionCreators(std::move(regionCreators)) { @@ -42,7 +42,7 @@ G4VPhysicalVolume* GeoModelDetectorConstruction::Construct() { // Create regions for (const auto& regionCreator : m_regionCreators) { - regionCreator->Construct(); + regionCreator->construct(); } } return m_g4World; @@ -50,7 +50,7 @@ G4VPhysicalVolume* GeoModelDetectorConstruction::Construct() { GeoModelDetectorConstructionFactory::GeoModelDetectorConstructionFactory( const Acts::GeoModelTree& geoModelTree, - std::vector> regionCreators) + std::vector> regionCreators) : m_geoModelTree(geoModelTree), m_regionCreators(std::move(regionCreators)) {} diff --git a/Examples/Algorithms/Geant4/src/MagneticFieldWrapper.cpp b/Examples/Algorithms/Geant4/src/MagneticFieldWrapper.cpp index 33f15fa6586..757cac35fea 100644 --- a/Examples/Algorithms/Geant4/src/MagneticFieldWrapper.cpp +++ b/Examples/Algorithms/Geant4/src/MagneticFieldWrapper.cpp @@ -12,21 +12,20 @@ #include "Acts/Definitions/Units.hpp" #include "Acts/MagneticField/MagneticFieldContext.hpp" #include "Acts/MagneticField/MagneticFieldProvider.hpp" -#include "Acts/Utilities/Result.hpp" -#include -#include #include #include #include -ActsExamples::MagneticFieldWrapper::MagneticFieldWrapper( +namespace ActsExamples::Geant4 { + +MagneticFieldWrapper::MagneticFieldWrapper( const Config& cfg, std::unique_ptr logger) : G4MagneticField(), m_cfg(cfg), m_logger(std::move(logger)) {} -void ActsExamples::MagneticFieldWrapper::GetFieldValue(const G4double Point[4], - G4double* Bfield) const { +void MagneticFieldWrapper::GetFieldValue(const G4double Point[4], + G4double* Bfield) const { constexpr double convertLength = CLHEP::mm / Acts::UnitConstants::mm; constexpr double convertField = CLHEP::tesla / Acts::UnitConstants::T; @@ -47,3 +46,5 @@ void ActsExamples::MagneticFieldWrapper::GetFieldValue(const G4double Point[4], Bfield[1] = convertField * field[1]; Bfield[2] = convertField * field[2]; } + +} // namespace ActsExamples::Geant4 diff --git a/Examples/Algorithms/Geant4/src/MaterialPhysicsList.cpp b/Examples/Algorithms/Geant4/src/MaterialPhysicsList.cpp index d115e9e1794..bc0d228e87d 100644 --- a/Examples/Algorithms/Geant4/src/MaterialPhysicsList.cpp +++ b/Examples/Algorithms/Geant4/src/MaterialPhysicsList.cpp @@ -15,27 +15,31 @@ #include #include -ActsExamples::MaterialPhysicsList::MaterialPhysicsList( +namespace ActsExamples::Geant4 { + +MaterialPhysicsList::MaterialPhysicsList( std::unique_ptr logger) : G4VUserPhysicsList(), m_logger(std::move(logger)) { defaultCutValue = 1.0 * CLHEP::cm; } -void ActsExamples::MaterialPhysicsList::ConstructParticle() { +void MaterialPhysicsList::ConstructParticle() { ACTS_DEBUG("Construct Geantinos and Charged Geantinos."); G4Geantino::GeantinoDefinition(); G4ChargedGeantino::ChargedGeantinoDefinition(); } -void ActsExamples::MaterialPhysicsList::ConstructProcess() { +void MaterialPhysicsList::ConstructProcess() { ACTS_DEBUG("Adding Transport as single supperted Process."); AddTransportation(); } -void ActsExamples::MaterialPhysicsList::SetCuts() { +void MaterialPhysicsList::SetCuts() { SetCutsWithDefault(); if (verboseLevel > 0) { DumpCutValuesTable(); } } + +} // namespace ActsExamples::Geant4 diff --git a/Examples/Algorithms/Geant4/src/MaterialSteppingAction.cpp b/Examples/Algorithms/Geant4/src/MaterialSteppingAction.cpp index c4f0e6528bd..6773079dcd7 100644 --- a/Examples/Algorithms/Geant4/src/MaterialSteppingAction.cpp +++ b/Examples/Algorithms/Geant4/src/MaterialSteppingAction.cpp @@ -24,14 +24,15 @@ #include #include -ActsExamples::MaterialSteppingAction::MaterialSteppingAction( +namespace ActsExamples::Geant4 { + +MaterialSteppingAction::MaterialSteppingAction( const Config& cfg, std::unique_ptr logger) : G4UserSteppingAction(), m_cfg(cfg), m_logger(std::move(logger)) {} -ActsExamples::MaterialSteppingAction::~MaterialSteppingAction() = default; +MaterialSteppingAction::~MaterialSteppingAction() = default; -void ActsExamples::MaterialSteppingAction::UserSteppingAction( - const G4Step* step) { +void MaterialSteppingAction::UserSteppingAction(const G4Step* step) { // Get the material & check if it is present G4Material* material = step->GetPreStepPoint()->GetMaterial(); if (material == nullptr) { @@ -111,3 +112,5 @@ void ActsExamples::MaterialSteppingAction::UserSteppingAction( mInteraction); } } + +} // namespace ActsExamples::Geant4 diff --git a/Examples/Algorithms/Geant4/src/ParticleKillAction.cpp b/Examples/Algorithms/Geant4/src/ParticleKillAction.cpp index 5090a74dafa..bbc55390c69 100644 --- a/Examples/Algorithms/Geant4/src/ParticleKillAction.cpp +++ b/Examples/Algorithms/Geant4/src/ParticleKillAction.cpp @@ -23,11 +23,13 @@ #include #include -ActsExamples::ParticleKillAction::ParticleKillAction( +namespace ActsExamples::Geant4 { + +ParticleKillAction::ParticleKillAction( const Config& cfg, std::unique_ptr logger) : G4UserSteppingAction(), m_cfg(cfg), m_logger(std::move(logger)) {} -void ActsExamples::ParticleKillAction::UserSteppingAction(const G4Step* step) { +void ParticleKillAction::UserSteppingAction(const G4Step* step) { constexpr double convertLength = Acts::UnitConstants::mm / CLHEP::mm; constexpr double convertTime = Acts::UnitConstants::ns / CLHEP::ns; @@ -72,3 +74,5 @@ void ActsExamples::ParticleKillAction::UserSteppingAction(const G4Step* step) { } } } + +} // namespace ActsExamples::Geant4 diff --git a/Examples/Algorithms/Geant4/src/ParticleTrackingAction.cpp b/Examples/Algorithms/Geant4/src/ParticleTrackingAction.cpp index ba59debc893..886646a3655 100644 --- a/Examples/Algorithms/Geant4/src/ParticleTrackingAction.cpp +++ b/Examples/Algorithms/Geant4/src/ParticleTrackingAction.cpp @@ -25,12 +25,13 @@ #include #include -ActsExamples::ParticleTrackingAction::ParticleTrackingAction( +namespace ActsExamples::Geant4 { + +ParticleTrackingAction::ParticleTrackingAction( const Config& cfg, std::unique_ptr logger) : G4UserTrackingAction(), m_cfg(cfg), m_logger(std::move(logger)) {} -void ActsExamples::ParticleTrackingAction::PreUserTrackingAction( - const G4Track* aTrack) { +void ParticleTrackingAction::PreUserTrackingAction(const G4Track* aTrack) { // If this is not the case, there are unhandled cases of particle stopping in // the SensitiveSteppingAction // TODO We could also merge the remaining hits to a hit here, but it would be @@ -66,8 +67,7 @@ void ActsExamples::ParticleTrackingAction::PreUserTrackingAction( } } -void ActsExamples::ParticleTrackingAction::PostUserTrackingAction( - const G4Track* aTrack) { +void ParticleTrackingAction::PostUserTrackingAction(const G4Track* aTrack) { // The initial particle maybe was not registered because of a particle ID // collision if (!eventStore().trackIdMapping.contains(aTrack->GetTrackID())) { @@ -83,7 +83,7 @@ void ActsExamples::ParticleTrackingAction::PostUserTrackingAction( if (!m_cfg.keepParticlesWithoutHits && !hasHits) { [[maybe_unused]] auto n = eventStore().particlesSimulated.erase( - ActsExamples::SimParticle(barcode, Acts::PdgParticle::eInvalid)); + SimParticle(barcode, Acts::PdgParticle::eInvalid)); assert(n == 1); return; } @@ -107,8 +107,8 @@ void ActsExamples::ParticleTrackingAction::PostUserTrackingAction( } } -ActsExamples::SimParticleState ActsExamples::ParticleTrackingAction::convert( - const G4Track& aTrack, SimBarcode particleId) const { +SimParticleState ParticleTrackingAction::convert(const G4Track& aTrack, + SimBarcode particleId) const { // Unit conversions G4->::ACTS constexpr double convertTime = Acts::UnitConstants::ns / CLHEP::ns; constexpr double convertLength = Acts::UnitConstants::mm / CLHEP::mm; @@ -147,9 +147,8 @@ ActsExamples::SimParticleState ActsExamples::ParticleTrackingAction::convert( return aParticle; } -std::optional -ActsExamples::ParticleTrackingAction::makeParticleId(G4int trackId, - G4int parentId) const { +std::optional ParticleTrackingAction::makeParticleId( + G4int trackId, G4int parentId) const { // We already have this particle registered (it is one of the input particles // or we are making a final particle state) if (eventStore().trackIdMapping.contains(trackId)) { @@ -174,3 +173,5 @@ ActsExamples::ParticleTrackingAction::makeParticleId(G4int trackId, return pid; } + +} // namespace ActsExamples::Geant4 diff --git a/Examples/Algorithms/Geant4/src/PhysicsListFactory.cpp b/Examples/Algorithms/Geant4/src/PhysicsListFactory.cpp index 95866efa188..e1b88971b5b 100644 --- a/Examples/Algorithms/Geant4/src/PhysicsListFactory.cpp +++ b/Examples/Algorithms/Geant4/src/PhysicsListFactory.cpp @@ -10,7 +10,7 @@ #include -namespace ActsExamples { +namespace ActsExamples::Geant4 { PhysicsListFactoryFunction::PhysicsListFactoryFunction(Function function) : m_function(std::move(function)) {} @@ -20,4 +20,4 @@ std::unique_ptr PhysicsListFactoryFunction::factorize() return m_function(); } -} // namespace ActsExamples +} // namespace ActsExamples::Geant4 diff --git a/Examples/Algorithms/Geant4/src/RegionCreator.cpp b/Examples/Algorithms/Geant4/src/RegionCreator.cpp index 4e3384a98b7..c38dcf83078 100644 --- a/Examples/Algorithms/Geant4/src/RegionCreator.cpp +++ b/Examples/Algorithms/Geant4/src/RegionCreator.cpp @@ -13,7 +13,7 @@ #include #include -namespace ActsExamples { +namespace ActsExamples::Geant4 { RegionCreator::RegionCreator(const Config& cfg, std::string name, Acts::Logging::Level level) @@ -21,7 +21,7 @@ RegionCreator::RegionCreator(const Config& cfg, std::string name, m_cfg(cfg), m_logger(Acts::getDefaultLogger(m_name, level)) {} -void RegionCreator::Construct() { +void RegionCreator::construct() { // create a new G4Region G4Region* region = new G4Region(m_name); @@ -68,4 +68,4 @@ void RegionCreator::Construct() { region->SetProductionCuts(cuts); } -} // namespace ActsExamples +} // namespace ActsExamples::Geant4 diff --git a/Examples/Algorithms/Geant4/src/SensitiveSteppingAction.cpp b/Examples/Algorithms/Geant4/src/SensitiveSteppingAction.cpp index 17df42bdb21..7050bef8f7f 100644 --- a/Examples/Algorithms/Geant4/src/SensitiveSteppingAction.cpp +++ b/Examples/Algorithms/Geant4/src/SensitiveSteppingAction.cpp @@ -13,7 +13,6 @@ #include "Acts/Geometry/GeometryIdentifier.hpp" #include "Acts/Surfaces/Surface.hpp" #include "Acts/Utilities/MultiIndex.hpp" -#include "ActsExamples/EventData/SimHit.hpp" #include "ActsExamples/Geant4/EventStore.hpp" #include "ActsExamples/Geant4/SensitiveSurfaceMapper.hpp" #include "ActsFatras/EventData/Barcode.hpp" @@ -33,8 +32,6 @@ #include #include -class G4PrimaryParticle; - #if BOOST_VERSION >= 107800 #include @@ -72,19 +69,19 @@ ActsFatras::Hit hitFromStep(const G4StepPoint* preStepPoint, G4ThreeVector postStepMomentum = convertEnergy * postStepPoint->GetMomentum(); G4double postStepEnergy = convertEnergy * postStepPoint->GetTotalEnergy(); - Acts::ActsScalar hX = 0.5 * (preStepPosition[0] + postStepPosition[0]); - Acts::ActsScalar hY = 0.5 * (preStepPosition[1] + postStepPosition[1]); - Acts::ActsScalar hZ = 0.5 * (preStepPosition[2] + postStepPosition[2]); - Acts::ActsScalar hT = 0.5 * (preStepTime + postStepTime); + double hX = 0.5 * (preStepPosition[0] + postStepPosition[0]); + double hY = 0.5 * (preStepPosition[1] + postStepPosition[1]); + double hZ = 0.5 * (preStepPosition[2] + postStepPosition[2]); + double hT = 0.5 * (preStepTime + postStepTime); - Acts::ActsScalar mXpre = preStepMomentum[0]; - Acts::ActsScalar mYpre = preStepMomentum[1]; - Acts::ActsScalar mZpre = preStepMomentum[2]; - Acts::ActsScalar mEpre = preStepEnergy; - Acts::ActsScalar mXpost = postStepMomentum[0]; - Acts::ActsScalar mYpost = postStepMomentum[1]; - Acts::ActsScalar mZpost = postStepMomentum[2]; - Acts::ActsScalar mEpost = postStepEnergy; + double mXpre = preStepMomentum[0]; + double mYpre = preStepMomentum[1]; + double mZpre = preStepMomentum[2]; + double mEpre = preStepEnergy; + double mXpost = postStepMomentum[0]; + double mYpost = postStepMomentum[1]; + double mZpost = postStepMomentum[2]; + double mEpost = postStepEnergy; Acts::Vector4 particlePosition(hX, hY, hZ, hT); Acts::Vector4 beforeMomentum(mXpre, mYpre, mZpre, mEpre); @@ -95,12 +92,13 @@ ActsFatras::Hit hitFromStep(const G4StepPoint* preStepPoint, } } // namespace -ActsExamples::SensitiveSteppingAction::SensitiveSteppingAction( +namespace ActsExamples::Geant4 { + +SensitiveSteppingAction::SensitiveSteppingAction( const Config& cfg, std::unique_ptr logger) : G4UserSteppingAction(), m_cfg(cfg), m_logger(std::move(logger)) {} -void ActsExamples::SensitiveSteppingAction::UserSteppingAction( - const G4Step* step) { +void SensitiveSteppingAction::UserSteppingAction(const G4Step* step) { // Unit conversions G4->::ACTS static constexpr double convertLength = Acts::UnitConstants::mm / CLHEP::mm; @@ -279,3 +277,5 @@ void ActsExamples::SensitiveSteppingAction::UserSteppingAction( assert(false && "should never reach this"); } + +} // namespace ActsExamples::Geant4 diff --git a/Examples/Algorithms/Geant4/src/SensitiveSurfaceMapper.cpp b/Examples/Algorithms/Geant4/src/SensitiveSurfaceMapper.cpp index 2fd1a924d94..924a898c238 100644 --- a/Examples/Algorithms/Geant4/src/SensitiveSurfaceMapper.cpp +++ b/Examples/Algorithms/Geant4/src/SensitiveSurfaceMapper.cpp @@ -63,6 +63,7 @@ struct access, Index> { } // namespace boost::geometry::traits namespace { + void writeG4Polyhedron( Acts::IVisualization3D& visualizer, const G4Polyhedron& polyhedron, const Acts::Transform3& trafo = Acts::Transform3::Identity(), @@ -89,10 +90,12 @@ void writeG4Polyhedron( visualizer.face(faces, color); } } + } // namespace -std::vector -ActsExamples::SensitiveCandidates::queryPosition( +namespace ActsExamples::Geant4 { + +std::vector SensitiveCandidates::queryPosition( const Acts::GeometryContext& gctx, const Acts::Vector3& position) const { std::vector surfaces; @@ -119,8 +122,7 @@ ActsExamples::SensitiveCandidates::queryPosition( return surfaces; } -std::vector ActsExamples::SensitiveCandidates::queryAll() - const { +std::vector SensitiveCandidates::queryAll() const { std::vector surfaces; const bool restrictToSensitives = true; @@ -130,11 +132,11 @@ std::vector ActsExamples::SensitiveCandidates::queryAll() return surfaces; } -ActsExamples::SensitiveSurfaceMapper::SensitiveSurfaceMapper( +SensitiveSurfaceMapper::SensitiveSurfaceMapper( const Config& cfg, std::unique_ptr logger) : m_cfg(cfg), m_logger(std::move(logger)) {} -void ActsExamples::SensitiveSurfaceMapper::remapSensitiveNames( +void SensitiveSurfaceMapper::remapSensitiveNames( State& state, const Acts::GeometryContext& gctx, G4VPhysicalVolume* g4PhysicalVolume, const Acts::Transform3& motherTransform) const { @@ -291,7 +293,7 @@ void ActsExamples::SensitiveSurfaceMapper::remapSensitiveNames( state.g4VolumeToSurfaces.insert({g4PhysicalVolume, mappedSurface}); } -bool ActsExamples::SensitiveSurfaceMapper::checkMapping( +bool SensitiveSurfaceMapper::checkMapping( const State& state, const Acts::GeometryContext& gctx, bool writeMissingG4VolsAsObj, bool writeMissingSurfacesAsObj) const { auto allSurfaces = m_cfg.candidateSurfaces->queryAll(); @@ -343,3 +345,5 @@ bool ActsExamples::SensitiveSurfaceMapper::checkMapping( return missing.empty(); } + +} // namespace ActsExamples::Geant4 diff --git a/Examples/Algorithms/Geant4/src/SimParticleTranslation.cpp b/Examples/Algorithms/Geant4/src/SimParticleTranslation.cpp index 8b8156ff3e4..e505edafa76 100644 --- a/Examples/Algorithms/Geant4/src/SimParticleTranslation.cpp +++ b/Examples/Algorithms/Geant4/src/SimParticleTranslation.cpp @@ -28,19 +28,17 @@ #include #include -namespace ActsExamples { -class WhiteBoard; -} // namespace ActsExamples +namespace ActsExamples::Geant4 { -ActsExamples::SimParticleTranslation::SimParticleTranslation( +SimParticleTranslation::SimParticleTranslation( const Config& cfg, std::unique_ptr logger) : G4VUserPrimaryGeneratorAction(), m_cfg(cfg), m_logger(std::move(logger)) {} -ActsExamples::SimParticleTranslation::~SimParticleTranslation() = default; +SimParticleTranslation::~SimParticleTranslation() = default; -void ActsExamples::SimParticleTranslation::GeneratePrimaries(G4Event* anEvent) { +void SimParticleTranslation::GeneratePrimaries(G4Event* anEvent) { anEvent->SetEventID(m_eventNr++); unsigned int eventID = anEvent->GetEventID(); @@ -158,3 +156,5 @@ void ActsExamples::SimParticleTranslation::GeneratePrimaries(G4Event* anEvent) { << lastVertex->transpose()); } } + +} // namespace ActsExamples::Geant4 diff --git a/Examples/Algorithms/Geant4/src/TelescopeG4DetectorConstruction.cpp b/Examples/Algorithms/Geant4/src/TelescopeG4DetectorConstruction.cpp index 423acf7e2a5..e8412a18c93 100644 --- a/Examples/Algorithms/Geant4/src/TelescopeG4DetectorConstruction.cpp +++ b/Examples/Algorithms/Geant4/src/TelescopeG4DetectorConstruction.cpp @@ -26,18 +26,17 @@ #include "G4RunManager.hh" #include "G4SystemOfUnits.hh" -ActsExamples::Telescope::TelescopeG4DetectorConstruction:: - TelescopeG4DetectorConstruction( - const TelescopeDetector::Config& cfg, - std::vector> regionCreators) +namespace ActsExamples { + +TelescopeG4DetectorConstruction::TelescopeG4DetectorConstruction( + const TelescopeDetector::Config& cfg, + std::vector> regionCreators) : m_cfg(cfg), m_regionCreators(std::move(regionCreators)) { - throw_assert(cfg.surfaceType == - static_cast(Telescope::TelescopeSurfaceType::Plane), + throw_assert(cfg.surfaceType == static_cast(TelescopeSurfaceType::Plane), "only plan is supported right now"); } -G4VPhysicalVolume* -ActsExamples::Telescope::TelescopeG4DetectorConstruction::Construct() { +G4VPhysicalVolume* TelescopeG4DetectorConstruction::Construct() { if (m_world != nullptr) { return m_world; } @@ -162,21 +161,21 @@ ActsExamples::Telescope::TelescopeG4DetectorConstruction::Construct() { // Create regions for (const auto& regionCreator : m_regionCreators) { - regionCreator->Construct(); + regionCreator->construct(); } return m_world; } -ActsExamples::Telescope::TelescopeG4DetectorConstructionFactory:: - TelescopeG4DetectorConstructionFactory( - const TelescopeDetector::Config& cfg, - std::vector> regionCreators) +TelescopeG4DetectorConstructionFactory::TelescopeG4DetectorConstructionFactory( + const TelescopeDetector::Config& cfg, + std::vector> regionCreators) : m_cfg(cfg), m_regionCreators(std::move(regionCreators)) {} std::unique_ptr -ActsExamples::Telescope::TelescopeG4DetectorConstructionFactory::factorize() - const { +TelescopeG4DetectorConstructionFactory::factorize() const { return std::make_unique(m_cfg, m_regionCreators); } + +} // namespace ActsExamples diff --git a/Examples/Algorithms/Geant4HepMC/include/ActsExamples/Geant4HepMC/EventRecording.hpp b/Examples/Algorithms/Geant4HepMC/include/ActsExamples/Geant4HepMC/EventRecording.hpp index 256a82a4471..6f45940182c 100644 --- a/Examples/Algorithms/Geant4HepMC/include/ActsExamples/Geant4HepMC/EventRecording.hpp +++ b/Examples/Algorithms/Geant4HepMC/include/ActsExamples/Geant4HepMC/EventRecording.hpp @@ -8,8 +8,6 @@ #pragma once -#include "Acts/Definitions/Algebra.hpp" -#include "Acts/Propagator/MaterialInteractor.hpp" #include "Acts/Utilities/Logger.hpp" #include "ActsExamples/EventData/SimParticle.hpp" #include "ActsExamples/Framework/DataHandle.hpp" @@ -24,9 +22,12 @@ class G4RunManager; -namespace ActsExamples { - +namespace ActsExamples::Geant4 { class DetectorConstructionFactory; +class RegionCreator; +} // namespace ActsExamples::Geant4 + +namespace ActsExamples { class EventRecording final : public ActsExamples::IAlgorithm { public: @@ -37,7 +38,8 @@ class EventRecording final : public ActsExamples::IAlgorithm { /// The recorded events output std::string outputHepMcTracks = "geant-outcome-tracks"; - std::shared_ptr detectorConstructionFactory; + std::shared_ptr + detectorConstructionFactory; /// random number seed 1 int seed1 = 12345; diff --git a/Examples/Algorithms/Geant4HepMC/src/EventRecording.cpp b/Examples/Algorithms/Geant4HepMC/src/EventRecording.cpp index e4900f63c05..93c27b0c1c1 100644 --- a/Examples/Algorithms/Geant4HepMC/src/EventRecording.cpp +++ b/Examples/Algorithms/Geant4HepMC/src/EventRecording.cpp @@ -11,9 +11,7 @@ #include "ActsExamples/EventData/SimParticle.hpp" #include "ActsExamples/Framework/WhiteBoard.hpp" #include "ActsExamples/Geant4/DetectorConstructionFactory.hpp" -#include "ActsExamples/Geant4/GdmlDetectorConstruction.hpp" -#include #include #include @@ -26,14 +24,15 @@ #include "RunAction.hpp" #include "SteppingAction.hpp" -ActsExamples::EventRecording::~EventRecording() { +namespace ActsExamples { + +EventRecording::~EventRecording() { m_runManager = nullptr; } -ActsExamples::EventRecording::EventRecording( - const ActsExamples::EventRecording::Config& config, - Acts::Logging::Level level) - : ActsExamples::IAlgorithm("EventRecording", level), +EventRecording::EventRecording(const EventRecording::Config& config, + Acts::Logging::Level level) + : IAlgorithm("EventRecording", level), m_cfg(config), m_runManager(std::make_unique()) { if (m_cfg.inputParticles.empty()) { @@ -42,7 +41,7 @@ ActsExamples::EventRecording::EventRecording( if (m_cfg.outputHepMcTracks.empty()) { throw std::invalid_argument("Missing output event collection"); } - if (!m_cfg.detectorConstructionFactory) { + if (m_cfg.detectorConstructionFactory == nullptr) { throw std::invalid_argument("Missing detector construction object"); } @@ -55,19 +54,17 @@ ActsExamples::EventRecording::EventRecording( m_runManager->SetUserInitialization( m_cfg.detectorConstructionFactory->factorize().release()); m_runManager->SetUserInitialization(new FTFP_BERT); - m_runManager->SetUserAction(new ActsExamples::Geant4::HepMC3::RunAction()); + m_runManager->SetUserAction(new Geant4::HepMC3::RunAction()); m_runManager->SetUserAction( - new ActsExamples::Geant4::HepMC3::EventAction(m_cfg.processesCombine)); + new Geant4::HepMC3::EventAction(m_cfg.processesCombine)); m_runManager->SetUserAction( - new ActsExamples::Geant4::HepMC3::PrimaryGeneratorAction(m_cfg.seed1, - m_cfg.seed2)); + new Geant4::HepMC3::PrimaryGeneratorAction(m_cfg.seed1, m_cfg.seed2)); m_runManager->SetUserAction( - new ActsExamples::Geant4::HepMC3::SteppingAction(m_cfg.processesReject)); + new Geant4::HepMC3::SteppingAction(m_cfg.processesReject)); m_runManager->Initialize(); } -ActsExamples::ProcessCode ActsExamples::EventRecording::execute( - const ActsExamples::AlgorithmContext& context) const { +ProcessCode EventRecording::execute(const AlgorithmContext& context) const { // ensure exclusive access to the geant run manager std::lock_guard guard(m_runManagerLock); @@ -80,8 +77,8 @@ ActsExamples::ProcessCode ActsExamples::EventRecording::execute( for (const auto& part : initialParticles) { // Prepare the particle gun - ActsExamples::Geant4::HepMC3::PrimaryGeneratorAction::instance() - ->prepareParticleGun(part); + Geant4::HepMC3::PrimaryGeneratorAction::instance()->prepareParticleGun( + part); // Begin with the simulation m_runManager->BeamOn(1); @@ -92,8 +89,7 @@ ActsExamples::ProcessCode ActsExamples::EventRecording::execute( } // Set event start time - HepMC3::GenEvent event = - ActsExamples::Geant4::HepMC3::EventAction::instance()->event(); + HepMC3::GenEvent event = Geant4::HepMC3::EventAction::instance()->event(); HepMC3::FourVector shift(0., 0., 0., part.time() / Acts::UnitConstants::mm); event.shift_position_by(shift); @@ -174,5 +170,7 @@ ActsExamples::ProcessCode ActsExamples::EventRecording::execute( // Write the recorded material to the event store m_outputEvents(context, std::move(events)); - return ActsExamples::ProcessCode::SUCCESS; + return ProcessCode::SUCCESS; } + +} // namespace ActsExamples diff --git a/Examples/Algorithms/Generators/ActsExamples/Generators/EventGenerator.cpp b/Examples/Algorithms/Generators/ActsExamples/Generators/EventGenerator.cpp index a11d62c928f..9d5c1b873d3 100644 --- a/Examples/Algorithms/Generators/ActsExamples/Generators/EventGenerator.cpp +++ b/Examples/Algorithms/Generators/ActsExamples/Generators/EventGenerator.cpp @@ -8,17 +8,23 @@ #include "ActsExamples/Generators/EventGenerator.hpp" +#include "Acts/Surfaces/PerigeeSurface.hpp" #include "ActsExamples/EventData/SimVertex.hpp" +#include "ActsExamples/EventData/Track.hpp" #include "ActsExamples/Framework/AlgorithmContext.hpp" #include "ActsFatras/EventData/Barcode.hpp" #include "ActsFatras/EventData/Particle.hpp" #include +#include +#include #include #include +#include -ActsExamples::EventGenerator::EventGenerator(const Config& cfg, - Acts::Logging::Level lvl) +namespace ActsExamples { + +EventGenerator::EventGenerator(const Config& cfg, Acts::Logging::Level lvl) : m_cfg(cfg), m_logger(Acts::getDefaultLogger("EventGenerator", lvl)) { if (m_cfg.outputParticles.empty()) { throw std::invalid_argument("Missing output particles collection"); @@ -37,17 +43,15 @@ ActsExamples::EventGenerator::EventGenerator(const Config& cfg, m_outputVertices.initialize(m_cfg.outputVertices); } -std::string ActsExamples::EventGenerator::name() const { +std::string EventGenerator::name() const { return "EventGenerator"; } -std::pair -ActsExamples::EventGenerator::availableEvents() const { +std::pair EventGenerator::availableEvents() const { return {0u, std::numeric_limits::max()}; } -ActsExamples::ProcessCode ActsExamples::EventGenerator::read( - const AlgorithmContext& ctx) { +ProcessCode EventGenerator::read(const AlgorithmContext& ctx) { SimParticleContainer particles; SimVertexContainer vertices; @@ -120,5 +124,8 @@ ActsExamples::ProcessCode ActsExamples::EventGenerator::read( // move generated event to the store m_outputParticles(ctx, std::move(particles)); m_outputVertices(ctx, std::move(vertices)); + return ProcessCode::SUCCESS; } + +} // namespace ActsExamples diff --git a/Examples/Algorithms/Generators/ActsExamples/Generators/EventGenerator.hpp b/Examples/Algorithms/Generators/ActsExamples/Generators/EventGenerator.hpp index 46720b9fff1..7a76ac03d71 100644 --- a/Examples/Algorithms/Generators/ActsExamples/Generators/EventGenerator.hpp +++ b/Examples/Algorithms/Generators/ActsExamples/Generators/EventGenerator.hpp @@ -18,7 +18,6 @@ #include "ActsExamples/Framework/RandomNumbers.hpp" #include -#include #include #include #include @@ -93,8 +92,9 @@ class EventGenerator final : public ActsExamples::IReader { struct Config { /// Name of the output particles collection. std::string outputParticles; - /// Name of the vertex collection. + /// Name of the output vertex collection. std::string outputVertices; + /// List of generators that should be used to generate the event. std::vector generators; /// The random number service. diff --git a/Examples/Algorithms/Generators/ActsExamples/Generators/ParametricParticleGenerator.cpp b/Examples/Algorithms/Generators/ActsExamples/Generators/ParametricParticleGenerator.cpp index 34363410f42..00411fc64c3 100644 --- a/Examples/Algorithms/Generators/ActsExamples/Generators/ParametricParticleGenerator.cpp +++ b/Examples/Algorithms/Generators/ActsExamples/Generators/ParametricParticleGenerator.cpp @@ -92,8 +92,8 @@ ParametricParticleGenerator::operator()(RandomEngine& rng) { SimParticleContainer::sequence_type particles; // create the primary vertex - auto& primaryVertex = vertices.emplace_back( - SimVertexBarcode{0}, SimVertex::Vector4(0., 0., 0., 0.)); + auto& primaryVertex = + vertices.emplace_back(SimVertexBarcode{0}, Acts::Vector4(0., 0., 0., 0.)); // counter will be reused as barcode particle number which must be non-zero. for (std::size_t ip = 1; ip <= m_cfg.numParticles; ++ip) { diff --git a/Examples/Algorithms/GeneratorsPythia8/ActsExamples/Generators/Pythia8ProcessGenerator.cpp b/Examples/Algorithms/GeneratorsPythia8/ActsExamples/Generators/Pythia8ProcessGenerator.cpp index cd80d64bf08..1b774a7bdf0 100644 --- a/Examples/Algorithms/GeneratorsPythia8/ActsExamples/Generators/Pythia8ProcessGenerator.cpp +++ b/Examples/Algorithms/GeneratorsPythia8/ActsExamples/Generators/Pythia8ProcessGenerator.cpp @@ -121,8 +121,7 @@ Pythia8Generator::operator()(RandomEngine& rng) { } // create the primary vertex - vertices.emplace_back(SimVertexBarcode{0}, - SimVertex::Vector4(0., 0., 0., 0.)); + vertices.emplace_back(SimVertexBarcode{0}, Acts::Vector4(0., 0., 0., 0.)); // convert generated final state particles into internal format for (int ip = 0; ip < m_pythia8->event.size(); ++ip) { diff --git a/Examples/Algorithms/Geometry/include/ActsExamples/Geometry/VolumeAssociationTest.hpp b/Examples/Algorithms/Geometry/include/ActsExamples/Geometry/VolumeAssociationTest.hpp index c86720c340a..a468051aff2 100644 --- a/Examples/Algorithms/Geometry/include/ActsExamples/Geometry/VolumeAssociationTest.hpp +++ b/Examples/Algorithms/Geometry/include/ActsExamples/Geometry/VolumeAssociationTest.hpp @@ -33,7 +33,7 @@ class VolumeAssociationTest final : public IAlgorithm { /// The random number service std::shared_ptr randomNumbers = nullptr; /// The random number range - std::vector randomRange = {}; + std::vector randomRange = {}; /// The detector std::shared_ptr detector = nullptr; }; diff --git a/Examples/Algorithms/Geometry/src/VolumeAssociationTest.cpp b/Examples/Algorithms/Geometry/src/VolumeAssociationTest.cpp index 353bcf94bac..dbb5ac2bc79 100644 --- a/Examples/Algorithms/Geometry/src/VolumeAssociationTest.cpp +++ b/Examples/Algorithms/Geometry/src/VolumeAssociationTest.cpp @@ -38,18 +38,17 @@ ActsExamples::ProcessCode ActsExamples::VolumeAssociationTest::execute( auto rng = m_cfg.randomNumbers->spawnGenerator(ctx); // Setup random number distributions for some quantities - std::uniform_real_distribution phiDist(-std::numbers::pi, - std::numbers::pi); - std::uniform_real_distribution rDist(0., - m_cfg.randomRange[0u]); - std::uniform_real_distribution zDist(-m_cfg.randomRange[1u], - m_cfg.randomRange[1u]); + std::uniform_real_distribution phiDist(-std::numbers::pi, + std::numbers::pi); + std::uniform_real_distribution rDist(0., m_cfg.randomRange[0u]); + std::uniform_real_distribution zDist(-m_cfg.randomRange[1u], + m_cfg.randomRange[1u]); // Lemma for vector creation auto testPosition = [&]() -> Acts::Vector3 { - Acts::ActsScalar r = rDist(rng); - Acts::ActsScalar phi = phiDist(rng); - Acts::ActsScalar z = zDist(rng); + double r = rDist(rng); + double phi = phiDist(rng); + double z = zDist(rng); return Acts::Vector3(r * cos(phi), r * sin(phi), z); }; diff --git a/Examples/Algorithms/MaterialMapping/include/ActsExamples/MaterialMapping/MaterialValidation.hpp b/Examples/Algorithms/MaterialMapping/include/ActsExamples/MaterialMapping/MaterialValidation.hpp index ad1a7a93dff..69558244027 100644 --- a/Examples/Algorithms/MaterialMapping/include/ActsExamples/MaterialMapping/MaterialValidation.hpp +++ b/Examples/Algorithms/MaterialMapping/include/ActsExamples/MaterialMapping/MaterialValidation.hpp @@ -37,11 +37,10 @@ class MaterialValidation : public IAlgorithm { Acts::Vector3 startPosition = Acts::Vector3(0., 0., 0.); /// Start direction for the scan: phi - std::pair phiRange = {-std::numbers::pi, - std::numbers::pi}; + std::pair phiRange = {-std::numbers::pi, std::numbers::pi}; /// Start direction for the scan: eta - std::pair etaRange = {-4., 4.}; + std::pair etaRange = {-4., 4.}; /// Random number service std::shared_ptr randomNumberSvc = nullptr; diff --git a/Examples/Algorithms/MaterialMapping/src/MaterialValidation.cpp b/Examples/Algorithms/MaterialMapping/src/MaterialValidation.cpp index c75c654ed2b..a162edd2129 100644 --- a/Examples/Algorithms/MaterialMapping/src/MaterialValidation.cpp +++ b/Examples/Algorithms/MaterialMapping/src/MaterialValidation.cpp @@ -47,9 +47,9 @@ ProcessCode MaterialValidation::execute(const AlgorithmContext& context) const { // Loop over the number of tracks for (std::size_t iTrack = 0; iTrack < m_cfg.ntracks; ++iTrack) { // Generate a random phi and eta - Acts::ActsScalar phi = phiDist(rng); - Acts::ActsScalar eta = etaDist(rng); - Acts::ActsScalar theta = 2 * std::atan(std::exp(-eta)); + double phi = phiDist(rng); + double eta = etaDist(rng); + double theta = 2 * std::atan(std::exp(-eta)); Acts::Vector3 direction(std::cos(phi) * std::sin(theta), std::sin(phi) * std::sin(theta), std::cos(theta)); diff --git a/Examples/Algorithms/Propagation/include/ActsExamples/Propagation/PropagatorInterface.hpp b/Examples/Algorithms/Propagation/include/ActsExamples/Propagation/PropagatorInterface.hpp index 2aa3b2292ac..7f113d47b56 100644 --- a/Examples/Algorithms/Propagation/include/ActsExamples/Propagation/PropagatorInterface.hpp +++ b/Examples/Algorithms/Propagation/include/ActsExamples/Propagation/PropagatorInterface.hpp @@ -117,6 +117,8 @@ class ConcretePropagator : public PropagatorInterface { resultValue.template get(); summary.steps = std::move(steppingResults.steps); + summary.statistics = resultValue.statistics; + // Also set the material recording result - if configured if (cfg.recordMaterialInteractions) { auto materialResult = diff --git a/Examples/Algorithms/Propagation/src/SimHitToSummaryConversion.cpp b/Examples/Algorithms/Propagation/src/SimHitToSummaryConversion.cpp index 2d90a2bc8ac..a653794dec1 100644 --- a/Examples/Algorithms/Propagation/src/SimHitToSummaryConversion.cpp +++ b/Examples/Algorithms/Propagation/src/SimHitToSummaryConversion.cpp @@ -29,7 +29,7 @@ Acts::detail::Step concatenateSteps( concatStep.position += step.position; concatStep.momentum += step.momentum; } - Acts::ActsScalar weight = 1.0 / static_cast(steps.size()); + double weight = 1. / steps.size(); concatStep.position *= weight; concatStep.momentum *= weight; } else { @@ -92,9 +92,9 @@ ActsExamples::ProcessCode ActsExamples::SimHitToSummaryConversion::execute( if (!moduleSteps.contains(paritcleId)) { moduleSteps[paritcleId] = std::vector(); } - Acts::ActsScalar hx = simHit.fourPosition().x() / Acts::UnitConstants::mm; - Acts::ActsScalar hy = simHit.fourPosition().y() / Acts::UnitConstants::mm; - Acts::ActsScalar hz = simHit.fourPosition().z() / Acts::UnitConstants::mm; + double hx = simHit.fourPosition().x() / Acts::UnitConstants::mm; + double hy = simHit.fourPosition().y() / Acts::UnitConstants::mm; + double hz = simHit.fourPosition().z() / Acts::UnitConstants::mm; Acts::detail::Step step; step.position = Acts::Vector3(hx, hy, hz); step.momentum = simHit.direction(); diff --git a/Examples/Algorithms/TrackFinding/CMakeLists.txt b/Examples/Algorithms/TrackFinding/CMakeLists.txt index 38781494068..33b924e35aa 100644 --- a/Examples/Algorithms/TrackFinding/CMakeLists.txt +++ b/Examples/Algorithms/TrackFinding/CMakeLists.txt @@ -10,6 +10,7 @@ add_library( src/TrackParamsEstimationAlgorithm.cpp src/MuonHoughSeeder.cpp src/GbtsSeedingAlgorithm.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..5777f90ef18 --- /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 TrackParamsLookup readLookup(const std::string& path) const = 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..9cddadae062 --- /dev/null +++ b/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/ITrackParamsLookupWriter.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 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 TrackParamsLookup& lookup) const = 0; +}; + +} // 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..e50991cd944 --- /dev/null +++ b/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/TrackParamsLookupEstimation.hpp @@ -0,0 +1,78 @@ +// 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/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 + +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: + using TrackParamsLookupAccumulator = + Acts::TrackParamsLookupAccumulator; + + /// @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 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; } + + 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..5b9c1fabd83 --- /dev/null +++ b/Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/TrackParamsLookupTable.hpp @@ -0,0 +1,44 @@ +// 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/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 TrackParamsLookupAxis = + Acts::Axis; + +/// @brief Track parameters lookup table axis generator +/// used in the track estimation algorithm +using TrackParamsLookupAxisGen = Acts::GridAxisGenerators::EqOpenEqOpen; + +/// @brief Lookup grid for track parameters estimation +/// in a given layer +using TrackParamsLookupGrid = + Acts::Grid; + +/// @brief Lookup table for track parameters estimation +/// in the track estimation algorithm +using TrackParamsLookup = + std::unordered_map; + +} // namespace ActsExamples diff --git a/Examples/Algorithms/TrackFinding/src/MuonHoughSeeder.cpp b/Examples/Algorithms/TrackFinding/src/MuonHoughSeeder.cpp index b074d14ab91..dda3349d254 100644 --- a/Examples/Algorithms/TrackFinding/src/MuonHoughSeeder.cpp +++ b/Examples/Algorithms/TrackFinding/src/MuonHoughSeeder.cpp @@ -88,10 +88,9 @@ ActsExamples::ProcessCode ActsExamples::MuonHoughSeeder::execute( // create the function parametrising the drift radius uncertainty auto houghWidth_fromDC = [](double, const DriftCircle& DC) { - return std::min(DC.rDriftError() * 3., - 1.0); // scale reported errors up to at least 1mm or 3 - // times the reported error as drift circle calib not - // fully reliable at this stage + // scale reported errors up to at least 1mm or 3 times the reported error as + // drift circle calib not fully reliable at this stage + return std::min(DC.rDriftError() * 3., 1.0); }; // store the true parameters @@ -100,12 +99,12 @@ ActsExamples::ProcessCode ActsExamples::MuonHoughSeeder::execute( // instantiate the hough plane Acts::HoughTransformUtils::HoughPlane houghPlane(planeCfg); - // also insantiate the peak finder + // also instantiate the peak finder Acts::HoughTransformUtils::PeakFinders::IslandsAroundMax< Acts::GeometryIdentifier::Value> peakFinder(peakFinderCfg); - // loop pver true hirs + // loop over true hits for (auto& SH : gotSH) { // read the identifier MuonMdtIdentifierFields detailedInfo = @@ -113,10 +112,9 @@ ActsExamples::ProcessCode ActsExamples::MuonHoughSeeder::execute( // store the true parameters truePatterns.emplace_back(SH.direction().y() / SH.direction().z(), SH.fourPosition().y()); - // std::cout<<"station name=" << - // static_cast(SH.stationName)< #include #include #include #include -#include #include #include @@ -119,16 +117,14 @@ ProcessCode TrackParamsEstimationAlgorithm::execute( } // Estimate the track parameters from seed - auto optParams = Acts::estimateTrackParamsFromSeed( - ctx.geoContext, seed.sp().begin(), seed.sp().end(), *surface, field, - logger()); - if (!optParams.has_value()) { - ACTS_WARNING("Estimation of track parameters for seed " << iseed - << " failed."); + const auto paramsResult = Acts::estimateTrackParamsFromSeed( + ctx.geoContext, seed.sp(), *surface, field); + if (!paramsResult.ok()) { + ACTS_WARNING("Skip track because param estimation failed " + << paramsResult.error()); continue; } - - const auto& params = optParams.value(); + const auto& params = *paramsResult; Acts::EstimateTrackParamCovarianceConfig config{ .initialSigmas = diff --git a/Examples/Algorithms/TrackFinding/src/TrackParamsLookupEstimation.cpp b/Examples/Algorithms/TrackFinding/src/TrackParamsLookupEstimation.cpp new file mode 100644 index 00000000000..4e4b283ddf9 --- /dev/null +++ b/Examples/Algorithms/TrackFinding/src/TrackParamsLookupEstimation.cpp @@ -0,0 +1,104 @@ +// 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/Surfaces/RectangleBounds.hpp" +#include "ActsExamples/Framework/ProcessCode.hpp" + +ActsExamples::TrackParamsLookupEstimation::TrackParamsLookupEstimation( + const Config& config, Acts::Logging::Level level) + : IAlgorithm("TrackParamsLookupEstimation", level), m_cfg(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"); + } + if (refSurface->type() != Acts::Surface::SurfaceType::Plane) { + throw std::invalid_argument("Only plane surfaces supported"); + } + + // Initialize the accumulator grid + auto halfX = bounds->halfLengthX(); + auto halfY = bounds->halfLengthY(); + + TrackParamsLookupAxisGen axisGen{ + {-halfX, halfX}, m_cfg.bins.first, {-halfY, halfY}, m_cfg.bins.second}; + + // Each reference layer has its own accumulator + m_accumulators[geoId] = std::make_unique( + TrackParamsLookupGrid(axisGen())); + } + + m_inputParticles.initialize(m_cfg.inputParticles); + m_inputSimHits.initialize(m_cfg.inputHits); +} + +ActsExamples::ProcessCode +ActsExamples::TrackParamsLookupEstimation::finalize() { + // Finiliaze the lookup tables and write them + ActsExamples::TrackParamsLookup lookup; + for (auto& [id, acc] : m_accumulators) { + lookup.insert({id, acc->finalizeLookup()}); + } + for (const auto& writer : m_cfg.trackLookupGridWriters) { + writer->writeLookup(lookup); + } + + return ActsExamples::ProcessCode::SUCCESS; +}; + +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/Algorithms/TrackFindingExaTrkX/include/ActsExamples/TrackFindingExaTrkX/TrackFindingAlgorithmExaTrkX.hpp b/Examples/Algorithms/TrackFindingExaTrkX/include/ActsExamples/TrackFindingExaTrkX/TrackFindingAlgorithmExaTrkX.hpp index f85a000aac7..79ee477f662 100644 --- a/Examples/Algorithms/TrackFindingExaTrkX/include/ActsExamples/TrackFindingExaTrkX/TrackFindingAlgorithmExaTrkX.hpp +++ b/Examples/Algorithms/TrackFindingExaTrkX/include/ActsExamples/TrackFindingExaTrkX/TrackFindingAlgorithmExaTrkX.hpp @@ -13,6 +13,7 @@ #include "Acts/Plugins/ExaTrkX/Stages.hpp" #include "Acts/Plugins/ExaTrkX/TorchGraphStoreHook.hpp" #include "ActsExamples/EventData/Cluster.hpp" +#include "ActsExamples/EventData/GeometryContainers.hpp" #include "ActsExamples/EventData/Graph.hpp" #include "ActsExamples/EventData/ProtoTrack.hpp" #include "ActsExamples/EventData/SimHit.hpp" @@ -34,24 +35,60 @@ namespace ActsExamples { class TrackFindingAlgorithmExaTrkX final : public IAlgorithm { public: enum class NodeFeature { + // SP features eR, ePhi, eX, eY, eZ, eEta, + // Single cluster features eCellCount, - eCellSum, - eClusterX, - eClusterY, + eChargeSum, + eClusterLoc0, + eClusterLoc1, + // Cluster 1 features + eCluster1X, + eCluster1Y, + eCluster1Z, eCluster1R, - eCluster2R, eCluster1Phi, - eCluster2Phi, - eCluster1Z, - eCluster2Z, eCluster1Eta, + eCellCount1, + eChargeSum1, + eLocEta1, + eLocPhi1, + eLocDir01, + eLocDir11, + eLocDir21, + eLengthDir01, + eLengthDir11, + eLengthDir21, + eGlobEta1, + eGlobPhi1, + eEtaAngle1, + ePhiAngle1, + // Cluster 2 features + eCluster2X, + eCluster2Y, + eCluster2Z, + eCluster2R, + eCluster2Phi, eCluster2Eta, + eCellCount2, + eChargeSum2, + eLocEta2, + eLocPhi2, + eLocDir02, + eLocDir12, + eLocDir22, + eLengthDir02, + eLengthDir12, + eLengthDir22, + eGlobEta2, + eGlobPhi2, + eEtaAngle2, + ePhiAngle2, }; struct Config { @@ -63,14 +100,16 @@ class TrackFindingAlgorithmExaTrkX final : public IAlgorithm { std::string inputTruthGraph; /// Output prototracks std::string outputProtoTracks; - /// Output graph (optional) std::string outputGraph; + /// Graph constructor std::shared_ptr graphConstructor; + /// List of edge classifiers std::vector> edgeClassifiers; + /// The track builder std::shared_ptr trackBuilder; /// Node features @@ -81,7 +120,10 @@ class TrackFindingAlgorithmExaTrkX final : public IAlgorithm { std::vector featureScales = {1.f, 1.f, 1.f}; /// Remove track candidates with 2 or less hits - bool filterShortTracks = false; + std::size_t minMeasurementsPerTrack = 3; + + /// Optionally remap the geometry Ids that are put into the chain + std::shared_ptr geometryIdMap; }; /// Constructor of the track finding algorithm @@ -111,13 +153,17 @@ class TrackFindingAlgorithmExaTrkX final : public IAlgorithm { mutable std::mutex m_mutex; using Accumulator = boost::accumulators::accumulator_set< - float, boost::accumulators::features>; + float, + boost::accumulators::features< + boost::accumulators::tag::mean, boost::accumulators::tag::variance, + boost::accumulators::tag::max, boost::accumulators::tag::min>>; mutable struct { + Accumulator preprocessingTime; Accumulator graphBuildingTime; std::vector classifierTimes; Accumulator trackBuildingTime; + Accumulator postprocessingTime; } m_timing; ReadDataHandle m_inputSpacePoints{this, diff --git a/Examples/Algorithms/TrackFindingExaTrkX/src/PrototracksToParameters.cpp b/Examples/Algorithms/TrackFindingExaTrkX/src/PrototracksToParameters.cpp index 9ffe49ae460..53fe1cdbdad 100644 --- a/Examples/Algorithms/TrackFindingExaTrkX/src/PrototracksToParameters.cpp +++ b/Examples/Algorithms/TrackFindingExaTrkX/src/PrototracksToParameters.cpp @@ -167,17 +167,17 @@ ProcessCode PrototracksToParameters::execute( continue; } - auto pars = Acts::estimateTrackParamsFromSeed( - ctx.geoContext, seed.sp().begin(), seed.sp().end(), surface, field); - - if (not pars) { + auto parsResult = Acts::estimateTrackParamsFromSeed( + ctx.geoContext, seed.sp(), surface, field); + if (!parsResult.ok()) { ACTS_WARNING("Skip track because of bad params"); } + const auto &pars = *parsResult; seededTracks.push_back(track); seeds.emplace_back(std::move(seed)); parameters.push_back(Acts::BoundTrackParameters( - surface.getSharedPtr(), *pars, m_covariance, m_cfg.particleHypothesis)); + surface.getSharedPtr(), pars, m_covariance, m_cfg.particleHypothesis)); } if (skippedTracks > 0) { diff --git a/Examples/Algorithms/TrackFindingExaTrkX/src/TrackFindingAlgorithmExaTrkX.cpp b/Examples/Algorithms/TrackFindingExaTrkX/src/TrackFindingAlgorithmExaTrkX.cpp index df4b8998540..858b90359da 100644 --- a/Examples/Algorithms/TrackFindingExaTrkX/src/TrackFindingAlgorithmExaTrkX.cpp +++ b/Examples/Algorithms/TrackFindingExaTrkX/src/TrackFindingAlgorithmExaTrkX.cpp @@ -20,8 +20,11 @@ #include "ActsExamples/Framework/WhiteBoard.hpp" #include +#include #include +#include "createFeatures.hpp" + using namespace ActsExamples; using namespace Acts::UnitLiterals; @@ -87,8 +90,9 @@ ActsExamples::TrackFindingAlgorithmExaTrkX::TrackFindingAlgorithmExaTrkX( // Check if we want cluster features but do not have them const static std::array clFeatures = { - NodeFeature::eClusterX, NodeFeature::eClusterY, NodeFeature::eCellCount, - NodeFeature::eCellSum, NodeFeature::eCluster1R, NodeFeature::eCluster2R}; + NodeFeature::eClusterLoc0, NodeFeature::eClusterLoc0, + NodeFeature::eCellCount, NodeFeature::eChargeSum, + NodeFeature::eCluster1R, NodeFeature::eCluster2R}; auto wantClFeatures = std::ranges::any_of( m_cfg.nodeFeatures, @@ -108,6 +112,10 @@ ActsExamples::TrackFindingAlgorithmExaTrkX::TrackFindingAlgorithmExaTrkX( ActsExamples::ProcessCode ActsExamples::TrackFindingAlgorithmExaTrkX::execute( const ActsExamples::AlgorithmContext& ctx) const { + using Clock = std::chrono::high_resolution_clock; + using Duration = std::chrono::duration; + auto t0 = Clock::now(); + // Setup hooks LoopHook hook; @@ -139,10 +147,11 @@ ActsExamples::ProcessCode ActsExamples::TrackFindingAlgorithmExaTrkX::execute( ACTS_DEBUG("Received " << numSpacepoints << " spacepoints"); ACTS_DEBUG("Construct " << numFeatures << " node features"); - std::vector features(numSpacepoints * numFeatures); std::vector spacepointIDs; + std::vector moduleIds; spacepointIDs.reserve(spacepoints.size()); + moduleIds.reserve(spacepoints.size()); for (auto isp = 0ul; isp < numSpacepoints; ++isp) { const auto& sp = spacepoints[isp]; @@ -157,54 +166,25 @@ ActsExamples::ProcessCode ActsExamples::TrackFindingAlgorithmExaTrkX::execute( // to the pipeline spacepointIDs.push_back(isp); - // This should be fine, because check in constructor - Cluster* cl1 = clusters ? &clusters->at(sl1.index()) : nullptr; - Cluster* cl2 = cl1; - - if (sp.sourceLinks().size() == 2) { - const auto& sl2 = sp.sourceLinks()[1].template get(); - cl2 = clusters ? &clusters->at(sl2.index()) : nullptr; + if (m_cfg.geometryIdMap != nullptr) { + moduleIds.push_back(m_cfg.geometryIdMap->right.at(sl1.geometryId())); + } else { + moduleIds.push_back(sl1.geometryId().value()); } + } - // I would prefer to use a std::span or boost::span here once available - float* f = features.data() + isp * numFeatures; - - using NF = NodeFeature; - - for (auto ift = 0ul; ift < numFeatures; ++ift) { - // clang-format off - switch(m_cfg.nodeFeatures[ift]) { - break; case NF::eR: f[ift] = std::hypot(sp.x(), sp.y()); - break; case NF::ePhi: f[ift] = std::atan2(sp.y(), sp.x()); - break; case NF::eZ: f[ift] = sp.z(); - break; case NF::eX: f[ift] = sp.x(); - break; case NF::eY: f[ift] = sp.y(); - break; case NF::eEta: f[ift] = Acts::VectorHelpers::eta(Acts::Vector3{sp.x(), sp.y(), sp.z()}); - break; case NF::eClusterX: f[ift] = cl1->sizeLoc0; - break; case NF::eClusterY: f[ift] = cl1->sizeLoc1; - break; case NF::eCellSum: f[ift] = cl1->sumActivations(); - break; case NF::eCellCount: f[ift] = cl1->channels.size(); - break; case NF::eCluster1R: f[ift] = std::hypot(cl1->globalPosition[Acts::ePos0], cl1->globalPosition[Acts::ePos1]); - break; case NF::eCluster2R: f[ift] = std::hypot(cl2->globalPosition[Acts::ePos0], cl2->globalPosition[Acts::ePos1]); - break; case NF::eCluster1Phi: f[ift] = std::atan2(cl1->globalPosition[Acts::ePos1], cl1->globalPosition[Acts::ePos0]); - break; case NF::eCluster2Phi: f[ift] = std::atan2(cl2->globalPosition[Acts::ePos1], cl2->globalPosition[Acts::ePos0]); - break; case NF::eCluster1Z: f[ift] = cl1->globalPosition[Acts::ePos2]; - break; case NF::eCluster2Z: f[ift] = cl2->globalPosition[Acts::ePos2]; - break; case NF::eCluster1Eta: f[ift] = Acts::VectorHelpers::eta(Acts::Vector3{cl1->globalPosition[Acts::ePos0], cl1->globalPosition[Acts::ePos1], cl1->globalPosition[Acts::ePos2]}); - break; case NF::eCluster2Eta: f[ift] = Acts::VectorHelpers::eta(Acts::Vector3{cl2->globalPosition[Acts::ePos0], cl2->globalPosition[Acts::ePos1], cl2->globalPosition[Acts::ePos2]}); - } - // clang-format on + auto features = createFeatures(spacepoints, clusters, m_cfg.nodeFeatures, + m_cfg.featureScales); - f[ift] /= m_cfg.featureScales[ift]; - } - } + auto t1 = Clock::now(); // Run the pipeline const auto trackCandidates = [&]() { std::lock_guard lock(m_mutex); Acts::ExaTrkXTiming timing; - auto res = m_pipeline.run(features, spacepointIDs, hook, &timing); + auto res = + m_pipeline.run(features, moduleIds, spacepointIDs, hook, &timing); m_timing.graphBuildingTime(timing.graphBuildingTime.count()); @@ -219,6 +199,8 @@ ActsExamples::ProcessCode ActsExamples::TrackFindingAlgorithmExaTrkX::execute( return res; }(); + auto t2 = Clock::now(); + ACTS_DEBUG("Done with pipeline, received " << trackCandidates.size() << " candidates"); @@ -228,20 +210,28 @@ ActsExamples::ProcessCode ActsExamples::TrackFindingAlgorithmExaTrkX::execute( int nShortTracks = 0; - for (auto& x : trackCandidates) { - if (m_cfg.filterShortTracks && x.size() < 3) { + /// TODO the whole conversion back to meas idxs should be pulled out of the + /// track trackBuilder + for (auto& candidate : trackCandidates) { + ProtoTrack onetrack; + onetrack.reserve(candidate.size()); + + for (auto i : candidate) { + for (const auto& sl : spacepoints[i].sourceLinks()) { + onetrack.push_back(sl.template get().index()); + } + } + + if (onetrack.size() < m_cfg.minMeasurementsPerTrack) { nShortTracks++; continue; } - ProtoTrack onetrack; - onetrack.reserve(x.size()); - - std::copy(x.begin(), x.end(), std::back_inserter(onetrack)); protoTracks.push_back(std::move(onetrack)); } - ACTS_INFO("Removed " << nShortTracks << " with less then 3 hits"); + ACTS_INFO("Removed " << nShortTracks << " with less then " + << m_cfg.minMeasurementsPerTrack << " hits"); ACTS_INFO("Created " << protoTracks.size() << " proto tracks"); m_outputProtoTracks(ctx, std::move(protoTracks)); @@ -253,27 +243,33 @@ ActsExamples::ProcessCode ActsExamples::TrackFindingAlgorithmExaTrkX::execute( m_outputGraph(ctx, {graph.first, graph.second}); } + auto t3 = Clock::now(); + m_timing.preprocessingTime(Duration(t1 - t0).count()); + m_timing.postprocessingTime(Duration(t3 - t2).count()); + return ActsExamples::ProcessCode::SUCCESS; } ActsExamples::ProcessCode TrackFindingAlgorithmExaTrkX::finalize() { namespace ba = boost::accumulators; + auto print = [](const auto& t) { + std::stringstream ss; + ss << ba::mean(t) << " +- " << std::sqrt(ba::variance(t)) << " "; + ss << "[" << ba::min(t) << ", " << ba::max(t) << "]"; + return ss.str(); + }; + ACTS_INFO("Exa.TrkX timing info"); - { - const auto& t = m_timing.graphBuildingTime; - ACTS_INFO("- graph building: " << ba::mean(t) << " +- " - << std::sqrt(ba::variance(t))); - } + ACTS_INFO("- preprocessing: " << print(m_timing.preprocessingTime)); + ACTS_INFO("- graph building: " << print(m_timing.graphBuildingTime)); + // clang-format off for (const auto& t : m_timing.classifierTimes) { - ACTS_INFO("- classifier: " << ba::mean(t) << " +- " - << std::sqrt(ba::variance(t))); - } - { - const auto& t = m_timing.trackBuildingTime; - ACTS_INFO("- track building: " << ba::mean(t) << " +- " - << std::sqrt(ba::variance(t))); + ACTS_INFO("- classifier: " << print(t)); } + // clang-format on + ACTS_INFO("- track building: " << print(m_timing.trackBuildingTime)); + ACTS_INFO("- postprocessing: " << print(m_timing.postprocessingTime)); return {}; } diff --git a/Examples/Algorithms/TrackFindingExaTrkX/src/createFeatures.cpp b/Examples/Algorithms/TrackFindingExaTrkX/src/createFeatures.cpp new file mode 100644 index 00000000000..426a27428f0 --- /dev/null +++ b/Examples/Algorithms/TrackFindingExaTrkX/src/createFeatures.cpp @@ -0,0 +1,108 @@ +// 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 "createFeatures.hpp" + +#include "Acts/Utilities/AngleHelpers.hpp" +#include "Acts/Utilities/VectorHelpers.hpp" + +namespace ActsExamples { + +std::vector createFeatures( + const SimSpacePointContainer& spacepoints, + const std::optional& clusters, + const std::vector& nodeFeatures, + const std::vector& featureScales) { + using namespace ActsExamples; + + assert(nodeFeatures.size() == featureScales.size()); + std::vector features(spacepoints.size() * nodeFeatures.size()); + + for (auto isp = 0ul; isp < spacepoints.size(); ++isp) { + const auto& sp = spacepoints[isp]; + + // For now just take the first index since does require one single index + // per spacepoint + // TODO does it work for the module map construction to use only the first + // sp? + const auto& sl1 = sp.sourceLinks()[0].template get(); + + // This should be fine, because check in constructor + const Cluster* cl1 = clusters ? &clusters->at(sl1.index()) : nullptr; + const Cluster* cl2 = cl1; + + if (sp.sourceLinks().size() == 2) { + const auto& sl2 = sp.sourceLinks()[1].template get(); + cl2 = clusters ? &clusters->at(sl2.index()) : nullptr; + } + + // I would prefer to use a std::span or boost::span here once available + float* f = features.data() + isp * nodeFeatures.size(); + + using NF = TrackFindingAlgorithmExaTrkX::NodeFeature; + + using namespace Acts::VectorHelpers; + using namespace Acts::AngleHelpers; + + // clang-format off +#define MAKE_CLUSTER_FEATURES(n) \ + break; case NF::eCluster##n##X: f[ift] = cl##n->globalPosition[Acts::ePos0]; \ + break; case NF::eCluster##n##Y: f[ift] = cl##n->globalPosition[Acts::ePos1]; \ + break; case NF::eCluster##n##R: f[ift] = perp(cl##n->globalPosition); \ + break; case NF::eCluster##n##Phi: f[ift] = phi(cl##n->globalPosition); \ + break; case NF::eCluster##n##Z: f[ift] = cl##n->globalPosition[Acts::ePos2]; \ + break; case NF::eCluster##n##Eta: f[ift] = eta(cl##n->globalPosition); \ + break; case NF::eCellCount##n: f[ift] = cl##n->channels.size(); \ + break; case NF::eChargeSum##n: f[ift] = cl##n->sumActivations(); \ + break; case NF::eLocDir0##n: f[ift] = cl##n->localDirection[0]; \ + break; case NF::eLocDir1##n: f[ift] = cl##n->localDirection[1]; \ + break; case NF::eLocDir2##n: f[ift] = cl##n->localDirection[2]; \ + break; case NF::eLengthDir0##n: f[ift] = cl##n->lengthDirection[0]; \ + break; case NF::eLengthDir1##n: f[ift] = cl##n->lengthDirection[1]; \ + break; case NF::eLengthDir2##n: f[ift] = cl##n->lengthDirection[2]; \ + break; case NF::eLocEta##n: f[ift] = cl##n->localEta; \ + break; case NF::eLocPhi##n: f[ift] = cl##n->localPhi; \ + break; case NF::eGlobEta##n: f[ift] = cl##n->globalEta; \ + break; case NF::eGlobPhi##n: f[ift] = cl##n->globalPhi; \ + break; case NF::eEtaAngle##n: f[ift] = cl##n->etaAngle; \ + break; case NF::ePhiAngle##n: f[ift] = cl##n->phiAngle; + // clang-format on + + Acts::Vector3 spPos{sp.x(), sp.y(), sp.z()}; + + for (auto ift = 0ul; ift < nodeFeatures.size(); ++ift) { + // clang-format off + switch(nodeFeatures[ift]) { + // Spacepoint features + break; case NF::eR: f[ift] = perp(spPos); + break; case NF::ePhi: f[ift] = phi(spPos); + break; case NF::eZ: f[ift] = sp.z(); + break; case NF::eX: f[ift] = sp.x(); + break; case NF::eY: f[ift] = sp.y(); + break; case NF::eEta: f[ift] = eta(spPos); + // Single cluster features + break; case NF::eClusterLoc0: f[ift] = cl1->sizeLoc0; + break; case NF::eClusterLoc1: f[ift] = cl1->sizeLoc1; + break; case NF::eCellCount: f[ift] = cl1->channels.size(); + break; case NF::eChargeSum: f[ift] = cl1->sumActivations(); + // Features for split clusters + MAKE_CLUSTER_FEATURES(1) + MAKE_CLUSTER_FEATURES(2) + } + // clang-format on + + assert(std::isfinite(f[ift])); + f[ift] /= featureScales[ift]; + } +#undef MAKE_CLUSTER_FEATURES + } + + return features; +} + +} // namespace ActsExamples diff --git a/Examples/Algorithms/TrackFindingExaTrkX/src/createFeatures.hpp b/Examples/Algorithms/TrackFindingExaTrkX/src/createFeatures.hpp new file mode 100644 index 00000000000..dede5f3c11c --- /dev/null +++ b/Examples/Algorithms/TrackFindingExaTrkX/src/createFeatures.hpp @@ -0,0 +1,21 @@ +// 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/TrackFindingExaTrkX/TrackFindingAlgorithmExaTrkX.hpp" + +namespace ActsExamples { + +std::vector createFeatures( + const SimSpacePointContainer &spacepoints, + const std::optional &clusters, + const std::vector &nodeFeatures, + const std::vector &featureScales); + +} diff --git a/Examples/Algorithms/TrackFitting/src/RefittingCalibrator.cpp b/Examples/Algorithms/TrackFitting/src/RefittingCalibrator.cpp index b54efd0dcb4..154dc5d7285 100644 --- a/Examples/Algorithms/TrackFitting/src/RefittingCalibrator.cpp +++ b/Examples/Algorithms/TrackFitting/src/RefittingCalibrator.cpp @@ -30,14 +30,12 @@ void RefittingCalibrator::calibrate(const Acts::GeometryContext& /*gctx*/, using namespace Acts; constexpr int Size = decltype(N)::value; - trackState.allocateCalibrated(Size); - trackState.template calibrated() = - sl.state.template calibrated(); - trackState.template calibratedCovariance() = - sl.state.template calibratedCovariance(); + trackState.allocateCalibrated( + sl.state.template calibrated().eval(), + sl.state.template calibratedCovariance().eval()); }); - trackState.setBoundSubspaceIndices(sl.state.boundSubspaceIndices()); + trackState.setProjectorSubspaceIndices(sl.state.projectorSubspaceIndices()); } } // namespace ActsExamples diff --git a/Examples/Algorithms/TruthTracking/ActsExamples/TruthTracking/HitSelector.cpp b/Examples/Algorithms/TruthTracking/ActsExamples/TruthTracking/HitSelector.cpp new file mode 100644 index 00000000000..a494957a589 --- /dev/null +++ b/Examples/Algorithms/TruthTracking/ActsExamples/TruthTracking/HitSelector.cpp @@ -0,0 +1,97 @@ +// 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/TruthTracking/HitSelector.hpp" + +#include "Acts/Utilities/MathHelpers.hpp" +#include "ActsExamples/EventData/SimHit.hpp" +#include "ActsExamples/EventData/SimParticle.hpp" + +namespace ActsExamples { + +HitSelector::HitSelector(const Config& config, Acts::Logging::Level level) + : IAlgorithm("HitSelector", level), m_cfg(config) { + if (m_cfg.minX >= m_cfg.maxX || m_cfg.minY >= m_cfg.maxY || + m_cfg.minZ >= m_cfg.maxZ || m_cfg.minR >= m_cfg.maxR || + m_cfg.minTime >= m_cfg.maxTime || + m_cfg.minEnergyLoss >= m_cfg.maxEnergyLoss || + m_cfg.minPrimaryVertexId >= m_cfg.maxPrimaryVertexId) { + throw std::invalid_argument( + "Invalid bounds configuration: min values must be less than max " + "values"); + } + m_inputHits.initialize(m_cfg.inputHits); + m_inputParticlesSelected.maybeInitialize(m_cfg.inputParticlesSelected); + m_outputHits.initialize(m_cfg.outputHits); + + ACTS_DEBUG("selection particles " << m_cfg.inputParticlesSelected); + ACTS_DEBUG("selection hit x [" << m_cfg.minX << "," << m_cfg.maxX << ")"); + ACTS_DEBUG("selection hit y [" << m_cfg.minY << "," << m_cfg.maxY << ")"); + ACTS_DEBUG("selection hit z [" << m_cfg.minZ << "," << m_cfg.maxZ << ")"); + ACTS_DEBUG("selection hit r [" << m_cfg.minR << "," << m_cfg.maxR << ")"); + ACTS_DEBUG("selection hit time [" << m_cfg.minTime << "," << m_cfg.maxTime + << ")"); + ACTS_DEBUG("selection hit energy loss [" << m_cfg.minEnergyLoss << "," + << m_cfg.maxEnergyLoss << ")"); + ACTS_DEBUG("selection primary vertex ID [" << m_cfg.minPrimaryVertexId << "," + << m_cfg.maxPrimaryVertexId + << ")"); +} + +ProcessCode HitSelector::execute(const AlgorithmContext& ctx) const { + const SimHitContainer& hits = m_inputHits(ctx); + const SimParticleContainer* particlesSelected = + m_inputParticlesSelected.isInitialized() ? &m_inputParticlesSelected(ctx) + : nullptr; + + std::vector unorderedHits; + unorderedHits.reserve(hits.size()); + + for (const auto& hit : hits) { + const double r = Acts::fastHypot(hit.position().x(), hit.position().y()); + const std::uint64_t primaryVertexId = hit.particleId().vertexPrimary(); + + const bool validParticle = (particlesSelected == nullptr) || + particlesSelected->contains(hit.particleId()); + const bool validX = + (m_cfg.minX <= hit.position().x()) && (hit.position().x() < m_cfg.maxX); + const bool validY = + (m_cfg.minY <= hit.position().y()) && (hit.position().y() < m_cfg.maxY); + const bool validZ = + (m_cfg.minZ <= hit.position().z()) && (hit.position().z() < m_cfg.maxZ); + const bool validR = (m_cfg.minR <= r) && (r < m_cfg.maxR); + const bool validTime = + (m_cfg.minTime <= hit.time()) && (hit.time() < m_cfg.maxTime); + const bool validEnergyLoss = + (m_cfg.minEnergyLoss <= hit.depositedEnergy()) && + (hit.depositedEnergy() < m_cfg.maxEnergyLoss); + const bool validPrimaryVertexId = + (m_cfg.minPrimaryVertexId <= primaryVertexId) && + (primaryVertexId < m_cfg.maxPrimaryVertexId); + + const bool validHit = validParticle && validX && validY && validZ && + validR && validTime && validEnergyLoss && + validPrimaryVertexId; + if (validHit) { + unorderedHits.push_back(hit); + } + } + + // hits are still sorted after filtering + SimHitContainer selectedHits(boost::container::ordered_range_t{}, + unorderedHits.begin(), unorderedHits.end()); + + ACTS_DEBUG("selected " << selectedHits.size() << " from " << hits.size() + << " hits"); + + m_outputHits(ctx, std::move(selectedHits)); + + return ProcessCode::SUCCESS; +} + +} // namespace ActsExamples diff --git a/Examples/Algorithms/TruthTracking/ActsExamples/TruthTracking/HitSelector.hpp b/Examples/Algorithms/TruthTracking/ActsExamples/TruthTracking/HitSelector.hpp new file mode 100644 index 00000000000..37a4e8131ec --- /dev/null +++ b/Examples/Algorithms/TruthTracking/ActsExamples/TruthTracking/HitSelector.hpp @@ -0,0 +1,86 @@ +// 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/Utilities/Logger.hpp" +#include "ActsExamples/EventData/SimHit.hpp" +#include "ActsExamples/EventData/SimParticle.hpp" +#include "ActsExamples/Framework/DataHandle.hpp" +#include "ActsExamples/Framework/IAlgorithm.hpp" + +#include +#include + +namespace ActsExamples { + +/// Select hits by applying some selection cuts. +class HitSelector final : public IAlgorithm { + public: + struct Config { + /// Input hit collection. + std::string inputHits; + /// Optional input particle collection. + std::string inputParticlesSelected; + /// Output hit collection + std::string outputHits; + + /// Min x cut + double minX = -std::numeric_limits::max(); + /// Max x cut + double maxX = std::numeric_limits::max(); + + /// Min y cut + double minY = -std::numeric_limits::max(); + /// Max y cut + double maxY = std::numeric_limits::max(); + + /// Min z cut + double minZ = -std::numeric_limits::max(); + /// Max z cut + double maxZ = std::numeric_limits::max(); + + /// Min r cut + double minR = 0.0; + /// Max r cut + double maxR = std::numeric_limits::max(); + + /// Min time cut + double minTime = -std::numeric_limits::max(); + /// Max time cut + double maxTime = std::numeric_limits::max(); + + /// Min energy loss cut + double minEnergyLoss = 0; + /// Max energy loss cut + double maxEnergyLoss = std::numeric_limits::max(); + + /// Min primary vertex ID cut + std::uint64_t minPrimaryVertexId = 0; + /// Max primary vertex ID cut + std::uint64_t maxPrimaryVertexId = + std::numeric_limits::max(); + }; + + HitSelector(const Config& config, Acts::Logging::Level level); + + ProcessCode execute(const AlgorithmContext& ctx) const final; + + /// Get readonly access to the config parameters + const Config& config() const { return m_cfg; } + + private: + Config m_cfg; + + ReadDataHandle m_inputHits{this, "InputHits"}; + ReadDataHandle m_inputParticlesSelected{ + this, "InputParticlesSelected"}; + WriteDataHandle m_outputHits{this, "OutputHits"}; +}; + +} // namespace ActsExamples diff --git a/Examples/Algorithms/TruthTracking/ActsExamples/TruthTracking/ParticleSelector.cpp b/Examples/Algorithms/TruthTracking/ActsExamples/TruthTracking/ParticleSelector.cpp index 738399a1e42..b4ef0928da0 100644 --- a/Examples/Algorithms/TruthTracking/ActsExamples/TruthTracking/ParticleSelector.cpp +++ b/Examples/Algorithms/TruthTracking/ActsExamples/TruthTracking/ParticleSelector.cpp @@ -46,9 +46,17 @@ ActsExamples::ParticleSelector::ParticleSelector(const Config& config, << ")"); ACTS_DEBUG("selection particle m [" << m_cfg.mMin << "," << m_cfg.mMax << ")"); + ACTS_DEBUG("selection particle measurements [" + << m_cfg.measurementsMin << "," << m_cfg.measurementsMax << ")"); ACTS_DEBUG("remove charged particles " << m_cfg.removeCharged); ACTS_DEBUG("remove neutral particles " << m_cfg.removeNeutral); ACTS_DEBUG("remove secondary particles " << m_cfg.removeSecondaries); + ACTS_DEBUG("exclude pdgs: "); + for (auto pdg : m_cfg.excludeAbsPdgs) { + ACTS_DEBUG(" " << pdg); + } + ACTS_DEBUG("primary vertex ID [" << m_cfg.minPrimaryVertexId << "," + << m_cfg.maxPrimaryVertexId << ")"); } ActsExamples::ProcessCode ActsExamples::ParticleSelector::execute( @@ -73,6 +81,9 @@ ActsExamples::ProcessCode ActsExamples::ParticleSelector::execute( const bool validCharged = (p.charge() != 0) && !m_cfg.removeCharged; const bool validCharge = validNeutral || validCharged; const bool validSecondary = !m_cfg.removeSecondaries || !p.isSecondary(); + const bool validPrimaryVertexId = + within(p.particleId().vertexPrimary(), m_cfg.minPrimaryVertexId, + m_cfg.maxPrimaryVertexId); nInvalidCharge += static_cast(!validCharge); @@ -91,7 +102,8 @@ ActsExamples::ProcessCode ActsExamples::ParticleSelector::execute( } } - return validPdg && validCharge && validSecondary && validMeasurementCount && + return validPdg && validCharge && validSecondary && validPrimaryVertexId && + validMeasurementCount && within(p.transverseMomentum(), m_cfg.ptMin, m_cfg.ptMax) && within(std::abs(eta), m_cfg.absEtaMin, m_cfg.absEtaMax) && within(eta, m_cfg.etaMin, m_cfg.etaMax) && diff --git a/Examples/Algorithms/TruthTracking/ActsExamples/TruthTracking/ParticleSelector.hpp b/Examples/Algorithms/TruthTracking/ActsExamples/TruthTracking/ParticleSelector.hpp index 78326844f19..4bd465d1b4d 100644 --- a/Examples/Algorithms/TruthTracking/ActsExamples/TruthTracking/ParticleSelector.hpp +++ b/Examples/Algorithms/TruthTracking/ActsExamples/TruthTracking/ParticleSelector.hpp @@ -62,6 +62,12 @@ class ParticleSelector final : public IAlgorithm { bool removeSecondaries = false; /// Exclude particles depending on absolute pdg value std::vector excludeAbsPdgs; + + /// Min primary vertex ID cut + std::uint64_t minPrimaryVertexId = 0; + /// Max primary vertex ID cut + std::uint64_t maxPrimaryVertexId = + std::numeric_limits::max(); }; ParticleSelector(const Config& config, Acts::Logging::Level level); diff --git a/Examples/Algorithms/TruthTracking/ActsExamples/TruthTracking/ParticleSmearing.cpp b/Examples/Algorithms/TruthTracking/ActsExamples/TruthTracking/ParticleSmearing.cpp deleted file mode 100644 index 4c09134ef20..00000000000 --- a/Examples/Algorithms/TruthTracking/ActsExamples/TruthTracking/ParticleSmearing.cpp +++ /dev/null @@ -1,158 +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/TruthTracking/ParticleSmearing.hpp" - -#include "Acts/Definitions/Algebra.hpp" -#include "Acts/Definitions/TrackParametrization.hpp" -#include "Acts/Seeding/EstimateTrackParamsFromSeed.hpp" -#include "Acts/Surfaces/PerigeeSurface.hpp" -#include "Acts/Surfaces/Surface.hpp" -#include "Acts/Utilities/detail/periodic.hpp" -#include "ActsExamples/EventData/SimParticle.hpp" -#include "ActsExamples/EventData/Track.hpp" -#include "ActsExamples/Framework/AlgorithmContext.hpp" -#include "ActsExamples/Framework/RandomNumbers.hpp" - -#include -#include -#include -#include -#include - -ActsExamples::ParticleSmearing::ParticleSmearing(const Config& config, - Acts::Logging::Level level) - : IAlgorithm("ParticleSmearing", level), m_cfg(config) { - if (m_cfg.inputParticles.empty()) { - throw std::invalid_argument("Missing input truth particles collection"); - } - if (m_cfg.outputTrackParameters.empty()) { - throw std::invalid_argument("Missing output tracks parameters collection"); - } - if (m_cfg.randomNumbers == nullptr) { - throw std::invalid_argument("Missing random numbers tool"); - } - - if (m_cfg.particleHypothesis) { - ACTS_INFO("Override truth particle hypothesis with " - << *m_cfg.particleHypothesis); - } - - m_inputParticles.initialize(m_cfg.inputParticles); - m_outputTrackParameters.initialize(m_cfg.outputTrackParameters); -} - -ActsExamples::ProcessCode ActsExamples::ParticleSmearing::execute( - const AlgorithmContext& ctx) const { - // setup input and output containers - const auto& particles = m_inputParticles(ctx); - TrackParametersContainer parameters; - parameters.reserve(particles.size()); - - // setup random number generator and standard gaussian - auto rng = m_cfg.randomNumbers->spawnGenerator(ctx); - std::normal_distribution stdNormal(0.0, 1.0); - - for (auto&& [vtxId, vtxParticles] : groupBySecondaryVertex(particles)) { - // a group contains at least one particle by construction. assume that all - // particles within the group originate from the same position and use it to - // as the reference position for the perigee frame. - auto perigee = Acts::Surface::makeShared( - vtxParticles.begin()->position()); - - for (const auto& particle : vtxParticles) { - const auto time = particle.time(); - const auto phi = Acts::VectorHelpers::phi(particle.direction()); - const auto theta = Acts::VectorHelpers::theta(particle.direction()); - const auto pt = particle.transverseMomentum(); - const auto p = particle.absoluteMomentum(); - const auto qOverP = particle.qOverP(); - const auto particleHypothesis = - m_cfg.particleHypothesis.value_or(particle.hypothesis()); - - // compute momentum-dependent resolutions - const double sigmaD0 = - m_cfg.sigmaD0 + - m_cfg.sigmaD0PtA * std::exp(-1.0 * std::abs(m_cfg.sigmaD0PtB) * pt); - const double sigmaZ0 = - m_cfg.sigmaZ0 + - m_cfg.sigmaZ0PtA * std::exp(-1.0 * std::abs(m_cfg.sigmaZ0PtB) * pt); - // shortcuts for other resolutions - const double sigmaT0 = m_cfg.sigmaT0; - const double sigmaPhi = m_cfg.sigmaPhi; - const double sigmaTheta = m_cfg.sigmaTheta; - const double sigmaQOverP = - std::sqrt(std::pow(m_cfg.sigmaPtRel * qOverP, 2) + - std::pow(sigmaTheta * (qOverP * std::tan(theta)), 2)); - - Acts::BoundVector params = Acts::BoundVector::Zero(); - // smear the position/time - // note that we smear d0 and z0 in the perigee frame - params[Acts::eBoundLoc0] = sigmaD0 * stdNormal(rng); - params[Acts::eBoundLoc1] = sigmaZ0 * stdNormal(rng); - params[Acts::eBoundTime] = time + sigmaT0 * stdNormal(rng); - // smear direction angles phi,theta ensuring correct bounds - const auto [newPhi, newTheta] = Acts::detail::normalizePhiTheta( - phi + sigmaPhi * stdNormal(rng), theta + sigmaTheta * stdNormal(rng)); - params[Acts::eBoundPhi] = newPhi; - params[Acts::eBoundTheta] = newTheta; - // compute smeared q/p - params[Acts::eBoundQOverP] = qOverP + sigmaQOverP * stdNormal(rng); - - ACTS_VERBOSE("Smearing particle (pos, time, phi, theta, q/p):"); - ACTS_VERBOSE(" from: " << particle.position().transpose() << ", " << time - << ", " << phi << ", " << theta << ", " << qOverP); - ACTS_VERBOSE(" to: " << perigee - ->localToGlobal( - ctx.geoContext, - Acts::Vector2{params[Acts::eBoundLoc0], - params[Acts::eBoundLoc1]}, - particle.direction() * p) - .transpose() - << ", " << params[Acts::eBoundTime] << ", " - << params[Acts::eBoundPhi] << ", " - << params[Acts::eBoundTheta] << ", " - << params[Acts::eBoundQOverP]); - - // build the track covariance matrix using the smearing sigmas - Acts::BoundSquareMatrix cov = Acts::BoundSquareMatrix::Zero(); - if (m_cfg.initialSigmas) { - // use the initial sigmas if set - - Acts::EstimateTrackParamCovarianceConfig config{ - .initialSigmas = - Eigen::Map{ - m_cfg.initialSigmas->data()}, - .initialSigmaPtRel = m_cfg.initialSigmaPtRel, - .initialVarInflation = Eigen::Map{ - m_cfg.initialVarInflation.data()}}; - - cov = Acts::estimateTrackParamCovariance(config, params, false); - } else { - // otherwise use the smearing sigmas - - Acts::BoundVector sigmas = Acts::BoundVector( - {sigmaD0, sigmaZ0, sigmaPhi, sigmaTheta, sigmaQOverP, sigmaT0}); - - for (std::size_t i = Acts::eBoundLoc0; i < Acts::eBoundSize; ++i) { - double sigma = sigmas[i]; - double variance = sigma * sigma; - - // Inflate the initial covariance - variance *= m_cfg.initialVarInflation[i]; - - cov(i, i) = variance; - } - } - parameters.emplace_back(perigee, params, cov, particleHypothesis); - } - } - - m_outputTrackParameters(ctx, std::move(parameters)); - return ProcessCode::SUCCESS; -} diff --git a/Examples/Algorithms/TruthTracking/ActsExamples/TruthTracking/ParticleTrackParamExtractor.cpp b/Examples/Algorithms/TruthTracking/ActsExamples/TruthTracking/ParticleTrackParamExtractor.cpp new file mode 100644 index 00000000000..d480ca8f88f --- /dev/null +++ b/Examples/Algorithms/TruthTracking/ActsExamples/TruthTracking/ParticleTrackParamExtractor.cpp @@ -0,0 +1,72 @@ +// 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/TruthTracking/ParticleTrackParamExtractor.hpp" + +#include "Acts/Surfaces/PerigeeSurface.hpp" +#include "ActsExamples/EventData/SimParticle.hpp" +#include "ActsExamples/Framework/AlgorithmContext.hpp" + +#include +#include + +namespace ActsExamples { + +ParticleTrackParamExtractor::ParticleTrackParamExtractor( + const Config& config, Acts::Logging::Level level) + : IAlgorithm("ParticleTrackParamExtractor", level), m_cfg(config) { + if (m_cfg.inputParticles.empty()) { + throw std::invalid_argument("Missing input particles collection"); + } + if (m_cfg.outputTrackParameters.empty()) { + throw std::invalid_argument("Missing output track parameters collection"); + } + + m_inputParticles.initialize(m_cfg.inputParticles); + m_outputTrackParameters.initialize(m_cfg.outputTrackParameters); +} + +ActsExamples::ProcessCode ParticleTrackParamExtractor::execute( + const AlgorithmContext& ctx) const { + const SimParticleContainer& particles = m_inputParticles(ctx); + + std::unordered_map> + perigeeSurfaces; + + for (auto&& [vtxId, vtxParticles] : groupBySecondaryVertex(particles)) { + // a group contains at least one particle by construction. assume that all + // particles within the group originate from the same position and use it + // to as the reference position for the perigee frame. + auto perigee = Acts::Surface::makeShared( + vtxParticles.begin()->position()); + perigeeSurfaces[vtxId] = perigee; + } + + // create track parameters from the particles + TrackParametersContainer trackParameters; + + for (const auto& particle : particles) { + const auto vtxId = particle.particleId().vertexId(); + const auto particleHypothesis = particle.hypothesis(); + const auto phi = Acts::VectorHelpers::phi(particle.direction()); + const auto theta = Acts::VectorHelpers::theta(particle.direction()); + const auto qOverP = particle.qOverP(); + const auto time = particle.time(); + + trackParameters.emplace_back( + perigeeSurfaces.at(vtxId), + Acts::BoundVector{0, 0, phi, theta, qOverP, time}, std::nullopt, + particleHypothesis); + } + + m_outputTrackParameters(ctx, std::move(trackParameters)); + + return ProcessCode::SUCCESS; +} + +} // namespace ActsExamples diff --git a/Examples/Algorithms/Utilities/include/ActsExamples/Utilities/HitSelector.hpp b/Examples/Algorithms/TruthTracking/ActsExamples/TruthTracking/ParticleTrackParamExtractor.hpp similarity index 52% rename from Examples/Algorithms/Utilities/include/ActsExamples/Utilities/HitSelector.hpp rename to Examples/Algorithms/TruthTracking/ActsExamples/TruthTracking/ParticleTrackParamExtractor.hpp index bb1f7ba24e8..60882fa9ace 100644 --- a/Examples/Algorithms/Utilities/include/ActsExamples/Utilities/HitSelector.hpp +++ b/Examples/Algorithms/TruthTracking/ActsExamples/TruthTracking/ParticleTrackParamExtractor.hpp @@ -8,32 +8,29 @@ #pragma once -#include "Acts/TrackFinding/TrackSelector.hpp" #include "Acts/Utilities/Logger.hpp" -#include "ActsExamples/EventData/SimHit.hpp" +#include "ActsExamples/EventData/SimParticle.hpp" +#include "ActsExamples/EventData/Track.hpp" #include "ActsExamples/Framework/DataHandle.hpp" #include "ActsExamples/Framework/IAlgorithm.hpp" +#include "ActsExamples/Framework/ProcessCode.hpp" -#include -#include #include namespace ActsExamples { +struct AlgorithmContext; -/// Select tracks by applying some selection cuts. -class HitSelector final : public IAlgorithm { +/// Extract track parameters from particles. +class ParticleTrackParamExtractor final : public IAlgorithm { public: struct Config { - /// Input track collection. - std::string inputHits; - /// Output track collection - std::string outputHits; - - /// Time cut - double maxTime = std::numeric_limits::max(); + /// The input particles collection. + std::string inputParticles; + /// The output track parameters collection. + std::string outputTrackParameters; }; - HitSelector(const Config& config, Acts::Logging::Level level); + ParticleTrackParamExtractor(const Config& config, Acts::Logging::Level level); ProcessCode execute(const AlgorithmContext& ctx) const final; @@ -43,8 +40,9 @@ class HitSelector final : public IAlgorithm { private: Config m_cfg; - ReadDataHandle m_inputHits{this, "InputHits"}; - WriteDataHandle m_outputHits{this, "OutputHits"}; + ReadDataHandle m_inputParticles{this, "InputParticles"}; + WriteDataHandle m_outputTrackParameters{ + this, "OutputTrackParameters"}; }; } // namespace ActsExamples diff --git a/Examples/Algorithms/TruthTracking/ActsExamples/TruthTracking/TrackParameterSmearing.cpp b/Examples/Algorithms/TruthTracking/ActsExamples/TruthTracking/TrackParameterSmearing.cpp new file mode 100644 index 00000000000..f1789749f77 --- /dev/null +++ b/Examples/Algorithms/TruthTracking/ActsExamples/TruthTracking/TrackParameterSmearing.cpp @@ -0,0 +1,175 @@ +// 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/TruthTracking/TrackParameterSmearing.hpp" + +#include "Acts/Seeding/EstimateTrackParamsFromSeed.hpp" +#include "ActsExamples/EventData/Track.hpp" +#include "ActsExamples/Framework/AlgorithmContext.hpp" +#include "ActsExamples/Framework/RandomNumbers.hpp" + +#include +#include +#include + +namespace ActsExamples { + +TrackParameterSmearing::TrackParameterSmearing(const Config& config, + Acts::Logging::Level level) + : IAlgorithm("TrackParameterSmearing", level), m_cfg(config) { + if (m_cfg.inputTrackParameters.empty()) { + throw std::invalid_argument("Missing input track parameters collection"); + } + if (m_cfg.outputTrackParameters.empty()) { + throw std::invalid_argument("Missing output track parameters collection"); + } + if (m_cfg.randomNumbers == nullptr) { + throw std::invalid_argument("Missing random numbers tool"); + } + + if (m_cfg.particleHypothesis) { + ACTS_INFO("Override truth particle hypothesis with " + << *m_cfg.particleHypothesis); + } + + m_inputTrackParameters.initialize(m_cfg.inputTrackParameters); + m_outputTrackParameters.initialize(m_cfg.outputTrackParameters); + + ACTS_DEBUG("smearing track param loc0 " << m_cfg.sigmaLoc0 << " A " + << m_cfg.sigmaLoc0PtA << " B " + << m_cfg.sigmaLoc0PtB); + ACTS_DEBUG("smearing track param loc1 " << m_cfg.sigmaLoc1 << " A " + << m_cfg.sigmaLoc1PtA << " B " + << m_cfg.sigmaLoc1PtB); + ACTS_DEBUG("smearing track param time " << m_cfg.sigmaTime); + ACTS_DEBUG("smearing track param phi " << m_cfg.sigmaPhi); + ACTS_DEBUG("smearing track param theta " << m_cfg.sigmaTheta); + ACTS_DEBUG("smearing track param q/p " << m_cfg.sigmaPtRel); + ACTS_DEBUG( + "initial sigmas " + << Acts::BoundVector( + m_cfg.initialSigmas.value_or(std::array()).data()) + .transpose()); + ACTS_DEBUG("initial sigma pt rel " << m_cfg.initialSigmaPtRel); + ACTS_DEBUG( + "initial var inflation " + << Acts::BoundVector(m_cfg.initialVarInflation.data()).transpose()); + if (m_cfg.particleHypothesis) { + ACTS_DEBUG("particle hypothesis " << *m_cfg.particleHypothesis); + } else { + ACTS_DEBUG("particle hypothesis truth"); + } +} + +ProcessCode TrackParameterSmearing::execute(const AlgorithmContext& ctx) const { + // setup input and output containers + const auto& inputTrackParametersContainer = m_inputTrackParameters(ctx); + + ACTS_VERBOSE("Smearing " << inputTrackParametersContainer.size() + << " track parameters"); + + TrackParametersContainer outputTrackParametersContainer; + outputTrackParametersContainer.reserve(inputTrackParametersContainer.size()); + + // setup random number generator and standard gaussian + auto rng = m_cfg.randomNumbers->spawnGenerator(ctx); + std::normal_distribution stdNormal(0.0, 1.0); + + for (const auto& inputTrackParameters : inputTrackParametersContainer) { + const auto position = inputTrackParameters.localPosition(); + const auto time = inputTrackParameters.time(); + const auto phi = inputTrackParameters.phi(); + const auto theta = inputTrackParameters.theta(); + const auto pt = inputTrackParameters.transverseMomentum(); + const auto qOverP = inputTrackParameters.qOverP(); + const auto particleHypothesis = m_cfg.particleHypothesis.value_or( + inputTrackParameters.particleHypothesis()); + + // compute momentum-dependent resolutions + const double sigmaLoc0 = + m_cfg.sigmaLoc0 + + m_cfg.sigmaLoc0PtA * std::exp(-1.0 * std::abs(m_cfg.sigmaLoc0PtB) * pt); + const double sigmaLoc1 = + m_cfg.sigmaLoc1 + + m_cfg.sigmaLoc1PtA * std::exp(-1.0 * std::abs(m_cfg.sigmaLoc1PtB) * pt); + // shortcuts for other resolutions + const double sigmaTime = m_cfg.sigmaTime; + const double sigmaPhi = m_cfg.sigmaPhi; + const double sigmaTheta = m_cfg.sigmaTheta; + const double sigmaQOverP = + std::sqrt(std::pow(m_cfg.sigmaPtRel * qOverP, 2) + + std::pow(sigmaTheta * (qOverP * std::tan(theta)), 2)); + + Acts::BoundVector params = Acts::BoundVector::Zero(); + // smear the position/time + // note that we smear d0 and z0 in the perigee frame + params[Acts::eBoundLoc0] = position[0] + sigmaLoc0 * stdNormal(rng); + params[Acts::eBoundLoc1] = position[1] + sigmaLoc1 * stdNormal(rng); + params[Acts::eBoundTime] = time + sigmaTime * stdNormal(rng); + // smear direction angles phi,theta ensuring correct bounds + const auto [newPhi, newTheta] = Acts::detail::normalizePhiTheta( + phi + sigmaPhi * stdNormal(rng), theta + sigmaTheta * stdNormal(rng)); + params[Acts::eBoundPhi] = newPhi; + params[Acts::eBoundTheta] = newTheta; + // compute smeared q/p + params[Acts::eBoundQOverP] = qOverP + sigmaQOverP * stdNormal(rng); + + // build the track covariance matrix using the smearing sigmas + Acts::BoundSquareMatrix cov = Acts::BoundSquareMatrix::Zero(); + if (m_cfg.initialSigmas) { + // use the initial sigmas if set + + Acts::EstimateTrackParamCovarianceConfig config{ + .initialSigmas = + Eigen::Map{m_cfg.initialSigmas->data()}, + .initialSigmaPtRel = m_cfg.initialSigmaPtRel, + .initialVarInflation = Eigen::Map{ + m_cfg.initialVarInflation.data()}}; + + cov = Acts::estimateTrackParamCovariance(config, params, false); + } else { + // otherwise use the smearing sigmas + + Acts::BoundVector sigmas = Acts::BoundVector( + {sigmaLoc0, sigmaLoc1, sigmaPhi, sigmaTheta, sigmaQOverP, sigmaTime}); + + for (std::size_t i = Acts::eBoundLoc0; i < Acts::eBoundSize; ++i) { + double sigma = sigmas[i]; + double variance = sigma * sigma; + + // Inflate the initial covariance + variance *= m_cfg.initialVarInflation[i]; + + cov(i, i) = variance; + } + } + + const auto& outputTrackParameters = + outputTrackParametersContainer.emplace_back( + inputTrackParameters.referenceSurface().shared_from_this(), params, + cov, particleHypothesis); + + ACTS_VERBOSE("Smearing particle (pos, time, phi, theta, q/p):"); + ACTS_VERBOSE( + " from: " << inputTrackParameters.position(ctx.geoContext).transpose() + << ", " << time << ", " << phi << ", " << theta << ", " + << qOverP); + ACTS_VERBOSE( + " to: " << outputTrackParameters.position(ctx.geoContext).transpose() + << ", " << params[Acts::eBoundTime] << ", " + << params[Acts::eBoundPhi] << ", " + << params[Acts::eBoundTheta] << ", " + << params[Acts::eBoundQOverP]); + } + + m_outputTrackParameters(ctx, std::move(outputTrackParametersContainer)); + + return ProcessCode::SUCCESS; +} + +} // namespace ActsExamples diff --git a/Examples/Algorithms/TruthTracking/ActsExamples/TruthTracking/ParticleSmearing.hpp b/Examples/Algorithms/TruthTracking/ActsExamples/TruthTracking/TrackParameterSmearing.hpp similarity index 61% rename from Examples/Algorithms/TruthTracking/ActsExamples/TruthTracking/ParticleSmearing.hpp rename to Examples/Algorithms/TruthTracking/ActsExamples/TruthTracking/TrackParameterSmearing.hpp index 3b60f12b099..53bab3b62e5 100644 --- a/Examples/Algorithms/TruthTracking/ActsExamples/TruthTracking/ParticleSmearing.hpp +++ b/Examples/Algorithms/TruthTracking/ActsExamples/TruthTracking/TrackParameterSmearing.hpp @@ -11,7 +11,6 @@ #include "Acts/Definitions/Units.hpp" #include "Acts/EventData/ParticleHypothesis.hpp" #include "Acts/Utilities/Logger.hpp" -#include "ActsExamples/EventData/SimParticle.hpp" #include "ActsExamples/EventData/Track.hpp" #include "ActsExamples/Framework/DataHandle.hpp" #include "ActsExamples/Framework/IAlgorithm.hpp" @@ -19,7 +18,6 @@ #include "ActsExamples/Framework/RandomNumbers.hpp" #include -#include #include #include #include @@ -28,36 +26,38 @@ namespace ActsExamples { class RandomNumbers; struct AlgorithmContext; -/// Create track states by smearing truth particle information. +/// @brief Smear track parameters. /// -/// Particles are smeared in the perigee frame anchored at their true vertex -/// position. The `d0` and `z0` parameters are always defined within that -/// perigee frame and not globally. The generated bound parameters are stored in -/// the same order as the input particles. -class ParticleSmearing final : public IAlgorithm { +/// Track parameters are smeared in the local frame. The `loc0` and `loc1` +/// parameters are always defined within that local frame and not globally. The +/// generated bound parameters are stored in the same order as the input +/// parameters. +class TrackParameterSmearing final : public IAlgorithm { public: struct Config { - /// Input truth particles collection. - std::string inputParticles; - /// Output smeared tracks parameters collection. + /// Input track parameters collection. + std::string inputTrackParameters; + /// Output smeared track parameters collection. std::string outputTrackParameters; /// Random numbers service. std::shared_ptr randomNumbers = nullptr; // Smearing parameters - /// Constant term of the d0 resolution. - double sigmaD0 = 20 * Acts::UnitConstants::um; - /// Pt-dependent d0 resolution of the form sigma_d0 = A*exp(-1.*abs(B)*pt). - double sigmaD0PtA = 30 * Acts::UnitConstants::um; - double sigmaD0PtB = 0.3 / Acts::UnitConstants::GeV; - /// Constant term of the z0 resolution. - double sigmaZ0 = 20 * Acts::UnitConstants::um; - /// Pt-dependent z0 resolution of the form sigma_z0 = A*exp(-1.*abs(B)*pt). - double sigmaZ0PtA = 30 * Acts::UnitConstants::um; - double sigmaZ0PtB = 0.3 / Acts::UnitConstants::GeV; + /// Constant term of the loc0 resolution. + double sigmaLoc0 = 20 * Acts::UnitConstants::um; + /// Pt-dependent loc0 resolution of the form sigma_loc0 = + /// A*exp(-1.*abs(B)*pt). + double sigmaLoc0PtA = 30 * Acts::UnitConstants::um; + double sigmaLoc0PtB = 0.3 / Acts::UnitConstants::GeV; + /// Constant term of the loc1 resolution. + double sigmaLoc1 = 20 * Acts::UnitConstants::um; + /// Pt-dependent loc1 resolution of the form sigma_loc1 = + /// A*exp(-1.*abs(B)*pt). + double sigmaLoc1PtA = 30 * Acts::UnitConstants::um; + double sigmaLoc1PtB = 0.3 / Acts::UnitConstants::GeV; /// Time resolution. - double sigmaT0 = 1 * Acts::UnitConstants::ns; + double sigmaTime = 1 * Acts::UnitConstants::ns; /// Phi angular resolution. double sigmaPhi = 1 * Acts::UnitConstants::degree; /// Theta angular resolution. @@ -77,7 +77,7 @@ class ParticleSmearing final : public IAlgorithm { std::optional particleHypothesis = std::nullopt; }; - ParticleSmearing(const Config& config, Acts::Logging::Level level); + TrackParameterSmearing(const Config& config, Acts::Logging::Level level); ProcessCode execute(const AlgorithmContext& ctx) const override; @@ -87,7 +87,8 @@ class ParticleSmearing final : public IAlgorithm { private: Config m_cfg; - ReadDataHandle m_inputParticles{this, "InputParticles"}; + ReadDataHandle m_inputTrackParameters{ + this, "InputTrackParameters"}; WriteDataHandle m_outputTrackParameters{ this, "OutputTrackParameters"}; diff --git a/Examples/Algorithms/TruthTracking/CMakeLists.txt b/Examples/Algorithms/TruthTracking/CMakeLists.txt index 4594cdb7480..9f576efa1b4 100644 --- a/Examples/Algorithms/TruthTracking/CMakeLists.txt +++ b/Examples/Algorithms/TruthTracking/CMakeLists.txt @@ -2,13 +2,15 @@ add_library( ActsExamplesTruthTracking SHARED ActsExamples/TruthTracking/ParticleSelector.cpp - ActsExamples/TruthTracking/ParticleSmearing.cpp + ActsExamples/TruthTracking/ParticleTrackParamExtractor.cpp + ActsExamples/TruthTracking/TrackParameterSmearing.cpp ActsExamples/TruthTracking/TrackParameterSelector.cpp ActsExamples/TruthTracking/TrackModifier.cpp ActsExamples/TruthTracking/TrackTruthMatcher.cpp ActsExamples/TruthTracking/TruthTrackFinder.cpp ActsExamples/TruthTracking/TruthVertexFinder.cpp ActsExamples/TruthTracking/TruthSeedingAlgorithm.cpp + ActsExamples/TruthTracking/HitSelector.cpp ) target_include_directories( ActsExamplesTruthTracking diff --git a/Examples/Algorithms/Utilities/CMakeLists.txt b/Examples/Algorithms/Utilities/CMakeLists.txt index ba9419c1914..309ff662bc6 100644 --- a/Examples/Algorithms/Utilities/CMakeLists.txt +++ b/Examples/Algorithms/Utilities/CMakeLists.txt @@ -7,7 +7,6 @@ add_library( src/TrackSelectorAlgorithm.cpp src/TracksToTrajectories.cpp src/PrototracksToTracks.cpp - src/HitSelector.cpp src/TracksToParameters.cpp ) target_include_directories( diff --git a/Examples/Algorithms/Utilities/src/HitSelector.cpp b/Examples/Algorithms/Utilities/src/HitSelector.cpp deleted file mode 100644 index c9a33b5f65a..00000000000 --- a/Examples/Algorithms/Utilities/src/HitSelector.cpp +++ /dev/null @@ -1,33 +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/Utilities/HitSelector.hpp" - -ActsExamples::HitSelector::HitSelector(const Config& config, - Acts::Logging::Level level) - : IAlgorithm("HitSelector", level), m_cfg(config) { - m_inputHits.initialize(m_cfg.inputHits); - m_outputHits.initialize(m_cfg.outputHits); -} - -ActsExamples::ProcessCode ActsExamples::HitSelector::execute( - const ActsExamples::AlgorithmContext& ctx) const { - const auto& hits = m_inputHits(ctx); - SimHitContainer selectedHits; - - std::copy_if(hits.begin(), hits.end(), - std::inserter(selectedHits, selectedHits.begin()), - [&](const auto& hit) { return hit.time() < m_cfg.maxTime; }); - - ACTS_DEBUG("selected " << selectedHits.size() << " from " << hits.size() - << " hits"); - - m_outputHits(ctx, std::move(selectedHits)); - - return {}; -} diff --git a/Examples/Detectors/ContextualDetector/include/ActsExamples/ContextualDetector/AlignedDetector.hpp b/Examples/Detectors/ContextualDetector/include/ActsExamples/ContextualDetector/AlignedDetector.hpp index 66a0f3b6b42..cfd12568d63 100644 --- a/Examples/Detectors/ContextualDetector/include/ActsExamples/ContextualDetector/AlignedDetector.hpp +++ b/Examples/Detectors/ContextualDetector/include/ActsExamples/ContextualDetector/AlignedDetector.hpp @@ -23,20 +23,16 @@ class IMaterialDecorator; } // namespace Acts namespace ActsExamples { + class IContextDecorator; -namespace Generic { class GenericDetectorElement; -} // namespace Generic -} // namespace ActsExamples -namespace ActsExamples::Contextual { class InternallyAlignedDetectorElement; class InternalAlignmentDecorator; class AlignedDetector { public: - using ContextDecorators = - std::vector>; + using ContextDecorators = std::vector>; using TrackingGeometryPtr = std::shared_ptr; struct Config : public GenericDetector::Config { @@ -69,15 +65,15 @@ class AlignedDetector { const Config& cfg, std::shared_ptr mdecorator); - std::vector>>& + std::vector>>& detectorStore() { return m_detectorStore; } private: /// The Store of the detector elements (lifetime: job) - std::vector>> + std::vector>> m_detectorStore; }; -} // namespace ActsExamples::Contextual +} // namespace ActsExamples diff --git a/Examples/Detectors/ContextualDetector/include/ActsExamples/ContextualDetector/AlignmentDecorator.hpp b/Examples/Detectors/ContextualDetector/include/ActsExamples/ContextualDetector/AlignmentDecorator.hpp index 1edf7e03d06..27bc1272fcf 100644 --- a/Examples/Detectors/ContextualDetector/include/ActsExamples/ContextualDetector/AlignmentDecorator.hpp +++ b/Examples/Detectors/ContextualDetector/include/ActsExamples/ContextualDetector/AlignmentDecorator.hpp @@ -9,17 +9,10 @@ #pragma once #include "Acts/Definitions/Algebra.hpp" -#include "Acts/Utilities/Logger.hpp" -#include "ActsExamples/ContextualDetector/InternallyAlignedDetectorElement.hpp" -#include "ActsExamples/Framework/AlgorithmContext.hpp" #include "ActsExamples/Framework/IContextDecorator.hpp" #include "ActsExamples/Framework/RandomNumbers.hpp" -#include -#include -#include - -namespace ActsExamples::Contextual { +namespace ActsExamples { /// @brief A mockup service that rotates the modules in a /// simple tracking geometry @@ -85,4 +78,5 @@ class AlignmentDecorator : public IContextDecorator { } } }; -} // namespace ActsExamples::Contextual + +} // namespace ActsExamples diff --git a/Examples/Detectors/ContextualDetector/include/ActsExamples/ContextualDetector/ExternalAlignmentDecorator.hpp b/Examples/Detectors/ContextualDetector/include/ActsExamples/ContextualDetector/ExternalAlignmentDecorator.hpp index de3f58b7e0a..6b873a0bdc9 100644 --- a/Examples/Detectors/ContextualDetector/include/ActsExamples/ContextualDetector/ExternalAlignmentDecorator.hpp +++ b/Examples/Detectors/ContextualDetector/include/ActsExamples/ContextualDetector/ExternalAlignmentDecorator.hpp @@ -9,12 +9,10 @@ #pragma once #include "Acts/Definitions/Algebra.hpp" -#include "Acts/Geometry/GeometryContext.hpp" #include "Acts/Utilities/Logger.hpp" #include "ActsExamples/ContextualDetector/AlignmentDecorator.hpp" #include "ActsExamples/ContextualDetector/ExternallyAlignedDetectorElement.hpp" #include "ActsExamples/Framework/AlgorithmContext.hpp" -#include "ActsExamples/Framework/IContextDecorator.hpp" #include "ActsExamples/Framework/ProcessCode.hpp" #include @@ -31,8 +29,6 @@ class TrackingGeometry; namespace ActsExamples { struct AlgorithmContext; -namespace Contextual { - /// @brief A mockup service that rotates the modules in a /// simple tracking geometry /// @@ -96,6 +92,5 @@ class ExternalAlignmentDecorator : public AlignmentDecorator { /// @param tGeometry the tracking geometry void parseGeometry(const Acts::TrackingGeometry& tGeometry); }; -} // namespace Contextual } // namespace ActsExamples diff --git a/Examples/Detectors/ContextualDetector/include/ActsExamples/ContextualDetector/ExternallyAlignedDetectorElement.hpp b/Examples/Detectors/ContextualDetector/include/ActsExamples/ContextualDetector/ExternallyAlignedDetectorElement.hpp index 7456b9bb61e..f504b3a7c4a 100644 --- a/Examples/Detectors/ContextualDetector/include/ActsExamples/ContextualDetector/ExternallyAlignedDetectorElement.hpp +++ b/Examples/Detectors/ContextualDetector/include/ActsExamples/ContextualDetector/ExternallyAlignedDetectorElement.hpp @@ -10,13 +10,9 @@ #include "Acts/Definitions/Algebra.hpp" #include "Acts/Geometry/GeometryContext.hpp" -#include "Acts/Geometry/GeometryIdentifier.hpp" -#include "Acts/Surfaces/Surface.hpp" #include "ActsExamples/GenericDetector/GenericDetectorElement.hpp" -#include - -namespace ActsExamples::Contextual { +namespace ActsExamples { /// @class ExternallyAlignedDetectorElement extends GenericDetectorElement /// @@ -34,8 +30,7 @@ namespace ActsExamples::Contextual { /// In this simple implementation, it does rely on the Identifier /// to be orderded from 0 to N-1, as the identifier is simply taken /// as a vector index for the alignment store -class ExternallyAlignedDetectorElement - : public Generic::GenericDetectorElement { +class ExternallyAlignedDetectorElement : public GenericDetectorElement { public: struct AlignmentStore { // GenericDetector identifiers are sequential @@ -50,7 +45,7 @@ class ExternallyAlignedDetectorElement std::shared_ptr alignmentStore{nullptr}; }; - using Generic::GenericDetectorElement::GenericDetectorElement; + using GenericDetectorElement::GenericDetectorElement; /// Return local to global transform associated with this identifier /// @@ -80,4 +75,4 @@ inline const Acts::Transform3& ExternallyAlignedDetectorElement::transform( return alignContext.alignmentStore->transforms[idValue]; } -} // namespace ActsExamples::Contextual +} // namespace ActsExamples diff --git a/Examples/Detectors/ContextualDetector/include/ActsExamples/ContextualDetector/InternalAlignmentDecorator.hpp b/Examples/Detectors/ContextualDetector/include/ActsExamples/ContextualDetector/InternalAlignmentDecorator.hpp index e9af06d7755..d571c02ec2c 100644 --- a/Examples/Detectors/ContextualDetector/include/ActsExamples/ContextualDetector/InternalAlignmentDecorator.hpp +++ b/Examples/Detectors/ContextualDetector/include/ActsExamples/ContextualDetector/InternalAlignmentDecorator.hpp @@ -8,12 +8,10 @@ #pragma once -#include "Acts/Definitions/Algebra.hpp" #include "Acts/Utilities/Logger.hpp" #include "ActsExamples/ContextualDetector/AlignmentDecorator.hpp" #include "ActsExamples/ContextualDetector/InternallyAlignedDetectorElement.hpp" #include "ActsExamples/Framework/AlgorithmContext.hpp" -#include "ActsExamples/Framework/IContextDecorator.hpp" #include "ActsExamples/Framework/ProcessCode.hpp" #include "ActsExamples/Framework/RandomNumbers.hpp" @@ -25,9 +23,6 @@ #include namespace ActsExamples { -struct AlgorithmContext; - -namespace Contextual { class InternallyAlignedDetectorElement; /// @brief A mockup service that rotates the modules in a @@ -87,5 +82,5 @@ class InternalAlignmentDecorator : public AlignmentDecorator { /// Private access to the logging instance const Acts::Logger& logger() const { return *m_logger; } }; -} // namespace Contextual + } // namespace ActsExamples diff --git a/Examples/Detectors/ContextualDetector/include/ActsExamples/ContextualDetector/InternallyAlignedDetectorElement.hpp b/Examples/Detectors/ContextualDetector/include/ActsExamples/ContextualDetector/InternallyAlignedDetectorElement.hpp index aaa1c8d9b98..68c958e87b0 100644 --- a/Examples/Detectors/ContextualDetector/include/ActsExamples/ContextualDetector/InternallyAlignedDetectorElement.hpp +++ b/Examples/Detectors/ContextualDetector/include/ActsExamples/ContextualDetector/InternallyAlignedDetectorElement.hpp @@ -10,16 +10,12 @@ #include "Acts/Definitions/Algebra.hpp" #include "Acts/Geometry/GeometryContext.hpp" -#include "Acts/Geometry/GeometryIdentifier.hpp" -#include "Acts/Surfaces/Surface.hpp" #include "ActsExamples/GenericDetector/GenericDetectorElement.hpp" -#include -#include #include #include -namespace ActsExamples::Contextual { +namespace ActsExamples { /// @class InternallyAlignedDetectorElement extends GenericDetectorElement /// @@ -33,8 +29,7 @@ namespace ActsExamples::Contextual { /// store and then in a contextual call the actual detector element /// position is taken internal multi component store - the latter /// has to be filled though from an external source -class InternallyAlignedDetectorElement - : public Generic::GenericDetectorElement { +class InternallyAlignedDetectorElement : public GenericDetectorElement { public: struct ContextType { /// The current interval of validity @@ -43,7 +38,7 @@ class InternallyAlignedDetectorElement }; // Inherit constructor - using Generic::GenericDetectorElement::GenericDetectorElement; + using GenericDetectorElement::GenericDetectorElement; /// Return local to global transform associated with this identifier /// @@ -117,4 +112,4 @@ inline void InternallyAlignedDetectorElement::clearAlignedTransform( } } -} // namespace ActsExamples::Contextual +} // namespace ActsExamples diff --git a/Examples/Detectors/ContextualDetector/src/AlignedDetector.cpp b/Examples/Detectors/ContextualDetector/src/AlignedDetector.cpp index 044cc943a81..84e050c8470 100644 --- a/Examples/Detectors/ContextualDetector/src/AlignedDetector.cpp +++ b/Examples/Detectors/ContextualDetector/src/AlignedDetector.cpp @@ -8,8 +8,7 @@ #include "ActsExamples/ContextualDetector/AlignedDetector.hpp" -#include "Acts/Definitions/Units.hpp" -#include "Acts/Geometry/ILayerBuilder.hpp" +#include "Acts/Geometry/GeometryContext.hpp" #include "Acts/Geometry/TrackingGeometry.hpp" #include "Acts/Utilities/Logger.hpp" #include "ActsExamples/ContextualDetector/AlignmentDecorator.hpp" @@ -19,10 +18,8 @@ #include "ActsExamples/ContextualDetector/InternallyAlignedDetectorElement.hpp" #include "ActsExamples/Framework/RandomNumbers.hpp" #include "ActsExamples/GenericDetector/BuildGenericDetector.hpp" -#include "ActsExamples/GenericDetector/ProtoLayerCreatorT.hpp" -using namespace Acts::UnitLiterals; -namespace ActsExamples::Contextual { +namespace ActsExamples { auto AlignedDetector::finalize( const Config& cfg, @@ -31,10 +28,9 @@ auto AlignedDetector::finalize( ContextDecorators aContextDecorators; // Let's create a random number service - ActsExamples::RandomNumbers::Config randomNumberConfig; + RandomNumbers::Config randomNumberConfig; randomNumberConfig.seed = cfg.seed; - auto randomNumberSvc = - std::make_shared(randomNumberConfig); + auto randomNumberSvc = std::make_shared(randomNumberConfig); auto fillDecoratorConfig = [&](AlignmentDecorator::Config& config) { config.iovSize = cfg.iovSize; @@ -55,6 +51,7 @@ auto AlignedDetector::finalize( TrackingGeometryPtr aTrackingGeometry; if (cfg.mode == Config::Mode::External) { ExternallyAlignedDetectorElement::ContextType nominalContext; + Acts::GeometryContext geometryContext(nominalContext); ExternalAlignmentDecorator::Config agcsConfig; fillDecoratorConfig(agcsConfig); @@ -63,8 +60,8 @@ auto AlignedDetector::finalize( detectorStore; aTrackingGeometry = - ActsExamples::Generic::buildDetector( - nominalContext, detectorStore, cfg.buildLevel, + Generic::buildDetector( + geometryContext, detectorStore, cfg.buildLevel, std::move(mdecorator), cfg.buildProto, cfg.surfaceLogLevel, cfg.layerLogLevel, cfg.volumeLogLevel); @@ -84,13 +81,14 @@ auto AlignedDetector::finalize( } else { InternallyAlignedDetectorElement::ContextType nominalContext; nominalContext.nominal = true; + Acts::GeometryContext geometryContext(nominalContext); InternalAlignmentDecorator::Config agcsConfig; fillDecoratorConfig(agcsConfig); aTrackingGeometry = - ActsExamples::Generic::buildDetector( - nominalContext, agcsConfig.detectorStore, cfg.buildLevel, + Generic::buildDetector( + geometryContext, agcsConfig.detectorStore, cfg.buildLevel, std::move(mdecorator), cfg.buildProto, cfg.surfaceLogLevel, cfg.layerLogLevel, cfg.volumeLogLevel); @@ -112,4 +110,4 @@ auto AlignedDetector::finalize( std::move(aTrackingGeometry), std::move(aContextDecorators)); } -} // namespace ActsExamples::Contextual +} // namespace ActsExamples diff --git a/Examples/Detectors/ContextualDetector/src/ExternalAlignmentDecorator.cpp b/Examples/Detectors/ContextualDetector/src/ExternalAlignmentDecorator.cpp index bca56249419..5120a29c334 100644 --- a/Examples/Detectors/ContextualDetector/src/ExternalAlignmentDecorator.cpp +++ b/Examples/Detectors/ContextualDetector/src/ExternalAlignmentDecorator.cpp @@ -10,7 +10,6 @@ #include "Acts/Geometry/GeometryContext.hpp" #include "Acts/Geometry/TrackingGeometry.hpp" -#include "Acts/Surfaces/SurfaceArray.hpp" #include "ActsExamples/ContextualDetector/ExternallyAlignedDetectorElement.hpp" #include "ActsExamples/Framework/AlgorithmContext.hpp" #include "ActsExamples/Framework/RandomNumbers.hpp" @@ -20,9 +19,10 @@ #include #include -ActsExamples::Contextual::ExternalAlignmentDecorator:: - ExternalAlignmentDecorator(const Config& cfg, - std::unique_ptr logger) +namespace ActsExamples { + +ExternalAlignmentDecorator::ExternalAlignmentDecorator( + const Config& cfg, std::unique_ptr logger) : m_cfg(cfg), m_logger(std::move(logger)) { if (m_cfg.trackingGeometry != nullptr) { // parse and populate @@ -30,9 +30,7 @@ ActsExamples::Contextual::ExternalAlignmentDecorator:: } } -ActsExamples::ProcessCode -ActsExamples::Contextual::ExternalAlignmentDecorator::decorate( - AlgorithmContext& context) { +ProcessCode ExternalAlignmentDecorator::decorate(AlgorithmContext& context) { // Iov map access needs to be synchronized std::lock_guard lock{m_iovMutex}; @@ -96,7 +94,7 @@ ActsExamples::Contextual::ExternalAlignmentDecorator::decorate( return ProcessCode::SUCCESS; } -void ActsExamples::Contextual::ExternalAlignmentDecorator::parseGeometry( +void ExternalAlignmentDecorator::parseGeometry( const Acts::TrackingGeometry& tGeometry) { // Double-visit - first count std::size_t nTransforms = 0; @@ -125,3 +123,5 @@ void ActsExamples::Contextual::ExternalAlignmentDecorator::parseGeometry( tGeometry.visitSurfaces(fillTransforms); m_nominalStore = std::move(aStore); } + +} // namespace ActsExamples diff --git a/Examples/Detectors/ContextualDetector/src/InternalAlignmentDecorator.cpp b/Examples/Detectors/ContextualDetector/src/InternalAlignmentDecorator.cpp index 0ce8dd80f1c..c1b44ed0747 100644 --- a/Examples/Detectors/ContextualDetector/src/InternalAlignmentDecorator.cpp +++ b/Examples/Detectors/ContextualDetector/src/InternalAlignmentDecorator.cpp @@ -9,7 +9,6 @@ #include "ActsExamples/ContextualDetector/InternalAlignmentDecorator.hpp" #include "Acts/Definitions/Algebra.hpp" -#include "Acts/Geometry/GeometryContext.hpp" #include "ActsExamples/ContextualDetector/InternallyAlignedDetectorElement.hpp" #include "ActsExamples/Framework/AlgorithmContext.hpp" #include "ActsExamples/Framework/RandomNumbers.hpp" @@ -18,14 +17,13 @@ #include #include -ActsExamples::Contextual::InternalAlignmentDecorator:: - InternalAlignmentDecorator(const Config& cfg, - std::unique_ptr logger) +namespace ActsExamples { + +InternalAlignmentDecorator::InternalAlignmentDecorator( + const Config& cfg, std::unique_ptr logger) : m_cfg(cfg), m_logger(std::move(logger)) {} -ActsExamples::ProcessCode -ActsExamples::Contextual::InternalAlignmentDecorator::decorate( - AlgorithmContext& context) { +ProcessCode InternalAlignmentDecorator::decorate(AlgorithmContext& context) { // We need to lock the Decorator std::lock_guard alignmentLock(m_alignmentMutex); @@ -92,3 +90,5 @@ ActsExamples::Contextual::InternalAlignmentDecorator::decorate( return ProcessCode::SUCCESS; } + +} // namespace ActsExamples diff --git a/Examples/Detectors/DD4hepDetector/include/ActsExamples/DD4hepDetector/DD4hepDetector.hpp b/Examples/Detectors/DD4hepDetector/include/ActsExamples/DD4hepDetector/DD4hepDetector.hpp index 015b511825f..422af198ff5 100644 --- a/Examples/Detectors/DD4hepDetector/include/ActsExamples/DD4hepDetector/DD4hepDetector.hpp +++ b/Examples/Detectors/DD4hepDetector/include/ActsExamples/DD4hepDetector/DD4hepDetector.hpp @@ -8,7 +8,6 @@ #pragma once -#include "Acts/MagneticField/MagneticFieldProvider.hpp" #include "Acts/Plugins/DD4hep/DD4hepDetectorElement.hpp" #include "Acts/Plugins/DD4hep/DD4hepDetectorStructure.hpp" #include "ActsExamples/DD4hepDetector/DD4hepGeometryService.hpp" @@ -32,15 +31,12 @@ class Detector; } // namespace Acts namespace ActsExamples { -class IContextDecorator; -} // namespace ActsExamples -namespace ActsExamples::DD4hep { +class IContextDecorator; struct DD4hepDetector { /// @brief The context decorators - using ContextDecorators = - std::vector>; + using ContextDecorators = std::vector>; /// @brief The tracking geometry using TrackingGeometryPtr = std::shared_ptr; @@ -92,4 +88,4 @@ struct DD4hepDetector { std::shared_ptr field() const; }; -} // namespace ActsExamples::DD4hep +} // namespace ActsExamples diff --git a/Examples/Detectors/DD4hepDetector/include/ActsExamples/DD4hepDetector/DD4hepGeometryService.hpp b/Examples/Detectors/DD4hepDetector/include/ActsExamples/DD4hepDetector/DD4hepGeometryService.hpp index edbb720825c..1111f8de8e7 100644 --- a/Examples/Detectors/DD4hepDetector/include/ActsExamples/DD4hepDetector/DD4hepGeometryService.hpp +++ b/Examples/Detectors/DD4hepDetector/include/ActsExamples/DD4hepDetector/DD4hepGeometryService.hpp @@ -35,7 +35,7 @@ namespace dd4hep { class Detector; } // namespace dd4hep -namespace ActsExamples::DD4hep { +namespace ActsExamples { void sortFCChhDetElements(std::vector& det); @@ -115,11 +115,10 @@ class DD4hepGeometryService { private: /// Private method to initiate building of the DD4hep geometry - ActsExamples::ProcessCode buildDD4hepGeometry(); + ProcessCode buildDD4hepGeometry(); /// Private method to initiate building of the ACTS tracking geometry - ActsExamples::ProcessCode buildTrackingGeometry( - const Acts::GeometryContext& gctx); + ProcessCode buildTrackingGeometry(const Acts::GeometryContext& gctx); /// The config class Config m_cfg; @@ -135,4 +134,4 @@ class DD4hepGeometryService { std::unique_ptr m_logger; }; -} // namespace ActsExamples::DD4hep +} // namespace ActsExamples diff --git a/Examples/Detectors/DD4hepDetector/src/DD4hepDetector.cpp b/Examples/Detectors/DD4hepDetector/src/DD4hepDetector.cpp index a6494ce0860..4ecae308134 100644 --- a/Examples/Detectors/DD4hepDetector/src/DD4hepDetector.cpp +++ b/Examples/Detectors/DD4hepDetector/src/DD4hepDetector.cpp @@ -9,11 +9,9 @@ #include "ActsExamples/DD4hepDetector/DD4hepDetector.hpp" #include "Acts/Geometry/GeometryContext.hpp" -#include "Acts/MagneticField/MagneticFieldProvider.hpp" #include "Acts/Plugins/DD4hep/DD4hepFieldAdapter.hpp" #include "ActsExamples/DD4hepDetector/DD4hepGeometryService.hpp" -#include #include #include #include @@ -23,20 +21,19 @@ #include #include -namespace ActsExamples::DD4hep { +namespace ActsExamples { DD4hepDetector::DD4hepDetector( std::shared_ptr _geometryService) : geometryService(std::move(_geometryService)) {} auto DD4hepDetector::finalize( - ActsExamples::DD4hep::DD4hepGeometryService::Config config, + DD4hepGeometryService::Config config, std::shared_ptr mdecorator) -> std::pair { Acts::GeometryContext dd4HepContext; config.matDecorator = std::move(mdecorator); - geometryService = - std::make_shared(config); + geometryService = std::make_shared(config); TrackingGeometryPtr dd4tGeometry = geometryService->trackingGeometry(dd4HepContext); if (!dd4tGeometry) { @@ -85,4 +82,4 @@ std::shared_ptr DD4hepDetector::field() const { return std::make_shared(detector.field()); } -} // namespace ActsExamples::DD4hep +} // namespace ActsExamples diff --git a/Examples/Detectors/DD4hepDetector/src/DD4hepGeometryService.cpp b/Examples/Detectors/DD4hepDetector/src/DD4hepGeometryService.cpp index 2912e39b757..c746dd84343 100644 --- a/Examples/Detectors/DD4hepDetector/src/DD4hepGeometryService.cpp +++ b/Examples/Detectors/DD4hepDetector/src/DD4hepGeometryService.cpp @@ -22,10 +22,9 @@ #include #include -class TGeoNode; +namespace ActsExamples { -ActsExamples::DD4hep::DD4hepGeometryService::DD4hepGeometryService( - const ActsExamples::DD4hep::DD4hepGeometryService::Config& cfg) +DD4hepGeometryService::DD4hepGeometryService(const Config& cfg) : m_cfg(cfg), m_logger{Acts::getDefaultLogger("DD4hepGeometryService", cfg.logLevel)} { if (m_cfg.xmlFileNames.empty()) { @@ -33,12 +32,11 @@ ActsExamples::DD4hep::DD4hepGeometryService::DD4hepGeometryService( } } -ActsExamples::DD4hep::DD4hepGeometryService::~DD4hepGeometryService() { +DD4hepGeometryService::~DD4hepGeometryService() { drop(); } -ActsExamples::ProcessCode -ActsExamples::DD4hep::DD4hepGeometryService::buildDD4hepGeometry() { +ProcessCode DD4hepGeometryService::buildDD4hepGeometry() { const int old_gErrorIgnoreLevel = gErrorIgnoreLevel; switch (m_cfg.dd4hepLogLevel) { case Acts::Logging::Level::VERBOSE: @@ -83,33 +81,31 @@ ActsExamples::DD4hep::DD4hepGeometryService::buildDD4hepGeometry() { gErrorIgnoreLevel = old_gErrorIgnoreLevel; std::cout.clear(); - return ActsExamples::ProcessCode::SUCCESS; + return ProcessCode::SUCCESS; } -dd4hep::Detector& -ActsExamples::DD4hep::DD4hepGeometryService::DD4hepGeometryService::detector() { +dd4hep::Detector& DD4hepGeometryService::detector() { if (m_detector == nullptr) { buildDD4hepGeometry(); } return *m_detector; } -dd4hep::DetElement& ActsExamples::DD4hep::DD4hepGeometryService::geometry() { +dd4hep::DetElement& DD4hepGeometryService::geometry() { if (!m_geometry) { buildDD4hepGeometry(); } return m_geometry; } -TGeoNode& ActsExamples::DD4hep::DD4hepGeometryService::tgeoGeometry() { +TGeoNode& DD4hepGeometryService::tgeoGeometry() { if (!m_geometry) { buildDD4hepGeometry(); } return *m_geometry.placement().ptr(); } -ActsExamples::ProcessCode -ActsExamples::DD4hep::DD4hepGeometryService::buildTrackingGeometry( +ProcessCode DD4hepGeometryService::buildTrackingGeometry( const Acts::GeometryContext& gctx) { // Set the tracking geometry auto logger = Acts::getDefaultLogger("DD4hepConversion", m_cfg.logLevel); @@ -118,19 +114,18 @@ ActsExamples::DD4hep::DD4hepGeometryService::buildTrackingGeometry( m_cfg.envelopeR, m_cfg.envelopeZ, m_cfg.defaultLayerThickness, m_cfg.sortDetectors, gctx, m_cfg.matDecorator, m_cfg.geometryIdentifierHook); - return ActsExamples::ProcessCode::SUCCESS; + return ProcessCode::SUCCESS; } std::shared_ptr -ActsExamples::DD4hep::DD4hepGeometryService::trackingGeometry( - const Acts::GeometryContext& gctx) { +DD4hepGeometryService::trackingGeometry(const Acts::GeometryContext& gctx) { if (!m_trackingGeometry) { buildTrackingGeometry(gctx); } return m_trackingGeometry; } -void ActsExamples::DD4hep::DD4hepGeometryService::drop() { +void DD4hepGeometryService::drop() { if (m_detector == nullptr) { return; } @@ -140,12 +135,12 @@ void ActsExamples::DD4hep::DD4hepGeometryService::drop() { m_trackingGeometry = nullptr; } -void ActsExamples::DD4hep::sortFCChhDetElements( - std::vector& det) { +void sortFCChhDetElements(std::vector& det) { std::vector tracker; std::vector eCal; std::vector hCal; std::vector muon; + for (auto& detElement : det) { std::string detName = detElement.name(); if (detName.find("Muon") != std::string::npos) { @@ -158,22 +153,16 @@ void ActsExamples::DD4hep::sortFCChhDetElements( tracker.push_back(detElement); } } - sort(muon.begin(), muon.end(), - [](const dd4hep::DetElement& a, const dd4hep::DetElement& b) { - return (a.id() < b.id()); - }); - sort(eCal.begin(), eCal.end(), - [](const dd4hep::DetElement& a, const dd4hep::DetElement& b) { - return (a.id() < b.id()); - }); - sort(hCal.begin(), hCal.end(), - [](const dd4hep::DetElement& a, const dd4hep::DetElement& b) { - return (a.id() < b.id()); - }); - sort(tracker.begin(), tracker.end(), - [](const dd4hep::DetElement& a, const dd4hep::DetElement& b) { - return (a.id() < b.id()); - }); + + auto byId = [](const dd4hep::DetElement& a, + const dd4hep::DetElement& b) -> bool { + return a.id() < b.id(); + }; + sort(muon.begin(), muon.end(), byId); + sort(eCal.begin(), eCal.end(), byId); + sort(hCal.begin(), hCal.end(), byId); + sort(tracker.begin(), tracker.end(), byId); + det.clear(); det = tracker; @@ -181,3 +170,5 @@ void ActsExamples::DD4hep::sortFCChhDetElements( det.insert(det.end(), hCal.begin(), hCal.end()); det.insert(det.end(), muon.begin(), muon.end()); } + +} // namespace ActsExamples diff --git a/Examples/Detectors/Geant4Detector/include/ActsExamples/Geant4Detector/Geant4Detector.hpp b/Examples/Detectors/Geant4Detector/include/ActsExamples/Geant4Detector/Geant4Detector.hpp index 5a948c3f3b5..32c7a7568ea 100644 --- a/Examples/Detectors/Geant4Detector/include/ActsExamples/Geant4Detector/Geant4Detector.hpp +++ b/Examples/Detectors/Geant4Detector/include/ActsExamples/Geant4Detector/Geant4Detector.hpp @@ -31,9 +31,8 @@ class Detector; } // namespace Acts namespace ActsExamples { -class IContextDecorator; -namespace Geant4 { +class IContextDecorator; struct Geant4Detector { using DetectorElements = @@ -41,8 +40,7 @@ struct Geant4Detector { using DetectorPtr = std::shared_ptr; using Surfaces = std::vector>; - using ContextDecorators = - std::vector>; + using ContextDecorators = std::vector>; using TrackingGeometryPtr = std::shared_ptr; /// Nested configuration struct @@ -90,5 +88,4 @@ struct Geant4Detector { const Config& cfg, const Acts::Logger& logger) const; }; -} // namespace Geant4 } // namespace ActsExamples diff --git a/Examples/Detectors/Geant4Detector/src/Geant4Detector.cpp b/Examples/Detectors/Geant4Detector/src/Geant4Detector.cpp index e3b52f36cd3..67ab547db26 100644 --- a/Examples/Detectors/Geant4Detector/src/Geant4Detector.cpp +++ b/Examples/Detectors/Geant4Detector/src/Geant4Detector.cpp @@ -23,9 +23,10 @@ #include "G4Transform3D.hh" #include "G4VPhysicalVolume.hh" -auto ActsExamples::Geant4::Geant4Detector::constructDetector( - const ActsExamples::Geant4::Geant4Detector::Config& cfg, - const Acts::Logger& logger) +namespace ActsExamples { + +auto Geant4Detector::constructDetector(const Geant4Detector::Config& cfg, + const Acts::Logger& logger) -> std::tuple { if (cfg.g4World == nullptr) { throw std::invalid_argument( @@ -44,9 +45,8 @@ auto ActsExamples::Geant4::Geant4Detector::constructDetector( return std::tie(detector, decorators, elements); } -auto ActsExamples::Geant4::Geant4Detector::constructTrackingGeometry( - const ActsExamples::Geant4::Geant4Detector::Config& cfg, - const Acts::Logger& logger) +auto Geant4Detector::constructTrackingGeometry( + const Geant4Detector::Config& cfg, const Acts::Logger& logger) -> std::tuple { if (cfg.g4World == nullptr) { throw std::invalid_argument( @@ -104,10 +104,9 @@ auto ActsExamples::Geant4::Geant4Detector::constructTrackingGeometry( return std::tie(trackingGeometry, decorators, elements); } -auto ActsExamples::Geant4::Geant4Detector::convertGeant4Volumes( - const Geant4Detector::Config& cfg, const Acts::Logger& logger) const - -> std::tuple { +auto Geant4Detector::convertGeant4Volumes(const Geant4Detector::Config& cfg, + const Acts::Logger& logger) const + -> std::tuple { // Generate the surface cache Acts::Geant4DetectorSurfaceFactory::Cache g4SurfaceCache; G4Transform3D g4ToWorld; @@ -143,3 +142,5 @@ auto ActsExamples::Geant4::Geant4Detector::convertGeant4Volumes( return std::tie(surfaces, elements); } + +} // namespace ActsExamples diff --git a/Examples/Detectors/GenericDetector/include/ActsExamples/GenericDetector/BuildGenericDetector.hpp b/Examples/Detectors/GenericDetector/include/ActsExamples/GenericDetector/BuildGenericDetector.hpp index c5968ef4ca3..aea978be935 100644 --- a/Examples/Detectors/GenericDetector/include/ActsExamples/GenericDetector/BuildGenericDetector.hpp +++ b/Examples/Detectors/GenericDetector/include/ActsExamples/GenericDetector/BuildGenericDetector.hpp @@ -31,11 +31,7 @@ #include "ActsExamples/GenericDetector/LayerBuilderT.hpp" #include "ActsExamples/GenericDetector/ProtoLayerCreatorT.hpp" -#include -#include #include -#include -#include #include #include #include @@ -108,7 +104,7 @@ std::vector> modulePositionsDisc( /// return a unique vector to the tracking geometry template std::unique_ptr buildDetector( - const typename detector_element_t::ContextType& gctxIn, + const Acts::GeometryContext& gctxIn, std::vector>>& detectorStore, std::size_t level, @@ -782,7 +778,7 @@ std::unique_ptr buildDetector( Acts::getDefaultLogger("TrackerGeometryBuilder", volumeLLevel)); // get the geometry auto trackingGeometry = cylinderGeometryBuilder->trackingGeometry(gctx); - /// return the tracking geometry + // return the tracking geometry return trackingGeometry; } diff --git a/Examples/Detectors/GenericDetector/include/ActsExamples/GenericDetector/GenericDetector.hpp b/Examples/Detectors/GenericDetector/include/ActsExamples/GenericDetector/GenericDetector.hpp index c487f43d3a6..21a1f85bec6 100644 --- a/Examples/Detectors/GenericDetector/include/ActsExamples/GenericDetector/GenericDetector.hpp +++ b/Examples/Detectors/GenericDetector/include/ActsExamples/GenericDetector/GenericDetector.hpp @@ -24,17 +24,12 @@ namespace ActsExamples { class IContextDecorator; } // namespace ActsExamples -namespace ActsExamples::Generic { +namespace ActsExamples { + class GenericDetectorElement; -} // namespace ActsExamples::Generic struct GenericDetector { - using DetectorElement = ActsExamples::Generic::GenericDetectorElement; - using DetectorElementPtr = std::shared_ptr; - using DetectorStore = std::vector>; - - using ContextDecorators = - std::vector>; + using ContextDecorators = std::vector>; using TrackingGeometryPtr = std::shared_ptr; struct Config { @@ -46,9 +41,12 @@ struct GenericDetector { }; /// The Store of the detector elements (lifetime: job) - DetectorStore detectorStore; + std::vector>> + detectorStore; std::pair finalize( const Config& cfg, std::shared_ptr mdecorator); }; + +} // namespace ActsExamples diff --git a/Examples/Detectors/GenericDetector/include/ActsExamples/GenericDetector/GenericDetectorElement.hpp b/Examples/Detectors/GenericDetector/include/ActsExamples/GenericDetector/GenericDetectorElement.hpp index 97d2f7fad3e..9ac48f6cc68 100644 --- a/Examples/Detectors/GenericDetector/include/ActsExamples/GenericDetector/GenericDetectorElement.hpp +++ b/Examples/Detectors/GenericDetector/include/ActsExamples/GenericDetector/GenericDetectorElement.hpp @@ -22,7 +22,7 @@ class DiscBounds; class ISurfaceMaterial; } // namespace Acts -namespace ActsExamples::Generic { +namespace ActsExamples { /// @class GenericDetectorElement /// @@ -101,28 +101,4 @@ class GenericDetectorElement : public Acts::DetectorElementBase { std::shared_ptr m_elementDiscBounds = nullptr; }; -inline const Acts::Transform3& -ActsExamples::Generic::GenericDetectorElement::transform( - const Acts::GeometryContext& /*gctx*/) const { - return *m_elementTransform; -} - -inline const Acts::Surface& -ActsExamples::Generic::GenericDetectorElement::surface() const { - return *m_elementSurface; -} - -inline Acts::Surface& ActsExamples::Generic::GenericDetectorElement::surface() { - return *m_elementSurface; -} - -inline double ActsExamples::Generic::GenericDetectorElement::thickness() const { - return m_elementThickness; -} - -inline ActsExamples::Generic::GenericDetectorElement::Identifier -ActsExamples::Generic::GenericDetectorElement::identifier() const { - return m_elementIdentifier; -} - -} // namespace ActsExamples::Generic +} // namespace ActsExamples diff --git a/Examples/Detectors/GenericDetector/include/ActsExamples/GenericDetector/LayerBuilderT.hpp b/Examples/Detectors/GenericDetector/include/ActsExamples/GenericDetector/LayerBuilderT.hpp index 642b4a63ffc..66a5c8f2f37 100644 --- a/Examples/Detectors/GenericDetector/include/ActsExamples/GenericDetector/LayerBuilderT.hpp +++ b/Examples/Detectors/GenericDetector/include/ActsExamples/GenericDetector/LayerBuilderT.hpp @@ -15,17 +15,11 @@ #include "Acts/Geometry/ILayerBuilder.hpp" #include "Acts/Geometry/Layer.hpp" #include "Acts/Geometry/LayerCreator.hpp" -#include "Acts/Geometry/ProtoLayer.hpp" -#include "Acts/Material/HomogeneousSurfaceMaterial.hpp" -#include "Acts/Material/Material.hpp" -#include "Acts/Material/MaterialSlab.hpp" #include "Acts/Surfaces/Surface.hpp" #include "Acts/Utilities/Logger.hpp" #include "ActsExamples/GenericDetector/GenericDetectorElement.hpp" #include "ActsExamples/GenericDetector/ProtoLayerCreatorT.hpp" -#include - namespace ActsExamples::Generic { using Acts::VectorHelpers::eta; diff --git a/Examples/Detectors/GenericDetector/include/ActsExamples/GenericDetector/ProtoLayerCreatorT.hpp b/Examples/Detectors/GenericDetector/include/ActsExamples/GenericDetector/ProtoLayerCreatorT.hpp index fc4fa4c1459..d8e1ce24fb0 100644 --- a/Examples/Detectors/GenericDetector/include/ActsExamples/GenericDetector/ProtoLayerCreatorT.hpp +++ b/Examples/Detectors/GenericDetector/include/ActsExamples/GenericDetector/ProtoLayerCreatorT.hpp @@ -16,11 +16,8 @@ #include "Acts/Material/ISurfaceMaterial.hpp" #include "Acts/Surfaces/PlanarBounds.hpp" #include "Acts/Surfaces/PlaneSurface.hpp" -#include "Acts/Surfaces/RadialBounds.hpp" #include "Acts/Surfaces/RectangleBounds.hpp" #include "Acts/Surfaces/TrapezoidBounds.hpp" -#include "Acts/Utilities/BinUtility.hpp" -#include "Acts/Utilities/BinnedArray.hpp" #include "Acts/Utilities/Logger.hpp" #include "ActsExamples/GenericDetector/GenericDetectorElement.hpp" @@ -218,8 +215,8 @@ ProtoLayerCreatorT::centralProtoLayers( double moduleHalfY = m_cfg.centralModuleHalfY.at(icl); double moduleThickness = m_cfg.centralModuleThickness.at(icl); // create the shared module - std::shared_ptr moduleBounds( - new Acts::RectangleBounds(moduleHalfX, moduleHalfY)); + auto moduleBounds = + std::make_shared(moduleHalfX, moduleHalfY); std::size_t nCentralModules = m_cfg.centralModuleBinningSchema.at(icl).first * m_cfg.centralModuleBinningSchema.at(icl).second; @@ -414,15 +411,14 @@ ProtoLayerCreatorT::createProtoLayers( double moduleHalfY = m_cfg.posnegModuleHalfY.at(ipnl).at(ipnR); // (1) module bounds // create the bounds - Acts::PlanarBounds* pBounds = nullptr; + std::shared_ptr moduleBounds; if (moduleMaxHalfX != 0. && moduleMinHalfX != moduleMaxHalfX) { - pBounds = new Acts::TrapezoidBounds(moduleMinHalfX, moduleMaxHalfX, - moduleHalfY); + moduleBounds = std::make_shared( + moduleMinHalfX, moduleMaxHalfX, moduleHalfY); } else { - pBounds = new Acts::RectangleBounds(moduleMinHalfX, moduleHalfY); + moduleBounds = std::make_shared(moduleMinHalfX, + moduleHalfY); } - // now create the shared bounds from it - std::shared_ptr moduleBounds(pBounds); // (2)) module material // create the Module material from input std::shared_ptr moduleMaterialPtr = diff --git a/Examples/Detectors/GenericDetector/src/BuildGenericDetector.cpp b/Examples/Detectors/GenericDetector/src/BuildGenericDetector.cpp index 5f396bbe4e8..594ff3120d9 100644 --- a/Examples/Detectors/GenericDetector/src/BuildGenericDetector.cpp +++ b/Examples/Detectors/GenericDetector/src/BuildGenericDetector.cpp @@ -11,10 +11,8 @@ #include #include -namespace ActsExamples::Generic { - /// helper method for cylinder -std::vector modulePositionsCylinder( +std::vector ActsExamples::Generic::modulePositionsCylinder( double radius, double zStagger, double moduleHalfLength, double lOverlap, const std::pair& binningSchema) { int nPhiBins = binningSchema.first; @@ -45,7 +43,8 @@ std::vector modulePositionsCylinder( } /// helper method for disc -std::vector> modulePositionsDisc( +std::vector> +ActsExamples::Generic::modulePositionsDisc( double z, double ringStagger, std::vector phiStagger, std::vector phiSubStagger, double innerRadius, double outerRadius, const std::vector& discBinning, @@ -95,10 +94,9 @@ std::vector> modulePositionsDisc( } /// Helper method for positioning -std::vector modulePositionsRing(double z, double radius, - double phiStagger, - double phiSubStagger, - int nPhiBins) { +std::vector ActsExamples::Generic::modulePositionsRing( + double z, double radius, double phiStagger, double phiSubStagger, + int nPhiBins) { // create and fill the positions std::vector rPositions; rPositions.reserve(nPhiBins); @@ -130,5 +128,3 @@ std::vector modulePositionsRing(double z, double radius, } return rPositions; } - -} // namespace ActsExamples::Generic diff --git a/Examples/Detectors/GenericDetector/src/GenericDetector.cpp b/Examples/Detectors/GenericDetector/src/GenericDetector.cpp index 6a152128edc..bf033fc1e3e 100644 --- a/Examples/Detectors/GenericDetector/src/GenericDetector.cpp +++ b/Examples/Detectors/GenericDetector/src/GenericDetector.cpp @@ -8,20 +8,20 @@ #include "ActsExamples/GenericDetector/GenericDetector.hpp" -#include "Acts/Geometry/ILayerBuilder.hpp" #include "Acts/Geometry/TrackingGeometry.hpp" #include "ActsExamples/GenericDetector/BuildGenericDetector.hpp" #include "ActsExamples/GenericDetector/GenericDetectorElement.hpp" -#include "ActsExamples/GenericDetector/ProtoLayerCreatorT.hpp" + +namespace ActsExamples { auto GenericDetector::finalize( const Config& cfg, std::shared_ptr mdecorator) -> std::pair { - DetectorElement::ContextType nominalContext; + GenericDetectorElement::ContextType nominalContext; /// Return the generic detector TrackingGeometryPtr gGeometry = - ActsExamples::Generic::buildDetector( + Generic::buildDetector( nominalContext, detectorStore, cfg.buildLevel, std::move(mdecorator), cfg.buildProto, cfg.surfaceLogLevel, cfg.layerLogLevel, cfg.volumeLogLevel); @@ -30,3 +30,5 @@ auto GenericDetector::finalize( return std::make_pair( std::move(gGeometry), std::move(gContextDecorators)); } + +} // namespace ActsExamples diff --git a/Examples/Detectors/GenericDetector/src/GenericDetectorElement.cpp b/Examples/Detectors/GenericDetector/src/GenericDetectorElement.cpp index def22d443d3..c1448a67599 100644 --- a/Examples/Detectors/GenericDetector/src/GenericDetectorElement.cpp +++ b/Examples/Detectors/GenericDetector/src/GenericDetectorElement.cpp @@ -13,7 +13,9 @@ #include -ActsExamples::Generic::GenericDetectorElement::GenericDetectorElement( +namespace ActsExamples { + +GenericDetectorElement::GenericDetectorElement( const Identifier identifier, std::shared_ptr transform, std::shared_ptr pBounds, double thickness, @@ -29,7 +31,7 @@ ActsExamples::Generic::GenericDetectorElement::GenericDetectorElement( m_elementSurface->assignSurfaceMaterial(std::move(material)); } -ActsExamples::Generic::GenericDetectorElement::GenericDetectorElement( +GenericDetectorElement::GenericDetectorElement( const Identifier identifier, std::shared_ptr transform, std::shared_ptr dBounds, double thickness, @@ -44,3 +46,26 @@ ActsExamples::Generic::GenericDetectorElement::GenericDetectorElement( m_elementDiscBounds(std::move(dBounds)) { m_elementSurface->assignSurfaceMaterial(std::move(material)); } + +const Acts::Transform3& GenericDetectorElement::transform( + const Acts::GeometryContext& /*gctx*/) const { + return *m_elementTransform; +} + +const Acts::Surface& GenericDetectorElement::surface() const { + return *m_elementSurface; +} + +Acts::Surface& GenericDetectorElement::surface() { + return *m_elementSurface; +} + +double GenericDetectorElement::thickness() const { + return m_elementThickness; +} + +GenericDetectorElement::Identifier GenericDetectorElement::identifier() const { + return m_elementIdentifier; +} + +} // namespace ActsExamples diff --git a/Examples/Detectors/ITkModuleSplitting/include/ActsExamples/ITkModuleSplitting/ITkModuleSplitting.hpp b/Examples/Detectors/ITkModuleSplitting/include/ActsExamples/ITkModuleSplitting/ITkModuleSplitting.hpp index 591671bffb7..c0860bd31bf 100644 --- a/Examples/Detectors/ITkModuleSplitting/include/ActsExamples/ITkModuleSplitting/ITkModuleSplitting.hpp +++ b/Examples/Detectors/ITkModuleSplitting/include/ActsExamples/ITkModuleSplitting/ITkModuleSplitting.hpp @@ -6,14 +6,6 @@ // 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/. -// This file is part of the Acts project. -// -// Copyright (C) 2024 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 http://mozilla.org/MPL/2.0/. - #pragma once #include "Acts/Definitions/Algebra.hpp" @@ -25,7 +17,6 @@ #include #include #include -#include namespace ActsExamples::ITk { diff --git a/Examples/Detectors/MagneticField/include/ActsExamples/MagneticField/FieldMapRootIo.hpp b/Examples/Detectors/MagneticField/include/ActsExamples/MagneticField/FieldMapRootIo.hpp index b5a523c2c0e..3f05cad4cc7 100644 --- a/Examples/Detectors/MagneticField/include/ActsExamples/MagneticField/FieldMapRootIo.hpp +++ b/Examples/Detectors/MagneticField/include/ActsExamples/MagneticField/FieldMapRootIo.hpp @@ -57,8 +57,7 @@ detail::InterpolatedMagneticField2 makeMagneticFieldMapRzFromRoot( std::array nBinsRZ)>& localToGlobalBin, const std::string& fieldMapFile, const std::string& treeName, - Acts::ActsScalar lengthUnit, Acts::ActsScalar BFieldUnit, - bool firstQuadrant = false); + double lengthUnit, double BFieldUnit, bool firstQuadrant = false); /// Method to setup the FieldMap /// @param localToGlobalBin Function mapping the local bins of x,y,z to the @@ -105,7 +104,6 @@ detail::InterpolatedMagneticField3 makeMagneticFieldMapXyzFromRoot( std::array nBinsXYZ)>& localToGlobalBin, const std::string& fieldMapFile, const std::string& treeName, - Acts::ActsScalar lengthUnit, Acts::ActsScalar BFieldUnit, - bool firstOctant = false); + double lengthUnit, double BFieldUnit, bool firstOctant = false); } // namespace ActsExamples diff --git a/Examples/Detectors/MagneticField/include/ActsExamples/MagneticField/FieldMapTextIo.hpp b/Examples/Detectors/MagneticField/include/ActsExamples/MagneticField/FieldMapTextIo.hpp index ed191226705..f7ba1f2848a 100644 --- a/Examples/Detectors/MagneticField/include/ActsExamples/MagneticField/FieldMapTextIo.hpp +++ b/Examples/Detectors/MagneticField/include/ActsExamples/MagneticField/FieldMapTextIo.hpp @@ -58,8 +58,8 @@ detail::InterpolatedMagneticField2 makeMagneticFieldMapRzFromText( const std::function binsRZ, std::array nBinsRZ)>& localToGlobalBin, - const std::string& fieldMapFile, Acts::ActsScalar lengthUnit, - Acts::ActsScalar BFieldUnit, bool firstQuadrant = false); + const std::string& fieldMapFile, double lengthUnit, double BFieldUnit, + bool firstQuadrant = false); /// Method to setup the FieldMapper /// @param localToGlobalBin Function mapping the local bins of x,y,z to the @@ -107,7 +107,7 @@ detail::InterpolatedMagneticField3 makeMagneticFieldMapXyzFromText( const std::function binsXYZ, std::array nBinsXYZ)>& localToGlobalBin, - const std::string& fieldMapFile, Acts::ActsScalar lengthUnit, - Acts::ActsScalar BFieldUnit, bool firstOctant = false); + const std::string& fieldMapFile, double lengthUnit, double BFieldUnit, + bool firstOctant = false); } // namespace ActsExamples diff --git a/Examples/Detectors/MagneticField/include/ActsExamples/MagneticField/ScalableBField.hpp b/Examples/Detectors/MagneticField/include/ActsExamples/MagneticField/ScalableBField.hpp index 5def5740fa4..aa799319e29 100644 --- a/Examples/Detectors/MagneticField/include/ActsExamples/MagneticField/ScalableBField.hpp +++ b/Examples/Detectors/MagneticField/include/ActsExamples/MagneticField/ScalableBField.hpp @@ -16,14 +16,14 @@ namespace ActsExamples { /// The ScalableBField-specific magnetic field context. struct ScalableBFieldContext { - Acts::ActsScalar scalor = 1.; + double scalor = 1.; }; /// A constant magnetic field that is scaled depending on the event context. class ScalableBField final : public Acts::MagneticFieldProvider { public: struct Cache { - Acts::ActsScalar scalor = 1.; + double scalor = 1.; /// @brief constructor with context explicit Cache(const Acts::MagneticFieldContext& mctx) { @@ -41,8 +41,7 @@ class ScalableBField final : public Acts::MagneticFieldProvider { /// @param [in] Bx magnetic field component in global x-direction /// @param [in] By magnetic field component in global y-direction /// @param [in] Bz magnetic field component in global z-direction - ScalableBField(Acts::ActsScalar Bx = 0, Acts::ActsScalar By = 0, - Acts::ActsScalar Bz = 0) + ScalableBField(double Bx = 0, double By = 0, double Bz = 0) : m_BField(Bx, By, Bz) {} /// @brief retrieve magnetic field value diff --git a/Examples/Detectors/MagneticField/include/ActsExamples/MagneticField/ScalableBFieldService.hpp b/Examples/Detectors/MagneticField/include/ActsExamples/MagneticField/ScalableBFieldService.hpp index a228eccfe55..f39e7a6cf86 100644 --- a/Examples/Detectors/MagneticField/include/ActsExamples/MagneticField/ScalableBFieldService.hpp +++ b/Examples/Detectors/MagneticField/include/ActsExamples/MagneticField/ScalableBFieldService.hpp @@ -26,7 +26,7 @@ class ScalableBFieldService : public IContextDecorator { public: struct Config { /// Scaling factor. Unit value means the magnetic field is left unchanged. - Acts::ActsScalar scalor = 1.25; + double scalor = 1.25; }; /// Construct the magnetic field service. diff --git a/Examples/Detectors/MagneticField/src/FieldMapRootIo.cpp b/Examples/Detectors/MagneticField/src/FieldMapRootIo.cpp index bcc93238364..50aac0d0fae 100644 --- a/Examples/Detectors/MagneticField/src/FieldMapRootIo.cpp +++ b/Examples/Detectors/MagneticField/src/FieldMapRootIo.cpp @@ -23,8 +23,7 @@ ActsExamples::makeMagneticFieldMapRzFromRoot( std::array nBinsRZ)>& localToGlobalBin, const std::string& fieldMapFile, const std::string& treeName, - Acts::ActsScalar lengthUnit, Acts::ActsScalar BFieldUnit, - bool firstQuadrant) { + double lengthUnit, double BFieldUnit, bool firstQuadrant) { /// [1] Read in field map file // Grid position points in r and z std::vector rPos; @@ -32,7 +31,7 @@ ActsExamples::makeMagneticFieldMapRzFromRoot( // components of magnetic field on grid points std::vector bField; // [1] Read in file and fill values - TFile* inputFile = TFile::Open(fieldMapFile.c_str()); + std::unique_ptr inputFile(TFile::Open(fieldMapFile.c_str())); if (inputFile == nullptr) { throw std::runtime_error("file does not exist"); } @@ -62,7 +61,6 @@ ActsExamples::makeMagneticFieldMapRzFromRoot( zPos.push_back(z); bField.push_back(Acts::Vector2(Br, Bz)); } - delete inputFile; /// [2] use helper function in core return Acts::fieldMapRZ(localToGlobalBin, rPos, zPos, bField, lengthUnit, BFieldUnit, firstQuadrant); @@ -74,8 +72,7 @@ ActsExamples::makeMagneticFieldMapXyzFromRoot( std::array nBinsXYZ)>& localToGlobalBin, const std::string& fieldMapFile, const std::string& treeName, - Acts::ActsScalar lengthUnit, Acts::ActsScalar BFieldUnit, - bool firstOctant) { + double lengthUnit, double BFieldUnit, bool firstOctant) { /// [1] Read in field map file // Grid position points in x, y and z std::vector xPos; @@ -84,7 +81,7 @@ ActsExamples::makeMagneticFieldMapXyzFromRoot( // components of magnetic field on grid points std::vector bField; // [1] Read in file and fill values - TFile* inputFile = TFile::Open(fieldMapFile.c_str()); + std::unique_ptr inputFile(TFile::Open(fieldMapFile.c_str())); if (inputFile == nullptr) { throw std::runtime_error("file does not exist"); } @@ -118,7 +115,6 @@ ActsExamples::makeMagneticFieldMapXyzFromRoot( zPos.push_back(z); bField.push_back(Acts::Vector3(Bx, By, Bz)); } - delete inputFile; return Acts::fieldMapXYZ(localToGlobalBin, xPos, yPos, zPos, bField, lengthUnit, BFieldUnit, firstOctant); diff --git a/Examples/Detectors/MagneticField/src/FieldMapTextIo.cpp b/Examples/Detectors/MagneticField/src/FieldMapTextIo.cpp index d298ec046b2..4512355ba73 100644 --- a/Examples/Detectors/MagneticField/src/FieldMapTextIo.cpp +++ b/Examples/Detectors/MagneticField/src/FieldMapTextIo.cpp @@ -22,8 +22,8 @@ ActsExamples::makeMagneticFieldMapRzFromText( const std::function binsRZ, std::array nBinsRZ)>& localToGlobalBin, - const std::string& fieldMapFile, Acts::ActsScalar lengthUnit, - Acts::ActsScalar BFieldUnit, bool firstQuadrant) { + const std::string& fieldMapFile, double lengthUnit, double BFieldUnit, + bool firstQuadrant) { /// [1] Read in field map file // Grid position points in r and z std::vector rPos; @@ -65,8 +65,8 @@ ActsExamples::makeMagneticFieldMapXyzFromText( const std::function binsXYZ, std::array nBinsXYZ)>& localToGlobalBin, - const std::string& fieldMapFile, Acts::ActsScalar lengthUnit, - Acts::ActsScalar BFieldUnit, bool firstOctant) { + const std::string& fieldMapFile, double lengthUnit, double BFieldUnit, + bool firstOctant) { /// [1] Read in field map file // Grid position points in x, y and z std::vector xPos; diff --git a/Examples/Detectors/MagneticField/src/ScalableBFieldService.cpp b/Examples/Detectors/MagneticField/src/ScalableBFieldService.cpp index 0d1cb1bfa6a..2501ae42536 100644 --- a/Examples/Detectors/MagneticField/src/ScalableBFieldService.cpp +++ b/Examples/Detectors/MagneticField/src/ScalableBFieldService.cpp @@ -8,7 +8,6 @@ #include "ActsExamples/MagneticField/ScalableBFieldService.hpp" -#include "Acts/MagneticField/MagneticFieldContext.hpp" #include "ActsExamples/Framework/AlgorithmContext.hpp" #include "ActsExamples/MagneticField/ScalableBField.hpp" @@ -19,18 +18,21 @@ namespace { const std::string s_name = "ScalableBFieldService"; } -ActsExamples::ScalableBFieldService::ScalableBFieldService( - const Config& cfg, Acts::Logging::Level lvl) +namespace ActsExamples { + +ScalableBFieldService::ScalableBFieldService(const Config& cfg, + Acts::Logging::Level lvl) : m_cfg(cfg), m_logger(Acts::getDefaultLogger(s_name, lvl)) {} -const std::string& ActsExamples::ScalableBFieldService::name() const { +const std::string& ScalableBFieldService::name() const { return s_name; } -ActsExamples::ProcessCode ActsExamples::ScalableBFieldService::decorate( - AlgorithmContext& ctx) { +ProcessCode ScalableBFieldService::decorate(AlgorithmContext& ctx) { ScalableBFieldContext magCtx; magCtx.scalor = std::pow(m_cfg.scalor, ctx.eventNumber); ctx.magFieldContext = std::make_any(magCtx); return ProcessCode::SUCCESS; } + +} // namespace ActsExamples diff --git a/Examples/Detectors/MuonSpectrometerMockupDetector/src/MockupSectorBuilder.cpp b/Examples/Detectors/MuonSpectrometerMockupDetector/src/MockupSectorBuilder.cpp index f6431c5ddbe..585aef06756 100644 --- a/Examples/Detectors/MuonSpectrometerMockupDetector/src/MockupSectorBuilder.cpp +++ b/Examples/Detectors/MuonSpectrometerMockupDetector/src/MockupSectorBuilder.cpp @@ -24,7 +24,6 @@ #include "Acts/Surfaces/StrawSurface.hpp" #include "Acts/Surfaces/Surface.hpp" #include "Acts/Surfaces/SurfaceBounds.hpp" -#include "Acts/Utilities/Helpers.hpp" #include "Acts/Utilities/Logger.hpp" #include "Acts/Visualization/GeometryView3D.hpp" #include "Acts/Visualization/ObjVisualization3D.hpp" @@ -40,20 +39,21 @@ #include #include #include -#include #include #include -ActsExamples::MockupSectorBuilder::MockupSectorBuilder( - const ActsExamples::MockupSectorBuilder::Config& config) { +namespace ActsExamples { + +MockupSectorBuilder::MockupSectorBuilder( + const MockupSectorBuilder::Config& config) { mCfg = config; - ActsExamples::GdmlDetectorConstruction geo_gdml(mCfg.gdmlPath); + GdmlDetectorConstruction geo_gdml(mCfg.gdmlPath); g4World = geo_gdml.Construct(); } std::shared_ptr -ActsExamples::MockupSectorBuilder::buildChamber( - const ActsExamples::MockupSectorBuilder::ChamberConfig& chamberConfig) { +MockupSectorBuilder::buildChamber( + const MockupSectorBuilder::ChamberConfig& chamberConfig) { if (g4World == nullptr) { throw std::invalid_argument("MockupSector: No g4World initialized"); } @@ -61,7 +61,7 @@ ActsExamples::MockupSectorBuilder::buildChamber( const Acts::GeometryContext gctx; // Geant4Detector Config creator with the g4world from the gdml file - auto g4WorldConfig = ActsExamples::Geant4::Geant4Detector::Config(); + auto g4WorldConfig = Geant4Detector::Config(); g4WorldConfig.name = "Chamber"; g4WorldConfig.g4World = g4World; @@ -78,7 +78,7 @@ ActsExamples::MockupSectorBuilder::buildChamber( g4SurfaceOptions.passiveSurfaceSelector = g4Passive; g4WorldConfig.g4SurfaceOptions = g4SurfaceOptions; - auto g4detector = ActsExamples::Geant4::Geant4Detector(); + auto g4detector = Geant4Detector(); auto [detector, surfaces, detectorElements] = g4detector.constructDetector(g4WorldConfig, Acts::getDummyLogger()); @@ -127,14 +127,12 @@ ActsExamples::MockupSectorBuilder::buildChamber( Acts::Vector3 maxValues = {min_max[0].second, min_max[1].second, min_max[2].second}; - Acts::ActsScalar hx = + double hx = strawSurfaces.front()->bounds().values()[1] + mCfg.toleranceOverlap; - Acts::ActsScalar hy = - 0.5 * ((maxValues.y() + radius) - (minValues.y() - radius)) + - mCfg.toleranceOverlap; - Acts::ActsScalar hz = - 0.5 * ((maxValues.z() + radius) - (minValues.z() - radius)) + - mCfg.toleranceOverlap; + double hy = 0.5 * ((maxValues.y() + radius) - (minValues.y() - radius)) + + mCfg.toleranceOverlap; + double hz = 0.5 * ((maxValues.z() + radius) - (minValues.z() - radius)) + + mCfg.toleranceOverlap; auto detectorVolumeBounds = std::make_shared(hx, hy, hz); @@ -157,7 +155,7 @@ ActsExamples::MockupSectorBuilder::buildChamber( } std::shared_ptr -ActsExamples::MockupSectorBuilder::buildSector( +MockupSectorBuilder::buildSector( std::vector> detVolumes) { if (mCfg.NumberOfSectors > maxNumberOfSectors) { @@ -189,10 +187,9 @@ ActsExamples::MockupSectorBuilder::buildSector( // calculate the phi angles of the vectors auto phiA = Acts::VectorHelpers::phi(pointA); auto phiB = Acts::VectorHelpers::phi(pointB); - Acts::ActsScalar sectorAngle = std::numbers::pi_v; + double sectorAngle = std::numbers::pi; - Acts::ActsScalar halfPhi = - std::numbers::pi_v / mCfg.NumberOfSectors; + double halfPhi = std::numbers::pi / mCfg.NumberOfSectors; if (mCfg.NumberOfSectors == 1) { halfPhi = (phiB - phiA) / 2; @@ -316,7 +313,7 @@ ActsExamples::MockupSectorBuilder::buildSector( return detectorVolume; } -void ActsExamples::MockupSectorBuilder::drawSector( +void MockupSectorBuilder::drawSector( const std::shared_ptr& detectorVolumeSector, const std::string& nameObjFile) { @@ -330,3 +327,5 @@ void ActsExamples::MockupSectorBuilder::drawSector( objSector.write(nameObjFile); } + +} // namespace ActsExamples diff --git a/Examples/Detectors/TGeoDetector/include/ActsExamples/TGeoDetector/JsonTGeoDetectorConfig.hpp b/Examples/Detectors/TGeoDetector/include/ActsExamples/TGeoDetector/JsonTGeoDetectorConfig.hpp index eb038572fcf..c1b006f6593 100644 --- a/Examples/Detectors/TGeoDetector/include/ActsExamples/TGeoDetector/JsonTGeoDetectorConfig.hpp +++ b/Examples/Detectors/TGeoDetector/include/ActsExamples/TGeoDetector/JsonTGeoDetectorConfig.hpp @@ -58,15 +58,13 @@ namespace ActsExamples { namespace Options { /// Read config for options interval -void from_json(const nlohmann::json& j, - ActsExamples::Options::Interval& interval) { +void from_json(const nlohmann::json& j, Interval& interval) { interval.lower = j.at("lower"); interval.upper = j.at("upper"); } /// Write config for options interval -void to_json(nlohmann::json& j, - const ActsExamples::Options::Interval& interval) { +void to_json(nlohmann::json& j, const Interval& interval) { // no direct conversion from std::optional to json j = nlohmann::json{{"lower", interval.lower.value_or(0)}, {"upper", interval.upper.value_or(0)}}; @@ -74,8 +72,7 @@ void to_json(nlohmann::json& j, } // namespace Options -void from_json(const nlohmann::json& j, - ActsExamples::TGeoITkModuleSplitter::Config& msc) { +void from_json(const nlohmann::json& j, TGeoITkModuleSplitter::Config& msc) { msc.barrelMap = j["geo-tgeo-barrel-map"].get>(); msc.discMap = @@ -83,8 +80,7 @@ void from_json(const nlohmann::json& j, .get>>>(); } -void to_json(nlohmann::json& j, - const ActsExamples::TGeoITkModuleSplitter::Config& msc) { +void to_json(nlohmann::json& j, const TGeoITkModuleSplitter::Config& msc) { j["geo-tgeo-barrel-map"] = msc.barrelMap; j["geo-tgeo-disc-map"] = msc.discMap; } @@ -92,7 +88,7 @@ void to_json(nlohmann::json& j, /// Read layer configuration triplets template void from_json(const nlohmann::json& j, - ActsExamples::TGeoDetector::Config::LayerTriplet& ltr) { + TGeoDetector::Config::LayerTriplet& ltr) { ltr.negative = j.at("negative").get(); ltr.central = j.at("central").get(); ltr.positive = j.at("positive").get(); @@ -101,15 +97,14 @@ void from_json(const nlohmann::json& j, /// Write layer configuration triplets template void to_json(nlohmann::json& j, - const ActsExamples::TGeoDetector::Config::LayerTriplet& ltr) { + const TGeoDetector::Config::LayerTriplet& ltr) { j = nlohmann::json{{"negative", ltr.negative}, {"central", ltr.central}, {"positive", ltr.positive}}; } /// Read volume struct -void from_json(const nlohmann::json& j, - ActsExamples::TGeoDetector::Config::Volume& vol) { +void from_json(const nlohmann::json& j, TGeoDetector::Config::Volume& vol) { // subdetector selection vol.name = j.at("geo-tgeo-volume-name"); @@ -145,8 +140,7 @@ void from_json(const nlohmann::json& j, if (j.count("geo-tgeo-itk-module-split") != 0) { vol.itkModuleSplit = j.at("geo-tgeo-itk-module-split"); if (vol.itkModuleSplit) { - ActsExamples::TGeoITkModuleSplitter::Config itkConfig = - j.at("Splitters").at("ITk"); + TGeoITkModuleSplitter::Config itkConfig = j.at("Splitters").at("ITk"); vol.barrelMap = itkConfig.barrelMap; vol.discMap = itkConfig.discMap; } @@ -185,7 +179,7 @@ void to_json(nlohmann::json& j, const TGeoDetector::Config::Volume& vol) { j["Splitters"]["CylinderDisk"] = cdConfig; if (vol.itkModuleSplit) { - ActsExamples::TGeoITkModuleSplitter::Config itkConfig; + TGeoITkModuleSplitter::Config itkConfig; itkConfig.barrelMap = vol.barrelMap; itkConfig.discMap = vol.discMap; j["Splitters"]["ITk"] = itkConfig; diff --git a/Examples/Detectors/TGeoDetector/include/ActsExamples/TGeoDetector/TGeoDetector.hpp b/Examples/Detectors/TGeoDetector/include/ActsExamples/TGeoDetector/TGeoDetector.hpp index 0fae0df1c5a..41134fdfa54 100644 --- a/Examples/Detectors/TGeoDetector/include/ActsExamples/TGeoDetector/TGeoDetector.hpp +++ b/Examples/Detectors/TGeoDetector/include/ActsExamples/TGeoDetector/TGeoDetector.hpp @@ -29,17 +29,14 @@ class IMaterialDecorator; } // namespace Acts namespace ActsExamples { -class IContextDecorator; -} // namespace ActsExamples -namespace ActsExamples { +class IContextDecorator; struct TGeoDetector { using DetectorElementPtr = std::shared_ptr; using DetectorStore = std::vector; - using ContextDecorators = - std::vector>; + using ContextDecorators = std::vector>; using TrackingGeometryPtr = std::shared_ptr; /// The Store of the detector elements (lifetime: job) diff --git a/Examples/Detectors/TGeoDetector/src/TGeoDetector.cpp b/Examples/Detectors/TGeoDetector/src/TGeoDetector.cpp index aeed881eb1e..0ece428a438 100644 --- a/Examples/Detectors/TGeoDetector/src/TGeoDetector.cpp +++ b/Examples/Detectors/TGeoDetector/src/TGeoDetector.cpp @@ -30,10 +30,7 @@ #include #include -#include #include -#include -#include #include #include #include @@ -135,12 +132,12 @@ std::vector makeLayerBuilderConfigs( cdsConfig, logger.clone("TGeoCylinderDiscSplitter", config.layerLogLevel)); } else if (volume.itkModuleSplit) { - ActsExamples::TGeoITkModuleSplitter::Config itkConfig; + TGeoITkModuleSplitter::Config itkConfig; itkConfig.barrelMap = volume.barrelMap; itkConfig.discMap = volume.discMap; itkConfig.splitPatterns = volume.splitPatterns; layerBuilderConfig.detectorElementSplitter = - std::make_shared( + std::make_shared( itkConfig, logger.clone("TGeoITkModuleSplitter", config.layerLogLevel)); } diff --git a/Examples/Detectors/TGeoDetector/src/TGeoITkModuleSplitter.cpp b/Examples/Detectors/TGeoDetector/src/TGeoITkModuleSplitter.cpp index 42bbbd9c882..2ad248f2e13 100644 --- a/Examples/Detectors/TGeoDetector/src/TGeoITkModuleSplitter.cpp +++ b/Examples/Detectors/TGeoDetector/src/TGeoITkModuleSplitter.cpp @@ -21,14 +21,16 @@ #include #include -ActsExamples::TGeoITkModuleSplitter::TGeoITkModuleSplitter( - const ActsExamples::TGeoITkModuleSplitter::Config& cfg, +namespace ActsExamples { + +TGeoITkModuleSplitter::TGeoITkModuleSplitter( + const TGeoITkModuleSplitter::Config& cfg, std::unique_ptr logger) : m_cfg(cfg), m_logger(std::move(logger)) { initSplitCategories(); } -void ActsExamples::TGeoITkModuleSplitter::initSplitCategories() { +void TGeoITkModuleSplitter::initSplitCategories() { m_splitCategories.reserve(m_cfg.splitPatterns.size()); for (const std::pair& pattern_split_category : m_cfg.splitPatterns) { @@ -50,7 +52,7 @@ void ActsExamples::TGeoITkModuleSplitter::initSplitCategories() { /// If applicable, returns a split detector element inline std::vector> -ActsExamples::TGeoITkModuleSplitter::split( +TGeoITkModuleSplitter::split( const Acts::GeometryContext& gctx, std::shared_ptr detElement) const { // Is the current node covered by this splitter? @@ -66,10 +68,10 @@ ActsExamples::TGeoITkModuleSplitter::split( " node " + sensorName + " using split ranges of category " + std::get<1>(split_category)); if (!std::get<2>(split_category)) { - return ActsExamples::TGeoITkModuleSplitter::splitBarrelModule( + return TGeoITkModuleSplitter::splitBarrelModule( gctx, detElement, m_cfg.barrelMap.at(std::get<1>(split_category))); } else { - return ActsExamples::TGeoITkModuleSplitter::splitDiscModule( + return TGeoITkModuleSplitter::splitDiscModule( gctx, detElement, m_cfg.discMap.at(std::get<1>(split_category))); } } @@ -83,7 +85,7 @@ ActsExamples::TGeoITkModuleSplitter::split( /// If applicable, returns a split detector element inline std::vector> -ActsExamples::TGeoITkModuleSplitter::splitBarrelModule( +TGeoITkModuleSplitter::splitBarrelModule( const Acts::GeometryContext& gctx, const std::shared_ptr& detElement, unsigned int nSegments) const { @@ -101,11 +103,10 @@ ActsExamples::TGeoITkModuleSplitter::splitBarrelModule( /// If applicable, returns a split detector element inline std::vector> -ActsExamples::TGeoITkModuleSplitter::splitDiscModule( +TGeoITkModuleSplitter::splitDiscModule( const Acts::GeometryContext& gctx, const std::shared_ptr& detElement, - const std::vector& - splitRanges) const { + const std::vector& splitRanges) const { auto name = detElement->tgeoNode().GetName(); auto factory = [&](const auto& trafo, const auto& bounds) { @@ -117,3 +118,5 @@ ActsExamples::TGeoITkModuleSplitter::splitDiscModule( return ITk::splitDiscModule(gctx, detElement, splitRanges, factory, name, logger()); } + +} // namespace ActsExamples diff --git a/Examples/Detectors/TelescopeDetector/include/ActsExamples/TelescopeDetector/BuildTelescopeDetector.hpp b/Examples/Detectors/TelescopeDetector/include/ActsExamples/TelescopeDetector/BuildTelescopeDetector.hpp index 9e3b5977a6a..6e3b4e31cdf 100644 --- a/Examples/Detectors/TelescopeDetector/include/ActsExamples/TelescopeDetector/BuildTelescopeDetector.hpp +++ b/Examples/Detectors/TelescopeDetector/include/ActsExamples/TelescopeDetector/BuildTelescopeDetector.hpp @@ -9,9 +9,7 @@ #pragma once #include "Acts/Geometry/TrackingGeometry.hpp" -#include "Acts/Utilities/BinUtility.hpp" #include "Acts/Utilities/BinningType.hpp" -#include "ActsExamples/TelescopeDetector/TelescopeDetectorElement.hpp" #include #include @@ -21,7 +19,7 @@ namespace Acts { class TrackingGeometry; } // namespace Acts -namespace ActsExamples::Telescope { +namespace ActsExamples { /// The telescope detector surface type enum class TelescopeSurfaceType { @@ -45,13 +43,14 @@ enum class TelescopeSurfaceType { /// @param surfaceType is the detector surface type /// @param binValue indicates which axis the detector surface normals are /// parallel to -std::unique_ptr buildDetector( - const typename TelescopeDetectorElement::ContextType& gctx, - std::vector>& detectorStore, +std::unique_ptr buildTelescopeDetector( + const Acts::GeometryContext& gctx, + std::vector>& + detectorStore, const std::vector& positions, const std::vector& stereoAngles, const std::array& offsets, const std::array& bounds, double thickness, TelescopeSurfaceType surfaceType, Acts::BinningValue binValue = Acts::BinningValue::binZ); -} // namespace ActsExamples::Telescope +} // namespace ActsExamples diff --git a/Examples/Detectors/TelescopeDetector/include/ActsExamples/TelescopeDetector/TelescopeDetector.hpp b/Examples/Detectors/TelescopeDetector/include/ActsExamples/TelescopeDetector/TelescopeDetector.hpp index 31095f42636..76b81984fb0 100644 --- a/Examples/Detectors/TelescopeDetector/include/ActsExamples/TelescopeDetector/TelescopeDetector.hpp +++ b/Examples/Detectors/TelescopeDetector/include/ActsExamples/TelescopeDetector/TelescopeDetector.hpp @@ -9,37 +9,24 @@ #pragma once #include "Acts/Definitions/Units.hpp" -#include "Acts/Utilities/Logger.hpp" -#include "ActsExamples/Utilities/Options.hpp" +#include "Acts/Geometry/DetectorElementBase.hpp" #include #include #include #include -using namespace Acts::UnitLiterals; - namespace Acts { class TrackingGeometry; class IMaterialDecorator; } // namespace Acts namespace ActsExamples { -class IContextDecorator; -} // namespace ActsExamples - -namespace ActsExamples::Telescope { -class TelescopeDetectorElement; -class TelescopeG4DetectorConstruction; +class IContextDecorator; struct TelescopeDetector { - using DetectorElement = ActsExamples::Telescope::TelescopeDetectorElement; - using DetectorElementPtr = std::shared_ptr; - using DetectorStore = std::vector; - - using ContextDecorators = - std::vector>; + using ContextDecorators = std::vector>; using TrackingGeometryPtr = std::shared_ptr; struct Config { @@ -47,18 +34,18 @@ struct TelescopeDetector { std::vector stereos{{0, 0, 0, 0, 0, 0}}; std::array offsets{{0, 0}}; std::array bounds{{25, 100}}; - double thickness{80_um}; + double thickness{80 * Acts::UnitConstants::um}; int surfaceType{0}; int binValue{2}; }; Config config; /// The store of the detector elements (lifetime: job) - DetectorStore detectorStore; + std::vector> detectorStore; std::pair finalize( const Config& cfg, const std::shared_ptr& mdecorator); }; -} // namespace ActsExamples::Telescope +} // namespace ActsExamples diff --git a/Examples/Detectors/TelescopeDetector/include/ActsExamples/TelescopeDetector/TelescopeDetectorElement.hpp b/Examples/Detectors/TelescopeDetector/include/ActsExamples/TelescopeDetector/TelescopeDetectorElement.hpp index 5a5d276cf9e..f3fa5a4b8bd 100644 --- a/Examples/Detectors/TelescopeDetector/include/ActsExamples/TelescopeDetector/TelescopeDetectorElement.hpp +++ b/Examples/Detectors/TelescopeDetector/include/ActsExamples/TelescopeDetector/TelescopeDetectorElement.hpp @@ -24,7 +24,7 @@ class DiscBounds; class ISurfaceMaterial; } // namespace Acts -namespace ActsExamples::Telescope { +namespace ActsExamples { /// @class TelescopeDetectorElement /// @@ -159,4 +159,4 @@ TelescopeDetectorElement::alignedTransforms() const { return m_alignedTransforms; } -} // namespace ActsExamples::Telescope +} // namespace ActsExamples diff --git a/Examples/Detectors/TelescopeDetector/src/BuildTelescopeDetector.cpp b/Examples/Detectors/TelescopeDetector/src/BuildTelescopeDetector.cpp index 7e01a9499bd..d436d577235 100644 --- a/Examples/Detectors/TelescopeDetector/src/BuildTelescopeDetector.cpp +++ b/Examples/Detectors/TelescopeDetector/src/BuildTelescopeDetector.cpp @@ -12,6 +12,7 @@ #include "Acts/Definitions/Units.hpp" #include "Acts/Geometry/CuboidVolumeBounds.hpp" #include "Acts/Geometry/CylinderVolumeBounds.hpp" +#include "Acts/Geometry/DetectorElementBase.hpp" #include "Acts/Geometry/DiscLayer.hpp" #include "Acts/Geometry/GeometryContext.hpp" #include "Acts/Geometry/ILayerArrayCreator.hpp" @@ -28,22 +29,21 @@ #include "Acts/Surfaces/Surface.hpp" #include "Acts/Surfaces/SurfaceArray.hpp" #include "Acts/Utilities/Logger.hpp" +#include "ActsExamples/TelescopeDetector/TelescopeDetectorElement.hpp" #include #include #include std::unique_ptr -ActsExamples::Telescope::buildDetector( - const typename ActsExamples::Telescope::TelescopeDetectorElement:: - ContextType& gctx, - std::vector< - std::shared_ptr>& +ActsExamples::buildTelescopeDetector( + const Acts::GeometryContext& gctx, + std::vector>& detectorStore, const std::vector& positions, const std::vector& stereoAngles, const std::array& offsets, const std::array& bounds, - double thickness, ActsExamples::Telescope::TelescopeSurfaceType surfaceType, + double thickness, TelescopeSurfaceType surfaceType, Acts::BinningValue binValue) { using namespace Acts::UnitLiterals; diff --git a/Examples/Detectors/TelescopeDetector/src/TelescopeDetector.cpp b/Examples/Detectors/TelescopeDetector/src/TelescopeDetector.cpp index 7a5e262067a..bbf1aff4106 100644 --- a/Examples/Detectors/TelescopeDetector/src/TelescopeDetector.cpp +++ b/Examples/Detectors/TelescopeDetector/src/TelescopeDetector.cpp @@ -8,6 +8,7 @@ #include "ActsExamples/TelescopeDetector/TelescopeDetector.hpp" +#include "Acts/Geometry/GeometryContext.hpp" #include "Acts/Geometry/TrackingGeometry.hpp" #include "Acts/Utilities/BinningType.hpp" #include "ActsExamples/TelescopeDetector/BuildTelescopeDetector.hpp" @@ -16,10 +17,12 @@ #include #include -auto ActsExamples::Telescope::TelescopeDetector::finalize( +namespace ActsExamples { + +auto TelescopeDetector::finalize( const Config& cfg, const std::shared_ptr& /*mdecorator*/) -> std::pair { - DetectorElement::ContextType nominalContext; + TelescopeDetectorElement::ContextType nominalContext; if (cfg.surfaceType > 1) { throw std::invalid_argument( @@ -48,15 +51,18 @@ auto ActsExamples::Telescope::TelescopeDetector::finalize( std::vector stereos = cfg.stereos; std::ranges::sort(positions); - /// Return the telescope detector - TrackingGeometryPtr gGeometry = ActsExamples::Telescope::buildDetector( - nominalContext, detectorStore, positions, stereos, cfg.offsets, - cfg.bounds, cfg.thickness, - static_cast( - cfg.surfaceType), - static_cast(cfg.binValue)); + Acts::GeometryContext geometryContext(nominalContext); + + // Return the telescope detector + TrackingGeometryPtr gGeometry = + buildTelescopeDetector(geometryContext, detectorStore, positions, stereos, + cfg.offsets, cfg.bounds, cfg.thickness, + static_cast(cfg.surfaceType), + static_cast(cfg.binValue)); ContextDecorators gContextDecorators = {}; // return the pair of geometry and empty decorators return std::make_pair( std::move(gGeometry), std::move(gContextDecorators)); } + +} // namespace ActsExamples diff --git a/Examples/Detectors/TelescopeDetector/src/TelescopeDetectorElement.cpp b/Examples/Detectors/TelescopeDetector/src/TelescopeDetectorElement.cpp index 22421064ef1..25fdca6c852 100644 --- a/Examples/Detectors/TelescopeDetector/src/TelescopeDetectorElement.cpp +++ b/Examples/Detectors/TelescopeDetector/src/TelescopeDetectorElement.cpp @@ -11,7 +11,9 @@ #include "Acts/Surfaces/DiscSurface.hpp" #include "Acts/Surfaces/PlaneSurface.hpp" -ActsExamples::Telescope::TelescopeDetectorElement::TelescopeDetectorElement( +namespace ActsExamples { + +TelescopeDetectorElement::TelescopeDetectorElement( std::shared_ptr transform, std::shared_ptr pBounds, double thickness, std::shared_ptr material) @@ -27,7 +29,7 @@ ActsExamples::Telescope::TelescopeDetectorElement::TelescopeDetectorElement( mutableSurface->assignSurfaceMaterial(std::move(material)); } -ActsExamples::Telescope::TelescopeDetectorElement::TelescopeDetectorElement( +TelescopeDetectorElement::TelescopeDetectorElement( std::shared_ptr transform, std::shared_ptr dBounds, double thickness, std::shared_ptr material) @@ -40,3 +42,5 @@ ActsExamples::Telescope::TelescopeDetectorElement::TelescopeDetectorElement( m_elementDiscBounds(std::move(dBounds)) { m_elementSurface->assignSurfaceMaterial(std::move(material)); } + +} // namespace ActsExamples diff --git a/Examples/Framework/ML/src/NeuralCalibrator.cpp b/Examples/Framework/ML/src/NeuralCalibrator.cpp index 67c6e76db57..83c7a2bc09a 100644 --- a/Examples/Framework/ML/src/NeuralCalibrator.cpp +++ b/Examples/Framework/ML/src/NeuralCalibrator.cpp @@ -189,9 +189,7 @@ void ActsExamples::NeuralCalibrator::calibrate( calibratedCovariance(boundLoc0, boundLoc0) = output[iVar0]; calibratedCovariance(boundLoc1, boundLoc1) = output[iVar0 + 1]; - trackState.allocateCalibrated(kMeasurementSize); - trackState.calibrated() = calibratedParameters; - trackState.calibratedCovariance() = calibratedCovariance; - trackState.setSubspaceIndices(fixedMeasurement.subspaceIndices()); + trackState.allocateCalibrated(calibratedParameters, calibratedCovariance); + trackState.setProjectorSubspaceIndices(fixedMeasurement.subspaceIndices()); }); } diff --git a/Examples/Framework/include/ActsExamples/EventData/DriftCircle.hpp b/Examples/Framework/include/ActsExamples/EventData/DriftCircle.hpp index 88cad84fffe..3d9ab8c241f 100644 --- a/Examples/Framework/include/ActsExamples/EventData/DriftCircle.hpp +++ b/Examples/Framework/include/ActsExamples/EventData/DriftCircle.hpp @@ -23,8 +23,6 @@ namespace ActsExamples { /// representation of a drift circle measurement used for track finding class DriftCircle { - using Scalar = Acts::ActsScalar; - public: /// Construct the drift circle from the drift radius and tube location /// @@ -52,11 +50,11 @@ class DriftCircle { m_tubeLayer(tubeLayer), m_tube(tube) {} - constexpr Scalar x() const { return m_x; } - constexpr Scalar y() const { return m_y; } - constexpr Scalar z() const { return m_z; } - constexpr Scalar rDrift() const { return m_rho; } - constexpr Scalar rDriftError() const { return m_sigmaRho; } + constexpr double x() const { return m_x; } + constexpr double y() const { return m_y; } + constexpr double z() const { return m_z; } + constexpr double rDrift() const { return m_rho; } + constexpr double rDriftError() const { return m_sigmaRho; } constexpr int stationName() const { return m_stationName; } constexpr int stationEta() const { return m_stationEta; } constexpr int stationPhi() const { return m_stationPhi; } @@ -66,11 +64,11 @@ class DriftCircle { private: // Global position - Scalar m_x = 0.0f; - Scalar m_y = 0.0f; - Scalar m_z = 0.0f; - Scalar m_rho = 0.0f; - Scalar m_sigmaRho = 0.0f; + double m_x = 0.; + double m_y = 0.; + double m_z = 0.; + double m_rho = 0.; + double m_sigmaRho = 0.; int m_stationName = 0; int m_stationEta = 0; int m_stationPhi = 0; diff --git a/Examples/Framework/include/ActsExamples/EventData/Measurement.hpp b/Examples/Framework/include/ActsExamples/EventData/Measurement.hpp index ab232628341..174dc05ef40 100644 --- a/Examples/Framework/include/ActsExamples/EventData/Measurement.hpp +++ b/Examples/Framework/include/ActsExamples/EventData/Measurement.hpp @@ -10,25 +10,16 @@ #include "Acts/Definitions/Algebra.hpp" #include "Acts/Definitions/TrackParametrization.hpp" -#include "Acts/EventData/MeasurementHelpers.hpp" #include "Acts/EventData/SubspaceHelpers.hpp" #include "Acts/EventData/Types.hpp" -#include "Acts/EventData/detail/ParameterTraits.hpp" -#include "Acts/EventData/detail/PrintParameters.hpp" #include "Acts/Geometry/GeometryIdentifier.hpp" #include "Acts/Utilities/Iterator.hpp" #include "ActsExamples/EventData/GeometryContainers.hpp" #include "ActsExamples/EventData/IndexSourceLink.hpp" #include "ActsExamples/EventData/MeasurementConcept.hpp" -#include -#include -#include #include -#include -#include #include -#include #include #include @@ -138,6 +129,11 @@ class MeasurementContainer { return getMeasurement(addMeasurement(Size, geometryId)); } + template + VariableProxy copyMeasurement(const OtherDerived& other); + template + FixedProxy copyMeasurement(const OtherDerived& other); + template VariableProxy emplaceMeasurement(std::uint8_t size, Acts::GeometryIdentifier geometryId, @@ -494,6 +490,22 @@ class VariableMeasurementProxy } }; +template +MeasurementContainer::VariableProxy MeasurementContainer::copyMeasurement( + const OtherDerived& other) { + VariableProxy meas = makeMeasurement(other.size(), other.geometryId()); + meas.copyFrom(other); + return meas; +} + +template +MeasurementContainer::FixedProxy MeasurementContainer::copyMeasurement( + const OtherDerived& other) { + FixedProxy meas = makeMeasurement(other.geometryId()); + meas.copyFrom(other); + return meas; +} + template MeasurementContainer::VariableProxy MeasurementContainer::emplaceMeasurement( std::uint8_t size, Acts::GeometryIdentifier geometryId, Args&&... args) { diff --git a/Examples/Framework/include/ActsExamples/EventData/MeasurementConcept.hpp b/Examples/Framework/include/ActsExamples/EventData/MeasurementConcept.hpp index 14627a78c53..9394b1bf992 100644 --- a/Examples/Framework/include/ActsExamples/EventData/MeasurementConcept.hpp +++ b/Examples/Framework/include/ActsExamples/EventData/MeasurementConcept.hpp @@ -8,7 +8,6 @@ #pragma once -#include "Acts/EventData/SourceLink.hpp" #include "Acts/Geometry/GeometryIdentifier.hpp" #include @@ -23,4 +22,5 @@ concept MeasurementConcept = requires(const T& m) { { m.parameters() }; { m.covariance() }; }; + } // namespace ActsExamples diff --git a/Examples/Framework/include/ActsExamples/EventData/PropagationSummary.hpp b/Examples/Framework/include/ActsExamples/EventData/PropagationSummary.hpp index aa9a736675f..1d1ef44f499 100644 --- a/Examples/Framework/include/ActsExamples/EventData/PropagationSummary.hpp +++ b/Examples/Framework/include/ActsExamples/EventData/PropagationSummary.hpp @@ -10,6 +10,7 @@ #include "Acts/EventData/TrackParameters.hpp" #include "Acts/Propagator/MaterialInteractor.hpp" +#include "Acts/Propagator/PropagatorStatistics.hpp" #include "Acts/Propagator/detail/SteppingLogger.hpp" #include @@ -34,6 +35,9 @@ struct PropagationSummary { /// Steps std::vector steps; + + /// Propagation statistics + Acts::PropagatorStatistics statistics; }; using PropagationSummaries = std::vector; diff --git a/Examples/Framework/include/ActsExamples/EventData/SimParticle.hpp b/Examples/Framework/include/ActsExamples/EventData/SimParticle.hpp index cfcf8a5e25e..2bf9dcc8cbc 100644 --- a/Examples/Framework/include/ActsExamples/EventData/SimParticle.hpp +++ b/Examples/Framework/include/ActsExamples/EventData/SimParticle.hpp @@ -23,10 +23,6 @@ using SimParticleState = ::ActsFatras::Particle; class SimParticle final { public: - using Scalar = Acts::ActsScalar; - using Vector3 = Acts::ActsVector<3>; - using Vector4 = Acts::ActsVector<4>; - /// Construct a default particle with invalid identity. SimParticle() = default; @@ -39,8 +35,8 @@ class SimParticle final { /// /// @warning It is the users responsibility that charge and mass match /// the PDG particle number. - SimParticle(SimBarcode particleId, Acts::PdgParticle pdg, Scalar charge, - Scalar mass) + SimParticle(SimBarcode particleId, Acts::PdgParticle pdg, double charge, + double mass) : m_initial(particleId, pdg, charge, mass), m_final(particleId, pdg, charge, mass) {} @@ -89,13 +85,13 @@ class SimParticle final { return *this; } /// Set the charge. - SimParticle& setCharge(Scalar charge) { + SimParticle& setCharge(double charge) { initial().setCharge(charge); final().setCharge(charge); return *this; } /// Set the mass. - SimParticle& setMass(Scalar mass) { + SimParticle& setMass(double mass) { initial().setMass(mass); final().setMass(mass); return *this; diff --git a/Examples/Framework/include/ActsExamples/EventData/SimSpacePoint.hpp b/Examples/Framework/include/ActsExamples/EventData/SimSpacePoint.hpp index 0359913199f..bf5780c5a76 100644 --- a/Examples/Framework/include/ActsExamples/EventData/SimSpacePoint.hpp +++ b/Examples/Framework/include/ActsExamples/EventData/SimSpacePoint.hpp @@ -23,8 +23,6 @@ namespace ActsExamples { /// Space point representation of a measurement suitable for track seeding. class SimSpacePoint { - using Scalar = Acts::ActsScalar; - public: /// Construct the space point from global position and selected variances. /// @@ -44,10 +42,10 @@ class SimSpacePoint { /// @param validDoubleMeasurementDetails boolean to check if double measurements are valid template SimSpacePoint( - const Eigen::MatrixBase& pos, std::optional t, - Scalar varRho, Scalar varZ, std::optional varT, + const Eigen::MatrixBase& pos, std::optional t, + double varRho, double varZ, std::optional varT, boost::container::static_vector sourceLinks, - Scalar topHalfStripLength, Scalar bottomHalfStripLength, + double topHalfStripLength, double bottomHalfStripLength, const Acts::Vector3& topStripDirection, const Acts::Vector3& bottomStripDirection, const Acts::Vector3& stripCenterDistance, @@ -82,8 +80,8 @@ class SimSpacePoint { /// @param sourceLinks sourceLinks of the measurements template SimSpacePoint( - const Eigen::MatrixBase& pos, std::optional t, - Scalar varRho, Scalar varZ, std::optional varT, + const Eigen::MatrixBase& pos, std::optional t, + double varRho, double varZ, std::optional varT, boost::container::static_vector sourceLinks) : m_x(pos[Acts::ePos0]), m_y(pos[Acts::ePos1]), @@ -97,14 +95,14 @@ class SimSpacePoint { EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(position_t, 3); } - constexpr Scalar x() const { return m_x; } - constexpr Scalar y() const { return m_y; } - constexpr Scalar z() const { return m_z; } - constexpr std::optional t() const { return m_t; } - constexpr Scalar r() const { return m_rho; } - constexpr Scalar varianceR() const { return m_varianceRho; } - constexpr Scalar varianceZ() const { return m_varianceZ; } - constexpr std::optional varianceT() const { return m_varianceT; } + constexpr double x() const { return m_x; } + constexpr double y() const { return m_y; } + constexpr double z() const { return m_z; } + constexpr std::optional t() const { return m_t; } + constexpr double r() const { return m_rho; } + constexpr double varianceR() const { return m_varianceRho; } + constexpr double varianceZ() const { return m_varianceZ; } + constexpr std::optional varianceT() const { return m_varianceT; } const boost::container::static_vector& sourceLinks() const { @@ -127,15 +125,15 @@ class SimSpacePoint { private: // Global position - Scalar m_x; - Scalar m_y; - Scalar m_z; - std::optional m_t; - Scalar m_rho; + double m_x; + double m_y; + double m_z; + std::optional m_t; + double m_rho; // Variance in rho/z of the global coordinates - Scalar m_varianceRho; - Scalar m_varianceZ; - std::optional m_varianceT; + double m_varianceRho; + double m_varianceZ; + std::optional m_varianceT; // SourceLinks of the corresponding measurements. A Pixel (strip) SP has one // (two) sourceLink(s). boost::container::static_vector m_sourceLinks; diff --git a/Examples/Framework/include/ActsExamples/EventData/SimVertex.hpp b/Examples/Framework/include/ActsExamples/EventData/SimVertex.hpp index 0bdfbb4925c..db906790e8b 100644 --- a/Examples/Framework/include/ActsExamples/EventData/SimVertex.hpp +++ b/Examples/Framework/include/ActsExamples/EventData/SimVertex.hpp @@ -77,13 +77,10 @@ class SimVertexBarcode { /// A simulated vertex e.g. from a physics process. struct SimVertex { - using Scalar = Acts::ActsScalar; - using Vector4 = Acts::ActsVector<4>; - /// The vertex ID SimVertexBarcode id; /// The vertex four-position - Vector4 position4 = Vector4::Zero(); + Acts::Vector4 position4 = Acts::Vector4::Zero(); /// The vertex process type ActsFatras::ProcessType process = ActsFatras::ProcessType::eUndefined; /// The incoming particles into the vertex @@ -99,7 +96,7 @@ struct SimVertex { /// Associated particles are left empty by default and must be filled by the /// user after construction. SimVertex( - SimVertexBarcode id_, const Vector4& position4_, + SimVertexBarcode id_, const Acts::Vector4& position4_, ActsFatras::ProcessType process_ = ActsFatras::ProcessType::eUndefined) : id(id_), position4(position4_), process(process_) {} // explicitly default rule-of-five. @@ -113,7 +110,7 @@ struct SimVertex { /// The vertex three-position. auto position() const { return position4.head<3>(); } /// The vertex time. - Scalar time() const { return position4[3]; } + double time() const { return position4[3]; } }; namespace detail { diff --git a/Examples/Framework/src/EventData/MeasurementCalibration.cpp b/Examples/Framework/src/EventData/MeasurementCalibration.cpp index b4764844770..d7b8c96da70 100644 --- a/Examples/Framework/src/EventData/MeasurementCalibration.cpp +++ b/Examples/Framework/src/EventData/MeasurementCalibration.cpp @@ -41,11 +41,9 @@ void ActsExamples::PassThroughCalibrator::calibrate( static_cast>( measurement); - trackState.allocateCalibrated(kMeasurementSize); - trackState.calibrated() = fixedMeasurement.parameters(); - trackState.calibratedCovariance() = - fixedMeasurement.covariance(); - trackState.setSubspaceIndices(fixedMeasurement.subspaceIndices()); + trackState.allocateCalibrated(fixedMeasurement.parameters().eval(), + fixedMeasurement.covariance().eval()); + trackState.setProjectorSubspaceIndices(fixedMeasurement.subspaceIndices()); }); } diff --git a/Examples/Framework/src/EventData/ScalingCalibrator.cpp b/Examples/Framework/src/EventData/ScalingCalibrator.cpp index ae5c1eca4fe..50e693e8b15 100644 --- a/Examples/Framework/src/EventData/ScalingCalibrator.cpp +++ b/Examples/Framework/src/EventData/ScalingCalibrator.cpp @@ -178,9 +178,7 @@ void ActsExamples::ScalingCalibrator::calibrate( calibratedCovariance(boundLoc0, boundLoc0) *= ct.x_scale; calibratedCovariance(boundLoc1, boundLoc1) *= ct.y_scale; - trackState.allocateCalibrated(kMeasurementSize); - trackState.calibrated() = calibratedParameters; - trackState.calibratedCovariance() = calibratedCovariance; - trackState.setSubspaceIndices(fixedMeasurement.subspaceIndices()); + trackState.allocateCalibrated(calibratedParameters, calibratedCovariance); + trackState.setProjectorSubspaceIndices(fixedMeasurement.subspaceIndices()); }); } diff --git a/Examples/Io/Csv/src/CsvDriftCircleReader.cpp b/Examples/Io/Csv/src/CsvDriftCircleReader.cpp index ce179d9d5be..ad2500637ed 100644 --- a/Examples/Io/Csv/src/CsvDriftCircleReader.cpp +++ b/Examples/Io/Csv/src/CsvDriftCircleReader.cpp @@ -61,10 +61,9 @@ ActsExamples::ProcessCode ActsExamples::CsvDriftCircleReader::read( MuonDriftCircleData data; while (reader.read(data)) { - ActsFatras::Hit::Vector3 tube_pos{ - data.tubePositionx * Acts::UnitConstants::mm, - data.tubePositiony * Acts::UnitConstants::mm, - data.tubePositionz * Acts::UnitConstants::mm}; + Acts::Vector3 tube_pos{data.tubePositionx * Acts::UnitConstants::mm, + data.tubePositiony * Acts::UnitConstants::mm, + data.tubePositionz * Acts::UnitConstants::mm}; DriftCircles.push_back(DriftCircle(std::move(tube_pos), data.driftRadius, 0.0f, data.stationName, data.stationEta, diff --git a/Examples/Io/Csv/src/CsvMuonSimHitReader.cpp b/Examples/Io/Csv/src/CsvMuonSimHitReader.cpp index 58240dcecce..28836dc48de 100644 --- a/Examples/Io/Csv/src/CsvMuonSimHitReader.cpp +++ b/Examples/Io/Csv/src/CsvMuonSimHitReader.cpp @@ -61,18 +61,16 @@ ActsExamples::ProcessCode ActsExamples::CsvMuonSimHitReader::read( SimHitContainer::sequence_type unordered; while (reader.read(data)) { - ActsFatras::Hit::Vector4 pos{ - data.LocalPositionExtrx * Acts::UnitConstants::mm, - data.LocalPositionExtry * Acts::UnitConstants::mm, - data.LocalPositionExtrz * Acts::UnitConstants::mm, 0}; - ActsFatras::Hit::Vector4 mom{ - data.LocalDirectionx * Acts::UnitConstants::GeV, - data.LocalDirectiony * Acts::UnitConstants::GeV, - data.LocalDirectionz * Acts::UnitConstants::GeV, - std::sqrt(data.LocalDirectionx * data.LocalDirectionx + - data.LocalDirectiony * data.LocalDirectiony + - data.LocalDirectionz * data.LocalDirectionz) * - Acts::UnitConstants::GeV}; + Acts::Vector4 pos{data.LocalPositionExtrx * Acts::UnitConstants::mm, + data.LocalPositionExtry * Acts::UnitConstants::mm, + data.LocalPositionExtrz * Acts::UnitConstants::mm, 0}; + Acts::Vector4 mom{data.LocalDirectionx * Acts::UnitConstants::GeV, + data.LocalDirectiony * Acts::UnitConstants::GeV, + data.LocalDirectionz * Acts::UnitConstants::GeV, + std::sqrt(data.LocalDirectionx * data.LocalDirectionx + + data.LocalDirectiony * data.LocalDirectiony + + data.LocalDirectionz * data.LocalDirectionz) * + Acts::UnitConstants::GeV}; MuonMdtIdentifierFields f; f.multilayer = 0; f.tube = 0; diff --git a/Examples/Io/Csv/src/CsvSimHitReader.cpp b/Examples/Io/Csv/src/CsvSimHitReader.cpp index 949b6d4ce5c..ca77c7e0aa4 100644 --- a/Examples/Io/Csv/src/CsvSimHitReader.cpp +++ b/Examples/Io/Csv/src/CsvSimHitReader.cpp @@ -66,19 +66,19 @@ ActsExamples::ProcessCode ActsExamples::CsvSimHitReader::read( // TODO validate geo id consistency const auto particleId = ActsFatras::Barcode(data.particle_id); - ActsFatras::Hit::Vector4 pos4{ + Acts::Vector4 pos4{ data.tx * Acts::UnitConstants::mm, data.ty * Acts::UnitConstants::mm, data.tz * Acts::UnitConstants::mm, data.tt * Acts::UnitConstants::mm, }; - ActsFatras::Hit::Vector4 mom4{ + Acts::Vector4 mom4{ data.tpx * Acts::UnitConstants::GeV, data.tpy * Acts::UnitConstants::GeV, data.tpz * Acts::UnitConstants::GeV, data.te * Acts::UnitConstants::GeV, }; - ActsFatras::Hit::Vector4 delta4{ + Acts::Vector4 delta4{ data.deltapx * Acts::UnitConstants::GeV, data.deltapy * Acts::UnitConstants::GeV, data.deltapz * Acts::UnitConstants::GeV, diff --git a/Examples/Io/Csv/src/CsvTrackingGeometryWriter.cpp b/Examples/Io/Csv/src/CsvTrackingGeometryWriter.cpp index 1257be23ff6..e40c679a055 100644 --- a/Examples/Io/Csv/src/CsvTrackingGeometryWriter.cpp +++ b/Examples/Io/Csv/src/CsvTrackingGeometryWriter.cpp @@ -128,12 +128,12 @@ void writeSurface(SurfaceWriter& sfWriter, const Acts::Surface& surface, /// @param transform the layer transform /// @param representingBoundValues [in,out] the bound values /// @param last is the last layer -void writeCylinderLayerVolume( - LayerVolumeWriter& lvWriter, const Acts::Layer& lv, - const Acts::Transform3& transform, - std::vector& representingBoundValues, - std::vector& volumeBoundValues, - std::vector& lastBoundValues, bool last) { +void writeCylinderLayerVolume(LayerVolumeWriter& lvWriter, + const Acts::Layer& lv, + const Acts::Transform3& transform, + std::vector& representingBoundValues, + std::vector& volumeBoundValues, + std::vector& lastBoundValues, bool last) { // The layer volume to be written LayerVolumeData lvDims; lvDims.geometry_id = lv.geometryId().value(); @@ -229,9 +229,8 @@ void writeVolume(SurfaceWriter& sfWriter, SurfaceGridWriter& sfGridWriter, const auto& vTransform = volume.transform(); // Get the values of the volume boundaries - std::vector volumeBoundValues = - volume.volumeBounds().values(); - std::vector lastBoundValues; + std::vector volumeBoundValues = volume.volumeBounds().values(); + std::vector lastBoundValues; if (volume.volumeBounds().type() == Acts::VolumeBounds::eCylinder) { auto vTranslation = vTransform.translation(); @@ -285,7 +284,7 @@ void writeVolume(SurfaceWriter& sfWriter, SurfaceGridWriter& sfGridWriter, // Write the layer volume, exclude single layer volumes (written above) if (rVolume != nullptr && writeLayerVolume && layers.size() > 3) { // Get the values of the representing volume - std::vector representingBoundValues = + std::vector representingBoundValues = rVolume->volumeBounds().values(); if (rVolume->volumeBounds().type() == Acts::VolumeBounds::eCylinder) { bool last = (layerIdx + 2 == diff --git a/Examples/Io/EDM4hep/include/ActsExamples/Io/EDM4hep/EDM4hepMeasurementWriter.hpp b/Examples/Io/EDM4hep/include/ActsExamples/Io/EDM4hep/EDM4hepMeasurementWriter.hpp index d559ee9a5e4..04cf8805df4 100644 --- a/Examples/Io/EDM4hep/include/ActsExamples/Io/EDM4hep/EDM4hepMeasurementWriter.hpp +++ b/Examples/Io/EDM4hep/include/ActsExamples/Io/EDM4hep/EDM4hepMeasurementWriter.hpp @@ -16,9 +16,6 @@ #include -#include -#include - namespace ActsExamples { /// Write out a measurement cluster collection to EDM4hep. diff --git a/Examples/Io/EDM4hep/include/ActsExamples/Io/EDM4hep/EDM4hepReader.hpp b/Examples/Io/EDM4hep/include/ActsExamples/Io/EDM4hep/EDM4hepReader.hpp index 204f88ad83a..07c4e771857 100644 --- a/Examples/Io/EDM4hep/include/ActsExamples/Io/EDM4hep/EDM4hepReader.hpp +++ b/Examples/Io/EDM4hep/include/ActsExamples/Io/EDM4hep/EDM4hepReader.hpp @@ -25,9 +25,7 @@ namespace ActsExamples { -namespace DD4hep { struct DD4hepDetector; -} /// Read particles from EDM4hep. /// @@ -55,7 +53,7 @@ class EDM4hepReader final : public IReader { std::string graphvizOutput = ""; /// DD4hep detector for cellID resolution. - std::shared_ptr dd4hepDetector; + std::shared_ptr dd4hepDetector; /// Tracking geometry for cellID resolution. std::shared_ptr trackingGeometry; diff --git a/Examples/Io/EDM4hep/include/ActsExamples/Io/EDM4hep/EDM4hepUtil.hpp b/Examples/Io/EDM4hep/include/ActsExamples/Io/EDM4hep/EDM4hepUtil.hpp index bdce08bc876..4973763a087 100644 --- a/Examples/Io/EDM4hep/include/ActsExamples/Io/EDM4hep/EDM4hepUtil.hpp +++ b/Examples/Io/EDM4hep/include/ActsExamples/Io/EDM4hep/EDM4hepUtil.hpp @@ -8,6 +8,7 @@ #pragma once #include "Acts/Geometry/GeometryContext.hpp" +#include "Acts/Plugins/EDM4hep/TrackerHitCompatibility.hpp" #include "ActsExamples/EventData/Cluster.hpp" #include "ActsExamples/EventData/Measurement.hpp" #include "ActsExamples/EventData/SimParticle.hpp" @@ -16,15 +17,13 @@ #include -#include "edm4hep/MCParticle.h" -#include "edm4hep/MutableMCParticle.h" -#include "edm4hep/MutableSimTrackerHit.h" -#include "edm4hep/MutableTrack.h" -#include "edm4hep/MutableTrackerHitPlane.h" -#include "edm4hep/SimTrackerHit.h" -#include "edm4hep/TrackerHit.h" -#include "edm4hep/TrackerHitCollection.h" -#include "edm4hep/TrackerHitPlane.h" +#include +#include +#include +#include +#include +#include +#include namespace ActsExamples::EDM4hepUtil { @@ -91,7 +90,7 @@ void writeSimHit(const ActsFatras::Hit& from, edm4hep::MutableSimTrackerHit to, /// - local 2D coordinates and time are read from position VariableBoundMeasurementProxy readMeasurement( MeasurementContainer& container, const edm4hep::TrackerHitPlane& from, - const edm4hep::TrackerHitCollection* fromClusters, Cluster* toCluster, + const edm4hep::TrackerHit3DCollection* fromClusters, Cluster* toCluster, const MapGeometryIdFrom& geometryMapper); /// Writes a measurement cluster to EDM4hep. @@ -107,7 +106,7 @@ VariableBoundMeasurementProxy readMeasurement( void writeMeasurement(const ConstVariableBoundMeasurementProxy& from, edm4hep::MutableTrackerHitPlane to, const Cluster* fromCluster, - edm4hep::TrackerHitCollection& toClusters, + edm4hep::TrackerHit3DCollection& toClusters, const MapGeometryIdTo& geometryMapper); /// Writes a trajectory to EDM4hep. diff --git a/Examples/Io/EDM4hep/src/EDM4hepMeasurementReader.cpp b/Examples/Io/EDM4hep/src/EDM4hepMeasurementReader.cpp index 237ff19e3b6..5299da121ca 100644 --- a/Examples/Io/EDM4hep/src/EDM4hepMeasurementReader.cpp +++ b/Examples/Io/EDM4hep/src/EDM4hepMeasurementReader.cpp @@ -9,6 +9,7 @@ #include "ActsExamples/Io/EDM4hep/EDM4hepMeasurementReader.hpp" #include "Acts/Definitions/Units.hpp" +#include "Acts/Plugins/EDM4hep/TrackerHitCompatibility.hpp" #include "Acts/Plugins/Podio/PodioUtil.hpp" #include "ActsExamples/EventData/Cluster.hpp" #include "ActsExamples/EventData/Measurement.hpp" @@ -18,8 +19,6 @@ #include #include -#include -#include #include #include @@ -60,7 +59,7 @@ ProcessCode EDM4hepMeasurementReader::read(const AlgorithmContext& ctx) { const auto& trackerHitPlaneCollection = frame.get("ActsTrackerHitsPlane"); const auto& trackerHitRawCollection = - frame.get("ActsTrackerHitsRaw"); + frame.get("ActsTrackerHitsRaw"); for (const auto& trackerHitPlane : trackerHitPlaneCollection) { Cluster cluster; diff --git a/Examples/Io/EDM4hep/src/EDM4hepMeasurementWriter.cpp b/Examples/Io/EDM4hep/src/EDM4hepMeasurementWriter.cpp index 0f9e9422d28..23e291cc2dd 100644 --- a/Examples/Io/EDM4hep/src/EDM4hepMeasurementWriter.cpp +++ b/Examples/Io/EDM4hep/src/EDM4hepMeasurementWriter.cpp @@ -9,6 +9,7 @@ #include "ActsExamples/Io/EDM4hep/EDM4hepMeasurementWriter.hpp" #include "Acts/Definitions/Units.hpp" +#include "Acts/Plugins/EDM4hep/TrackerHitCompatibility.hpp" #include "ActsExamples/EventData/Cluster.hpp" #include "ActsExamples/EventData/Measurement.hpp" #include "ActsExamples/Framework/WhiteBoard.hpp" @@ -16,6 +17,8 @@ #include +#include +#include #include namespace ActsExamples { @@ -44,7 +47,7 @@ ActsExamples::ProcessCode EDM4hepMeasurementWriter::writeT( podio::Frame frame; edm4hep::TrackerHitPlaneCollection hitsPlane; - edm4hep::TrackerHitCollection hits; + edm4hep::TrackerHit3DCollection hits; if (!m_cfg.inputClusters.empty()) { ACTS_VERBOSE("Fetch clusters for writing: " << m_cfg.inputClusters); diff --git a/Examples/Io/EDM4hep/src/EDM4hepReader.cpp b/Examples/Io/EDM4hep/src/EDM4hepReader.cpp index 3d5008863a3..0b82a20181b 100644 --- a/Examples/Io/EDM4hep/src/EDM4hepReader.cpp +++ b/Examples/Io/EDM4hep/src/EDM4hepReader.cpp @@ -9,8 +9,8 @@ #include "ActsExamples/Io/EDM4hep/EDM4hepReader.hpp" #include "Acts/Definitions/Units.hpp" -#include "Acts/Geometry/GeometryIdentifier.hpp" #include "Acts/Plugins/DD4hep/DD4hepDetectorElement.hpp" +#include "Acts/Plugins/EDM4hep/EDM4hepUtil.hpp" #include "ActsExamples/DD4hepDetector/DD4hepDetector.hpp" #include "ActsExamples/EventData/SimHit.hpp" #include "ActsExamples/EventData/SimParticle.hpp" @@ -306,8 +306,9 @@ ProcessCode EDM4hepReader::read(const AlgorithmContext& ctx) { auto simHit = EDM4hepUtil::readSimHit( hit, [&](const auto& inParticle) { - ACTS_VERBOSE("SimHit has source particle: " - << hit.getMCParticle().getObjectID().index); + ACTS_VERBOSE( + "SimHit has source particle: " + << Acts::EDM4hepUtil::getParticle(hit).getObjectID().index); auto it = edm4hepParticleMap.find(inParticle.getObjectID().index); if (it == edm4hepParticleMap.end()) { ACTS_ERROR( @@ -371,8 +372,8 @@ ProcessCode EDM4hepReader::read(const AlgorithmContext& ctx) { for (auto it = hitsByParticle.begin(), end = hitsByParticle.end(); it != end; it = hitsByParticle.upper_bound(it->first)) { - std::cout << "Particle " << it->first << " has " - << hitsByParticle.count(it->first) << " hits" << std::endl; + ACTS_DEBUG("Particle " << it->first << " has " + << hitsByParticle.count(it->first) << " hits"); std::vector hitIndices; hitIndices.reserve(hitsByParticle.count(it->first)); diff --git a/Examples/Io/EDM4hep/src/EDM4hepUtil.cpp b/Examples/Io/EDM4hep/src/EDM4hepUtil.cpp index 38e26038779..adb433891d9 100644 --- a/Examples/Io/EDM4hep/src/EDM4hepUtil.cpp +++ b/Examples/Io/EDM4hep/src/EDM4hepUtil.cpp @@ -70,9 +70,10 @@ void EDM4hepUtil::writeParticle(const SimParticle& from, ActsFatras::Hit EDM4hepUtil::readSimHit( const edm4hep::SimTrackerHit& from, const MapParticleIdFrom& particleMapper, const MapGeometryIdFrom& geometryMapper) { - ActsFatras::Barcode particleId = particleMapper(from.getMCParticle()); + auto particle = Acts::EDM4hepUtil::getParticle(from); + ActsFatras::Barcode particleId = particleMapper(particle); - const auto mass = from.getMCParticle().getMass() * 1_GeV; + const auto mass = particle.getMass() * 1_GeV; const Acts::Vector3 momentum{ from.getMomentum().x * 1_GeV, from.getMomentum().y * 1_GeV, @@ -116,7 +117,7 @@ void EDM4hepUtil::writeSimHit(const ActsFatras::Hit& from, const auto delta4 = from.momentum4After() - momentum4Before; if (particleMapper) { - to.setMCParticle(particleMapper(from.particleId())); + Acts::EDM4hepUtil::setParticle(to, particleMapper(from.particleId())); } if (geometryMapper) { @@ -146,8 +147,8 @@ void EDM4hepUtil::writeSimHit(const ActsFatras::Hit& from, VariableBoundMeasurementProxy EDM4hepUtil::readMeasurement( MeasurementContainer& container, const edm4hep::TrackerHitPlane& from, - const edm4hep::TrackerHitCollection* fromClusters, Cluster* toCluster, - const MapGeometryIdFrom& geometryMapper) { + const edm4hep::TrackerHit3DCollection* /*fromClusters*/, + Cluster* /*toCluster*/, const MapGeometryIdFrom& geometryMapper) { // no need for digitization as we only want to identify the sensor Acts::GeometryIdentifier geometryId = geometryMapper(from.getCellID()); @@ -171,32 +172,15 @@ VariableBoundMeasurementProxy EDM4hepUtil::readMeasurement( auto to = createMeasurement(container, geometryId, dParameters); - if (fromClusters != nullptr) { - for (const auto objectId : from.getRawHits()) { - const auto& c = fromClusters->at(objectId.index); - - // TODO get EDM4hep fixed - // misusing some fields to store ACTS specific information - // don't ask ... - ActsFatras::Segmentizer::Bin2D bin{ - static_cast(c.getType()), - static_cast(c.getQuality())}; - ActsFatras::Segmentizer::Segment2D path2D{ - {Acts::Vector2::Zero(), Acts::Vector2::Zero()}}; - double activation = c.getTime(); - ActsFatras::Segmentizer::ChannelSegment cell{bin, path2D, activation}; - - toCluster->channels.push_back(cell); - } - } + // @TODO: Figure out if cell information is accessible return to; } void EDM4hepUtil::writeMeasurement( const ConstVariableBoundMeasurementProxy& from, - edm4hep::MutableTrackerHitPlane to, const Cluster* fromCluster, - edm4hep::TrackerHitCollection& toClusters, + edm4hep::MutableTrackerHitPlane to, const Cluster* /*fromCluster*/, + edm4hep::TrackerHit3DCollection& /*toClusters*/, const MapGeometryIdTo& geometryMapper) { Acts::GeometryIdentifier geoId = from.geometryId(); @@ -224,21 +208,7 @@ void EDM4hepUtil::writeMeasurement( 0, }); - if (fromCluster != nullptr) { - for (const auto& c : fromCluster->channels) { - auto toChannel = toClusters.create(); - to.addToRawHits(toChannel.getObjectID()); - - // TODO digitization channel - - // TODO get EDM4hep fixed - // misusing some fields to store ACTS specific information - // don't ask ... - toChannel.setType(c.bin[0]); - toChannel.setQuality(c.bin[1]); - toChannel.setTime(c.activation); - } - } + // @TODO: Check if we can write cell info } void EDM4hepUtil::writeTrajectory( @@ -296,17 +266,18 @@ void EDM4hepUtil::writeTrajectory( trackState.referencePoint.z = center.z(); if (converted.covariance) { - const auto& c = converted.covariance.value(); - - trackState.covMatrix = { - static_cast(c(0, 0)), static_cast(c(1, 0)), - static_cast(c(1, 1)), static_cast(c(2, 0)), - static_cast(c(2, 1)), static_cast(c(2, 2)), - static_cast(c(3, 0)), static_cast(c(3, 1)), - static_cast(c(3, 2)), static_cast(c(3, 3)), - static_cast(c(4, 0)), static_cast(c(4, 1)), - static_cast(c(4, 2)), static_cast(c(4, 3)), - static_cast(c(4, 4))}; + auto c = [&](std::size_t row, std::size_t col) { + return static_cast(converted.covariance.value()(row, col)); + }; + + // clang-format off + trackState.covMatrix = {c(0, 0), + c(1, 0), c(1, 1), + c(2, 0), c(2, 1), c(2, 2), + c(3, 0), c(3, 1), c(3, 2), c(3, 3), + c(4, 0), c(4, 1), c(4, 2), c(4, 3), c(4, 4), + c(5, 0), c(5, 1), c(5, 2), c(5, 3), c(5, 4), c(5, 5)}; + // clang-format on } to.addToTrackStates(trackState); diff --git a/Examples/Io/Json/CMakeLists.txt b/Examples/Io/Json/CMakeLists.txt index 255d862881f..5461f5dd98d 100644 --- a/Examples/Io/Json/CMakeLists.txt +++ b/Examples/Io/Json/CMakeLists.txt @@ -4,7 +4,6 @@ add_library( src/JsonGeometryList.cpp src/JsonMaterialWriter.cpp src/JsonSurfacesWriter.cpp - src/JsonSurfacesReader.cpp src/JsonDigitizationConfig.cpp ) target_include_directories( 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..94abea8b903 --- /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/Plugins/Json/GridJsonConverter.hpp" +#include "Acts/Surfaces/RectangleBounds.hpp" +#include "ActsExamples/TrackFinding/ITrackParamsLookupReader.hpp" + +#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 + refLayers; + /// Binning of the grid to be emposed + /// onto the reference layers + std::pair bins; + }; + + explicit JsonTrackParamsLookupReader(const Config& config) : m_cfg(config) {}; + + ~JsonTrackParamsLookupReader() override = default; + + /// @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) const override { + // Read the json file + std::ifstream ifj(path); + nlohmann::json jLookup; + ifj >> jLookup; + + TrackParamsLookup lookup; + // Iterate over the json and deserialize the grids + for (const auto& jGrid : jLookup) { + Acts::GeometryIdentifier id(jGrid["geo_id"]); + + if (!m_cfg.refLayers.contains(id)) { + 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(); + + TrackParamsLookupAxisGen axisGen{{-halfX, halfX}, + m_cfg.bins.first, + {-halfY, halfY}, + m_cfg.bins.second}; + + // Deserialize the grid + TrackParamsLookupGrid grid = + Acts::GridJsonConverter::fromJson( + jGrid["grid"], axisGen); + + lookup.try_emplace(id, std::move(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..63a2c083618 --- /dev/null +++ b/Examples/Io/Json/include/ActsExamples/Io/Json/JsonTrackParamsLookupWriter.hpp @@ -0,0 +1,69 @@ +// 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/Plugins/Json/GridJsonConverter.hpp" +#include "ActsExamples/TrackFinding/ITrackParamsLookupWriter.hpp" + +#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 + explicit JsonTrackParamsLookupWriter(const Config& config) : m_cfg(config) {}; + + /// Virtual destructor + ~JsonTrackParamsLookupWriter() override = default; + + /// Write out track parameters lookup table + /// + /// @param lookup The lookup to write + void writeLookup(const TrackParamsLookup& lookup) const override { + 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/Io/Json/src/JsonDigitizationConfig.cpp b/Examples/Io/Json/src/JsonDigitizationConfig.cpp index 489c86087bf..8e3b3abe2cc 100644 --- a/Examples/Io/Json/src/JsonDigitizationConfig.cpp +++ b/Examples/Io/Json/src/JsonDigitizationConfig.cpp @@ -87,12 +87,12 @@ void from_json( if (sType == "Gauss") { f = Digitization::Gauss(j["stddev"]); } else if (sType == "GaussTrunc") { - Acts::ActsScalar sigma = j["stddev"]; - std::pair range = j["range"]; + double sigma = j["stddev"]; + std::pair range = j["range"]; f = Digitization::GaussTrunc(sigma, range); } else if (sType == "GaussClipped") { - Acts::ActsScalar sigma = j["stddev"]; - std::pair range = j["range"]; + double sigma = j["stddev"]; + std::pair range = j["range"]; f = Digitization::GaussClipped(sigma, range); } else if (sType == "Uniform") { Acts::BinningData bd; @@ -159,7 +159,7 @@ void ActsExamples::from_json(const nlohmann::json& j, for (const auto& jvar : jvariances) { auto idx = static_cast(jvar["index"].get()); - auto vars = jvar["rms"].get>(); + auto vars = jvar["rms"].get>(); gdc.varianceMap[idx] = vars; } } diff --git a/Examples/Io/Root/include/ActsExamples/Io/Root/RootAthenaNTupleReader.hpp b/Examples/Io/Root/include/ActsExamples/Io/Root/RootAthenaNTupleReader.hpp index 7f4d6f7bc73..e6bba0782eb 100644 --- a/Examples/Io/Root/include/ActsExamples/Io/Root/RootAthenaNTupleReader.hpp +++ b/Examples/Io/Root/include/ActsExamples/Io/Root/RootAthenaNTupleReader.hpp @@ -178,6 +178,8 @@ class RootAthenaNTupleReader : public ActsExamples::IReader { /// @param config The Configuration struct RootAthenaNTupleReader(const Config &config, Acts::Logging::Level level); + ~RootAthenaNTupleReader() override; + /// Framework name() method std::string name() const final { return "RootAthenaNTupleReader"; } @@ -214,7 +216,7 @@ class RootAthenaNTupleReader : public ActsExamples::IReader { std::size_t m_events = 0; /// The input tree name - TChain *m_inputChain = nullptr; + std::unique_ptr m_inputChain; /// The handle to branches in current event BranchPointerWrapper m_branches; diff --git a/Examples/Io/Root/include/ActsExamples/Io/Root/RootMaterialTrackReader.hpp b/Examples/Io/Root/include/ActsExamples/Io/Root/RootMaterialTrackReader.hpp index 3c3bf2aece3..4c95c7e8d1d 100644 --- a/Examples/Io/Root/include/ActsExamples/Io/Root/RootMaterialTrackReader.hpp +++ b/Examples/Io/Root/include/ActsExamples/Io/Root/RootMaterialTrackReader.hpp @@ -94,7 +94,7 @@ class RootMaterialTrackReader : public IReader { std::size_t m_batchSize = 0; /// The input tree name - TChain* m_inputChain = nullptr; + std::unique_ptr m_inputChain; /// Event identifier. std::uint32_t m_eventId = 0; diff --git a/Examples/Io/Root/include/ActsExamples/Io/Root/RootParticleReader.hpp b/Examples/Io/Root/include/ActsExamples/Io/Root/RootParticleReader.hpp index 0bcd108570c..1e1e4f2adde 100644 --- a/Examples/Io/Root/include/ActsExamples/Io/Root/RootParticleReader.hpp +++ b/Examples/Io/Root/include/ActsExamples/Io/Root/RootParticleReader.hpp @@ -83,7 +83,7 @@ class RootParticleReader : public IReader { std::size_t m_events = 0; /// The input tree name - TChain* m_inputChain = nullptr; + std::unique_ptr m_inputChain; /// Event identifier. std::uint32_t m_eventId = 0; diff --git a/Examples/Io/Root/include/ActsExamples/Io/Root/RootPropagationSummaryWriter.hpp b/Examples/Io/Root/include/ActsExamples/Io/Root/RootPropagationSummaryWriter.hpp index c1f6afe9059..f9eea212b12 100644 --- a/Examples/Io/Root/include/ActsExamples/Io/Root/RootPropagationSummaryWriter.hpp +++ b/Examples/Io/Root/include/ActsExamples/Io/Root/RootPropagationSummaryWriter.hpp @@ -8,22 +8,18 @@ #pragma once -#include "Acts/Propagator/detail/SteppingLogger.hpp" #include "Acts/Utilities/Logger.hpp" #include "ActsExamples/Framework/ProcessCode.hpp" #include "ActsExamples/Framework/WriterT.hpp" #include "ActsExamples/Propagation/PropagationAlgorithm.hpp" -#include #include #include -#include class TFile; class TTree; namespace ActsExamples { -struct AlgorithmContext; /// @class RootPropagationSummaryWriter /// @@ -110,10 +106,17 @@ class RootPropagationSummaryWriter : public WriterT { int m_nMaterials = 0; int m_nPortals = 0; - // steper statistics - int m_nSteps = 0; - int m_nStepTrials = 0; - int m_pathLength = 0; + // stepper statistics + std::size_t m_nAttemptedSteps = 0; + std::size_t m_nRejectedSteps = 0; + std::size_t m_nSuccessfulSteps = 0; + std::size_t m_nReverseSteps = 0; + double m_pathLength = 0; + double m_absolutePathLength = 0; + + // navigator statistics + std::size_t m_nRenavigations = 0; + std::size_t m_nVolumeSwitches = 0; }; } // namespace ActsExamples diff --git a/Examples/Io/Root/include/ActsExamples/Io/Root/RootSimHitReader.hpp b/Examples/Io/Root/include/ActsExamples/Io/Root/RootSimHitReader.hpp index bf05678cd8f..7b784b87a58 100644 --- a/Examples/Io/Root/include/ActsExamples/Io/Root/RootSimHitReader.hpp +++ b/Examples/Io/Root/include/ActsExamples/Io/Root/RootSimHitReader.hpp @@ -48,6 +48,8 @@ class RootSimHitReader : public IReader { /// @param config The Configuration struct RootSimHitReader(const Config &config, Acts::Logging::Level level); + ~RootSimHitReader() override; + /// Framework name() method std::string name() const override { return "RootSimHitReader"; } @@ -79,7 +81,7 @@ class RootSimHitReader : public IReader { std::vector> m_eventMap; /// The input tree name - TChain *m_inputChain = nullptr; + std::unique_ptr m_inputChain; /// The keys we have in the ROOT file constexpr static std::array m_floatKeys = { diff --git a/Examples/Io/Root/include/ActsExamples/Io/Root/RootTrackSummaryReader.hpp b/Examples/Io/Root/include/ActsExamples/Io/Root/RootTrackSummaryReader.hpp index 71ff807fb32..1f43918c82b 100644 --- a/Examples/Io/Root/include/ActsExamples/Io/Root/RootTrackSummaryReader.hpp +++ b/Examples/Io/Root/include/ActsExamples/Io/Root/RootTrackSummaryReader.hpp @@ -92,7 +92,7 @@ class RootTrackSummaryReader : public IReader { std::size_t m_events = 0; /// The input tree name - TChain* m_inputChain = nullptr; + std::unique_ptr m_inputChain; /// the event number std::uint32_t m_eventNr{0}; diff --git a/Examples/Io/Root/include/ActsExamples/Io/Root/RootTrackSummaryWriter.hpp b/Examples/Io/Root/include/ActsExamples/Io/Root/RootTrackSummaryWriter.hpp index 5c9a71d6c94..9f23300be06 100644 --- a/Examples/Io/Root/include/ActsExamples/Io/Root/RootTrackSummaryWriter.hpp +++ b/Examples/Io/Root/include/ActsExamples/Io/Root/RootTrackSummaryWriter.hpp @@ -49,9 +49,9 @@ class RootTrackSummaryWriter final : public WriterT { struct Config { /// Input (fitted) tracks collection std::string inputTracks; - /// Input particles collection. + /// Input particles collection (optional). std::string inputParticles; - /// Input track-particle matching. + /// Input track-particle matching (optional). std::string inputTrackParticleMatching; /// Output filename. std::string filePath = "tracksummary.root"; diff --git a/Examples/Io/Root/include/ActsExamples/Io/Root/RootVertexReader.hpp b/Examples/Io/Root/include/ActsExamples/Io/Root/RootVertexReader.hpp index 46afe962bdb..b40c0b9ba6b 100644 --- a/Examples/Io/Root/include/ActsExamples/Io/Root/RootVertexReader.hpp +++ b/Examples/Io/Root/include/ActsExamples/Io/Root/RootVertexReader.hpp @@ -82,7 +82,7 @@ class RootVertexReader : public IReader { std::size_t m_events = 0; /// The input tree name - TChain* m_inputChain = nullptr; + std::unique_ptr m_inputChain; /// Event identifier. std::uint32_t m_eventId = 0; diff --git a/Examples/Io/Root/src/RootAthenaNTupleReader.cpp b/Examples/Io/Root/src/RootAthenaNTupleReader.cpp index ac06349c595..bf61b919c5b 100644 --- a/Examples/Io/Root/src/RootAthenaNTupleReader.cpp +++ b/Examples/Io/Root/src/RootAthenaNTupleReader.cpp @@ -43,7 +43,7 @@ ActsExamples::RootAthenaNTupleReader::RootAthenaNTupleReader( m_outputRecoVtxParameters.initialize(m_cfg.outputRecoVtxParameters); m_outputBeamspotConstraint.initialize(m_cfg.outputBeamspotConstraint); - m_inputChain = new TChain(m_cfg.inputTreeName.c_str()); + m_inputChain = std::make_unique(m_cfg.inputTreeName.c_str()); // unused event identifier std::int32_t eventNumber = 0; @@ -116,6 +116,8 @@ ActsExamples::RootAthenaNTupleReader::RootAthenaNTupleReader( ACTS_DEBUG("The full chain has " << m_events << " entries."); } +ActsExamples::RootAthenaNTupleReader::~RootAthenaNTupleReader() = default; + ActsExamples::ProcessCode ActsExamples::RootAthenaNTupleReader::read( const ActsExamples::AlgorithmContext& context) { ACTS_DEBUG("Trying to read track parameters from ntuple."); diff --git a/Examples/Io/Root/src/RootBFieldWriter.cpp b/Examples/Io/Root/src/RootBFieldWriter.cpp index b8cb8b6c104..894636d61c9 100644 --- a/Examples/Io/Root/src/RootBFieldWriter.cpp +++ b/Examples/Io/Root/src/RootBFieldWriter.cpp @@ -48,13 +48,13 @@ void RootBFieldWriter::run(const Config& config, // Setup ROOT I/O ACTS_INFO("Registering new ROOT output File : " << config.fileName); - TFile* outputFile = - TFile::Open(config.fileName.c_str(), config.fileMode.c_str()); + std::unique_ptr outputFile( + TFile::Open(config.fileName.c_str(), config.fileMode.c_str())); if (outputFile == nullptr) { throw std::ios_base::failure("Could not open '" + config.fileName + "'"); } TTree* outputTree = new TTree(config.treeName.c_str(), - config.treeName.c_str(), 99, outputFile); + config.treeName.c_str(), 99, outputFile.get()); if (outputTree == nullptr) { throw std::bad_alloc(); } @@ -277,6 +277,5 @@ void RootBFieldWriter::run(const Config& config, // Tear down ROOT I/O ACTS_INFO("Closing and Writing ROOT output File : " << config.fileName); outputTree->Write(); - delete outputFile; } } // namespace ActsExamples diff --git a/Examples/Io/Root/src/RootMaterialTrackReader.cpp b/Examples/Io/Root/src/RootMaterialTrackReader.cpp index 70b2ab8d997..dc8a48e137e 100644 --- a/Examples/Io/Root/src/RootMaterialTrackReader.cpp +++ b/Examples/Io/Root/src/RootMaterialTrackReader.cpp @@ -34,7 +34,7 @@ RootMaterialTrackReader::RootMaterialTrackReader(const Config& config, throw std::invalid_argument{"No input files given"}; } - m_inputChain = new TChain(m_cfg.treeName.c_str()); + m_inputChain = std::make_unique(m_cfg.treeName.c_str()); // loop over the input files for (const auto& inputFile : m_cfg.fileList) { @@ -83,9 +83,6 @@ RootMaterialTrackReader::RootMaterialTrackReader(const Config& config, ACTS_DEBUG("The full chain has " << nentries << " entries for " << m_events << " events this corresponds to a batch size of: " << m_batchSize); - std::cout << "The full chain has " << nentries << " entries for " << m_events - << " events this corresponds to a batch size of: " << m_batchSize - << std::endl; // Sort the entry numbers of the events { @@ -103,8 +100,6 @@ RootMaterialTrackReader::RootMaterialTrackReader(const Config& config, } RootMaterialTrackReader::~RootMaterialTrackReader() { - delete m_inputChain; - delete m_step_x; delete m_step_y; delete m_step_z; diff --git a/Examples/Io/Root/src/RootMaterialTrackWriter.cpp b/Examples/Io/Root/src/RootMaterialTrackWriter.cpp index a7a5ee39f8c..bec096d2ca7 100644 --- a/Examples/Io/Root/src/RootMaterialTrackWriter.cpp +++ b/Examples/Io/Root/src/RootMaterialTrackWriter.cpp @@ -10,7 +10,6 @@ #include "Acts/Geometry/GeometryIdentifier.hpp" #include "Acts/Geometry/TrackingVolume.hpp" -#include "Acts/Geometry/Volume.hpp" #include "Acts/Material/Material.hpp" #include "Acts/Material/MaterialInteraction.hpp" #include "Acts/Material/MaterialSlab.hpp" @@ -23,11 +22,9 @@ #include "Acts/Utilities/VectorHelpers.hpp" #include "ActsExamples/Framework/AlgorithmContext.hpp" -#include #include #include #include -#include #include #include diff --git a/Examples/Io/Root/src/RootParticleReader.cpp b/Examples/Io/Root/src/RootParticleReader.cpp index 631fc25ef3e..0eafeaa666b 100644 --- a/Examples/Io/Root/src/RootParticleReader.cpp +++ b/Examples/Io/Root/src/RootParticleReader.cpp @@ -28,7 +28,7 @@ RootParticleReader::RootParticleReader(const RootParticleReader::Config& config, : IReader(), m_cfg(config), m_logger(Acts::getDefaultLogger(name(), level)) { - m_inputChain = new TChain(m_cfg.treeName.c_str()); + m_inputChain = std::make_unique(m_cfg.treeName.c_str()); if (m_cfg.filePath.empty()) { throw std::invalid_argument("Missing input filename"); diff --git a/Examples/Io/Root/src/RootPropagationStepsWriter.cpp b/Examples/Io/Root/src/RootPropagationStepsWriter.cpp index c7866e056eb..643956a6ed1 100644 --- a/Examples/Io/Root/src/RootPropagationStepsWriter.cpp +++ b/Examples/Io/Root/src/RootPropagationStepsWriter.cpp @@ -9,15 +9,12 @@ #include "ActsExamples/Io/Root/RootPropagationStepsWriter.hpp" #include "Acts/Definitions/Algebra.hpp" +#include "Acts/Geometry/GeometryIdentifier.hpp" +#include "Acts/Propagator/ConstrainedStep.hpp" #include "Acts/Utilities/Helpers.hpp" #include "Acts/Utilities/VectorHelpers.hpp" #include "ActsExamples/EventData/PropagationSummary.hpp" #include "ActsExamples/Framework/AlgorithmContext.hpp" -#include -#include -#include -#include -#include #include #include diff --git a/Examples/Io/Root/src/RootPropagationSummaryWriter.cpp b/Examples/Io/Root/src/RootPropagationSummaryWriter.cpp index 07a1cfa105f..7df19539c57 100644 --- a/Examples/Io/Root/src/RootPropagationSummaryWriter.cpp +++ b/Examples/Io/Root/src/RootPropagationSummaryWriter.cpp @@ -8,19 +8,11 @@ #include "ActsExamples/Io/Root/RootPropagationSummaryWriter.hpp" -#include "Acts/Definitions/Algebra.hpp" -#include "Acts/Utilities/Helpers.hpp" #include "Acts/Utilities/VectorHelpers.hpp" #include "ActsExamples/Framework/AlgorithmContext.hpp" #include "ActsExamples/Propagation/PropagationAlgorithm.hpp" -#include -#include -#include -#include -#include #include -#include #include #include @@ -77,9 +69,15 @@ RootPropagationSummaryWriter::RootPropagationSummaryWriter( m_outputTree->Branch("nMaterials", &m_nMaterials); m_outputTree->Branch("nPortals", &m_nPortals); - m_outputTree->Branch("nSteps", &m_nSteps); - m_outputTree->Branch("nStepTrials", &m_nStepTrials); + m_outputTree->Branch("nAttemptedSteps", &m_nAttemptedSteps); + m_outputTree->Branch("nRejectedSteps", &m_nRejectedSteps); + m_outputTree->Branch("nSuccessfulSteps", &m_nSuccessfulSteps); + m_outputTree->Branch("nReverseSteps", &m_nReverseSteps); m_outputTree->Branch("pathLength", &m_pathLength); + m_outputTree->Branch("absolutePathLength", &m_absolutePathLength); + + m_outputTree->Branch("nRenavigations", &m_nRenavigations); + m_outputTree->Branch("nVolumeSwitches", &m_nVolumeSwitches); } RootPropagationSummaryWriter::~RootPropagationSummaryWriter() { @@ -133,11 +131,6 @@ ProcessCode RootPropagationSummaryWriter::writeT( m_pt = static_cast(startParameters.transverseMomentum()); m_p = static_cast(startParameters.absoluteMomentum()); - // Stepper statistics - m_nSteps = static_cast(summary.steps.size()); - m_nStepTrials = static_cast(summary.nStepTrials); - m_pathLength = static_cast(summary.pathLength); - m_nMaterials = 0; m_nSensitives = 0; m_nPortals = 0; @@ -160,6 +153,19 @@ ProcessCode RootPropagationSummaryWriter::writeT( } } }); + + // Stepper statistics + m_nAttemptedSteps = summary.statistics.stepping.nAttemptedSteps; + m_nRejectedSteps = summary.statistics.stepping.nRejectedSteps; + m_nSuccessfulSteps = summary.statistics.stepping.nSuccessfulSteps; + m_nReverseSteps = summary.statistics.stepping.nReverseSteps; + m_pathLength = summary.statistics.stepping.pathLength; + m_absolutePathLength = summary.statistics.stepping.absolutePathLength; + + // Navigator statistics + m_nRenavigations = summary.statistics.navigation.nRenavigations; + m_nVolumeSwitches = summary.statistics.navigation.nVolumeSwitches; + m_outputTree->Fill(); } diff --git a/Examples/Io/Root/src/RootSimHitReader.cpp b/Examples/Io/Root/src/RootSimHitReader.cpp index 4f0d805dc7e..407c70c5dea 100644 --- a/Examples/Io/Root/src/RootSimHitReader.cpp +++ b/Examples/Io/Root/src/RootSimHitReader.cpp @@ -29,7 +29,7 @@ RootSimHitReader::RootSimHitReader(const RootSimHitReader::Config& config, : IReader(), m_cfg(config), m_logger(Acts::getDefaultLogger(name(), level)) { - m_inputChain = new TChain(m_cfg.treeName.c_str()); + m_inputChain = std::make_unique(m_cfg.treeName.c_str()); if (m_cfg.filePath.empty()) { throw std::invalid_argument("Missing input filename"); @@ -103,6 +103,8 @@ RootSimHitReader::RootSimHitReader(const RootSimHitReader::Config& config, << availableEvents().second); } +RootSimHitReader::~RootSimHitReader() = default; + std::pair RootSimHitReader::availableEvents() const { return {std::get<0>(m_eventMap.front()), std::get<0>(m_eventMap.back()) + 1}; } diff --git a/Examples/Io/Root/src/RootTrackStatesWriter.cpp b/Examples/Io/Root/src/RootTrackStatesWriter.cpp index edf396384de..37d7cdf2fc9 100644 --- a/Examples/Io/Root/src/RootTrackStatesWriter.cpp +++ b/Examples/Io/Root/src/RootTrackStatesWriter.cpp @@ -12,28 +12,22 @@ #include "Acts/Definitions/Common.hpp" #include "Acts/Definitions/TrackParametrization.hpp" #include "Acts/EventData/MultiTrajectory.hpp" -#include "Acts/EventData/MultiTrajectoryHelpers.hpp" -#include "Acts/EventData/TrackParameters.hpp" #include "Acts/EventData/TransformationHelpers.hpp" #include "Acts/EventData/VectorMultiTrajectory.hpp" -#include "Acts/Geometry/GeometryContext.hpp" #include "Acts/Utilities/Helpers.hpp" #include "Acts/Utilities/MultiIndex.hpp" +#include "Acts/Utilities/TrackHelpers.hpp" #include "Acts/Utilities/detail/periodic.hpp" #include "ActsExamples/EventData/AverageSimHits.hpp" #include "ActsExamples/EventData/IndexSourceLink.hpp" #include "ActsExamples/EventData/Track.hpp" #include "ActsExamples/Framework/AlgorithmContext.hpp" #include "ActsExamples/Utilities/Range.hpp" -#include "ActsExamples/Validation/TrackClassification.hpp" #include "ActsFatras/EventData/Barcode.hpp" -#include "ActsFatras/EventData/Particle.hpp" #include -#include #include #include -#include #include #include #include @@ -458,8 +452,8 @@ ProcessCode RootTrackStatesWriter::writeT(const AlgorithmContext& ctx, m_t_eT.push_back(static_cast(truthParams[Acts::eBoundTime])); // expand the local measurements into the full bound space - Acts::BoundVector meas = state.effectiveProjector().transpose() * - state.effectiveCalibrated(); + Acts::BoundVector meas = state.projectorSubspaceHelper().expandVector( + state.effectiveCalibrated()); // extract local and global position Acts::Vector2 local(meas[Acts::eBoundLoc0], meas[Acts::eBoundLoc1]); Acts::Vector3 global = @@ -487,21 +481,7 @@ ProcessCode RootTrackStatesWriter::writeT(const AlgorithmContext& ctx, } if (ipar == eUnbiased && state.hasSmoothed() && state.hasProjector() && state.hasCalibrated()) { - // calculate the unbiased track parameters (i.e. fitted track - // parameters with this measurement removed) using Eq.(12a)-Eq.(12c) - // of NIMA 262, 444 (1987) - auto m = state.effectiveCalibrated(); - auto H = state.effectiveProjector(); - auto V = state.effectiveCalibratedCovariance(); - auto K = - (state.smoothedCovariance() * H.transpose() * - (H * state.smoothedCovariance() * H.transpose() - V).inverse()) - .eval(); - auto unbiasedParamsVec = - state.smoothed() + K * (m - H * state.smoothed()); - auto unbiasedParamsCov = - state.smoothedCovariance() - K * H * state.smoothedCovariance(); - return std::make_pair(unbiasedParamsVec, unbiasedParamsCov); + return Acts::calculateUnbiasedParametersCovariance(state); } return std::nullopt; }; @@ -653,7 +633,9 @@ ProcessCode RootTrackStatesWriter::writeT(const AlgorithmContext& ctx, if (ipar == ePredicted) { // local hit residual info - auto H = state.effectiveProjector(); + auto H = + state.projectorSubspaceHelper().fullProjector().topLeftCorner( + state.calibratedSize(), Acts::eBoundSize); auto V = state.effectiveCalibratedCovariance(); auto resCov = V + H * covariance * H.transpose(); Acts::ActsDynamicVector res = diff --git a/Examples/Io/Root/src/RootTrackSummaryReader.cpp b/Examples/Io/Root/src/RootTrackSummaryReader.cpp index 9ff3590271a..33da0026ef7 100644 --- a/Examples/Io/Root/src/RootTrackSummaryReader.cpp +++ b/Examples/Io/Root/src/RootTrackSummaryReader.cpp @@ -31,7 +31,7 @@ RootTrackSummaryReader::RootTrackSummaryReader( : IReader(), m_logger{Acts::getDefaultLogger(name(), level)}, m_cfg(config) { - m_inputChain = new TChain(m_cfg.treeName.c_str()); + m_inputChain = std::make_unique(m_cfg.treeName.c_str()); if (m_cfg.filePath.empty()) { throw std::invalid_argument("Missing input filename"); diff --git a/Examples/Io/Root/src/RootTrackSummaryWriter.cpp b/Examples/Io/Root/src/RootTrackSummaryWriter.cpp index ad23b4e6195..de6753ce3bf 100644 --- a/Examples/Io/Root/src/RootTrackSummaryWriter.cpp +++ b/Examples/Io/Root/src/RootTrackSummaryWriter.cpp @@ -53,12 +53,6 @@ RootTrackSummaryWriter::RootTrackSummaryWriter( : WriterT(config.inputTracks, "RootTrackSummaryWriter", level), m_cfg(config) { // tracks collection name is already checked by base ctor - if (m_cfg.inputParticles.empty()) { - throw std::invalid_argument("Missing particles input collection"); - } - if (m_cfg.inputTrackParticleMatching.empty()) { - throw std::invalid_argument("Missing input track particles matching"); - } if (m_cfg.filePath.empty()) { throw std::invalid_argument("Missing output filename"); } @@ -66,8 +60,9 @@ RootTrackSummaryWriter::RootTrackSummaryWriter( throw std::invalid_argument("Missing tree name"); } - m_inputParticles.initialize(m_cfg.inputParticles); - m_inputTrackParticleMatching.initialize(m_cfg.inputTrackParticleMatching); + m_inputParticles.maybeInitialize(m_cfg.inputParticles); + m_inputTrackParticleMatching.maybeInitialize( + m_cfg.inputTrackParticleMatching); // Setup ROOT I/O auto path = m_cfg.filePath; @@ -220,9 +215,16 @@ ProcessCode RootTrackSummaryWriter::finalize() { ProcessCode RootTrackSummaryWriter::writeT(const AlgorithmContext& ctx, const ConstTrackContainer& tracks) { - // Read additional input collections - const auto& particles = m_inputParticles(ctx); - const auto& trackParticleMatching = m_inputTrackParticleMatching(ctx); + // In case we do not have truth info, we bind to a empty collection + const static SimParticleContainer emptyParticles; + const static TrackParticleMatching emptyTrackParticleMatching; + + const auto& particles = + m_inputParticles.isInitialized() ? m_inputParticles(ctx) : emptyParticles; + const auto& trackParticleMatching = + m_inputTrackParticleMatching.isInitialized() + ? m_inputTrackParticleMatching(ctx) + : emptyTrackParticleMatching; // For each particle within a track, how many hits did it contribute std::vector particleHitCounts; @@ -244,6 +246,7 @@ ProcessCode RootTrackSummaryWriter::writeT(const AlgorithmContext& ctx, m_nSharedHits.push_back(track.nSharedHits()); m_chi2Sum.push_back(track.chi2()); m_NDF.push_back(track.nDoF()); + { std::vector measurementChi2; std::vector measurementVolume; @@ -266,8 +269,6 @@ ProcessCode RootTrackSummaryWriter::writeT(const AlgorithmContext& ctx, measurementLayer.push_back(layer); } } - // IDs are stored as double (as the vector of vector of int is not known - // to ROOT) m_measurementChi2.push_back(std::move(measurementChi2)); m_measurementVolume.push_back(std::move(measurementVolume)); m_measurementLayer.push_back(std::move(measurementLayer)); diff --git a/Examples/Io/Root/src/RootVertexReader.cpp b/Examples/Io/Root/src/RootVertexReader.cpp index 31a8e6d5bec..d2d2848749d 100644 --- a/Examples/Io/Root/src/RootVertexReader.cpp +++ b/Examples/Io/Root/src/RootVertexReader.cpp @@ -28,7 +28,7 @@ RootVertexReader::RootVertexReader(const RootVertexReader::Config& config, : IReader(), m_cfg(config), m_logger(Acts::getDefaultLogger(name(), level)) { - m_inputChain = new TChain(m_cfg.treeName.c_str()); + m_inputChain = std::make_unique(m_cfg.treeName.c_str()); if (m_cfg.filePath.empty()) { throw std::invalid_argument("Missing input filename"); diff --git a/Examples/Io/Root/src/VertexNTupleWriter.cpp b/Examples/Io/Root/src/VertexNTupleWriter.cpp index 07c71f115c1..6304af1cb8d 100644 --- a/Examples/Io/Root/src/VertexNTupleWriter.cpp +++ b/Examples/Io/Root/src/VertexNTupleWriter.cpp @@ -345,24 +345,24 @@ ProcessCode VertexNTupleWriter::writeT( }; // Helper function for computing the pull - auto pull = - [this](const Acts::ActsScalar& diff, const Acts::ActsScalar& variance, - const std::string& variableStr, const bool& afterFit = true) { - if (variance <= 0) { - std::string tempStr; - if (afterFit) { - tempStr = "after"; - } else { - tempStr = "before"; - } - ACTS_WARNING("Nonpositive variance " - << tempStr << " vertex fit: Var(" << variableStr - << ") = " << variance << " <= 0."); - return std::numeric_limits::quiet_NaN(); - } - double std = std::sqrt(variance); - return diff / std; - }; + auto pull = [this](const double& diff, const double& variance, + const std::string& variableStr, + const bool& afterFit = true) { + if (variance <= 0) { + std::string tempStr; + if (afterFit) { + tempStr = "after"; + } else { + tempStr = "before"; + } + ACTS_WARNING("Nonpositive variance " << tempStr << " vertex fit: Var(" + << variableStr << ") = " << variance + << " <= 0."); + return std::numeric_limits::quiet_NaN(); + } + double std = std::sqrt(variance); + return diff / std; + }; auto calculateTruthPrimaryVertexDensity = [this, truthVertices](const Acts::Vertex& vtx) { @@ -571,14 +571,14 @@ ProcessCode VertexNTupleWriter::writeT( m_recoZ.push_back(vtx.fullPosition()[Acts::CoordinateIndices::eZ]); m_recoT.push_back(vtx.fullPosition()[Acts::CoordinateIndices::eTime]); - Acts::ActsScalar varX = vtx.fullCovariance()(Acts::CoordinateIndices::eX, - Acts::CoordinateIndices::eX); - Acts::ActsScalar varY = vtx.fullCovariance()(Acts::CoordinateIndices::eY, - Acts::CoordinateIndices::eY); - Acts::ActsScalar varZ = vtx.fullCovariance()(Acts::CoordinateIndices::eZ, - Acts::CoordinateIndices::eZ); - Acts::ActsScalar varTime = vtx.fullCovariance()( - Acts::CoordinateIndices::eTime, Acts::CoordinateIndices::eTime); + double varX = vtx.fullCovariance()(Acts::CoordinateIndices::eX, + Acts::CoordinateIndices::eX); + double varY = vtx.fullCovariance()(Acts::CoordinateIndices::eY, + Acts::CoordinateIndices::eY); + double varZ = vtx.fullCovariance()(Acts::CoordinateIndices::eZ, + Acts::CoordinateIndices::eZ); + double varTime = vtx.fullCovariance()(Acts::CoordinateIndices::eTime, + Acts::CoordinateIndices::eTime); m_covXX.push_back(varX); m_covYY.push_back(varY); diff --git a/Examples/Io/Root/src/detail/NuclearInteractionParametrisation.cpp b/Examples/Io/Root/src/detail/NuclearInteractionParametrisation.cpp index 174f3648ce1..244c30ca039 100644 --- a/Examples/Io/Root/src/detail/NuclearInteractionParametrisation.cpp +++ b/Examples/Io/Root/src/detail/NuclearInteractionParametrisation.cpp @@ -32,15 +32,20 @@ namespace { /// @return The location in a standard normal distribution float gaussianValue(TH1F const* histo, const float mom) { // Get the cumulative probability distribution - TH1F* normalised = static_cast(histo->DrawNormalized()); - TH1F* cumulative = static_cast(normalised->GetCumulative()); + + // DrawNormalized and GetCumulative return pointers to histograms where ROOT + // transfers ownership to the caller. + std::unique_ptr normalised( + dynamic_cast(histo->DrawNormalized())); + std::unique_ptr cumulative( + dynamic_cast(normalised->GetCumulative())); + assert(cumulative); + assert(normalised); // Find the cumulative probability const float binContent = cumulative->GetBinContent(cumulative->FindBin(mom)); // Transform the probability to an entry in a standard normal distribution const float value = TMath::ErfInverse(2. * binContent - 1.); - delete (normalised); - delete (cumulative); return value; } @@ -53,8 +58,8 @@ float gaussianValue(TH1F const* histo, const float mom) { float invariantMass(const Acts::Vector4& fourVector1, const Acts::Vector4& fourVector2) { Acts::Vector4 sum = fourVector1 + fourVector2; - const Acts::ActsScalar energy = sum[Acts::eEnergy]; - Acts::ActsScalar momentum = sum.template segment<3>(Acts::eMom0).norm(); + const double energy = sum[Acts::eEnergy]; + double momentum = sum.template segment<3>(Acts::eMom0).norm(); return std::sqrt(energy * energy - momentum * momentum); } diff --git a/Examples/Io/Svg/include/ActsExamples/Io/Svg/SvgPointWriter.hpp b/Examples/Io/Svg/include/ActsExamples/Io/Svg/SvgPointWriter.hpp index 3ad6527a882..8695fe2e7f1 100644 --- a/Examples/Io/Svg/include/ActsExamples/Io/Svg/SvgPointWriter.hpp +++ b/Examples/Io/Svg/include/ActsExamples/Io/Svg/SvgPointWriter.hpp @@ -82,7 +82,7 @@ class SvgPointWriter final : public WriterT> { std::string outputDir; ///< where to place output files std::size_t outputPrecision = 6; ///< floating point precision - Acts::ActsScalar spSize = 10.; //!< size of the space point to be drawn + double spSize = 10.; //!< size of the space point to be drawn Acts::Svg::Style spStyle = s_pointStyle; //!< The style of the space point to be drawn @@ -91,11 +91,11 @@ class SvgPointWriter final : public WriterT> { Acts::Svg::Style infoBoxStyle = s_infoStyle; // The style of the info box bool projectionXY = true; ///< xy projection - std::array zRangeXY = { - std::numeric_limits::lowest(), - std::numeric_limits::max()}; ///< View range in z of - ///< the XY view - bool projectionZR = true; ///< zr projection + std::array zRangeXY = { + std::numeric_limits::lowest(), + std::numeric_limits::max()}; ///< View range in z of + ///< the XY view + bool projectionZR = true; ///< zr projection std::shared_ptr trackingGeometry = nullptr; ///< The tracking geometry, a set pointer will cause the diff --git a/Examples/Python/python/acts/examples/reconstruction.py b/Examples/Python/python/acts/examples/reconstruction.py index bc1b1d4df9d..a365572cabc 100644 --- a/Examples/Python/python/acts/examples/reconstruction.py +++ b/Examples/Python/python/acts/examples/reconstruction.py @@ -13,9 +13,20 @@ "Default TruthSmeared TruthEstimated Orthogonal HoughTransform Gbts Hashing", ) -ParticleSmearingSigmas = namedtuple( - "ParticleSmearingSigmas", - ["d0", "d0PtA", "d0PtB", "z0", "z0PtA", "z0PtB", "t0", "phi", "theta", "ptRel"], +TrackSmearingSigmas = namedtuple( + "TrackSmearingSigmas", + [ + "loc0", + "loc0PtA", + "loc0PtB", + "loc1", + "loc1PtA", + "loc1PtB", + "time", + "phi", + "theta", + "ptRel", + ], defaults=[None] * 10, ) @@ -123,10 +134,42 @@ "maxSharedHits", "maxChi2", "nMeasurementsGroupMin", + "requireReferenceSurface", ], - defaults=[(None, None)] * 7 + [None] * 7, + defaults=[(None, None)] * 7 + [None] * 8, ) + +def trackSelectorDefaultKWArgs(c): + """ + Encapsulate this boilerplate code into a function so different uses do not get out of sync + """ + return acts.examples.defaultKWArgs( + loc0Min=c.loc0[0], + loc0Max=c.loc0[1], + loc1Min=c.loc1[0], + loc1Max=c.loc1[1], + timeMin=c.time[0], + timeMax=c.time[1], + phiMin=c.phi[0], + phiMax=c.phi[1], + etaMin=c.eta[0], + etaMax=c.eta[1], + absEtaMin=c.absEta[0], + absEtaMax=c.absEta[1], + ptMin=c.pt[0], + ptMax=c.pt[1], + minMeasurements=c.nMeasurementsMin, + maxHoles=c.maxHoles, + maxOutliers=c.maxOutliers, + maxHolesAndOutliers=c.maxHolesAndOutliers, + maxSharedHits=c.maxSharedHits, + maxChi2=c.maxChi2, + measurementCounter=c.nMeasurementsGroupMin, + requireReferenceSurface=c.requireReferenceSurface, + ) + + CkfConfig = namedtuple( "CkfConfig", [ @@ -224,7 +267,7 @@ class VertexFinder(Enum): @acts.examples.NamedTypeArgs( seedingAlgorithm=SeedingAlgorithm, - particleSmearingSigmas=ParticleSmearingSigmas, + trackSmearingSigmas=TrackSmearingSigmas, seedFinderConfigArg=SeedFinderConfigArg, seedFinderOptionsArg=SeedFinderOptionsArg, seedFilterConfigArg=SeedFilterConfigArg, @@ -243,7 +286,7 @@ def addSeeding( layerMappingConfigFile: Optional[Union[Path, str]] = None, connector_inputConfigFile: Optional[Union[Path, str]] = None, seedingAlgorithm: SeedingAlgorithm = SeedingAlgorithm.Default, - particleSmearingSigmas: ParticleSmearingSigmas = ParticleSmearingSigmas(), + trackSmearingSigmas: TrackSmearingSigmas = TrackSmearingSigmas(), initialSigmas: Optional[list] = None, initialSigmaPtRel: Optional[float] = None, initialVarInflation: Optional[list] = None, @@ -281,15 +324,15 @@ def addSeeding( Json file for space point geometry selection. Not required for SeedingAlgorithm.TruthSmeared. seedingAlgorithm : SeedingAlgorithm, Default seeding algorithm to use: one of Default (no truth information used), TruthSmeared, TruthEstimated - particleSmearingSigmas : ParticleSmearingSigmas(d0, d0PtA, d0PtB, z0, z0PtA, z0PtB, t0, phi, theta, ptRel) - ParticleSmearing configuration. - Defaults specified in Examples/Algorithms/TruthTracking/ActsExamples/TruthTracking/ParticleSmearing.hpp + trackSmearingSigmas : TrackSmearingSigmas(loc0, loc0PtA, loc0PtB, loc1, loc1PtA, loc1PtB, time, phi, theta, ptRel) + TrackSmearing configuration. + Defaults specified in Examples/Algorithms/TruthTracking/ActsExamples/TruthTracking/TrackParameterSmearing.hpp initialSigmas : list Sets the initial covariance matrix diagonal. This is ignored in case of TruthSmearing. Defaults specified in Examples/Algorithms/TrackFinding/include/ActsExamples/TrackFinding/TrackParamsEstimationAlgorithm.hpp initialVarInflation : list List of 6 scale factors to inflate the initial covariance matrix - Defaults (all 1) specified in Examples/Algorithms/TruthTracking/ActsExamples/TruthTracking/ParticleSmearing.hpp + Defaults (all 1) specified in Examples/Algorithms/TruthTracking/ActsExamples/TruthTracking/TrackParameterSmearing.hpp seedFinderConfigArg : SeedFinderConfigArg(maxSeedsPerSpM, cotThetaMax, sigmaScattering, radLengthPerSeed, minPt, impactMax, deltaPhiMax, interactionPointCut, deltaZMax, maxPtScattering, zBinEdges, zBinsCustomLooping, rRangeMiddleSP, useVariableMiddleSPRange, binSizeR, seedConfirmation, centralSeedConfirmationRange, forwardSeedConfirmationRange, deltaR, deltaRBottomSP, deltaRTopSP, deltaRMiddleSPRange, collisionRegion, r, z) SeedFinderConfig settings. deltaR, deltaRBottomSP, deltaRTopSP, deltaRMiddleSPRange, collisionRegion, r, z. Defaults specified in Core/include/Acts/Seeding/SeedFinderConfig.hpp @@ -334,7 +377,7 @@ def addSeeding( s=s, rnd=rnd, selectedParticles=selectedParticles, - particleSmearingSigmas=particleSmearingSigmas, + trackSmearingSigmas=trackSmearingSigmas, initialSigmas=initialSigmas, initialSigmaPtRel=initialSigmaPtRel, initialVarInflation=initialVarInflation, @@ -488,7 +531,7 @@ def addTruthSmearedSeeding( s: acts.examples.Sequencer, rnd: Optional[acts.examples.RandomNumbers], selectedParticles: str, - particleSmearingSigmas: ParticleSmearingSigmas, + trackSmearingSigmas: TrackSmearingSigmas, initialSigmas: Optional[List[float]], initialSigmaPtRel: Optional[float], initialVarInflation: Optional[List[float]], @@ -500,31 +543,39 @@ def addTruthSmearedSeeding( """ rnd = rnd or acts.examples.RandomNumbers(seed=42) - # Run particle smearing - ptclSmear = acts.examples.ParticleSmearing( + + trkParamExtractor = acts.examples.ParticleTrackParamExtractor( level=logLevel, inputParticles=selectedParticles, + outputTrackParameters="trueparameters", + ) + s.addAlgorithm(trkParamExtractor) + + # Smearing track parameters + trkSmear = acts.examples.TrackParameterSmearing( + level=logLevel, + inputTrackParameters=trkParamExtractor.config.outputTrackParameters, outputTrackParameters="estimatedparameters", randomNumbers=rnd, # gaussian sigmas to smear particle parameters **acts.examples.defaultKWArgs( - sigmaD0=particleSmearingSigmas.d0, - sigmaD0PtA=particleSmearingSigmas.d0PtA, - sigmaD0PtB=particleSmearingSigmas.d0PtB, - sigmaZ0=particleSmearingSigmas.z0, - sigmaZ0PtA=particleSmearingSigmas.z0PtA, - sigmaZ0PtB=particleSmearingSigmas.z0PtB, - sigmaT0=particleSmearingSigmas.t0, - sigmaPhi=particleSmearingSigmas.phi, - sigmaTheta=particleSmearingSigmas.theta, - sigmaPtRel=particleSmearingSigmas.ptRel, + sigmaLoc0=trackSmearingSigmas.loc0, + sigmaLoc0PtA=trackSmearingSigmas.loc0PtA, + sigmaLoc0PtB=trackSmearingSigmas.loc0PtB, + sigmaLoc1=trackSmearingSigmas.loc1, + sigmaLoc1PtA=trackSmearingSigmas.loc1PtA, + sigmaLoc1PtB=trackSmearingSigmas.loc1PtB, + sigmaTime=trackSmearingSigmas.time, + sigmaPhi=trackSmearingSigmas.phi, + sigmaTheta=trackSmearingSigmas.theta, + sigmaPtRel=trackSmearingSigmas.ptRel, initialSigmas=initialSigmas, initialSigmaPtRel=initialSigmaPtRel, initialVarInflation=initialVarInflation, particleHypothesis=particleHypothesis, ), ) - s.addAlgorithm(ptclSmear) + s.addAlgorithm(trkSmear) truthTrkFndAlg = acts.examples.TruthTrackFinder( level=logLevel, @@ -1424,32 +1475,10 @@ def addCKFTracks( else trackSelectorConfig ) ) + + overwriteArgs = dict() if len(tslist) == 1 else dict(absEtaMax=None) cutSets = [ - acts.TrackSelector.Config( - **acts.examples.defaultKWArgs( - loc0Min=c.loc0[0], - loc0Max=c.loc0[1], - loc1Min=c.loc1[0], - loc1Max=c.loc1[1], - timeMin=c.time[0], - timeMax=c.time[1], - phiMin=c.phi[0], - phiMax=c.phi[1], - etaMin=c.eta[0], - etaMax=c.eta[1], - absEtaMin=c.absEta[0], - absEtaMax=c.absEta[1] if len(tslist) == 1 else None, - ptMin=c.pt[0], - ptMax=c.pt[1], - minMeasurements=c.nMeasurementsMin, - maxHoles=c.maxHoles, - maxOutliers=c.maxOutliers, - maxHolesAndOutliers=c.maxHolesAndOutliers, - maxSharedHits=c.maxSharedHits, - maxChi2=c.maxChi2, - measurementCounter=c.nMeasurementsGroupMin, - ) - ) + acts.TrackSelector.Config(**(trackSelectorDefaultKWArgs(c) | overwriteArgs)) for c in tslist ] if len(tslist) == 0: @@ -1702,23 +1731,7 @@ def addTrackSelection( # single cut config for implicit single bin eta configuration selectorConfig = acts.TrackSelector.Config( - **acts.examples.defaultKWArgs( - loc0Min=trackSelectorConfig.loc0[0], - loc0Max=trackSelectorConfig.loc0[1], - loc1Min=trackSelectorConfig.loc1[0], - loc1Max=trackSelectorConfig.loc1[1], - timeMin=trackSelectorConfig.time[0], - timeMax=trackSelectorConfig.time[1], - phiMin=trackSelectorConfig.phi[0], - phiMax=trackSelectorConfig.phi[1], - etaMin=trackSelectorConfig.eta[0], - etaMax=trackSelectorConfig.eta[1], - absEtaMin=trackSelectorConfig.absEta[0], - absEtaMax=trackSelectorConfig.absEta[1], - ptMin=trackSelectorConfig.pt[0], - ptMax=trackSelectorConfig.pt[1], - minMeasurements=trackSelectorConfig.nMeasurementsMin, - ) + **trackSelectorDefaultKWArgs(trackSelectorConfig) ) trackSelector = acts.examples.TrackSelectorAlgorithm( diff --git a/Examples/Python/src/DD4hepComponent.cpp b/Examples/Python/src/DD4hepComponent.cpp index f4ad0277aea..e38a33cf82c 100644 --- a/Examples/Python/src/DD4hepComponent.cpp +++ b/Examples/Python/src/DD4hepComponent.cpp @@ -16,32 +16,25 @@ #include "ActsExamples/DD4hepDetector/DD4hepDetector.hpp" #include "ActsExamples/DD4hepDetector/DD4hepGeometryService.hpp" #include "ActsExamples/Framework/IContextDecorator.hpp" -#include "ActsExamples/Framework/ProcessCode.hpp" -#include #include #include -#include #include #include -namespace Acts { -class IMaterialDecorator; -} // namespace Acts - namespace py = pybind11; using namespace ActsExamples; using namespace Acts::Python; PYBIND11_MODULE(ActsPythonBindingsDD4hep, m) { { - using Config = DD4hep::DD4hepGeometryService::Config; - auto s = py::class_>( + using Config = DD4hepGeometryService::Config; + auto s = py::class_>( m, "DD4hepGeometryService") .def(py::init()) - .def("drop", &DD4hep::DD4hepGeometryService::drop); + .def("drop", &DD4hepGeometryService::drop); auto c = py::class_(s, "Config").def(py::init<>()); ACTS_PYTHON_STRUCT_BEGIN(c, Config); @@ -155,20 +148,20 @@ PYBIND11_MODULE(ActsPythonBindingsDD4hep, m) { } { - py::class_>( + py::class_>( m, "DD4hepDetector") .def(py::init<>()) - .def(py::init>()) + .def(py::init>()) .def("finalize", - py::overload_cast>( - &DD4hep::DD4hepDetector::finalize)) + &DD4hepDetector::finalize)) .def("finalize", py::overload_cast< const Acts::GeometryContext&, const Acts::Experimental::DD4hepDetectorStructure::Options&>( - &DD4hep::DD4hepDetector::finalize)) - .def("drop", &DD4hep::DD4hepDetector::drop) - .def_property_readonly("field", &DD4hep::DD4hepDetector::field); + &DD4hepDetector::finalize)) + .def("drop", &DD4hepDetector::drop) + .def_property_readonly("field", &DD4hepDetector::field); } } diff --git a/Examples/Python/src/Detector.cpp b/Examples/Python/src/Detector.cpp index 6b9ef68f927..94770ce7283 100644 --- a/Examples/Python/src/Detector.cpp +++ b/Examples/Python/src/Detector.cpp @@ -10,7 +10,6 @@ #include "Acts/Material/IMaterialDecorator.hpp" #include "Acts/Plugins/Python/Utilities.hpp" #include "Acts/Utilities/BinningType.hpp" -#include "Acts/Utilities/Logger.hpp" #include "ActsExamples/ContextualDetector/AlignedDetector.hpp" #include "ActsExamples/Framework/IContextDecorator.hpp" #include "ActsExamples/GenericDetector/GenericDetector.hpp" @@ -18,12 +17,9 @@ #include "ActsExamples/TelescopeDetector/TelescopeDetector.hpp" #include "ActsExamples/Utilities/Options.hpp" -#include -#include #include #include #include -#include #include #include @@ -34,6 +30,7 @@ namespace py = pybind11; using namespace ActsExamples; namespace Acts::Python { + void addDetector(Context& ctx) { auto [m, mex] = ctx.get("main", "examples"); { @@ -44,16 +41,17 @@ void addDetector(Context& ctx) { } { - using Config = GenericDetector::Config; + using Detector = GenericDetector; + using Config = Detector::Config; - auto gd = py::class_>( - mex, "GenericDetector") - .def(py::init<>()) - .def("finalize", - py::overload_cast< - const Config&, - std::shared_ptr>( - &GenericDetector::finalize)); + auto gd = + py::class_>(mex, "GenericDetector") + .def(py::init<>()) + .def("finalize", + py::overload_cast< + const Config&, + std::shared_ptr>( + &Detector::finalize)); py::class_(gd, "Config") .def(py::init<>()) @@ -65,18 +63,18 @@ void addDetector(Context& ctx) { } { - using TelescopeDetector = Telescope::TelescopeDetector; - using Config = TelescopeDetector::Config; + using Detector = TelescopeDetector; + using Config = Detector::Config; auto td = - py::class_>( - mex, "TelescopeDetector") + py::class_>(mex, + "TelescopeDetector") .def(py::init<>()) .def("finalize", py::overload_cast< const Config&, const std::shared_ptr&>( - &TelescopeDetector::finalize)); + &Detector::finalize)); py::class_(td, "Config") .def(py::init<>()) @@ -90,17 +88,17 @@ void addDetector(Context& ctx) { } { - using AlignedDetector = Contextual::AlignedDetector; - using Config = AlignedDetector::Config; - - auto d = py::class_>( - mex, "AlignedDetector") - .def(py::init<>()) - .def("finalize", - py::overload_cast< - const Config&, - std::shared_ptr>( - &AlignedDetector::finalize)); + using Detector = AlignedDetector; + using Config = Detector::Config; + + auto d = + py::class_>(mex, "AlignedDetector") + .def(py::init<>()) + .def("finalize", + py::overload_cast< + const Config&, + std::shared_ptr>( + &Detector::finalize)); auto c = py::class_(d, "Config") .def(py::init<>()); @@ -124,16 +122,17 @@ void addDetector(Context& ctx) { } { - using Config = TGeoDetector::Config; + using Detector = TGeoDetector; + using Config = Detector::Config; - auto d = py::class_>( - mex, "TGeoDetector") - .def(py::init<>()) - .def("finalize", - py::overload_cast< - const Config&, - std::shared_ptr>( - &TGeoDetector::finalize)); + auto d = + py::class_>(mex, "TGeoDetector") + .def(py::init<>()) + .def("finalize", + py::overload_cast< + const Config&, + std::shared_ptr>( + &Detector::finalize)); py::class_(mex, "Interval") .def(py::init<>()) @@ -222,6 +221,12 @@ void addDetector(Context& ctx) { patchKwargsConstructor(c); } + + { + py::class_>( + mex, "DetectorElementBase"); + } } } // namespace Acts::Python diff --git a/Examples/Python/src/ExaTrkXTrackFinding.cpp b/Examples/Python/src/ExaTrkXTrackFinding.cpp index 3778e8576f5..c7a30b51d2e 100644 --- a/Examples/Python/src/ExaTrkXTrackFinding.cpp +++ b/Examples/Python/src/ExaTrkXTrackFinding.cpp @@ -30,6 +30,7 @@ namespace py = pybind11; using namespace ActsExamples; using namespace Acts; +using namespace py::literals; namespace Acts::Python { @@ -67,7 +68,7 @@ void addExaTrkXTrackFinding(Context &ctx) { auto c = py::class_(alg, "Config").def(py::init<>()); ACTS_PYTHON_STRUCT_BEGIN(c, Config); ACTS_PYTHON_MEMBER(modelPath); - ACTS_PYTHON_MEMBER(numFeatures); + ACTS_PYTHON_MEMBER(selectedFeatures); ACTS_PYTHON_MEMBER(embeddingDim); ACTS_PYTHON_MEMBER(rVal); ACTS_PYTHON_MEMBER(knnVal); @@ -91,11 +92,12 @@ void addExaTrkXTrackFinding(Context &ctx) { auto c = py::class_(alg, "Config").def(py::init<>()); ACTS_PYTHON_STRUCT_BEGIN(c, Config); ACTS_PYTHON_MEMBER(modelPath); - ACTS_PYTHON_MEMBER(numFeatures); + ACTS_PYTHON_MEMBER(selectedFeatures); ACTS_PYTHON_MEMBER(cut); ACTS_PYTHON_MEMBER(nChunks); ACTS_PYTHON_MEMBER(undirected); ACTS_PYTHON_MEMBER(deviceID); + ACTS_PYTHON_MEMBER(useEdgeFeatures); ACTS_PYTHON_STRUCT_END(); } { @@ -174,36 +176,61 @@ void addExaTrkXTrackFinding(Context &ctx) { inputMeasurementSimHitsMap, inputMeasurementParticlesMap, outputGraph, targetMinPT, targetMinSize, uniqueModules); - py::enum_(mex, "NodeFeature") - .value("R", TrackFindingAlgorithmExaTrkX::NodeFeature::eR) - .value("Phi", TrackFindingAlgorithmExaTrkX::NodeFeature::ePhi) - .value("Z", TrackFindingAlgorithmExaTrkX::NodeFeature::eZ) - .value("X", TrackFindingAlgorithmExaTrkX::NodeFeature::eX) - .value("Y", TrackFindingAlgorithmExaTrkX::NodeFeature::eY) - .value("Eta", TrackFindingAlgorithmExaTrkX::NodeFeature::eEta) - .value("ClusterX", TrackFindingAlgorithmExaTrkX::NodeFeature::eClusterX) - .value("ClusterY", TrackFindingAlgorithmExaTrkX::NodeFeature::eClusterY) - .value("CellCount", TrackFindingAlgorithmExaTrkX::NodeFeature::eCellCount) - .value("CellSum", TrackFindingAlgorithmExaTrkX::NodeFeature::eCellSum) - .value("Cluster1R", TrackFindingAlgorithmExaTrkX::NodeFeature::eCluster1R) - .value("Cluster2R", TrackFindingAlgorithmExaTrkX::NodeFeature::eCluster2R) - .value("Cluster1Phi", - TrackFindingAlgorithmExaTrkX::NodeFeature::eCluster1Phi) - .value("Cluster2Phi", - TrackFindingAlgorithmExaTrkX::NodeFeature::eCluster2Phi) - .value("Cluster1Z", TrackFindingAlgorithmExaTrkX::NodeFeature::eCluster1Z) - .value("Cluster2Z", TrackFindingAlgorithmExaTrkX::NodeFeature::eCluster2Z) - .value("Cluster1Eta", - TrackFindingAlgorithmExaTrkX::NodeFeature::eCluster1Eta) - .value("Cluster2Eta", - TrackFindingAlgorithmExaTrkX::NodeFeature::eCluster2Eta); - - ACTS_PYTHON_DECLARE_ALGORITHM(ActsExamples::TrackFindingAlgorithmExaTrkX, mex, - "TrackFindingAlgorithmExaTrkX", - inputSpacePoints, inputClusters, - inputTruthGraph, outputProtoTracks, outputGraph, - graphConstructor, edgeClassifiers, trackBuilder, - nodeFeatures, featureScales, filterShortTracks); + { + auto nodeFeatureEnum = + py::enum_(mex, "NodeFeature") + .value("R", TrackFindingAlgorithmExaTrkX::NodeFeature::eR) + .value("Phi", TrackFindingAlgorithmExaTrkX::NodeFeature::ePhi) + .value("Z", TrackFindingAlgorithmExaTrkX::NodeFeature::eZ) + .value("X", TrackFindingAlgorithmExaTrkX::NodeFeature::eX) + .value("Y", TrackFindingAlgorithmExaTrkX::NodeFeature::eY) + .value("Eta", TrackFindingAlgorithmExaTrkX::NodeFeature::eEta) + .value("ClusterX", + TrackFindingAlgorithmExaTrkX::NodeFeature::eClusterLoc0) + .value("ClusterY", + TrackFindingAlgorithmExaTrkX::NodeFeature::eClusterLoc1) + .value("CellCount", + TrackFindingAlgorithmExaTrkX::NodeFeature::eCellCount) + .value("ChargeSum", + TrackFindingAlgorithmExaTrkX::NodeFeature::eChargeSum); + + // clang-format off +#define ADD_FEATURE_ENUMS(n) \ + nodeFeatureEnum \ + .value("Cluster" #n "X", TrackFindingAlgorithmExaTrkX::NodeFeature::eCluster##n##X) \ + .value("Cluster" #n "Y", TrackFindingAlgorithmExaTrkX::NodeFeature::eCluster##n##Y) \ + .value("Cluster" #n "Z", TrackFindingAlgorithmExaTrkX::NodeFeature::eCluster##n##Z) \ + .value("Cluster" #n "R", TrackFindingAlgorithmExaTrkX::NodeFeature::eCluster##n##R) \ + .value("Cluster" #n "Phi", TrackFindingAlgorithmExaTrkX::NodeFeature::eCluster##n##Phi) \ + .value("Cluster" #n "Eta", TrackFindingAlgorithmExaTrkX::NodeFeature::eCluster##n##Eta) \ + .value("CellCount" #n, TrackFindingAlgorithmExaTrkX::NodeFeature::eCellCount##n) \ + .value("ChargeSum" #n, TrackFindingAlgorithmExaTrkX::NodeFeature::eChargeSum##n) \ + .value("LocEta" #n, TrackFindingAlgorithmExaTrkX::NodeFeature::eLocEta##n) \ + .value("LocPhi" #n, TrackFindingAlgorithmExaTrkX::NodeFeature::eLocPhi##n) \ + .value("LocDir0" #n, TrackFindingAlgorithmExaTrkX::NodeFeature::eLocDir0##n) \ + .value("LocDir1" #n, TrackFindingAlgorithmExaTrkX::NodeFeature::eLocDir1##n) \ + .value("LocDir2" #n, TrackFindingAlgorithmExaTrkX::NodeFeature::eLocDir2##n) \ + .value("LengthDir0" #n, TrackFindingAlgorithmExaTrkX::NodeFeature::eLengthDir0##n) \ + .value("LengthDir1" #n, TrackFindingAlgorithmExaTrkX::NodeFeature::eLengthDir1##n) \ + .value("LengthDir2" #n, TrackFindingAlgorithmExaTrkX::NodeFeature::eLengthDir2##n) \ + .value("GlobEta" #n, TrackFindingAlgorithmExaTrkX::NodeFeature::eGlobEta##n) \ + .value("GlobPhi" #n, TrackFindingAlgorithmExaTrkX::NodeFeature::eGlobPhi##n) \ + .value("EtaAngle" #n, TrackFindingAlgorithmExaTrkX::NodeFeature::eEtaAngle##n) \ + .value("PhiAngle" #n, TrackFindingAlgorithmExaTrkX::NodeFeature::ePhiAngle##n) + // clang-format on + + ADD_FEATURE_ENUMS(1); + ADD_FEATURE_ENUMS(2); + +#undef ADD_FEATURE_ENUMS + } + + ACTS_PYTHON_DECLARE_ALGORITHM( + ActsExamples::TrackFindingAlgorithmExaTrkX, mex, + "TrackFindingAlgorithmExaTrkX", inputSpacePoints, inputClusters, + inputTruthGraph, outputProtoTracks, outputGraph, graphConstructor, + edgeClassifiers, trackBuilder, nodeFeatures, featureScales, + minMeasurementsPerTrack, geometryIdMap); { auto cls = @@ -239,7 +266,8 @@ void addExaTrkXTrackFinding(Context &ctx) { py::arg("graphConstructor"), py::arg("edgeClassifiers"), py::arg("trackBuilder"), py::arg("level")) .def("run", &ExaTrkXPipeline::run, py::arg("features"), - py::arg("spacepoints"), py::arg("hook") = Acts::ExaTrkXHook{}, + py::arg("moduleIds"), py::arg("spacepoints"), + py::arg("hook") = Acts::ExaTrkXHook{}, py::arg("timing") = nullptr); } diff --git a/Examples/Python/src/ExampleAlgorithms.cpp b/Examples/Python/src/ExampleAlgorithms.cpp index 7d9007183e8..411973d147e 100644 --- a/Examples/Python/src/ExampleAlgorithms.cpp +++ b/Examples/Python/src/ExampleAlgorithms.cpp @@ -109,6 +109,7 @@ void addExampleAlgorithms(Context& ctx) { ACTS_PYTHON_MEMBER(maxSharedHits); ACTS_PYTHON_MEMBER(maxChi2); ACTS_PYTHON_MEMBER(measurementCounter); + ACTS_PYTHON_MEMBER(requireReferenceSurface); ACTS_PYTHON_STRUCT_END(); pythonRangeProperty(c, "loc0", &Config::loc0Min, &Config::loc0Max); diff --git a/Examples/Python/src/Geant4Component.cpp b/Examples/Python/src/Geant4Component.cpp index 1a7edd58e7f..53984168740 100644 --- a/Examples/Python/src/Geant4Component.cpp +++ b/Examples/Python/src/Geant4Component.cpp @@ -16,7 +16,6 @@ #include "Acts/Plugins/Python/Utilities.hpp" #include "Acts/Surfaces/SurfaceVisitorConcept.hpp" #include "Acts/Utilities/Logger.hpp" -#include "ActsExamples/Framework/AlgorithmContext.hpp" #include "ActsExamples/Framework/IContextDecorator.hpp" #include "ActsExamples/Geant4/DetectorConstructionFactory.hpp" #include "ActsExamples/Geant4/GdmlDetectorConstruction.hpp" @@ -43,17 +42,6 @@ #include #include -class G4UserSteppingAction; -class G4VUserPhysicsList; -namespace Acts { -class MagneticFieldProvider; -class TrackingGeometry; -class Volume; -} // namespace Acts -namespace ActsExamples { -class RandomNumbers; -} // namespace ActsExamples - namespace py = pybind11; using namespace pybind11::literals; @@ -65,7 +53,8 @@ namespace Acts::Python { void addGeant4HepMC3(Context& ctx); } -struct ExperimentalSensitiveCandidates : public SensitiveCandidatesBase { +struct ExperimentalSensitiveCandidates + : public Geant4::SensitiveCandidatesBase { std::shared_ptr detector; /// Find the sensitive surfaces for a given position @@ -97,8 +86,8 @@ struct ExperimentalSensitiveCandidates : public SensitiveCandidatesBase { }; PYBIND11_MODULE(ActsPythonBindingsGeant4, mod) { - py::class_>( + py::class_>( mod, "DetectorConstructionFactory"); py::class_>( @@ -129,14 +118,14 @@ PYBIND11_MODULE(ActsPythonBindingsGeant4, mod) { } { - using Config = SensitiveSurfaceMapper::Config; - using State = SensitiveSurfaceMapper::State; + using Config = Geant4::SensitiveSurfaceMapper::Config; + using State = Geant4::SensitiveSurfaceMapper::State; auto sm = - py::class_>( + py::class_>( mod, "SensitiveSurfaceMapper") .def(py::init([](const Config& cfg, Acts::Logging::Level level) { - return std::make_shared( + return std::make_shared( cfg, getDefaultLogger("SensitiveSurfaceMapper", level)); })); @@ -155,10 +144,10 @@ PYBIND11_MODULE(ActsPythonBindingsGeant4, mod) { // Set a new surface finder Config ccfg = cfg; auto candidateSurfaces = - std::make_shared(); + std::make_shared(); candidateSurfaces->trackingGeometry = tGeometry; ccfg.candidateSurfaces = candidateSurfaces; - return std::make_shared( + return std::make_shared( ccfg, getDefaultLogger("SensitiveSurfaceMapper", level)); }); @@ -173,20 +162,21 @@ PYBIND11_MODULE(ActsPythonBindingsGeant4, mod) { std::make_shared(); candidateSurfaces->detector = detector; ccfg.candidateSurfaces = candidateSurfaces; - return std::make_shared( + return std::make_shared( ccfg, getDefaultLogger("SensitiveSurfaceMapper", level)); }); sm.def( "remapSensitiveNames", - [](SensitiveSurfaceMapper& self, State& state, GeometryContext& gctx, - DetectorConstructionFactory& factory, Transform3& transform) { + [](Geant4::SensitiveSurfaceMapper& self, State& state, + GeometryContext& gctx, Geant4::DetectorConstructionFactory& factory, + Transform3& transform) { return self.remapSensitiveNames( state, gctx, factory.factorize()->Construct(), transform); }, "state"_a, "gctx"_a, "g4physicalVolume"_a, "motherTransform"_a); - sm.def("checkMapping", &SensitiveSurfaceMapper::checkMapping, "state"_a, - "gctx"_a, "writeMappedAsObj"_a, "writeMissingAsObj"_a); + sm.def("checkMapping", &Geant4::SensitiveSurfaceMapper::checkMapping, + "state"_a, "gctx"_a, "writeMappedAsObj"_a, "writeMissingAsObj"_a); } { @@ -237,27 +227,27 @@ PYBIND11_MODULE(ActsPythonBindingsGeant4, mod) { } { - py::class_>( mod, "GdmlDetectorConstructionFactory") .def(py::init>>(), + std::vector>>(), py::arg("path"), py::arg("regionCreators") = - std::vector>()); + std::vector>()); } { - py::class_< - Telescope::TelescopeG4DetectorConstructionFactory, - DetectorConstructionFactory, - std::shared_ptr>( + py::class_>( mod, "TelescopeG4DetectorConstructionFactory") - .def(py::init>>(), + .def(py::init>>(), py::arg("cfg"), py::arg("regionCreators") = - std::vector>()); + std::vector>()); } { @@ -287,31 +277,29 @@ PYBIND11_MODULE(ActsPythonBindingsGeant4, mod) { std::shared_ptr>( mod, "Geant4DetectorElement"); - using Geant4Detector = Geant4::Geant4Detector; + using Detector = Geant4Detector; + using Config = Detector::Config; auto g = - py::class_>( - mod, "Geant4Detector") + py::class_>(mod, "Geant4Detector") .def(py::init<>()) .def( "constructDetector", - [](Geant4Detector& self, const Geant4Detector::Config& cfg, - Logging::Level logLevel) { + [](Detector& self, const Config& cfg, Logging::Level logLevel) { auto logger = getDefaultLogger("Geant4Detector", logLevel); return self.constructDetector(cfg, *logger); }, py::arg("cfg"), py::arg("logLevel") = Logging::INFO) .def( "constructTrackingGeometry", - [](Geant4Detector& self, const Geant4Detector::Config& cfg, - Logging::Level logLevel) { + [](Detector& self, const Config& cfg, Logging::Level logLevel) { auto logger = getDefaultLogger("Geant4Detector", logLevel); return self.constructTrackingGeometry(cfg, *logger); }, py::arg("cfg"), py::arg("logLevel") = Logging::INFO); - auto c = py::class_(g, "Config").def(py::init<>()); - ACTS_PYTHON_STRUCT_BEGIN(c, Geant4Detector::Config); + auto c = py::class_(g, "Config").def(py::init<>()); + ACTS_PYTHON_STRUCT_BEGIN(c, Config); ACTS_PYTHON_MEMBER(name); ACTS_PYTHON_MEMBER(g4World); ACTS_PYTHON_MEMBER(g4SurfaceOptions); @@ -412,7 +400,7 @@ PYBIND11_MODULE(ActsPythonBindingsGeant4, mod) { } { - using Tool = RegionCreator; + using Tool = Geant4::RegionCreator; using Config = Tool::Config; auto tool = py::class_>(mod, "RegionCreator") .def(py::init(), diff --git a/Examples/Python/src/Geant4DD4hepComponent.cpp b/Examples/Python/src/Geant4DD4hepComponent.cpp index 16ed3b40223..409bca273d1 100644 --- a/Examples/Python/src/Geant4DD4hepComponent.cpp +++ b/Examples/Python/src/Geant4DD4hepComponent.cpp @@ -8,15 +8,12 @@ #include "ActsExamples/DD4hepDetector/DD4hepDetector.hpp" #include "ActsExamples/DDG4/DDG4DetectorConstruction.hpp" -#include "ActsExamples/Framework/ProcessCode.hpp" #include "ActsExamples/Geant4/RegionCreator.hpp" #include #include #include -class G4VUserDetectorConstruction; - namespace py = pybind11; using namespace ActsExamples; @@ -25,12 +22,13 @@ using namespace Acts; PYBIND11_MODULE(ActsPythonBindingsDDG4, m) { py::module_::import("acts.ActsPythonBindingsGeant4"); - py::class_>( m, "DDG4DetectorConstructionFactory") - .def(py::init, - std::vector>>(), + .def(py::init, + std::vector>>(), py::arg("detector"), py::arg("regionCreators") = - std::vector>()); + std::vector>()); } diff --git a/Examples/Python/src/Geant4GeoModelComponent.cpp b/Examples/Python/src/Geant4GeoModelComponent.cpp index 80f6f89eec8..d9c372984db 100644 --- a/Examples/Python/src/Geant4GeoModelComponent.cpp +++ b/Examples/Python/src/Geant4GeoModelComponent.cpp @@ -6,7 +6,6 @@ // 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/Framework/ProcessCode.hpp" #include "ActsExamples/Geant4/DetectorConstructionFactory.hpp" #include "ActsExamples/Geant4/RegionCreator.hpp" #include "ActsExamples/GeoModelG4/GeoModelDetectorConstruction.hpp" @@ -25,12 +24,13 @@ using namespace Acts; PYBIND11_MODULE(ActsPythonBindingsGeoModelG4, m) { py::module_::import("acts.ActsPythonBindingsGeant4"); - py::class_>( m, "GeoModelDetectorConstructionFactory") .def(py::init>>(), + std::vector>>(), py::arg("geoModelTree"), py::arg("regionCreators") = - std::vector>()); + std::vector>()); } diff --git a/Examples/Python/src/Generators.cpp b/Examples/Python/src/Generators.cpp index 454227ddbf6..bc24b8e43f7 100644 --- a/Examples/Python/src/Generators.cpp +++ b/Examples/Python/src/Generators.cpp @@ -16,8 +16,6 @@ #include "ActsExamples/Generators/ParametricParticleGenerator.hpp" #include "ActsExamples/Generators/VertexGenerators.hpp" -#include -#include #include #include #include diff --git a/Examples/Python/src/Geometry.cpp b/Examples/Python/src/Geometry.cpp index ee98bac3fb5..d69b35a86ba 100644 --- a/Examples/Python/src/Geometry.cpp +++ b/Examples/Python/src/Geometry.cpp @@ -199,8 +199,8 @@ void addGeometry(Context& ctx) { py::class_, Acts::VolumeBounds>(m, "CylinderVolumeBounds") - .def(py::init(), + .def(py::init(), "rmin"_a, "rmax"_a, "halfz"_a, "halfphi"_a = std::numbers::pi, "avgphi"_a = 0., "bevelMinZ"_a = 0., "bevelMaxZ"_a = 0.); @@ -282,7 +282,7 @@ void addGeometry(Context& ctx) { py::arg("envelope") = ExtentEnvelope::Zero()) .def("range", [](const Acts::Extent& self, - Acts::BinningValue bval) -> std::array { + Acts::BinningValue bval) -> std::array { return {self.min(bval), self.max(bval)}; }) .def("__str__", &Extent::toString); @@ -382,11 +382,10 @@ void addExperimentalGeometry(Context& ctx) { // Be able to construct a proto binning py::class_(m, "ProtoBinning") .def(py::init&, std::size_t>(), + const std::vector&, std::size_t>(), "bValue"_a, "bType"_a, "e"_a, "exp"_a = 0u) - .def(py::init(), + .def(py::init(), "bValue"_a, "bType"_a, "minE"_a, "maxE"_a, "nbins"_a, "exp"_a = 0u) .def(py::init(), @@ -436,13 +435,13 @@ void addExperimentalGeometry(Context& ctx) { } { - using RangeXDDim1 = Acts::RangeXD<1u, Acts::ActsScalar>; + using RangeXDDim1 = Acts::RangeXD<1u, double>; using KdtSurfacesDim1Bin100 = Acts::Experimental::KdtSurfaces<1u, 100u>; using KdtSurfacesProviderDim1Bin100 = Acts::Experimental::KdtSurfacesProvider<1u, 100u>; py::class_(m, "RangeXDDim1") - .def(py::init([](const std::array& irange) { + .def(py::init([](const std::array& irange) { RangeXDDim1 range; range[0].shrink(irange[0], irange[1]); return range; @@ -464,14 +463,14 @@ void addExperimentalGeometry(Context& ctx) { } { - using RangeXDDim2 = Acts::RangeXD<2u, Acts::ActsScalar>; + using RangeXDDim2 = Acts::RangeXD<2u, double>; using KdtSurfacesDim2Bin100 = Acts::Experimental::KdtSurfaces<2u, 100u>; using KdtSurfacesProviderDim2Bin100 = Acts::Experimental::KdtSurfacesProvider<2u, 100u>; py::class_(m, "RangeXDDim2") - .def(py::init([](const std::array& range0, - const std::array& range1) { + .def(py::init([](const std::array& range0, + const std::array& range1) { RangeXDDim2 range; range[0].shrink(range0[0], range0[1]); range[1].shrink(range1[0], range1[1]); diff --git a/Examples/Python/src/Json.cpp b/Examples/Python/src/Json.cpp index be367612ac2..1eb1d83bfc0 100644 --- a/Examples/Python/src/Json.cpp +++ b/Examples/Python/src/Json.cpp @@ -11,14 +11,16 @@ #include "Acts/Detector/ProtoDetector.hpp" #include "Acts/Plugins/Json/DetectorJsonConverter.hpp" #include "Acts/Plugins/Json/JsonMaterialDecorator.hpp" +#include "Acts/Plugins/Json/JsonSurfacesReader.hpp" #include "Acts/Plugins/Json/MaterialMapJsonConverter.hpp" #include "Acts/Plugins/Json/ProtoDetectorJsonConverter.hpp" #include "Acts/Plugins/Python/Utilities.hpp" #include "Acts/Utilities/Logger.hpp" #include "ActsExamples/Framework/ProcessCode.hpp" #include "ActsExamples/Io/Json/JsonMaterialWriter.hpp" -#include "ActsExamples/Io/Json/JsonSurfacesReader.hpp" #include "ActsExamples/Io/Json/JsonSurfacesWriter.hpp" +#include "ActsExamples/Io/Json/JsonTrackParamsLookupReader.hpp" +#include "ActsExamples/Io/Json/JsonTrackParamsLookupWriter.hpp" #include #include @@ -37,6 +39,11 @@ class IMaterialDecorator; namespace ActsExamples { class IMaterialWriter; class IWriter; + +namespace Experimental { +class ITrackParamsLookupWriter; +} // namespace Experimental + } // namespace ActsExamples namespace py = pybind11; @@ -111,6 +118,50 @@ 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::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_( - mex, "SurfaceJsonOptions") - .def(py::init<>()); + auto sjOptions = + py::class_(m, "SurfaceJsonOptions") + .def(py::init<>()); - ACTS_PYTHON_STRUCT_BEGIN(sjOptions, - ActsExamples::JsonSurfacesReader::Options); + ACTS_PYTHON_STRUCT_BEGIN(sjOptions, Acts::JsonSurfacesReader::Options); ACTS_PYTHON_MEMBER(inputFile); ACTS_PYTHON_MEMBER(jsonEntryPath); ACTS_PYTHON_STRUCT_END(); - mex.def("readSurfaceHierarchyMapFromJson", - ActsExamples::JsonSurfacesReader::readHierarchyMap); + m.def("readSurfaceHierarchyMapFromJson", + Acts::JsonSurfacesReader::readHierarchyMap); + + m.def("readSurfaceVectorFromJson", Acts::JsonSurfacesReader::readVector); + + py::class_>( + m, "JsonDetectorElement") + .def("surface", [](Acts::JsonDetectorElement& self) { + return self.surface().getSharedPtr(); + }); - mex.def("readSurfaceVectorFromJson", - ActsExamples::JsonSurfacesReader::readVector); + m.def("readDetectorElementsFromJson", + Acts::JsonSurfacesReader::readDetectorElements); } { diff --git a/Examples/Python/src/Output.cpp b/Examples/Python/src/Output.cpp index 5f174777429..4281f2db26e 100644 --- a/Examples/Python/src/Output.cpp +++ b/Examples/Python/src/Output.cpp @@ -48,6 +48,8 @@ #include "ActsExamples/MaterialMapping/IMaterialWriter.hpp" #include "ActsExamples/Plugins/Obj/ObjPropagationStepsWriter.hpp" #include "ActsExamples/Plugins/Obj/ObjTrackingGeometryWriter.hpp" +#include "ActsExamples/TrackFinding/ITrackParamsLookupReader.hpp" +#include "ActsExamples/TrackFinding/ITrackParamsLookupWriter.hpp" #include #include @@ -279,6 +281,14 @@ void addOutput(Context& ctx) { py::class_>( mex, "IMaterialWriter"); + py::class_>( + mex, "ITrackParamsLookupWriter"); + + py::class_>( + 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..54eb7e76641 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/Python/src/TruthTracking.cpp b/Examples/Python/src/TruthTracking.cpp index 3f0d8a0915a..319ee24e2ee 100644 --- a/Examples/Python/src/TruthTracking.cpp +++ b/Examples/Python/src/TruthTracking.cpp @@ -8,15 +8,16 @@ #include "Acts/Plugins/Python/Utilities.hpp" #include "Acts/Utilities/Logger.hpp" +#include "ActsExamples/TruthTracking/HitSelector.hpp" #include "ActsExamples/TruthTracking/ParticleSelector.hpp" -#include "ActsExamples/TruthTracking/ParticleSmearing.hpp" +#include "ActsExamples/TruthTracking/ParticleTrackParamExtractor.hpp" #include "ActsExamples/TruthTracking/TrackModifier.hpp" #include "ActsExamples/TruthTracking/TrackParameterSelector.hpp" +#include "ActsExamples/TruthTracking/TrackParameterSmearing.hpp" #include "ActsExamples/TruthTracking/TrackTruthMatcher.hpp" #include "ActsExamples/TruthTracking/TruthSeedingAlgorithm.hpp" #include "ActsExamples/TruthTracking/TruthTrackFinder.hpp" #include "ActsExamples/TruthTracking/TruthVertexFinder.hpp" -#include "ActsExamples/Utilities/HitSelector.hpp" #include @@ -41,12 +42,16 @@ void addTruthTracking(Context& ctx) { ActsExamples::TruthTrackFinder, mex, "TruthTrackFinder", inputParticles, inputMeasurementParticlesMap, outputProtoTracks); + ACTS_PYTHON_DECLARE_ALGORITHM(ActsExamples::ParticleTrackParamExtractor, mex, + "ParticleTrackParamExtractor", inputParticles, + outputTrackParameters); + ACTS_PYTHON_DECLARE_ALGORITHM( - ActsExamples::ParticleSmearing, mex, "ParticleSmearing", inputParticles, - outputTrackParameters, sigmaD0, sigmaD0PtA, sigmaD0PtB, sigmaZ0, - sigmaZ0PtA, sigmaZ0PtB, sigmaT0, sigmaPhi, sigmaTheta, sigmaPtRel, - initialSigmas, initialSigmaPtRel, initialVarInflation, particleHypothesis, - randomNumbers); + ActsExamples::TrackParameterSmearing, mex, "TrackParameterSmearing", + inputTrackParameters, outputTrackParameters, sigmaLoc0, sigmaLoc0PtA, + sigmaLoc0PtB, sigmaLoc1, sigmaLoc1PtA, sigmaLoc1PtB, sigmaTime, sigmaPhi, + sigmaTheta, sigmaPtRel, initialSigmas, initialSigmaPtRel, + initialVarInflation, particleHypothesis, randomNumbers); { using Alg = ActsExamples::ParticleSelector; @@ -85,6 +90,8 @@ void addTruthTracking(Context& ctx) { ACTS_PYTHON_MEMBER(removeNeutral); ACTS_PYTHON_MEMBER(removeSecondaries); ACTS_PYTHON_MEMBER(excludeAbsPdgs); + ACTS_PYTHON_MEMBER(minPrimaryVertexId); + ACTS_PYTHON_MEMBER(maxPrimaryVertexId); ACTS_PYTHON_STRUCT_END(); pythonRangeProperty(c, "rho", &Config::rhoMin, &Config::rhoMax); @@ -97,6 +104,8 @@ void addTruthTracking(Context& ctx) { pythonRangeProperty(c, "pt", &Config::ptMin, &Config::ptMax); pythonRangeProperty(c, "measurements", &Config::measurementsMin, &Config::measurementsMax); + pythonRangeProperty(c, "primaryVertexId", &Config::minPrimaryVertexId, + &Config::maxPrimaryVertexId); } { @@ -154,7 +163,10 @@ void addTruthTracking(Context& ctx) { outputParticles, outputSeeds, outputProtoTracks, deltaRMin, deltaRMax); ACTS_PYTHON_DECLARE_ALGORITHM(ActsExamples::HitSelector, mex, "HitSelector", - inputHits, outputHits, maxTime); + inputHits, inputParticlesSelected, outputHits, + minX, maxX, minY, maxY, minZ, maxZ, minR, maxR, + minTime, maxTime, minEnergyLoss, maxEnergyLoss, + minPrimaryVertexId, maxPrimaryVertexId); ACTS_PYTHON_DECLARE_ALGORITHM( ActsExamples::TrackTruthMatcher, mex, "TrackTruthMatcher", inputTracks, diff --git a/Examples/Python/tests/conftest.py b/Examples/Python/tests/conftest.py index 71c0899fe3f..4bd8a430730 100644 --- a/Examples/Python/tests/conftest.py +++ b/Examples/Python/tests/conftest.py @@ -209,19 +209,12 @@ def _basic_prop_seq_factory(geo, s=None): rnd=rng, ) - # Run particle smearing - trackParametersGenerator = acts.examples.ParticleSmearing( - level=acts.logging.INFO, + trkParamExtractor = acts.examples.ParticleTrackParamExtractor( + level=acts.logging.WARNING, inputParticles="particles_input", - outputTrackParameters="start_parameters", - randomNumbers=rng, - sigmaD0=0.0, - sigmaZ0=0.0, - sigmaPhi=0.0, - sigmaTheta=0.0, - sigmaPtRel=0.0, + outputTrackParameters="params_particles_input", ) - s.addAlgorithm(trackParametersGenerator) + s.addAlgorithm(trkParamExtractor) nav = acts.Navigator(trackingGeometry=geo) stepper = acts.StraightLineStepper() @@ -232,11 +225,11 @@ def _basic_prop_seq_factory(geo, s=None): level=acts.logging.WARNING, propagatorImpl=prop, sterileLogger=False, - inputTrackParameters="start_parameters", + inputTrackParameters="params_particles_input", outputSummaryCollection="propagation_summary", ) - s.addAlgorithm(alg) + return s, alg return _basic_prop_seq_factory diff --git a/Examples/Python/tests/requirements.txt b/Examples/Python/tests/requirements.txt index c4067c4adf6..535d3458274 100644 --- a/Examples/Python/tests/requirements.txt +++ b/Examples/Python/tests/requirements.txt @@ -4,42 +4,46 @@ # # pip-compile Examples/Python/tests/requirements.in # -awkward==2.6.1 +awkward==2.7.0 # via # -r Examples/Python/tests/requirements.in # uproot -awkward-cpp==29 +awkward-cpp==41 # via awkward -execnet==2.0.2 +cramjam==2.9.0 + # via uproot +execnet==2.1.1 # via pytest-xdist -fsspec==2024.2.0 +fsspec==2024.10.0 # via # awkward # uproot iniconfig==2.0.0 # via pytest -numpy==1.26.4 +numpy==2.1.3 # via # awkward # awkward-cpp # uproot -packaging==23.2 +packaging==24.2 # via # awkward # pytest # uproot -pluggy==1.4.0 +pluggy==1.5.0 # via pytest -pytest==8.0.0 +pytest==8.3.3 # via # -r Examples/Python/tests/requirements.in # pytest-check # pytest-xdist -pytest-check==2.3.1 +pytest-check==2.4.1 # via -r Examples/Python/tests/requirements.in -pytest-xdist==3.5.0 +pytest-xdist==3.6.1 # via -r Examples/Python/tests/requirements.in -pyyaml==6.0.1 +pyyaml==6.0.2 # via -r Examples/Python/tests/requirements.in -uproot==5.2.2 +uproot==5.5.0 # via -r Examples/Python/tests/requirements.in +xxhash==3.5.0 + # via uproot diff --git a/Examples/Python/tests/root_file_hashes.txt b/Examples/Python/tests/root_file_hashes.txt index 45337b2f762..6eeaaebff44 100644 --- a/Examples/Python/tests/root_file_hashes.txt +++ b/Examples/Python/tests/root_file_hashes.txt @@ -16,7 +16,7 @@ test_itk_seeding__estimatedparams.root: fc042037f12a434f2236df7d225b8ca24209b691 test_itk_seeding__performance_seeding.root: 78ebda54cd0f026ba4b7f316724ffd946de56a932735914baf1b7bba9505c29d test_itk_seeding__particles.root: 907ff693262c0db14b12c74b16586cb20d79caf5f03f93b178943e41ed35a1b6 test_itk_seeding__particles_simulation.root: ef0246069aa697019f28a8b270a68de95312cae5f2f2c74848566c3ce4f70363 -test_propagation__propagation_summary.root: 280c1a6fcfe71974ac39587b4afad27a31640bec42ca6537cc92e2d5e09d7ed6 +test_propagation__propagation_summary.root: de0c105ab0de0096241855fe3db46d7c5d054d897625ede4df276472a7e43c57 test_material_recording__geant4_material_tracks.root: c022b9362249b29f57a07926b20644e3ab4ab8ebcf03f773fbf46c446fc1a0a1 test_truth_tracking_gsf[generic]__trackstates_gsf.root: 4df2c69d5dd7d5446a547651e4e962daf17924f5c8617165a93a3223c8ba18fd test_truth_tracking_gsf[generic]__tracksummary_gsf.root: 8c01d139cb865afa1959c62dbca76f3a1fb8b684c57ea4c2968baa6ffedadb6f @@ -24,30 +24,30 @@ test_truth_tracking_gsf[odd]__trackstates_gsf.root: c7397e53ea093f2432943ae263fc test_truth_tracking_gsf[odd]__tracksummary_gsf.root: 4562341f12a61ea0d5e25872b6bf466b79a73781dc95fc18ef9c6515f0a47916 test_particle_gun__particles.root: 669d0304eb8bcf244aa627809a117944e5e3b994fdfcfb8710f2b9a8f9a62d3b test_material_mapping__material-map_tracks.root: 938b1a855369e9304401cb10d2751df3fd7acf32a2573f2057eb1691cd94edf3 -test_material_mapping__propagation-material.root: 5eacd0cb804d381171c8fb65d7b2d36e1d57db9f4cb2b58c0f24703479218cbf +test_material_mapping__propagation-material.root: e2b4eade0d8124c03c89e01bf6ff5029dd12e3c9efc0a19c22a12c5cd2800e77 test_volume_material_mapping__material-map-volume_tracks.root: 98e212d32ca054fa3d01af4167c1f49755a139d43b82c57908197f5985e0a4ff -test_volume_material_mapping__propagation-volume-material.root: 3e9d38cc541a1956b2f33be320d457559bb230311130a8531bf09371c272f913 +test_volume_material_mapping__propagation-volume-material.root: 42bb2fd9c50d44210c914e487903bbdef65a0491f0a85a7159c0e078ac983a80 test_digitization_example[smeared]__measurements.root: 2b583b886b76f94786c6c2832aa84d176059cbbc35882fb34b4fd1f22dd4c006 test_digitization_example[geometric]__measurements.root: 85efa861d14207fd7d1798dab093edcd0a2685bc189b4fc9a96b07d1001013a0 test_digitization_example_input[smeared]__particles.root: 669d0304eb8bcf244aa627809a117944e5e3b994fdfcfb8710f2b9a8f9a62d3b test_digitization_example_input[smeared]__measurements.root: 243c2f69b7b0db9dbeaa7494d4ea0f3dd1691dc90f16e10df6c0491ff4dc7d62 test_digitization_example_input[geometric]__particles.root: 669d0304eb8bcf244aa627809a117944e5e3b994fdfcfb8710f2b9a8f9a62d3b test_digitization_example_input[geometric]__measurements.root: 63ec81635979058fb8976f94455bf490cf92b7b142c4a05cc39de6225f5de2fb -test_ckf_tracks_example[generic-full_seeding]__trackstates_ckf.root: ec6487dfca5f944cfacfef903eb4b9a97f8f6a668d07f77d0c3ec45c68054824 -test_ckf_tracks_example[generic-full_seeding]__tracksummary_ckf.root: 84085bcc63562cfb1b4c70d2665bf06938ac559bb40c2b01c076e1d8b5c7b43b +test_ckf_tracks_example[generic-full_seeding]__trackstates_ckf.root: f0b4c6018d0b2641024b88f6ac717f16a2ca486007c2e9bf166c85dc5e161739 +test_ckf_tracks_example[generic-full_seeding]__tracksummary_ckf.root: e5187591a0902d7214dd211adf459e2ec43b200b43c7ebdb90e5af50ee828f91 test_ckf_tracks_example[generic-full_seeding]__performance_seeding_trees.root: 0e0676ffafdb27112fbda50d1cf627859fa745760f98073261dcf6db3f2f991e -test_ckf_tracks_example[generic-truth_estimated]__trackstates_ckf.root: 8e15cceeef4b115708596702988925b7506d39e0531dc5534636ec411a9b4ca2 -test_ckf_tracks_example[generic-truth_estimated]__tracksummary_ckf.root: 8e0116c656e1cc67446d54a5205c4a3e2f4c1fc90fa551bb608c881877dfa0ab +test_ckf_tracks_example[generic-truth_estimated]__trackstates_ckf.root: 1d3198e1926cf2c568d1c854c3ec7d638ed296163ac3cd1ff68273ab21a12657 +test_ckf_tracks_example[generic-truth_estimated]__tracksummary_ckf.root: 0b0266b28e20efab834b74e816ed9c658527496f6ef55ca8c073133aae0825b1 test_ckf_tracks_example[generic-truth_estimated]__performance_seeding.root: 1facb05c066221f6361b61f015cdf0918e94d9f3fce2269ec7b6a4dffeb2bc7e -test_ckf_tracks_example[generic-truth_smeared]__trackstates_ckf.root: 82a6744980553e6274df78eea15f0dec22676b1c04e14afc3828bff9bbf5e1b1 -test_ckf_tracks_example[generic-truth_smeared]__tracksummary_ckf.root: 06d6ae1d05cb611b19df3c59531997c9b0108f5ef6027d76c4827bd2d9edb921 -test_ckf_tracks_example[odd-full_seeding]__trackstates_ckf.root: 17c48c5a61b1a5495d91336cdf06f9c24e50d81349c1f31d7c70ffff5810a376 -test_ckf_tracks_example[odd-full_seeding]__tracksummary_ckf.root: b5805e54030ab8ac80a8c0a764700c65433dc659783fc8ff3b2c96e512a1d045 +test_ckf_tracks_example[generic-truth_smeared]__trackstates_ckf.root: d043c7d28772954fa2c1e4b320384c26589586bc4cdd95e0506fab59a37135d7 +test_ckf_tracks_example[generic-truth_smeared]__tracksummary_ckf.root: f063e4ab1f7f55106fa8b61bac627ca4739f04434ee35c77db603910a6e1a747 +test_ckf_tracks_example[odd-full_seeding]__trackstates_ckf.root: d5388653cf5613e765e6ce1e5afe94d94ff5182d7734e75251bc415f0192f444 +test_ckf_tracks_example[odd-full_seeding]__tracksummary_ckf.root: 2a98d8ec8fae97e18f4661580b71885f558d7222f94bca5edfbf5cdb595021f7 test_ckf_tracks_example[odd-full_seeding]__performance_seeding_trees.root: 43c58577aafe07645e5660c4f43904efadf91d8cda45c5c04c248bbe0f59814f -test_ckf_tracks_example[odd-truth_estimated]__trackstates_ckf.root: 86be5a086d2a87dfde9320bb880bd0788d733ea9727cb5ee6dc0282ec4be39f4 -test_ckf_tracks_example[odd-truth_estimated]__tracksummary_ckf.root: ffce6a73f16986cb3f0386d4a8c1e0ff6f0b4130b9bb12d1af0eb905d000e3e9 +test_ckf_tracks_example[odd-truth_estimated]__trackstates_ckf.root: 6ed8f0db3f3e7f1b71b6d9da7371597d4fb5f95b3d2f2ab18be43d1763ce41c1 +test_ckf_tracks_example[odd-truth_estimated]__tracksummary_ckf.root: 1eaae038ced2cc5c757480ca42eab60cdaff14d812c34a807a841267d6bfa110 test_ckf_tracks_example[odd-truth_estimated]__performance_seeding.root: 1a36b7017e59f1c08602ef3c2cb0483c51df248f112e3780c66594110719c575 -test_ckf_tracks_example[odd-truth_smeared]__trackstates_ckf.root: 35a65e15a6f479f628a96f56ee78e1ac371d71a686ee0c974944d681499fe6bd +test_ckf_tracks_example[odd-truth_smeared]__trackstates_ckf.root: a519202b1233d8e7aac3c9038ee6e16b5d3cdfe2027212d6900e00ee0fcec21d test_ckf_tracks_example[odd-truth_smeared]__tracksummary_ckf.root: 3e257de624674fa9a19dcc72598c78c29a52633821acaa56dc2aa39a1395f1b5 test_vertex_fitting_reading[Truth-False-100]__performance_vertexing.root: 76ef6084d758dfdfc0151ddec2170e12d73394424e3dac4ffe46f0f339ec8293 test_vertex_fitting_reading[Iterative-False-100]__performance_vertexing.root: 60372210c830a04f95ceb78c6c68a9b0de217746ff59e8e73053750c837b57eb @@ -56,9 +56,9 @@ test_vertex_fitting_reading[AMVF-False-100]__performance_vertexing.root: 009e4b1 test_vertex_fitting_reading[AMVF-True-100]__performance_vertexing.root: 2d0dc1e02bfd1f7eaae26ef8ac657ce0291f70c7e4efddd35d171d31988a631e test_bfield_writing__solenoid.root: 7be51f0ed9cb99f59ae0271ba79cdb84635e6ee3d2109ea8a4b521875029c21d test_bfield_writing__solenoid2.root: 2db149336c9cd749dc50025076b49f9bc0586d53792b87a0fdd7f21a649a01a5 -test_root_prop_step_writer[configPosConstructor]__prop_steps.root: a783d525eebb4737e6e6bcf20d63d6f35520f4bcf23301ae8c4657309cbccdda -test_root_prop_step_writer[configKwConstructor]__prop_steps.root: a783d525eebb4737e6e6bcf20d63d6f35520f4bcf23301ae8c4657309cbccdda -test_root_prop_step_writer[kwargsConstructor]__prop_steps.root: a783d525eebb4737e6e6bcf20d63d6f35520f4bcf23301ae8c4657309cbccdda +test_root_prop_step_writer[configPosConstructor]__prop_steps.root: 200ece7cde60eb0dd8835cf4830835e9058d897ba5759099d96914b06a1df092 +test_root_prop_step_writer[configKwConstructor]__prop_steps.root: 200ece7cde60eb0dd8835cf4830835e9058d897ba5759099d96914b06a1df092 +test_root_prop_step_writer[kwargsConstructor]__prop_steps.root: 200ece7cde60eb0dd8835cf4830835e9058d897ba5759099d96914b06a1df092 test_root_particle_writer[configPosConstructor]__particles.root: e5d723e138b4e121c6e74a6dba072072f622995e117a40b8e63755ac784baad6 test_root_particle_writer[configKwConstructor]__particles.root: e5d723e138b4e121c6e74a6dba072072f622995e117a40b8e63755ac784baad6 test_root_particle_writer[kwargsConstructor]__particles.root: e5d723e138b4e121c6e74a6dba072072f622995e117a40b8e63755ac784baad6 diff --git a/Examples/Python/tests/test_algorithms.py b/Examples/Python/tests/test_algorithms.py index 4cca7199291..6311dc6460a 100644 --- a/Examples/Python/tests/test_algorithms.py +++ b/Examples/Python/tests/test_algorithms.py @@ -14,7 +14,7 @@ TruthTrackFinder, ParticleSelector, TruthVertexFinder, - ParticleSmearing, + TrackParameterSmearing, TrackSelectorAlgorithm, TrackFittingAlgorithm, SurfaceSortingAlgorithm, @@ -44,7 +44,7 @@ TruthTrackFinder, ParticleSelector, TruthVertexFinder, - ParticleSmearing, + TrackParameterSmearing, TrackSelectorAlgorithm, TrackFittingAlgorithm, SurfaceSortingAlgorithm, diff --git a/Examples/Python/tests/test_propagation.py b/Examples/Python/tests/test_propagation.py index 6583098f427..adfc55ba8c2 100644 --- a/Examples/Python/tests/test_propagation.py +++ b/Examples/Python/tests/test_propagation.py @@ -56,34 +56,27 @@ def test_steppers(conf_const, trk_geo): rnd=rnd, ) - # Run particle smearing - trackParametersGenerator = acts.examples.ParticleSmearing( - level=acts.logging.INFO, - inputParticles="particles_input", - outputTrackParameters="start_parameters", - randomNumbers=rnd, - sigmaD0=0.0, - sigmaZ0=0.0, - sigmaPhi=0.0, - sigmaTheta=0.0, - sigmaPtRel=0.0, - ) - seq.addAlgorithm(trackParametersGenerator) - prop = acts.examples.ConcretePropagator( acts.Propagator(stepper=s, navigator=nav) ) + trkParamExtractor = acts.examples.ParticleTrackParamExtractor( + level=acts.logging.WARNING, + inputParticles="particles_input", + outputTrackParameters="params_particles_input", + ) + seq.addAlgorithm(trkParamExtractor) + alg = conf_const( acts.examples.PropagationAlgorithm, level=acts.logging.WARNING, propagatorImpl=prop, - inputTrackParameters="start_parameters", + inputTrackParameters="params_particles_input", outputSummaryCollection="propagation_summary", sterileLogger=False, ) - seq.addAlgorithm(alg) + chkAlg = AssertCollectionExistsAlg( "propagation_summary", "chk_alg", level=acts.logging.WARNING ) diff --git a/Examples/Python/tests/test_writer.py b/Examples/Python/tests/test_writer.py index 4c9e220f899..ac64fa4048f 100644 --- a/Examples/Python/tests/test_writer.py +++ b/Examples/Python/tests/test_writer.py @@ -197,6 +197,43 @@ def test_root_simhits_writer(tmp_path, fatras, conf_const, assert_root_hash): assert_root_hash(out.name, out) +@pytest.mark.root +def test_root_tracksummary_writer(tmp_path, fatras, conf_const): + detector, trackingGeometry, decorators = GenericDetector.create() + field = acts.ConstantBField(acts.Vector3(0, 0, 2 * u.T)) + s = Sequencer(numThreads=1, events=10) + + from truth_tracking_kalman import runTruthTrackingKalman + + # This also runs the RootTrackSummaryWriter with truth information + runTruthTrackingKalman( + trackingGeometry, + field, + digiConfigFile=Path( + str( + Path(__file__).parent.parent.parent.parent + / "Examples/Algorithms/Digitization/share/default-smearing-config-generic.json" + ) + ), + outputDir=tmp_path, + s=s, + ) + + # Run the RootTrackSummaryWriter without the truth information + s.addWriter( + conf_const( + RootTrackSummaryWriter, + level=acts.logging.INFO, + inputTracks="tracks", + filePath=str(tmp_path / "track_summary_kf_no_truth.root"), + ) + ) + + s.run() + assert (tmp_path / "tracksummary_kf.root").exists() + assert (tmp_path / "track_summary_kf_no_truth.root").exists() + + @pytest.mark.csv def test_csv_meas_writer(tmp_path, fatras, trk_geo, conf_const): s = Sequencer(numThreads=1, events=10) diff --git a/Examples/Scripts/MaterialMapping/MaterialComposition.cpp b/Examples/Scripts/MaterialMapping/MaterialComposition.cpp index 348a4912f29..7e7731af846 100644 --- a/Examples/Scripts/MaterialMapping/MaterialComposition.cpp +++ b/Examples/Scripts/MaterialMapping/MaterialComposition.cpp @@ -24,7 +24,7 @@ #include #define BOOST_AVAILABLE 1 -#if ((BOOST_VERSION / 100) % 1000) <= 71 +#if BOOST_VERSION < 107200 // Boost <=1.71 and lower do not have progress_display.hpp as a replacement yet #include diff --git a/Examples/Scripts/Optimization/ckf.py b/Examples/Scripts/Optimization/ckf.py index ba18291735c..e0cd5fd9870 100755 --- a/Examples/Scripts/Optimization/ckf.py +++ b/Examples/Scripts/Optimization/ckf.py @@ -123,7 +123,7 @@ def runCKFTracks( from acts.examples.reconstruction import ( addSeeding, - ParticleSmearingSigmas, + TrackSmearingSigmas, SeedFinderConfigArg, SeedFinderOptionsArg, SeedingAlgorithm, @@ -188,15 +188,15 @@ def runCKFTracks( s, trackingGeometry, field, - ParticleSmearingSigmas( # only used by SeedingAlgorithm.TruthSmeared + TrackSmearingSigmas( # only used by SeedingAlgorithm.TruthSmeared # zero eveything so the CKF has a chance to find the measurements - d0=0, - d0PtA=0, - d0PtB=0, - z0=0, - z0PtA=0, - z0PtB=0, - t0=0, + loc0=0, + loc0PtA=0, + loc0PtB=0, + loc1=0, + loc1PtA=0, + loc1PtB=0, + time=0, phi=0, theta=0, ptRel=0, diff --git a/Examples/Scripts/Python/ckf_tracks.py b/Examples/Scripts/Python/ckf_tracks.py index 97f56d17ff0..75ec8a7c316 100755 --- a/Examples/Scripts/Python/ckf_tracks.py +++ b/Examples/Scripts/Python/ckf_tracks.py @@ -34,7 +34,7 @@ def runCKFTracks( from acts.examples.reconstruction import ( addSeeding, - ParticleSmearingSigmas, + TrackSmearingSigmas, SeedFinderConfigArg, SeedFinderOptionsArg, SeedingAlgorithm, @@ -99,15 +99,15 @@ def runCKFTracks( s, trackingGeometry, field, - ParticleSmearingSigmas( # only used by SeedingAlgorithm.TruthSmeared + TrackSmearingSigmas( # only used by SeedingAlgorithm.TruthSmeared # zero eveything so the CKF has a chance to find the measurements - d0=0, - d0PtA=0, - d0PtB=0, - z0=0, - z0PtA=0, - z0PtB=0, - t0=0, + loc0=0, + loc0PtA=0, + loc0PtB=0, + loc1=0, + loc1PtA=0, + loc1PtB=0, + time=0, phi=0, theta=0, ptRel=0, diff --git a/Examples/Scripts/Python/full_chain_test.py b/Examples/Scripts/Python/full_chain_test.py index f0010bd498e..595dbd43a4e 100755 --- a/Examples/Scripts/Python/full_chain_test.py +++ b/Examples/Scripts/Python/full_chain_test.py @@ -521,7 +521,7 @@ def full_chain(args): from acts.examples.reconstruction import ( addSeeding, - ParticleSmearingSigmas, + TrackSmearingSigmas, addCKFTracks, CkfConfig, SeedingAlgorithm, @@ -547,7 +547,7 @@ def full_chain(args): seedingAlgorithm=args.seeding_algorithm, **( dict( - particleSmearingSigmas=ParticleSmearingSigmas(ptRel=0.01), + trackSmearingSigmas=TrackSmearingSigmas(ptRel=0.01), rnd=rnd, ) if args.seeding_algorithm == SeedingAlgorithm.TruthSmeared diff --git a/Examples/Scripts/Python/material_validation.py b/Examples/Scripts/Python/material_validation.py index ebc26041cd2..94c0f21b94a 100755 --- a/Examples/Scripts/Python/material_validation.py +++ b/Examples/Scripts/Python/material_validation.py @@ -40,30 +40,22 @@ def runMaterialValidation( rnd=rnd, ) - # Run particle smearing - trackParametersGenerator = acts.examples.ParticleSmearing( + trkParamExtractor = acts.examples.ParticleTrackParamExtractor( level=acts.logging.INFO, inputParticles="particles_input", - outputTrackParameters="start_parameters", - randomNumbers=rnd, - sigmaD0=0.0, - sigmaZ0=0.0, - sigmaPhi=0.0, - sigmaTheta=0.0, - sigmaPtRel=0.0, + outputTrackParameters="params_particles_input", ) - s.addAlgorithm(trackParametersGenerator) + s.addAlgorithm(trkParamExtractor) alg = acts.examples.PropagationAlgorithm( propagatorImpl=prop, level=acts.logging.INFO, sterileLogger=True, recordMaterialInteractions=True, - inputTrackParameters="start_parameters", + inputTrackParameters="params_particles_input", outputSummaryCollection="propagation_summary", outputMaterialCollection="material_tracks", ) - s.addAlgorithm(alg) s.addWriter( diff --git a/Examples/Scripts/Python/material_validation_itk.py b/Examples/Scripts/Python/material_validation_itk.py index 759f75a5ea2..4d5f095ef10 100755 --- a/Examples/Scripts/Python/material_validation_itk.py +++ b/Examples/Scripts/Python/material_validation_itk.py @@ -10,6 +10,8 @@ def runMaterialValidation( + nevents, + ntracks, trackingGeometry, decorators, field, @@ -18,7 +20,8 @@ def runMaterialValidation( dumpPropagationSteps=False, s=None, ): - s = s or Sequencer(events=1000, numThreads=-1) + # Create a sequencer + s = s or Sequencer(events=nevents, numThreads=-1) rnd = acts.examples.RandomNumbers(seed=42) @@ -44,31 +47,22 @@ def runMaterialValidation( rnd=rnd, ) - # Run particle smearing - trackParametersGenerator = acts.examples.ParticleSmearing( + trkParamExtractor = acts.examples.ParticleTrackParamExtractor( level=acts.logging.INFO, inputParticles="particles_input", - outputTrackParameters="start_parameters", - randomNumbers=rnd, - sigmaD0=0.0, - sigmaZ0=0.0, - sigmaPhi=0.0, - sigmaTheta=0.0, - sigmaPRel=0.0, - addCovariances=False, + outputTrackParameters="params_particles_input", ) - s.addAlgorithm(trackParametersGenerator) + s.addAlgorithm(trkParamExtractor) alg = acts.examples.PropagationAlgorithm( propagatorImpl=prop, level=acts.logging.INFO, sterileLogger=False, recordMaterialInteractions=True, - inputTrackParameters="start_parameters", + inputTrackParameters="params_particles_input", outputPropagationSteps="propagation_steps", outputMaterialTracks="material-tracks", ) - s.addAlgorithm(alg) s.addWriter( diff --git a/Examples/Scripts/Python/propagation.py b/Examples/Scripts/Python/propagation.py index ea54919a89f..59be3385ca0 100755 --- a/Examples/Scripts/Python/propagation.py +++ b/Examples/Scripts/Python/propagation.py @@ -31,19 +31,12 @@ def runPropagation(trackingGeometry, field, outputDir, s=None, decorators=[]): rnd=rnd, ) - # Run particle smearing - trackParametersGenerator = acts.examples.ParticleSmearing( - level=acts.logging.INFO, + trkParamExtractor = acts.examples.ParticleTrackParamExtractor( + level=acts.logging.WARNING, inputParticles="particles_input", - outputTrackParameters="start_parameters", - randomNumbers=rnd, - sigmaD0=0.0, - sigmaZ0=0.0, - sigmaPhi=0.0, - sigmaTheta=0.0, - sigmaPtRel=0.0, + outputTrackParameters="params_particles_input", ) - s.addAlgorithm(trackParametersGenerator) + s.addAlgorithm(trkParamExtractor) nav = acts.Navigator(trackingGeometry=trackingGeometry) @@ -57,7 +50,7 @@ def runPropagation(trackingGeometry, field, outputDir, s=None, decorators=[]): propagatorImpl=propagator, level=acts.logging.INFO, sterileLogger=True, - inputTrackParameters="start_parameters", + inputTrackParameters="params_particles_input", outputSummaryCollection="propagation_summary", ) s.addAlgorithm(propagationAlgorithm) 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..ecdffc20ec3 --- /dev/null +++ b/Examples/Scripts/Python/telescope_track_params_lookup_generation.py @@ -0,0 +1,111 @@ +#!/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) diff --git a/Examples/Scripts/Python/vertex_fitting.py b/Examples/Scripts/Python/vertex_fitting.py index e8797a5ed12..c6088f618a6 100755 --- a/Examples/Scripts/Python/vertex_fitting.py +++ b/Examples/Scripts/Python/vertex_fitting.py @@ -6,7 +6,7 @@ from acts.examples import ( Sequencer, ParticleSelector, - ParticleSmearing, + TrackParameterSmearing, TrackParameterSelector, ) from acts.examples.simulation import addPythia8 @@ -65,9 +65,16 @@ def runVertexFitting( if inputTrackSummary is None or inputParticlePath is None: logger.info("Using smeared particles") - ptclSmearing = ParticleSmearing( - level=acts.logging.INFO, + trkParamExtractor = acts.examples.ParticleTrackParamExtractor( + level=acts.logging.WARNING, inputParticles=selectedParticles, + outputTrackParameters="params_particles_input", + ) + s.addAlgorithm(trkParamExtractor) + + ptclSmearing = TrackParameterSmearing( + level=acts.logging.INFO, + inputTrackParameters="params_particles_input", outputTrackParameters=trackParameters, randomNumbers=rnd, ) diff --git a/Examples/Scripts/TrackingPerformance/TrackSummary.cpp b/Examples/Scripts/TrackingPerformance/TrackSummary.cpp index deba72311d5..0e806ff0a90 100644 --- a/Examples/Scripts/TrackingPerformance/TrackSummary.cpp +++ b/Examples/Scripts/TrackingPerformance/TrackSummary.cpp @@ -27,7 +27,7 @@ #include #define BOOST_AVAILABLE 1 -#if ((BOOST_VERSION / 100) % 1000) <= 71 +#if BOOST_VERSION < 107200 // Boost <=1.71 and lower do not have progress_display.hpp as a replacement yet #include diff --git a/Examples/Scripts/requirements.txt b/Examples/Scripts/requirements.txt index 371122cba63..05f1e49374f 100644 --- a/Examples/Scripts/requirements.txt +++ b/Examples/Scripts/requirements.txt @@ -4,45 +4,51 @@ # # pip-compile Examples/Scripts/requirements.in # -annotated-types==0.6.0 +annotated-types==0.7.0 # via pydantic -awkward==2.5.0 +awkward==2.7.0 # via # -r Examples/Scripts/requirements.in # uproot -awkward-cpp==26 +awkward-cpp==41 # via awkward -boost-histogram==1.4.0 +boost-histogram==1.5.0 # via hist click==8.1.7 # via # histoprint # typer -contourpy==1.2.0 +contourpy==1.3.1 # via matplotlib +cramjam==2.9.0 + # via uproot cycler==0.12.1 # via matplotlib -fonttools==4.46.0 +fonttools==4.55.0 # via matplotlib -hist==2.7.2 +fsspec==2024.10.0 + # via + # awkward + # uproot +hist==2.8.0 # via -r Examples/Scripts/requirements.in -histoprint==2.4.0 +histoprint==2.5.0 # via hist -kiwisolver==1.4.5 +kiwisolver==1.4.7 # via matplotlib markdown-it-py==3.0.0 # via rich -matplotlib==3.8.2 +matplotlib==3.9.2 # via # -r Examples/Scripts/requirements.in # mplhep mdurl==0.1.2 # via markdown-it-py -mplhep==0.3.31 +mplhep==0.3.55 # via -r Examples/Scripts/requirements.in -mplhep-data==0.0.3 +mplhep-data==0.0.4 # via mplhep -numpy==1.26.2 +numpy==2.1.3 # via # awkward # awkward-cpp @@ -56,50 +62,56 @@ numpy==1.26.2 # scipy # uhi # uproot -packaging==23.2 +packaging==24.2 # via # awkward # matplotlib # mplhep # uproot -pandas==2.1.3 +pandas==2.2.3 # via -r Examples/Scripts/requirements.in -pillow==10.1.0 +pillow==11.0.0 # via matplotlib -pydantic==2.5.2 +pydantic==2.9.2 # via -r Examples/Scripts/requirements.in -pydantic-core==2.14.5 +pydantic-core==2.23.4 # via pydantic -pygments==2.17.2 +pygments==2.18.0 # via rich -pyparsing==3.1.1 +pyparsing==3.2.0 # via matplotlib -python-dateutil==2.8.2 +python-dateutil==2.9.0.post0 # via # matplotlib # pandas -pytz==2023.3.post1 +pytz==2024.2 # via pandas -pyyaml==6.0.1 - # via -r Examples/Scripts/requirements.in -rich==13.7.0 +pyyaml==6.0.2 # via -r Examples/Scripts/requirements.in -scipy==1.11.4 +rich==13.9.4 + # via + # -r Examples/Scripts/requirements.in + # typer +scipy==1.14.1 # via -r Examples/Scripts/requirements.in +shellingham==1.5.4 + # via typer six==1.16.0 # via python-dateutil -typer==0.9.0 +typer==0.13.1 # via -r Examples/Scripts/requirements.in -typing-extensions==4.8.0 +typing-extensions==4.12.2 # via # pydantic # pydantic-core # typer -tzdata==2023.3 +tzdata==2024.2 # via pandas -uhi==0.4.0 +uhi==0.5.0 # via # histoprint # mplhep -uproot==5.1.2 +uproot==5.5.0 # via -r Examples/Scripts/requirements.in +xxhash==3.5.0 + # via uproot diff --git a/Fatras/Geant4/include/ActsFatras/Geant4/Geant4Decay.hpp b/Fatras/Geant4/include/ActsFatras/Geant4/Geant4Decay.hpp index 177e3ac6221..758df351071 100644 --- a/Fatras/Geant4/include/ActsFatras/Geant4/Geant4Decay.hpp +++ b/Fatras/Geant4/include/ActsFatras/Geant4/Geant4Decay.hpp @@ -27,8 +27,6 @@ namespace ActsFatras { /// Handle particle decays using the Geant4 decay models. class Geant4Decay { public: - using Scalar = Particle::Scalar; - /// Constructor Geant4Decay(); @@ -40,7 +38,7 @@ class Geant4Decay { /// /// @return Proper time limit of the particle template - Scalar generateProperTimeLimit(generator_t& generator, + double generateProperTimeLimit(generator_t& generator, const Particle& particle) const; /// Decay the particle and create the decay products. @@ -67,13 +65,13 @@ class Geant4Decay { }; template -Particle::Scalar Geant4Decay::generateProperTimeLimit( - generator_t& generator, const Particle& particle) const { +double Geant4Decay::generateProperTimeLimit(generator_t& generator, + const Particle& particle) const { // Get the particle properties const Acts::PdgParticle pdgCode = particle.pdg(); // Keep muons stable if (makeAbsolutePdgParticle(pdgCode) == Acts::PdgParticle::eMuon) { - return std::numeric_limits::infinity(); + return std::numeric_limits::infinity(); } // Get the Geant4 particle @@ -81,14 +79,14 @@ Particle::Scalar Geant4Decay::generateProperTimeLimit( // Fast exit if the particle is stable if (!pDef || pDef->GetPDGStable()) { - return std::numeric_limits::infinity(); + return std::numeric_limits::infinity(); } // Get average lifetime - constexpr Scalar convertTime = Acts::UnitConstants::mm / CLHEP::s; - const Scalar tau = pDef->GetPDGLifeTime() * convertTime; + constexpr double convertTime = Acts::UnitConstants::mm / CLHEP::s; + const double tau = pDef->GetPDGLifeTime() * convertTime; // Sample & return the lifetime - std::uniform_real_distribution uniformDistribution{0., 1.}; + std::uniform_real_distribution uniformDistribution{0., 1.}; return -tau * std::log(uniformDistribution(generator)); } diff --git a/Fatras/Geant4/src/Geant4Decay.cpp b/Fatras/Geant4/src/Geant4Decay.cpp index 41b5a3656b1..bf23566aa05 100644 --- a/Fatras/Geant4/src/Geant4Decay.cpp +++ b/Fatras/Geant4/src/Geant4Decay.cpp @@ -50,7 +50,7 @@ std::vector ActsFatras::Geant4Decay::decayParticle( } // Boost the decay products using the parents four-momentum - const Particle::Vector4 mom4 = parent.fourMomentum(); + const Acts::Vector4 mom4 = parent.fourMomentum(); products->Boost(mom4[Acts::eMom0] / mom4[Acts::eEnergy], mom4[Acts::eMom1] / mom4[Acts::eEnergy], mom4[Acts::eMom2] / mom4[Acts::eEnergy]); @@ -64,7 +64,7 @@ std::vector ActsFatras::Geant4Decay::decayParticle( // Convert the decay product from Geant4 to Acts const G4ThreeVector& mom = prod->GetMomentum(); - constexpr Scalar convertEnergy = Acts::UnitConstants::GeV / CLHEP::GeV; + constexpr double convertEnergy = Acts::UnitConstants::GeV / CLHEP::GeV; Acts::Vector3 amgMom(mom.x(), mom.y(), mom.z()); amgMom *= convertEnergy; const std::int32_t pdg = prod->GetPDGcode(); diff --git a/Fatras/include/ActsFatras/Digitization/DigitizationData.hpp b/Fatras/include/ActsFatras/Digitization/DigitizationData.hpp index 314cbcc5eb1..f2e808e00cb 100644 --- a/Fatras/include/ActsFatras/Digitization/DigitizationData.hpp +++ b/Fatras/include/ActsFatras/Digitization/DigitizationData.hpp @@ -17,7 +17,7 @@ namespace ActsFatras { /// A single cell definition: index, cell central value -using Cell = std::pair; +using Cell = std::pair; /// A channel definition: Cell identification, readout word, links /// @@ -35,7 +35,7 @@ struct Channel { /// Channel constructor /// - /// @param cellId_ The Cell idenficiation and position + /// @param cellId_ The Cell identification and position /// @param value_ The Cell value /// @param links_ The (optional) links to e.g. truth indices Channel(std::array cellId_, signal_t value_, @@ -51,7 +51,6 @@ struct Channel { /// @tparam kSize Number of cluster coordinates template struct Cluster { - using Scalar = Acts::ActsScalar; using ParametersVector = Acts::ActsVector; using CovarianceMatrix = Acts::ActsSquareMatrix; diff --git a/Fatras/include/ActsFatras/Digitization/UncorrelatedHitSmearer.hpp b/Fatras/include/ActsFatras/Digitization/UncorrelatedHitSmearer.hpp index 4420c8a6200..caf5efa8c61 100644 --- a/Fatras/include/ActsFatras/Digitization/UncorrelatedHitSmearer.hpp +++ b/Fatras/include/ActsFatras/Digitization/UncorrelatedHitSmearer.hpp @@ -41,7 +41,6 @@ using SingleParameterSmearFunction = /// vector and associated covariance matrix. template struct BoundParametersSmearer { - using Scalar = Acts::ActsScalar; using ParametersVector = Acts::ActsVector; using CovarianceMatrix = Acts::ActsSquareMatrix; using Result = Acts::Result>; @@ -116,7 +115,6 @@ struct BoundParametersSmearer { /// individually is not recommended template struct FreeParametersSmearer { - using Scalar = Acts::ActsScalar; using ParametersVector = Acts::ActsVector; using CovarianceMatrix = Acts::ActsSquareMatrix; using Result = Acts::Result>; diff --git a/Fatras/include/ActsFatras/EventData/Hit.hpp b/Fatras/include/ActsFatras/EventData/Hit.hpp index d5eb25662f8..b3838299ca6 100644 --- a/Fatras/include/ActsFatras/EventData/Hit.hpp +++ b/Fatras/include/ActsFatras/EventData/Hit.hpp @@ -26,10 +26,6 @@ namespace ActsFatras { /// thus stored as two separate four-vectors. class Hit { public: - using Scalar = Acts::ActsScalar; - using Vector3 = Acts::ActsVector<3>; - using Vector4 = Acts::ActsVector<4>; - /// Construct default hit with (mostly) invalid information. Hit() = default; /// Construct from four-position and four-momenta. @@ -45,8 +41,8 @@ class Hit { /// users responsibility to ensure that the position correspond to a /// position on the given surface. Hit(Acts::GeometryIdentifier geometryId, Barcode particleId, - const Vector4& pos4, const Vector4& before4, const Vector4& after4, - std::int32_t index_ = -1) + const Acts::Vector4& pos4, const Acts::Vector4& before4, + const Acts::Vector4& after4, std::int32_t index_ = -1) : m_geometryId(geometryId), m_particleId(particleId), m_index(index_), @@ -68,26 +64,26 @@ class Hit { constexpr std::int32_t index() const { return m_index; } /// Space-time position four-vector. - const Vector4& fourPosition() const { return m_pos4; } + const Acts::Vector4& fourPosition() const { return m_pos4; } /// Three-position, i.e. spatial coordinates without the time. auto position() const { return m_pos4.segment<3>(Acts::ePos0); } /// Time coordinate. - Scalar time() const { return m_pos4[Acts::eTime]; } + double time() const { return m_pos4[Acts::eTime]; } /// Particle four-momentum before the hit. - const Vector4& momentum4Before() const { return m_before4; } + const Acts::Vector4& momentum4Before() const { return m_before4; } /// Particle four-momentum after the hit. - const Vector4& momentum4After() const { return m_after4; } + const Acts::Vector4& momentum4After() const { return m_after4; } /// Normalized particle direction vector before the hit. - Vector3 directionBefore() const { + Acts::Vector3 directionBefore() const { return m_before4.segment<3>(Acts::eMom0).normalized(); } /// Normalized particle direction vector the hit. - Vector3 directionAfter() const { + Acts::Vector3 directionAfter() const { return m_after4.segment<3>(Acts::eMom0).normalized(); } /// Average normalized particle direction vector through the surface. - Vector3 direction() const { + Acts::Vector3 direction() const { auto dir0 = m_before4.segment<3>(Acts::eMom0).normalized(); auto dir1 = m_after4.segment<3>(Acts::eMom0).normalized(); return ((dir0 + dir1) / 2.).segment<3>(Acts::eMom0).normalized(); @@ -96,7 +92,7 @@ class Hit { /// /// @retval positive if the particle lost energy when it passed the surface /// @retval negative if magic was involved - Scalar depositedEnergy() const { + double depositedEnergy() const { return m_before4[Acts::eEnergy] - m_after4[Acts::eEnergy]; } @@ -108,11 +104,11 @@ class Hit { /// Index of the hit along the particle trajectory. std::int32_t m_index = -1; /// Global space-time position four-vector. - Vector4 m_pos4 = Vector4::Zero(); + Acts::Vector4 m_pos4 = Acts::Vector4::Zero(); /// Global particle energy-momentum four-vector before the hit. - Vector4 m_before4 = Vector4::Zero(); + Acts::Vector4 m_before4 = Acts::Vector4::Zero(); /// Global particle energy-momentum four-vector after the hit. - Vector4 m_after4 = Vector4::Zero(); + Acts::Vector4 m_after4 = Acts::Vector4::Zero(); }; } // namespace ActsFatras diff --git a/Fatras/include/ActsFatras/EventData/Particle.hpp b/Fatras/include/ActsFatras/EventData/Particle.hpp index 5b6eb2f7a61..fbf9244fcea 100644 --- a/Fatras/include/ActsFatras/EventData/Particle.hpp +++ b/Fatras/include/ActsFatras/EventData/Particle.hpp @@ -32,10 +32,6 @@ namespace ActsFatras { /// Also stores some simulation-specific properties. class Particle { public: - using Scalar = Acts::ActsScalar; - using Vector3 = Acts::ActsVector<3>; - using Vector4 = Acts::ActsVector<4>; - /// Construct a default particle with invalid identity. Particle() = default; /// Construct a particle at rest with explicit mass and charge. @@ -47,8 +43,8 @@ class Particle { /// /// @warning It is the users responsibility that charge and mass match /// the PDG particle number. - Particle(Barcode particleId, Acts::PdgParticle pdg, Scalar charge, - Scalar mass) + Particle(Barcode particleId, Acts::PdgParticle pdg, double charge, + double mass) : m_particleId(particleId), m_pdg(pdg), m_charge(charge), m_mass(mass) {} /// Construct a particle at rest from a PDG particle number. /// @@ -84,12 +80,12 @@ class Particle { return *this; } /// Set the charge. - Particle setCharge(Scalar charge) { + Particle setCharge(double charge) { m_charge = charge; return *this; } /// Set the mass. - Particle setMass(Scalar mass) { + Particle setMass(double mass) { m_mass = mass; return *this; } @@ -99,18 +95,18 @@ class Particle { return *this; } /// Set the space-time position four-vector. - Particle &setPosition4(const Vector4 &pos4) { + Particle &setPosition4(const Acts::Vector4 &pos4) { m_position4 = pos4; return *this; } /// Set the space-time position four-vector from three-position and time. - Particle &setPosition4(const Vector3 &position, Scalar time) { + Particle &setPosition4(const Acts::Vector3 &position, double time) { m_position4.segment<3>(Acts::ePos0) = position; m_position4[Acts::eTime] = time; return *this; } /// Set the space-time position four-vector from scalar components. - Particle &setPosition4(Scalar x, Scalar y, Scalar z, Scalar time) { + Particle &setPosition4(double x, double y, double z, double time) { m_position4[Acts::ePos0] = x; m_position4[Acts::ePos1] = y; m_position4[Acts::ePos2] = z; @@ -118,13 +114,13 @@ class Particle { return *this; } /// Set the direction three-vector - Particle &setDirection(const Vector3 &direction) { + Particle &setDirection(const Acts::Vector3 &direction) { m_direction = direction; m_direction.normalize(); return *this; } /// Set the direction three-vector from scalar components. - Particle &setDirection(Scalar dx, Scalar dy, Scalar dz) { + Particle &setDirection(double dx, double dy, double dz) { m_direction[Acts::ePos0] = dx; m_direction[Acts::ePos1] = dy; m_direction[Acts::ePos2] = dz; @@ -132,7 +128,7 @@ class Particle { return *this; } /// Set the absolute momentum. - Particle &setAbsoluteMomentum(Scalar absMomentum) { + Particle &setAbsoluteMomentum(double absMomentum) { m_absMomentum = absMomentum; return *this; } @@ -142,10 +138,10 @@ class Particle { /// Energy loss corresponds to a negative change. If the updated energy /// would result in an unphysical value, the particle is put to rest, i.e. /// its absolute momentum is set to zero. - Particle &correctEnergy(Scalar delta) { + Particle &correctEnergy(double delta) { const auto newEnergy = std::hypot(m_mass, m_absMomentum) + delta; if (newEnergy <= m_mass) { - m_absMomentum = Scalar{0}; + m_absMomentum = 0.; } else { m_absMomentum = std::sqrt(newEnergy * newEnergy - m_mass * m_mass); } @@ -163,30 +159,30 @@ class Particle { return Acts::makeAbsolutePdgParticle(pdg()); } /// Particle charge. - Scalar charge() const { return m_charge; } + double charge() const { return m_charge; } /// Particle absolute charge. - Scalar absoluteCharge() const { return std::abs(m_charge); } + double absoluteCharge() const { return std::abs(m_charge); } /// Particle mass. - Scalar mass() const { return m_mass; } + double mass() const { return m_mass; } /// Particle hypothesis. Acts::ParticleHypothesis hypothesis() const { return Acts::ParticleHypothesis(absolutePdg(), mass(), absoluteCharge()); } /// Particl qOverP. - Scalar qOverP() const { + double qOverP() const { return hypothesis().qOverP(absoluteMomentum(), charge()); } /// Space-time position four-vector. - const Vector4 &fourPosition() const { return m_position4; } + const Acts::Vector4 &fourPosition() const { return m_position4; } /// Three-position, i.e. spatial coordinates without the time. auto position() const { return m_position4.segment<3>(Acts::ePos0); } /// Time coordinate. - Scalar time() const { return m_position4[Acts::eTime]; } + double time() const { return m_position4[Acts::eTime]; } /// Energy-momentum four-vector. - Vector4 fourMomentum() const { - Vector4 mom4; + Acts::Vector4 fourMomentum() const { + Acts::Vector4 mom4; // stored direction is always normalized mom4[Acts::eMom0] = m_absMomentum * m_direction[Acts::ePos0]; mom4[Acts::eMom1] = m_absMomentum * m_direction[Acts::ePos1]; @@ -195,24 +191,24 @@ class Particle { return mom4; } /// Unit three-direction, i.e. the normalized momentum three-vector. - const Vector3 &direction() const { return m_direction; } + const Acts::Vector3 &direction() const { return m_direction; } /// Polar angle. - Scalar theta() const { return Acts::VectorHelpers::theta(direction()); } + double theta() const { return Acts::VectorHelpers::theta(direction()); } /// Azimuthal angle. - Scalar phi() const { return Acts::VectorHelpers::phi(direction()); } + double phi() const { return Acts::VectorHelpers::phi(direction()); } /// Absolute momentum in the x-y plane. - Scalar transverseMomentum() const { + double transverseMomentum() const { return m_absMomentum * m_direction.segment<2>(Acts::eMom0).norm(); } /// Absolute momentum. - Scalar absoluteMomentum() const { return m_absMomentum; } + double absoluteMomentum() const { return m_absMomentum; } /// Absolute momentum. - Vector3 momentum() const { return absoluteMomentum() * direction(); } + Acts::Vector3 momentum() const { return absoluteMomentum() * direction(); } /// Total energy, i.e. norm of the four-momentum. - Scalar energy() const { return std::hypot(m_mass, m_absMomentum); } + double energy() const { return std::hypot(m_mass, m_absMomentum); } /// Check if the particle is alive, i.e. is not at rest. - bool isAlive() const { return Scalar{0} < m_absMomentum; } + bool isAlive() const { return 0. < m_absMomentum; } /// Check if this is a secondary particle. bool isSecondary() const { @@ -225,26 +221,26 @@ class Particle { /// Set the proper time in the particle rest frame. /// /// @param properTime passed proper time in the rest frame - Particle &setProperTime(Scalar properTime) { + Particle &setProperTime(double properTime) { m_properTime = properTime; return *this; } /// Proper time in the particle rest frame. - Scalar properTime() const { return m_properTime; } + double properTime() const { return m_properTime; } /// Set the accumulated material measured in radiation/interaction lengths. /// /// @param pathInX0 accumulated material measured in radiation lengths /// @param pathInL0 accumulated material measured in interaction lengths - Particle &setMaterialPassed(Scalar pathInX0, Scalar pathInL0) { + Particle &setMaterialPassed(double pathInX0, double pathInL0) { m_pathInX0 = pathInX0; m_pathInL0 = pathInL0; return *this; } /// Accumulated path within material measured in radiation lengths. - Scalar pathInX0() const { return m_pathInX0; } + double pathInX0() const { return m_pathInX0; } /// Accumulated path within material measured in interaction lengths. - Scalar pathInL0() const { return m_pathInL0; } + double pathInL0() const { return m_pathInL0; } /// Set the reference surface. /// @@ -314,17 +310,17 @@ class Particle { /// PDG particle number. Acts::PdgParticle m_pdg = Acts::PdgParticle::eInvalid; // Particle charge and mass. - Scalar m_charge = Scalar{0}; - Scalar m_mass = Scalar{0}; + double m_charge = 0.; + double m_mass = 0.; // kinematics, i.e. things that change over the particle lifetime. - Vector3 m_direction = Vector3::UnitZ(); - Scalar m_absMomentum = Scalar{0}; - Vector4 m_position4 = Vector4::Zero(); + Acts::Vector3 m_direction = Acts::Vector3::UnitZ(); + double m_absMomentum = 0.; + Acts::Vector4 m_position4 = Acts::Vector4::Zero(); /// proper time in the particle rest frame - Scalar m_properTime = Scalar{0}; + double m_properTime = 0.; // accumulated material - Scalar m_pathInX0 = Scalar{0}; - Scalar m_pathInL0 = Scalar{0}; + double m_pathInX0 = 0.; + double m_pathInL0 = 0.; /// number of hits std::uint32_t m_numberOfHits = 0; /// reference surface diff --git a/Fatras/include/ActsFatras/Kernel/InteractionList.hpp b/Fatras/include/ActsFatras/Kernel/InteractionList.hpp index eb6816c490a..b8faaf7f0ad 100644 --- a/Fatras/include/ActsFatras/Kernel/InteractionList.hpp +++ b/Fatras/include/ActsFatras/Kernel/InteractionList.hpp @@ -83,9 +83,7 @@ template concept PointLikeProcessConcept = requires( const process_t& p, std::uniform_int_distribution& rng, const Particle& prt) { - { - p.generatePathLimits(rng, prt) - } -> std::same_as>; + { p.generatePathLimits(rng, prt) } -> std::same_as>; }; template @@ -177,10 +175,8 @@ class InteractionList { public: /// Point-like interaction selection. struct Selection { - Particle::Scalar x0Limit = - std::numeric_limits::infinity(); - Particle::Scalar l0Limit = - std::numeric_limits::infinity(); + double x0Limit = std::numeric_limits::infinity(); + double l0Limit = std::numeric_limits::infinity(); std::size_t x0Process = std::numeric_limits::max(); std::size_t l0Process = std::numeric_limits::max(); }; diff --git a/Fatras/include/ActsFatras/Kernel/Simulation.hpp b/Fatras/include/ActsFatras/Kernel/Simulation.hpp index b6975c34172..07c03bb5d40 100644 --- a/Fatras/include/ActsFatras/Kernel/Simulation.hpp +++ b/Fatras/include/ActsFatras/Kernel/Simulation.hpp @@ -224,7 +224,7 @@ struct Simulation { // only need to switch between charged/neutral. SingleParticleSimulationResult result = SingleParticleSimulationResult::success({}); - if (initialParticle.charge() != Particle::Scalar{0}) { + if (initialParticle.charge() != 0.) { result = charged.simulate(geoCtx, magCtx, generator, initialParticle); } else { result = neutral.simulate(geoCtx, magCtx, generator, initialParticle); @@ -267,7 +267,7 @@ struct Simulation { private: /// Select if the particle should be simulated at all. bool selectParticle(const Particle &particle) const { - if (particle.charge() != Particle::Scalar{0}) { + if (particle.charge() != 0.) { return selectCharged(particle); } else { return selectNeutral(particle); diff --git a/Fatras/include/ActsFatras/Kernel/SimulationResult.hpp b/Fatras/include/ActsFatras/Kernel/SimulationResult.hpp index 2750e01b616..fa6cf211673 100644 --- a/Fatras/include/ActsFatras/Kernel/SimulationResult.hpp +++ b/Fatras/include/ActsFatras/Kernel/SimulationResult.hpp @@ -38,11 +38,10 @@ struct SimulationResult { // Whether the particle is still alive and the simulation should continue bool isAlive = true; // Proper time limit before decay. - Particle::Scalar properTimeLimit = - std::numeric_limits::quiet_NaN(); + double properTimeLimit = std::numeric_limits::quiet_NaN(); // Accumulated radiation/interaction length limit before next interaction. - Particle::Scalar x0Limit = std::numeric_limits::quiet_NaN(); - Particle::Scalar l0Limit = std::numeric_limits::quiet_NaN(); + double x0Limit = std::numeric_limits::quiet_NaN(); + double l0Limit = std::numeric_limits::quiet_NaN(); // Process selection for the next interaction. std::size_t x0Process = std::numeric_limits::max(); std::size_t l0Process = std::numeric_limits::max(); diff --git a/Fatras/include/ActsFatras/Kernel/detail/SimulationActor.hpp b/Fatras/include/ActsFatras/Kernel/detail/SimulationActor.hpp index acbaaaa713d..bee570485b0 100644 --- a/Fatras/include/ActsFatras/Kernel/detail/SimulationActor.hpp +++ b/Fatras/include/ActsFatras/Kernel/detail/SimulationActor.hpp @@ -53,7 +53,7 @@ struct SimulationActor { Particle initialParticle; /// Relative tolerance of the particles proper time limit - Particle::Scalar properTimeRelativeTolerance = 1e-3; + double properTimeRelativeTolerance = 1e-3; /// Simulate the interaction with a single surface. /// @@ -180,7 +180,7 @@ struct SimulationActor { result.hits.emplace_back( surface.geometryId(), before.particleId(), // the interaction could potentially modify the particle position - Hit::Scalar{0.5} * (before.fourPosition() + after.fourPosition()), + 0.5 * (before.fourPosition() + after.fourPosition()), before.fourMomentum(), after.fourMomentum(), result.hits.size()); after.setNumberOfHits(result.hits.size()); diff --git a/Fatras/include/ActsFatras/Physics/Decay/NoDecay.hpp b/Fatras/include/ActsFatras/Physics/Decay/NoDecay.hpp index 17aefd7341b..11889f3af06 100644 --- a/Fatras/include/ActsFatras/Physics/Decay/NoDecay.hpp +++ b/Fatras/include/ActsFatras/Physics/Decay/NoDecay.hpp @@ -21,9 +21,9 @@ struct NoDecay { /// /// @returns Always returns infinity as limit. template - constexpr Particle::Scalar generateProperTimeLimit( + constexpr double generateProperTimeLimit( generator_t& /* rng */, const Particle& /* particle */) const { - return std::numeric_limits::infinity(); + return std::numeric_limits::infinity(); } /// Decay the particle without generating any descendant particles. template diff --git a/Fatras/include/ActsFatras/Physics/ElectroMagnetic/BetheHeitler.hpp b/Fatras/include/ActsFatras/Physics/ElectroMagnetic/BetheHeitler.hpp index d0529837b7f..6cfbce087c9 100644 --- a/Fatras/include/ActsFatras/Physics/ElectroMagnetic/BetheHeitler.hpp +++ b/Fatras/include/ActsFatras/Physics/ElectroMagnetic/BetheHeitler.hpp @@ -25,9 +25,6 @@ namespace ActsFatras { /// "A Gaussian-mixture approximation of the Bethe–Heitler model of electron /// energy loss by bremsstrahlung" R. Frühwirth struct BetheHeitler { - using Scalar = Particle::Scalar; - using Vector3 = Particle::Vector3; - /// A scaling factor to double scaleFactor = 1.; @@ -42,9 +39,9 @@ struct BetheHeitler { /// @param [in] rndTheta1 Random number for the polar angle /// @param [in] rndTheta2 Random number for the polar angle /// @param [in] rndTheta3 Random number for the polar angle - Particle bremPhoton(const Particle &particle, Scalar gammaE, Scalar rndPsi, - Scalar rndTheta1, Scalar rndTheta2, - Scalar rndTheta3) const; + Particle bremPhoton(const Particle &particle, double gammaE, double rndPsi, + double rndTheta1, double rndTheta2, + double rndTheta3) const; /// Simulate energy loss and update the particle parameters. /// @@ -67,7 +64,7 @@ struct BetheHeitler { const auto sampledEnergyLoss = std::abs(scaleFactor * particle.energy() * (z - 1.)); - std::uniform_real_distribution uDist(0., 1.); + std::uniform_real_distribution uDist(0., 1.); // Build the produced photon Particle photon = bremPhoton(particle, sampledEnergyLoss, uDist(generator), diff --git a/Fatras/include/ActsFatras/Physics/ElectroMagnetic/PhotonConversion.hpp b/Fatras/include/ActsFatras/Physics/ElectroMagnetic/PhotonConversion.hpp index d54b17e7407..af45481258e 100644 --- a/Fatras/include/ActsFatras/Physics/ElectroMagnetic/PhotonConversion.hpp +++ b/Fatras/include/ActsFatras/Physics/ElectroMagnetic/PhotonConversion.hpp @@ -34,12 +34,10 @@ namespace ActsFatras { /// interaction itself. class PhotonConversion { public: - using Scalar = ActsFatras::Particle::Scalar; - /// Scaling factor of children energy - Scalar childEnergyScaleFactor = 2.; + double childEnergyScaleFactor = 2.; /// Scaling factor for photon conversion probability - Scalar conversionProbScaleFactor = 0.98; + double conversionProbScaleFactor = 0.98; /// Method for evaluating the distance after which the photon /// conversion will occur. @@ -50,7 +48,7 @@ class PhotonConversion { /// /// @return valid X0 limit and no limit on L0 template - std::pair generatePathLimits(generator_t& generator, + std::pair generatePathLimits(generator_t& generator, const Particle& particle) const; /// This method evaluates the final state due to the photon conversion. @@ -74,8 +72,8 @@ class PhotonConversion { /// /// @return Array containing the produced leptons std::array generateChildren( - const Particle& photon, Scalar childEnergy, - const Particle::Vector3& childDirection) const; + const Particle& photon, double childEnergy, + const Acts::Vector3& childDirection) const; /// Generate the energy fraction of the first child particle. /// @@ -85,8 +83,8 @@ class PhotonConversion { /// /// @return The energy of the child particle template - Scalar generateFirstChildEnergyFraction(generator_t& generator, - Scalar gammaMom) const; + double generateFirstChildEnergyFraction(generator_t& generator, + double gammaMom) const; /// Generate the direction of the child particles. /// @@ -96,27 +94,27 @@ class PhotonConversion { /// /// @return The direction vector of the child particle template - Particle::Vector3 generateChildDirection(generator_t& generator, - const Particle& particle) const; + Acts::Vector3 generateChildDirection(generator_t& generator, + const Particle& particle) const; /// Helper methods for momentum evaluation /// @note These methods are taken from the Geant4 class /// G4PairProductionRelModel - Scalar screenFunction1(Scalar delta) const; - Scalar screenFunction2(Scalar delta) const; + double screenFunction1(double delta) const; + double screenFunction2(double delta) const; /// Electron mass. This is an static constant and not a member variable so the /// struct has no internal state. Otherwise, the interaction list breaks. - static const Scalar kElectronMass; + static const double kElectronMass; }; -inline Particle::Scalar PhotonConversion::screenFunction1(Scalar delta) const { +inline double PhotonConversion::screenFunction1(double delta) const { // Compute the value of the screening function 3*PHI1(delta) - PHI2(delta) return (delta > 1.4) ? 42.038 - 8.29 * std::log(delta + 0.958) : 42.184 - delta * (7.444 - 1.623 * delta); } -inline Particle::Scalar PhotonConversion::screenFunction2(Scalar delta) const { +inline double PhotonConversion::screenFunction2(double delta) const { // Compute the value of the screening function 1.5*PHI1(delta) // +0.5*PHI2(delta) return (delta > 1.4) ? 42.038 - 8.29 * std::log(delta + 0.958) @@ -124,16 +122,15 @@ inline Particle::Scalar PhotonConversion::screenFunction2(Scalar delta) const { } template -std::pair -PhotonConversion::generatePathLimits(generator_t& generator, - const Particle& particle) const { +std::pair PhotonConversion::generatePathLimits( + generator_t& generator, const Particle& particle) const { /// This method is based upon the Athena class PhotonConversionTool // Fast exit if not a photon or the energy is too low if (particle.pdg() != Acts::PdgParticle::eGamma || particle.absoluteMomentum() < (2 * kElectronMass)) { - return std::make_pair(std::numeric_limits::infinity(), - std::numeric_limits::infinity()); + return std::make_pair(std::numeric_limits::infinity(), + std::numeric_limits::infinity()); } // Use for the moment only Al data - Yung Tsai - Rev.Mod.Particle Physics Vol. @@ -149,73 +146,73 @@ PhotonConversion::generatePathLimits(generator_t& generator, // 1 p0 -7.01612e-03 8.43478e-01 1.62766e-04 1.11914e-05 // 2 p1 7.69040e-02 1.00059e+00 8.90718e-05 -8.41167e-07 // 3 p2 -6.07682e-01 5.13256e+00 6.07228e-04 -9.44448e-07 - constexpr Scalar p0 = -7.01612e-03; - constexpr Scalar p1 = 7.69040e-02; - constexpr Scalar p2 = -6.07682e-01; + constexpr double p0 = -7.01612e-03; + constexpr double p1 = 7.69040e-02; + constexpr double p2 = -6.07682e-01; // Calculate xi - const Scalar xi = p0 + p1 * std::pow(particle.absoluteMomentum(), p2); + const double xi = p0 + p1 * std::pow(particle.absoluteMomentum(), p2); - std::uniform_real_distribution uniformDistribution{0., 1.}; + std::uniform_real_distribution uniformDistribution{0., 1.}; // This is a transformation of eq. 3.75 return std::make_pair(-9. / 7. * std::log(conversionProbScaleFactor * (1 - uniformDistribution(generator))) / (1. - xi), - std::numeric_limits::infinity()); + std::numeric_limits::infinity()); } template -Particle::Scalar PhotonConversion::generateFirstChildEnergyFraction( - generator_t& generator, Scalar gammaMom) const { +double PhotonConversion::generateFirstChildEnergyFraction( + generator_t& generator, double gammaMom) const { /// This method is based upon the Geant4 class G4PairProductionRelModel /// @note This method is from the Geant4 class G4Element // // Compute Coulomb correction factor (Phys Rev. D50 3-1 (1994) page 1254) - constexpr Scalar k1 = 0.0083; - constexpr Scalar k2 = 0.20206; - constexpr Scalar k3 = 0.0020; // This term is missing in Athena - constexpr Scalar k4 = 0.0369; - constexpr Scalar alphaEM = 1. / 137.; - constexpr Scalar m_Z = 13.; // Aluminium - constexpr Scalar az2 = (alphaEM * m_Z) * (alphaEM * m_Z); - constexpr Scalar az4 = az2 * az2; - constexpr Scalar coulombFactor = + constexpr double k1 = 0.0083; + constexpr double k2 = 0.20206; + constexpr double k3 = 0.0020; // This term is missing in Athena + constexpr double k4 = 0.0369; + constexpr double alphaEM = 1. / 137.; + constexpr double m_Z = 13.; // Aluminium + constexpr double az2 = (alphaEM * m_Z) * (alphaEM * m_Z); + constexpr double az4 = az2 * az2; + constexpr double coulombFactor = (k1 * az4 + k2 + 1. / (1. + az2)) * az2 - (k3 * az4 + k4) * az4; - const Scalar logZ13 = std::log(m_Z) * 1. / 3.; - const Scalar FZ = 8. * (logZ13 + coulombFactor); - const Scalar deltaMax = exp((42.038 - FZ) * 0.1206) - 0.958; + const double logZ13 = std::log(m_Z) * 1. / 3.; + const double FZ = 8. * (logZ13 + coulombFactor); + const double deltaMax = std::exp((42.038 - FZ) * 0.1206) - 0.958; - const Scalar deltaPreFactor = 136. / std::pow(m_Z, 1. / 3.); - const Scalar eps0 = kElectronMass / gammaMom; - const Scalar deltaFactor = deltaPreFactor * eps0; - const Scalar deltaMin = 4. * deltaFactor; + const double deltaPreFactor = 136. / std::pow(m_Z, 1. / 3.); + const double eps0 = kElectronMass / gammaMom; + const double deltaFactor = deltaPreFactor * eps0; + const double deltaMin = 4. * deltaFactor; // Compute the limits of eps - const Scalar epsMin = + const double epsMin = std::max(eps0, 0.5 - 0.5 * std::sqrt(1. - deltaMin / deltaMax)); - const Scalar epsRange = 0.5 - epsMin; + const double epsRange = 0.5 - epsMin; // Sample the energy rate (eps) of the created electron (or positron) - const Scalar F10 = screenFunction1(deltaMin) - FZ; - const Scalar F20 = screenFunction2(deltaMin) - FZ; - const Scalar NormF1 = F10 * epsRange * epsRange; - const Scalar NormF2 = 1.5 * F20; + const double F10 = screenFunction1(deltaMin) - FZ; + const double F20 = screenFunction2(deltaMin) - FZ; + const double NormF1 = F10 * epsRange * epsRange; + const double NormF2 = 1.5 * F20; // We will need 3 uniform random number for each trial of sampling - Scalar greject = 0.; - Scalar eps = 0.; - std::uniform_real_distribution rndmEngine; + double greject = 0.; + double eps = 0.; + std::uniform_real_distribution rndmEngine; do { if (NormF1 > rndmEngine(generator) * (NormF1 + NormF2)) { eps = 0.5 - epsRange * std::pow(rndmEngine(generator), 1. / 3.); - const Scalar delta = deltaFactor / (eps * (1. - eps)); + const double delta = deltaFactor / (eps * (1. - eps)); greject = (screenFunction1(delta) - FZ) / F10; } else { eps = epsMin + epsRange * rndmEngine(generator); - const Scalar delta = deltaFactor / (eps * (1. - eps)); + const double delta = deltaFactor / (eps * (1. - eps)); greject = (screenFunction2(delta) - FZ) / F20; } } while (greject < rndmEngine(generator)); @@ -224,16 +221,16 @@ Particle::Scalar PhotonConversion::generateFirstChildEnergyFraction( } template -Particle::Vector3 PhotonConversion::generateChildDirection( +Acts::Vector3 PhotonConversion::generateChildDirection( generator_t& generator, const Particle& particle) const { /// This method is based upon the Athena class PhotonConversionTool // Following the Geant4 approximation from L. Urban // the azimutal angle - Scalar theta = kElectronMass / particle.energy(); + double theta = kElectronMass / particle.energy(); - std::uniform_real_distribution uniformDistribution{0., 1.}; - const Scalar u = -std::log(uniformDistribution(generator) * + std::uniform_real_distribution uniformDistribution{0., 1.}; + const double u = -std::log(uniformDistribution(generator) * uniformDistribution(generator)) * 1.6; @@ -257,20 +254,20 @@ Particle::Vector3 PhotonConversion::generateChildDirection( } inline std::array PhotonConversion::generateChildren( - const Particle& photon, Scalar childEnergy, - const Particle::Vector3& childDirection) const { + const Particle& photon, double childEnergy, + const Acts::Vector3& childDirection) const { using namespace Acts::UnitLiterals; // Calculate the child momentum - const Scalar massChild = kElectronMass; - const Scalar momentum1 = + const double massChild = kElectronMass; + const double momentum1 = sqrt(childEnergy * childEnergy - massChild * massChild); // Use energy-momentum conservation for the other child - const Particle::Vector3 vtmp = + const Acts::Vector3 vtmp = photon.fourMomentum().template segment<3>(Acts::eMom0) - momentum1 * childDirection; - const Scalar momentum2 = vtmp.norm(); + const double momentum2 = vtmp.norm(); // The daughter particles are created with the explicit electron mass used in // the calculations for consistency. Using the full Particle constructor with @@ -304,17 +301,16 @@ bool PhotonConversion::run(generator_t& generator, Particle& particle, } // Fast exit if momentum is too low - const Scalar p = particle.absoluteMomentum(); + const double p = particle.absoluteMomentum(); if (p < (2 * kElectronMass)) { return false; } // Get one child energy - const Scalar childEnergy = p * generateFirstChildEnergyFraction(generator, p); + const double childEnergy = p * generateFirstChildEnergyFraction(generator, p); // Now get the deflection - const Particle::Vector3 childDir = - generateChildDirection(generator, particle); + const Acts::Vector3 childDir = generateChildDirection(generator, particle); // Produce the final state const std::array finalState = diff --git a/Fatras/include/ActsFatras/Physics/NuclearInteraction/NuclearInteraction.hpp b/Fatras/include/ActsFatras/Physics/NuclearInteraction/NuclearInteraction.hpp index 89072e78536..d372cf8ffc9 100644 --- a/Fatras/include/ActsFatras/Physics/NuclearInteraction/NuclearInteraction.hpp +++ b/Fatras/include/ActsFatras/Physics/NuclearInteraction/NuclearInteraction.hpp @@ -38,7 +38,6 @@ namespace ActsFatras { /// interaction. Either the initial particle survives (soft) or it gets /// destroyed (hard) by this process. struct NuclearInteraction { - using Scalar = Particle::Scalar; /// The storage of the parameterisation detail::MultiParticleNuclearInteractionParametrisation multiParticleParameterisation; @@ -55,12 +54,12 @@ struct NuclearInteraction { /// /// @return valid X0 limit and no limit on L0 template - std::pair generatePathLimits(generator_t& generator, + std::pair generatePathLimits(generator_t& generator, const Particle& particle) const { // Fast exit: No parameterisation provided if (multiParticleParameterisation.empty()) { - return std::make_pair(std::numeric_limits::infinity(), - std::numeric_limits::infinity()); + return std::make_pair(std::numeric_limits::infinity(), + std::numeric_limits::infinity()); } // Find the parametrisation that corresponds to the particle type for (const auto& particleParametrisation : multiParticleParameterisation) { @@ -79,14 +78,14 @@ struct NuclearInteraction { const auto& distribution = parametrisation.nuclearInteractionProbability; auto limits = - std::make_pair(std::numeric_limits::infinity(), + std::make_pair(std::numeric_limits::infinity(), sampleContinuousValues( uniformDistribution(generator), distribution)); return limits; } } - return std::make_pair(std::numeric_limits::infinity(), - std::numeric_limits::infinity()); + return std::make_pair(std::numeric_limits::infinity(), + std::numeric_limits::infinity()); } /// This method performs a nuclear interaction. @@ -292,10 +291,8 @@ struct NuclearInteraction { /// /// @return Azimuthal and polar angle of the second particle in the global /// coordinate system - std::pair - globalAngle(ActsFatras::Particle::Scalar phi1, - ActsFatras::Particle::Scalar theta1, float phi2, - float theta2) const; + std::pair globalAngle(double phi1, double theta1, float phi2, + float theta2) const; /// Converter from sampled numbers to a vector of particles /// @@ -337,7 +334,7 @@ struct NuclearInteraction { /// neighbouring bins should be performed instead of a bin lookup /// /// @return The sampled value - Scalar sampleContinuousValues( + double sampleContinuousValues( double rnd, const detail::NuclearInteractionParameters::CumulativeDistribution& distribution, @@ -416,8 +413,8 @@ Acts::ActsDynamicVector NuclearInteraction::sampleInvariantMasses( // Sample in the eigenspace for (unsigned int i = 0; i < size; i++) { float variance = parametrisation.eigenvaluesInvariantMass[i]; - std::normal_distribution dist{ - parametrisation.meanInvariantMass[i], std::sqrt(variance)}; + std::normal_distribution dist{parametrisation.meanInvariantMass[i], + std::sqrt(variance)}; parameters[i] = dist(generator); } // Transform to multivariate normal distribution @@ -446,8 +443,8 @@ Acts::ActsDynamicVector NuclearInteraction::sampleMomenta( // Sample in the eigenspace for (unsigned int i = 0; i < size; i++) { float variance = parametrisation.eigenvaluesMomentum[i]; - std::normal_distribution dist{ - parametrisation.meanMomentum[i], std::sqrt(variance)}; + std::normal_distribution dist{parametrisation.meanMomentum[i], + std::sqrt(variance)}; parameters[i] = dist(generator); } diff --git a/Fatras/include/ActsFatras/Selectors/ParticleSelectors.hpp b/Fatras/include/ActsFatras/Selectors/ParticleSelectors.hpp index 4deb110969e..d784048abbd 100644 --- a/Fatras/include/ActsFatras/Selectors/ParticleSelectors.hpp +++ b/Fatras/include/ActsFatras/Selectors/ParticleSelectors.hpp @@ -21,28 +21,28 @@ struct EveryParticle { /// Select neutral particles. struct NeutralSelector { bool operator()(const Particle &particle) const { - return (particle.charge() == Particle::Scalar{0}); + return (particle.charge() == 0.); } }; /// Select all charged particles. struct ChargedSelector { bool operator()(const Particle &particle) const { - return (particle.charge() != Particle::Scalar{0}); + return (particle.charge() != 0.); } }; /// Select positively charged particles. struct PositiveSelector { bool operator()(const Particle &particle) const { - return (Particle::Scalar{0} < particle.charge()); + return (0. < particle.charge()); } }; /// Select negatively charged particles. struct NegativeSelector { bool operator()(const Particle &particle) const { - return (particle.charge() < Particle::Scalar{0}); + return (particle.charge() < 0.); } }; diff --git a/Fatras/src/Physics/BetheHeitler.cpp b/Fatras/src/Physics/BetheHeitler.cpp index af8cbd2711f..bb635ecb934 100644 --- a/Fatras/src/Physics/BetheHeitler.cpp +++ b/Fatras/src/Physics/BetheHeitler.cpp @@ -20,8 +20,8 @@ #include ActsFatras::Particle ActsFatras::BetheHeitler::bremPhoton( - const Particle &particle, Scalar gammaE, Scalar rndPsi, Scalar rndTheta1, - Scalar rndTheta2, Scalar rndTheta3) const { + const Particle &particle, double gammaE, double rndPsi, double rndTheta1, + double rndTheta2, double rndTheta3) const { // ------------------------------------------------------ // simple approach // (a) simulate theta uniform within the opening angle of the relativistic @@ -31,10 +31,10 @@ ActsFatras::Particle ActsFatras::BetheHeitler::bremPhoton( // later // the azimutal angle - Scalar psi = 2. * std::numbers::pi * rndPsi; + double psi = 2. * std::numbers::pi * rndPsi; // the start of the equation - Scalar theta = 0.; + double theta = 0.; if (uniformHertzDipoleAngle) { // the simplest simulation theta = particle.mass() / particle.energy() * rndTheta1; @@ -42,13 +42,13 @@ ActsFatras::Particle ActsFatras::BetheHeitler::bremPhoton( // -----> theta = particle.mass() / particle.energy(); // follow - constexpr Scalar a = 0.625; // 5/8 - Scalar u = -log(rndTheta2 * rndTheta3) / a; + constexpr double a = 0.625; // 5/8 + double u = -log(rndTheta2 * rndTheta3) / a; theta *= (rndTheta1 < 0.25) ? u : u / 3.; // 9./(9.+27) = 0.25 } - Vector3 particleDirection = particle.direction(); - Vector3 photonDirection = particleDirection; + Acts::Vector3 particleDirection = particle.direction(); + Acts::Vector3 photonDirection = particleDirection; // construct the combined rotation to the scattered direction Acts::RotationMatrix3 rotation( diff --git a/Fatras/src/Physics/NuclearInteraction/NuclearInteraction.cpp b/Fatras/src/Physics/NuclearInteraction/NuclearInteraction.cpp index 1515fc3c626..84ab93921fe 100644 --- a/Fatras/src/Physics/NuclearInteraction/NuclearInteraction.cpp +++ b/Fatras/src/Physics/NuclearInteraction/NuclearInteraction.cpp @@ -67,14 +67,14 @@ unsigned int NuclearInteraction::sampleDiscreteValues( return static_cast(distribution.first[iBin]); } -Particle::Scalar NuclearInteraction::sampleContinuousValues( +double NuclearInteraction::sampleContinuousValues( double rnd, const detail::NuclearInteractionParameters::CumulativeDistribution& distribution, bool interpolate) const { // Fast exit if (distribution.second.empty()) { - return std::numeric_limits::infinity(); + return std::numeric_limits::infinity(); } // Find the bin @@ -82,7 +82,7 @@ Particle::Scalar NuclearInteraction::sampleContinuousValues( std::numeric_limits::max() * rnd); // Fast exit for non-normalised CDFs like interaction probability if (int_rnd > distribution.second.back()) { - return std::numeric_limits::infinity(); + return std::numeric_limits::infinity(); } const auto it = std::upper_bound(distribution.second.begin(), distribution.second.end(), int_rnd); @@ -111,10 +111,10 @@ unsigned int NuclearInteraction::finalStateMultiplicity( return sampleDiscreteValues(rnd, distribution); } -std::pair -NuclearInteraction::globalAngle(ActsFatras::Particle::Scalar phi1, - ActsFatras::Particle::Scalar theta1, float phi2, - float theta2) const { +std::pair NuclearInteraction::globalAngle(double phi1, + double theta1, + float phi2, + float theta2) const { // Rotation around the global y-axis Acts::SquareMatrix3 rotY = Acts::SquareMatrix3::Zero(); rotY(0, 0) = std::cos(theta1); diff --git a/Fatras/src/Physics/PhotonConversion.cpp b/Fatras/src/Physics/PhotonConversion.cpp index 73bb83ad413..bf71af4cae2 100644 --- a/Fatras/src/Physics/PhotonConversion.cpp +++ b/Fatras/src/Physics/PhotonConversion.cpp @@ -10,6 +10,5 @@ #include "Acts/Definitions/ParticleData.hpp" -const ActsFatras::PhotonConversion::Scalar - ActsFatras::PhotonConversion::kElectronMass = - Acts::findMass(Acts::PdgParticle::eElectron).value(); +const double ActsFatras::PhotonConversion::kElectronMass = + Acts::findMass(Acts::PdgParticle::eElectron).value(); diff --git a/Plugins/ActSVG/include/Acts/Plugins/ActSVG/EventDataSvgConverter.hpp b/Plugins/ActSVG/include/Acts/Plugins/ActSVG/EventDataSvgConverter.hpp index c05539d6dd4..ddcf1654eb1 100644 --- a/Plugins/ActSVG/include/Acts/Plugins/ActSVG/EventDataSvgConverter.hpp +++ b/Plugins/ActSVG/include/Acts/Plugins/ActSVG/EventDataSvgConverter.hpp @@ -23,8 +23,8 @@ namespace Acts::Svg::EventDataConverter { /// @param idx the running index /// /// @return a vector of svg objects -actsvg::svg::object pointXY(const Vector3& pos, ActsScalar size, - const Style& style, unsigned int idx = 0); +actsvg::svg::object pointXY(const Vector3& pos, double size, const Style& style, + unsigned int idx = 0); /// Write/create a 3D point in ZR view /// @@ -34,8 +34,8 @@ actsvg::svg::object pointXY(const Vector3& pos, ActsScalar size, /// @param indx the running index /// /// @return a vector of svg objects -actsvg::svg::object pointZR(const Vector3& pos, ActsScalar size, - const Style& style, unsigned int idx = 0); +actsvg::svg::object pointZR(const Vector3& pos, double size, const Style& style, + unsigned int idx = 0); /// Write/create a 3D point in a given view /// @@ -46,8 +46,8 @@ actsvg::svg::object pointZR(const Vector3& pos, ActsScalar size, /// /// @return a vector of svg objects template -actsvg::svg::object point(const Vector3& pos, ActsScalar size, - const Style& style, unsigned int idx) { +actsvg::svg::object point(const Vector3& pos, double size, const Style& style, + unsigned int idx) { view_type view; std::vector ps = {pos}; auto ppos = view(ps)[0]; diff --git a/Plugins/ActSVG/include/Acts/Plugins/ActSVG/GridSvgConverter.hpp b/Plugins/ActSVG/include/Acts/Plugins/ActSVG/GridSvgConverter.hpp index 909fc44a356..c81698de5c2 100644 --- a/Plugins/ActSVG/include/Acts/Plugins/ActSVG/GridSvgConverter.hpp +++ b/Plugins/ActSVG/include/Acts/Plugins/ActSVG/GridSvgConverter.hpp @@ -31,7 +31,7 @@ using ProtoGrid = actsvg::proto::grid; namespace GridConverter { // An optional range and binning value -using AxisBound = std::tuple, BinningValue>; +using AxisBound = std::tuple, BinningValue>; /// Nested Options struct struct Options { @@ -65,8 +65,8 @@ ProtoGrid convert(const grid_type& grid, // The edge values - these need to follow the ACTSVG convention, // so there could be swapping when necessary - std::vector edges0; - std::vector edges1; + std::vector edges0; + std::vector edges1; // 1D case (more to be filled in later) if constexpr (grid_type::DIM == 1u) { diff --git a/Plugins/ActSVG/include/Acts/Plugins/ActSVG/IndexedSurfacesSvgConverter.hpp b/Plugins/ActSVG/include/Acts/Plugins/ActSVG/IndexedSurfacesSvgConverter.hpp index 788ac36aca5..b90803b07a5 100644 --- a/Plugins/ActSVG/include/Acts/Plugins/ActSVG/IndexedSurfacesSvgConverter.hpp +++ b/Plugins/ActSVG/include/Acts/Plugins/ActSVG/IndexedSurfacesSvgConverter.hpp @@ -115,7 +115,7 @@ ProtoIndexedSurfaceGrid convertImpl(const GeometryContext& gctx, if constexpr (index_grid::grid_type::DIM == 1u) { if (indexGrid.casts[0u] == BinningValue::binPhi) { auto estRangeR = constrain.range(BinningValue::binR); - std::array rRange = {estRangeR.min(), estRangeR.max()}; + std::array rRange = {estRangeR.min(), estRangeR.max()}; gridOptions.optionalBound = {rRange, BinningValue::binR}; } } @@ -139,7 +139,7 @@ ProtoIndexedSurfaceGrid convertImpl(const GeometryContext& gctx, // Register the bin naming std::string binInfo = std::string("- bin : [") + std::to_string(ib0) + std::string("]"); - ActsScalar binCenter = 0.5 * (binEdges[ib0] + binEdges[ib0 - 1u]); + double binCenter = 0.5 * (binEdges[ib0] + binEdges[ib0 - 1u]); binInfo += "\n - center : (" + std::to_string(binCenter) + ")"; pGrid._bin_ids.push_back(binInfo); } @@ -158,8 +158,8 @@ ProtoIndexedSurfaceGrid convertImpl(const GeometryContext& gctx, std::string binInfo = std::string("- bin : [") + std::to_string(ib0) + std::string(", ") + std::to_string(ib1) + std::string("]"); - ActsScalar binCenter0 = 0.5 * (binEdges0[ib0] + binEdges0[ib0 - 1u]); - ActsScalar binCenter1 = 0.5 * (binEdges1[ib1] + binEdges1[ib1 - 1u]); + double binCenter0 = 0.5 * (binEdges0[ib0] + binEdges0[ib0 - 1u]); + double binCenter1 = 0.5 * (binEdges1[ib1] + binEdges1[ib1 - 1u]); binInfo += "\n - center : (" + std::to_string(binCenter0) + ", " + std::to_string(binCenter1) + ")"; pGrid._bin_ids.push_back(binInfo); diff --git a/Plugins/ActSVG/include/Acts/Plugins/ActSVG/LayerSvgConverter.hpp b/Plugins/ActSVG/include/Acts/Plugins/ActSVG/LayerSvgConverter.hpp index 079f5ae7aec..c5cf43675dd 100644 --- a/Plugins/ActSVG/include/Acts/Plugins/ActSVG/LayerSvgConverter.hpp +++ b/Plugins/ActSVG/include/Acts/Plugins/ActSVG/LayerSvgConverter.hpp @@ -24,13 +24,10 @@ namespace Svg { using ProtoVolume = actsvg::proto::volume>; -static std::array noLimitZ = { - std::numeric_limits::lowest(), - std::numeric_limits::max()}; +static std::array noLimitZ = {std::numeric_limits::lowest(), + std::numeric_limits::max()}; -static std::array noLimitPhi = { - -std::numbers::pi_v, - std::numbers::pi_v}; +static std::array noLimitPhi = {-std::numbers::pi, std::numbers::pi}; namespace LayerConverter { @@ -49,16 +46,16 @@ struct Options { /// The style of the surface objects GeometryHierarchyMap