Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-11-25 09:03:00

0001 // This file is part of the ACTS project.
0002 //
0003 // Copyright (C) 2016 CERN for the benefit of the ACTS project
0004 //
0005 // This Source Code Form is subject to the terms of the Mozilla Public
0006 // License, v. 2.0. If a copy of the MPL was not distributed with this
0007 // file, You can obtain one at https://mozilla.org/MPL/2.0/.
0008 
0009 #pragma once
0010 
0011 #include <algorithm>
0012 #include <array>
0013 #include <bit>
0014 #include <bitset>
0015 #include <cmath>
0016 #include <cstddef>
0017 #include <cstdint>
0018 #include <iterator>
0019 #include <limits>
0020 #include <numeric>
0021 #include <span>
0022 #include <utility>
0023 
0024 namespace Acts::detail {
0025 
0026 /// The limit up to which a quadratic sort is used: the rank sort for the whole
0027 /// list instead of the linear bucket sort, and the insertion pass for one
0028 /// bucket instead of std::ranges::stable_sort. A general value, not tuned for
0029 /// one architecture: anything from 32 to 256 does about as well, below 32 it
0030 /// can get slower.
0031 inline constexpr std::size_t kQuadraticLinearCrossover = 32;
0032 
0033 /// Sorts at most @p kMaxSize items stably by key with a rank sort: an item's
0034 /// new position is the number of smaller keys, plus the number of equal keys
0035 /// before it.
0036 template <std::size_t kMaxSize, typename item_t, typename key_of_t>
0037 void rankSortByKey(std::span<item_t> items, const key_of_t& keyOf) {
0038   // A smaller rank sort while the items fit in half, down to two items
0039   if constexpr (kMaxSize > 2) {
0040     if (items.size() <= kMaxSize / 2) {
0041       rankSortByKey<kMaxSize / 2>(items, keyOf);
0042       return;
0043     }
0044   }
0045 
0046   // The type keyOf returns for an item
0047   using key_t = decltype(keyOf(items.front()));
0048   const std::size_t n = items.size();
0049 
0050   // The keys, padded to kMaxSize with the largest value: the comparison loop
0051   // below then has a fixed length, which the compiler can vectorise.
0052   std::array<key_t, kMaxSize> keys{};
0053   std::ranges::fill(keys, std::numeric_limits<key_t>::max());
0054   std::ranges::transform(items, keys.begin(), keyOf);
0055 
0056   // Each item's place is the number of smaller keys. Every place taken is
0057   // marked as one bit of the mask taken.
0058   std::array<std::uint32_t, kMaxSize> places{};
0059   std::bitset<kMaxSize> taken;
0060   for (std::size_t i = 0; i < n; ++i) {
0061     const key_t key = keys[i];
0062     std::uint32_t place = 0;
0063     for (const key_t other : keys) {
0064       place += other < key;
0065     }
0066     places[i] = place;
0067 
0068     // Mark the place as taken
0069     taken[place] = true;
0070   }
0071 
0072   // Equal keys share a place, so fewer places are taken than there are
0073   // items: only then is each item moved past the equal keys before it.
0074   if (taken.count() != n) {
0075     for (std::size_t i = 0; i < n; ++i) {
0076       const key_t key = keys[i];
0077       std::uint32_t place = places[i];
0078       for (std::size_t j = 0; j < i; ++j) {
0079         place += keys[j] == key;
0080       }
0081       places[i] = place;
0082     }
0083   }
0084 
0085   // Each item moved to its place, then all of them back in order
0086   std::array<item_t, kMaxSize> sorted{};
0087   for (std::size_t i = 0; i < n; ++i) {
0088     sorted[places[i]] = std::move(items[i]);
0089   }
0090 
0091   std::ranges::move(std::span(sorted).first(n), items.begin());
0092 }
0093 
0094 /// Sorts @p items stably by key, given the smallest and the largest key: they
0095 /// are spread over buckets across the key range, then each bucket is put in
0096 /// order with an insertion pass. A bucket that gets more than
0097 /// kQuadraticLinearCrossover items is sorted with std::ranges::stable_sort
0098 /// instead, so that uneven keys cannot make it slow. The keys must lie well
0099 /// within float's range.
0100 template <typename item_t, typename storage_t, typename key_of_t,
0101           typename key_t>
0102 void bucketSortByKey(std::span<item_t> items, storage_t& storage,
0103                      const key_of_t& keyOf, const key_t minKey,
0104                      const key_t maxKey) {
0105   if (maxKey == minKey) {
0106     return;  // all keys equal
0107   }
0108 
0109   // Two buckets per item keep most of them at one item or none.
0110   const std::size_t n = items.size();
0111   const std::size_t nBuckets = 2 * std::bit_ceil(n);
0112 
0113   // The bucket arithmetic is done in float for any key type: the conversion
0114   // keeps the keys' order, which is all the buckets need.
0115   const auto lo = static_cast<float>(minKey);
0116   const auto hi = static_cast<float>(maxKey);
0117 
0118   // A range of about zero, too small to divide by, as when different keys
0119   // round to the same float, falls back to std::ranges::stable_sort
0120   const float range = hi - lo;
0121   if (range <
0122       static_cast<float>(nBuckets) / std::numeric_limits<float>::max()) {
0123     std::ranges::stable_sort(items, {}, keyOf);
0124     return;
0125   }
0126 
0127   const float scale = static_cast<float>(nBuckets) / range;
0128   const auto bucketOf = [&](const item_t& item) {
0129     const auto key = static_cast<float>(keyOf(item));
0130     return std::min(static_cast<std::size_t>((key - lo) * scale), nBuckets - 1);
0131   };
0132 
0133   // The storage holds each bucket's first position, then each item's bucket
0134   storage.buckets.resize(nBuckets + n);
0135   const std::span<std::uint32_t> starts =
0136       std::span(storage.buckets).first(nBuckets);
0137   const std::span<std::uint32_t> bucketOfItem =
0138       std::span(storage.buckets).subspan(nBuckets, n);
0139 
0140   // Count the items in each bucket, and the most in any one
0141   std::ranges::fill(starts, 0u);
0142   std::uint32_t largest = 0;
0143   for (std::size_t i = 0; i < n; ++i) {
0144     bucketOfItem[i] = static_cast<std::uint32_t>(bucketOf(items[i]));
0145     ++starts[bucketOfItem[i]];
0146     largest = std::max(largest, starts[bucketOfItem[i]]);
0147   }
0148 
0149   // Turn the counts into each bucket's first position
0150   std::exclusive_scan(starts.begin(), starts.end(), starts.begin(),
0151                       std::uint32_t{0});
0152 
0153   // Spread the items over the buckets, in order
0154   auto& spread = storage.scratch;
0155   spread.resize(n);
0156   for (std::size_t i = 0; i < n; ++i) {
0157     spread[starts[bucketOfItem[i]]] = std::move(items[i]);
0158     ++starts[bucketOfItem[i]];
0159   }
0160 
0161   // A crowded bucket, as when one key is far from the others, is sorted on its
0162   // own: the insertion below is quadratic in a bucket's size, and the worst
0163   // case stays O(n log n).
0164   if (largest > kQuadraticLinearCrossover) {
0165     std::uint32_t begin = 0;
0166     for (const std::uint32_t end : starts) {
0167       if (end - begin > kQuadraticLinearCrossover) {
0168         std::ranges::stable_sort(std::span(spread).subspan(begin, end - begin),
0169                                  {}, keyOf);
0170       }
0171       begin = end;
0172     }
0173   }
0174 
0175   // Back in order: each item moves only past the larger keys of its bucket.
0176   for (std::size_t i = 0; i < n; ++i) {
0177     const key_t key = keyOf(spread[i]);
0178     std::size_t j = i;
0179     for (; j > 0 && key < keyOf(items[j - 1]); --j) {
0180       items[j] = std::move(items[j - 1]);
0181     }
0182 
0183     items[j] = std::move(spread[i]);
0184   }
0185 }
0186 
0187 /// Sorts @p items stably by the number @p keyOf gives each, of any arithmetic
0188 /// type: the rank sort up to kQuadraticLinearCrossover items, the bucket
0189 /// sort above, and std::ranges::stable_sort where a key is not finite.
0190 ///
0191 /// @param items The items to sort
0192 /// @param storage Kept between calls: `scratch`, a vector of items, and
0193 ///        `buckets`, a vector of std::uint32_t, both of any content
0194 /// @param keyOf Returns the key of an item
0195 template <typename item_t, typename storage_t, typename key_of_t>
0196 void sortByKey(std::span<item_t> items, storage_t& storage,
0197                const key_of_t& keyOf) {
0198   // The type keyOf returns for an item
0199   using key_t = decltype(keyOf(items.front()));
0200 
0201   // Find the key range for the bucket sort. A list with a NaN or infinite key
0202   // is sorted by std::ranges::stable_sort instead; isfinite is checked before
0203   // the key is compared here, as comparing a NaN traps where floating point
0204   // exceptions are enabled.
0205   bool finite = true;
0206   key_t minKey = std::numeric_limits<key_t>::max();
0207   key_t maxKey = std::numeric_limits<key_t>::lowest();
0208 
0209   for (const item_t& item : items) {
0210     const key_t key = keyOf(item);
0211     if (std::isfinite(key)) {
0212       minKey = std::min(minKey, key);
0213       maxKey = std::max(maxKey, key);
0214     } else {
0215       finite = false;
0216     }
0217   }
0218 
0219   if (!finite) {
0220     std::ranges::stable_sort(items, {}, keyOf);
0221     return;
0222   }
0223 
0224   if (items.size() <= kQuadraticLinearCrossover) {
0225     rankSortByKey<kQuadraticLinearCrossover>(items, keyOf);
0226   } else {
0227     bucketSortByKey(items, storage, keyOf, minKey, maxKey);
0228   }
0229 }
0230 
0231 /// Sorts @p items stably by key, and the items with equal keys by
0232 /// @p orderOfEqualKeys. With float keys equal keys are rare, so this costs
0233 /// little more than the sort by key.
0234 ///
0235 /// @param items The items to sort
0236 /// @param storage Kept between calls: `scratch`, a vector of items, and
0237 ///        `buckets`, a vector of std::uint32_t, both of any content
0238 /// @param keyOf Returns the key of an item
0239 /// @param orderOfEqualKeys Whether the first of two items with equal keys goes
0240 ///        before the second, a strict weak order; it is called only on items
0241 ///        with equal keys
0242 template <typename item_t, typename storage_t, typename key_of_t,
0243           typename order_t>
0244 void sortByKey(std::span<item_t> items, storage_t& storage,
0245                const key_of_t& keyOf, const order_t& orderOfEqualKeys) {
0246   sortByKey(items, storage, keyOf);
0247 
0248   for (auto first = items.begin(); first != items.end();) {
0249     const auto key = keyOf(*first);
0250     const auto last =
0251         std::find_if(std::next(first), items.end(),
0252                      [&](const item_t& item) { return keyOf(item) != key; });
0253     if (std::distance(first, last) > 1) {
0254       std::stable_sort(first, last, orderOfEqualKeys);
0255     }
0256     first = last;
0257   }
0258 }
0259 
0260 }  // namespace Acts::detail