Skip to content

Commit

Permalink
ci: Add script and CI job to force std::size_t over size_t (#2671)
Browse files Browse the repository at this point in the history
Co-authored-by: Andreas Salzburger <asalzburger@gmail.com>
  • Loading branch information
paulgessinger and asalzburger authored Nov 15, 2023
1 parent e9ff5da commit bd74d01
Show file tree
Hide file tree
Showing 412 changed files with 1,964 additions and 1,775 deletions.
10 changes: 10 additions & 0 deletions .github/workflows/checks.yml
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,16 @@ jobs:
- name: Check
run: >
CI/check_end_of_file.py . --exclude "thirdparty/*" --reject-multiple-newlines --github
size_t:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-python@v4
with:
python-version: '3.10'
- name: Check
run: >
CI/check_size_t.py . --exclude "thirdparty/*"
boost_test_macro:
runs-on: ubuntu-latest
steps:
Expand Down
18 changes: 9 additions & 9 deletions Alignment/include/ActsAlignment/Kernel/Alignment.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,8 @@ struct AlignmentOptions {
const AlignedTransformUpdater& aTransformUpdater,
const std::vector<Acts::DetectorElementBase*>& aDetElements = {},
double chi2CutOff = 0.5,
const std::pair<size_t, double>& deltaChi2CutOff = {5, 0.01},
size_t maxIters = 5,
const std::pair<std::size_t, double>& deltaChi2CutOff = {5, 0.01},
std::size_t maxIters = 5,
const std::map<unsigned int, AlignmentMask>& iterState = {})
: fitOptions(fOptions),
alignedTransformUpdater(aTransformUpdater),
Expand All @@ -79,10 +79,10 @@ struct AlignmentOptions {

// The delta of average chi2/ndf within a couple of iterations to determine if
// alignment is converged
std::pair<size_t, double> deltaAverageChi2ONdfCutOff = {5, 0.01};
std::pair<std::size_t, double> deltaAverageChi2ONdfCutOff = {5, 0.01};

// The maximum number of iterations to run alignment
size_t maxIterations = 5;
std::size_t maxIterations = 5;

// The alignment mask for different iterations
std::map<unsigned int, AlignmentMask> iterationState;
Expand Down Expand Up @@ -111,16 +111,16 @@ struct AlignmentResult {
double chi2 = 0;

// The measurement dimension from all tracks
size_t measurementDim = 0;
std::size_t measurementDim = 0;

// The alignment degree of freedom
size_t alignmentDof = 0;
std::size_t alignmentDof = 0;

// The number of tracks used for alignment
size_t numTracks = 0;
std::size_t numTracks = 0;

// The indexed alignable surfaces
std::unordered_map<const Acts::Surface*, size_t> idxedAlignSurfaces;
std::unordered_map<const Acts::Surface*, std::size_t> idxedAlignSurfaces;

Acts::Result<void> result{Acts::Result<void>::success()};
};
Expand Down Expand Up @@ -163,7 +163,7 @@ struct Alignment {
const Acts::GeometryContext& gctx,
const std::vector<source_link_t>& sourcelinks,
const start_parameters_t& sParameters, const fit_options_t& fitOptions,
const std::unordered_map<const Acts::Surface*, size_t>&
const std::unordered_map<const Acts::Surface*, std::size_t>&
idxedAlignSurfaces,
const AlignmentMask& alignMask) const;

Expand Down
5 changes: 3 additions & 2 deletions Alignment/include/ActsAlignment/Kernel/Alignment.ipp
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ ActsAlignment::Alignment<fitter_t>::evaluateTrackAlignmentState(
const Acts::GeometryContext& gctx,
const std::vector<source_link_t>& sourcelinks,
const start_parameters_t& sParameters, const fit_options_t& fitOptions,
const std::unordered_map<const Acts::Surface*, size_t>& idxedAlignSurfaces,
const std::unordered_map<const Acts::Surface*, std::size_t>&
idxedAlignSurfaces,
const ActsAlignment::AlignmentMask& alignMask) const {
Acts::TrackContainer tracks{Acts::VectorTrackContainer{},
Acts::VectorMultiTrajectory{}};
Expand Down Expand Up @@ -122,7 +123,7 @@ void ActsAlignment::Alignment<fitter_t>::calculateAlignmentParameters(
// Get the inverse of chi2 second derivative matrix (we need this to
// calculate the covariance of the alignment parameters)
// @Todo: use more stable method for solving the inverse
size_t alignDof = alignResult.alignmentDof;
std::size_t alignDof = alignResult.alignmentDof;
Acts::ActsDynamicMatrix sumChi2SecondDerivativeInverse =
Acts::ActsDynamicMatrix::Zero(alignDof, alignDof);
sumChi2SecondDerivativeInverse = sumChi2SecondDerivative.inverse();
Expand Down
37 changes: 19 additions & 18 deletions Alignment/include/ActsAlignment/Kernel/detail/AlignmentEngine.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,13 @@ using namespace Acts;
///
struct TrackAlignmentState {
// The dimension of measurements
size_t measurementDim = 0;
std::size_t measurementDim = 0;

// The dimension of track parameters
size_t trackParametersDim = 0;
std::size_t trackParametersDim = 0;

// The contributed alignment degree of freedom
size_t alignmentDof = 0;
std::size_t alignmentDof = 0;

// The measurements covariance
ActsDynamicMatrix measurementCovariance;
Expand Down Expand Up @@ -65,7 +65,8 @@ struct TrackAlignmentState {

// The alignable surfaces on the track and their indices in both the global
// alignable surfaces pool and those relevant with this track
std::unordered_map<const Surface*, std::pair<size_t, size_t>> alignedSurfaces;
std::unordered_map<const Surface*, std::pair<std::size_t, std::size_t>>
alignedSurfaces;
};

/// Reset some columns of the alignment to bound derivative to zero if the
Expand Down Expand Up @@ -104,24 +105,24 @@ void resetAlignmentDerivative(Acts::AlignmentToBoundMatrix& alignToBound,
template <typename traj_t, typename parameters_t = BoundTrackParameters>
TrackAlignmentState trackAlignmentState(
const GeometryContext& gctx, const traj_t& multiTraj,
const size_t& entryIndex,
const std::pair<ActsDynamicMatrix, std::unordered_map<size_t, size_t>>&
const std::size_t& entryIndex,
const std::pair<ActsDynamicMatrix,
std::unordered_map<std::size_t, std::size_t>>&
globalTrackParamsCov,
const std::unordered_map<const Surface*, size_t>& idxedAlignSurfaces,
const std::unordered_map<const Surface*, std::size_t>& idxedAlignSurfaces,
const AlignmentMask& alignMask) {
using CovMatrix = typename parameters_t::CovarianceMatrix;

// Construct an alignment state
TrackAlignmentState alignState;

// Remember the index within the trajectory and whether it's alignable
std::vector<std::pair<size_t, bool>> measurementStates;
std::vector<std::pair<std::size_t, bool>> measurementStates;
measurementStates.reserve(15);
// Number of smoothed states on the track
// size_t nSmoothedStates = 0; // commented because clang-tidy complains about
// unused
// Number of alignable surfaces on the track
size_t nAlignSurfaces = 0;
// std::size_t nSmoothedStates = 0; // commented because clang-tidy complains
// about unused Number of alignable surfaces on the track
std::size_t nAlignSurfaces = 0;

// Visit the track states on the track
multiTraj.visitBackwards(entryIndex, [&](const auto& ts) {
Expand Down Expand Up @@ -192,12 +193,12 @@ TrackAlignmentState trackAlignmentState(

// Loop over the measurement states to fill those alignment matrices
// This is done in reverse order
size_t iMeasurement = alignState.measurementDim;
size_t iParams = alignState.trackParametersDim;
size_t iSurface = nAlignSurfaces;
std::size_t iMeasurement = alignState.measurementDim;
std::size_t iParams = alignState.trackParametersDim;
std::size_t iSurface = nAlignSurfaces;
for (const auto& [rowStateIndex, isAlignable] : measurementStates) {
const auto& state = multiTraj.getTrackState(rowStateIndex);
const size_t measdim = state.calibratedSize();
const std::size_t measdim = state.calibratedSize();
// Update index of current measurement and parameter
iMeasurement -= measdim;
iParams -= eBoundSize;
Expand Down Expand Up @@ -251,14 +252,14 @@ TrackAlignmentState trackAlignmentState(
// @Todo: add helper function to select rows/columns of a matrix
for (unsigned int iColState = 0; iColState < measurementStates.size();
iColState++) {
size_t colStateIndex = measurementStates.at(iColState).first;
std::size_t colStateIndex = measurementStates.at(iColState).first;
// Retrieve the block from the source covariance matrix
CovMatrix correlation =
sourceTrackParamsCov.block<eBoundSize, eBoundSize>(
stateRowIndices.at(rowStateIndex),
stateRowIndices.at(colStateIndex));
// Fill the block of the target covariance matrix
size_t iCol =
std::size_t iCol =
alignState.trackParametersDim - (iColState + 1) * eBoundSize;
alignState.trackParametersCovariance.block<eBoundSize, eBoundSize>(
iParams, iCol) = correlation;
Expand Down
82 changes: 82 additions & 0 deletions CI/check_size_t.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
#!/usr/bin/env python3

from pathlib import Path
import os
import argparse
from fnmatch import fnmatch
import re
import sys

ex = re.compile(r"(\b(?<!std::)size_t)\b")

github = "GITHUB_ACTIONS" in os.environ


def main():
p = argparse.ArgumentParser()
p.add_argument("input")
p.add_argument(
"--fix", action="store_true", help="Attempt to fix any license issues found."
)
p.add_argument("--exclude", "-e", action="append", default=[])

args = p.parse_args()

# walk over all files
exit = 0
for root, _, files in os.walk("."):
root = Path(root)
for filename in files:
# get the full path of the file
filepath = root / filename
if filepath.suffix not in (
".hpp",
".cpp",
".ipp",
".h",
".C",
".c",
".cu",
".cuh",
):
continue

if any([fnmatch(str(filepath), e) for e in args.exclude]):
continue

changed_lines = handle_file(filepath, fix=args.fix)
if len(changed_lines) > 0:
exit = 1
print()
print(filepath)
for i, oline in changed_lines:
print(f"{i}: {oline}")

if github:
print(
f"::error file={filepath},line={i+1},title=Do not use C-style size_t::Replace size_t with std::size_t"
)

return exit


def handle_file(file: Path, fix: bool) -> list[tuple[int, str]]:
content = file.read_text()
lines = content.splitlines()

changed_lines = []

for i, oline in enumerate(lines):
line, n_subs = ex.subn(r"std::size_t", oline)
lines[i] = line
if n_subs > 0:
changed_lines.append((i, oline))

if fix and len(changed_lines) > 0:
file.write_text("\n".join(lines) + "\n")

return changed_lines


if "__main__" == __name__:
sys.exit(main())
8 changes: 4 additions & 4 deletions Core/include/Acts/TrackFitting/GlobalChiSquareFitter.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -646,7 +646,7 @@ class Gx2Fitter {
// Iterate the fit and improve result. Abort after n steps or after
// convergence
// nUpdate is initialized outside to save its state for the track
size_t nUpdate = 0;
std::size_t nUpdate = 0;
for (nUpdate = 0; nUpdate < gx2fOptions.nUpdateMax; nUpdate++) {
ACTS_VERBOSE("nUpdate = " << nUpdate + 1 << "/"
<< gx2fOptions.nUpdateMax);
Expand Down Expand Up @@ -758,7 +758,7 @@ class Gx2Fitter {
BoundMatrix fullCovariancePredicted = BoundMatrix::Identity();
bool aMatrixIsInvertible = false;
if (gx2fOptions.zeroField) {
constexpr size_t reducedMatrixSize = 4;
constexpr std::size_t reducedMatrixSize = 4;

auto safeReducedCovariance = safeInverse(
aMatrix.topLeftCorner<reducedMatrixSize, reducedMatrixSize>().eval());
Expand All @@ -769,7 +769,7 @@ class Gx2Fitter {
*safeReducedCovariance;
}
} else {
constexpr size_t reducedMatrixSize = 5;
constexpr std::size_t reducedMatrixSize = 5;

auto safeReducedCovariance = safeInverse(
aMatrix.topLeftCorner<reducedMatrixSize, reducedMatrixSize>().eval());
Expand All @@ -789,7 +789,7 @@ class Gx2Fitter {
ACTS_VERBOSE("final covariance:\n" << fullCovariancePredicted);

if (!trackContainer.hasColumn(Acts::hashString("Gx2fnUpdateColumn"))) {
trackContainer.template addColumn<size_t>("Gx2fnUpdateColumn");
trackContainer.template addColumn<std::size_t>("Gx2fnUpdateColumn");
}

// Prepare track for return
Expand Down
4 changes: 2 additions & 2 deletions Core/include/Acts/Utilities/detail/TypeList.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,10 @@ struct getSize {};

template <typename... Ts>
struct getSize<TypeList<Ts...>>
: std::integral_constant<size_t, sizeof...(Ts)> {};
: std::integral_constant<std::size_t, sizeof...(Ts)> {};

template <typename L>
constexpr inline size_t size{getSize<L>()};
constexpr inline std::size_t size{getSize<L>()};
/// @}

/// Access the first type
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,9 +77,9 @@ class AlignmentAlgorithm final : public IAlgorithm {
/// Cutoff value for average chi2/ndf
double chi2ONdfCutOff = 0.10;
/// Cutoff value for delta of average chi2/ndf within a couple of iterations
std::pair<size_t, double> deltaChi2ONdfCutOff = {10, 0.00001};
std::pair<std::size_t, double> deltaChi2ONdfCutOff = {10, 0.00001};
/// Maximum number of iterations
size_t maxNumIterations = 100;
std::size_t maxNumIterations = 100;
/// Number of tracks to be used for alignment
int maxNumTracks = -1;
};
Expand Down
4 changes: 2 additions & 2 deletions Examples/Algorithms/Alignment/src/AlignmentAlgorithm.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ ActsExamples::ProcessCode ActsExamples::AlignmentAlgorithm::execute(
return ProcessCode::ABORT;
}

size_t numTracksUsed = protoTracks.size();
std::size_t numTracksUsed = protoTracks.size();
if (m_cfg.maxNumTracks > 0 &&
m_cfg.maxNumTracks < static_cast<int>(protoTracks.size())) {
numTracksUsed = m_cfg.maxNumTracks;
Expand All @@ -70,7 +70,7 @@ ActsExamples::ProcessCode ActsExamples::AlignmentAlgorithm::execute(
std::vector<std::vector<IndexSourceLink>> sourceLinkTrackContainer;
sourceLinkTrackContainer.reserve(numTracksUsed);
std::vector<IndexSourceLink> trackSourceLinks;
for (size_t itrack = 0; itrack < numTracksUsed; ++itrack) {
for (std::size_t itrack = 0; itrack < numTracksUsed; ++itrack) {
// The list of hits and the initial start parameters
const auto& protoTrack = protoTracks[itrack];

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ class GreedyAmbiguityResolutionAlgorithm final : public IAlgorithm {
std::uint32_t maximumIterations = 1000;

/// Minimum number of measurement to form a track.
size_t nMeasurementsMin = 7;
std::size_t nMeasurementsMin = 7;
};

/// Construct the ambiguity resolution algorithm.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,9 @@ Acts::GreedyAmbiguityResolution::Config transformConfig(
return result;
}

size_t sourceLinkHash(const Acts::SourceLink& a) {
return static_cast<size_t>(a.get<ActsExamples::IndexSourceLink>().index());
std::size_t sourceLinkHash(const Acts::SourceLink& a) {
return static_cast<std::size_t>(
a.get<ActsExamples::IndexSourceLink>().index());
}

bool sourceLinkEquality(const Acts::SourceLink& a, const Acts::SourceLink& b) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ class DigitizationAlgorithm final : public IAlgorithm {

/// Nested smearer struct that holds geometric digitizer and smearing
/// Support up to 4 dimensions.
template <size_t kSmearDIM>
template <std::size_t kSmearDIM>
struct CombinedDigitizer {
GeometricConfig geometric;
ActsFatras::BoundParametersSmearer<RandomEngine, kSmearDIM> smearing;
Expand Down Expand Up @@ -121,7 +121,7 @@ class DigitizationAlgorithm final : public IAlgorithm {
/// @param cfg Is the digitization configuration input
///
/// @return a variant of a Digitizer
template <size_t kSmearDIM>
template <std::size_t kSmearDIM>
static Digitizer makeDigitizer(const DigiComponentsConfig& cfg) {
CombinedDigitizer<kSmearDIM> impl;
// Copy the geometric configuration
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,8 @@ struct GeometricConfig {
/// Position and Covariance generation (currently not implemented)
/// Takes as an argument the clsuter size and an random engine
/// @return a vector of uncorrelated covariance values
std::vector<Acts::ActsScalar> variances(size_t /*size0*/, size_t /*size1*/,
std::vector<Acts::ActsScalar> variances(std::size_t /*size0*/,
std::size_t /*size1*/,
RandomEngine & /*rng*/) const {
return {};
};
Expand Down
Loading

0 comments on commit bd74d01

Please sign in to comment.