diff --git a/Framework/Core/CMakeLists.txt b/Framework/Core/CMakeLists.txt index b31e951bb7ec1..a356a9d4e0372 100644 --- a/Framework/Core/CMakeLists.txt +++ b/Framework/Core/CMakeLists.txt @@ -367,6 +367,7 @@ foreach(b ASoA ASoAHelpers EventMixing + SparseSlicing HistogramRegistry ExternalFairMQDeviceProxies ) diff --git a/Framework/Core/include/Framework/ASoA.h b/Framework/Core/include/Framework/ASoA.h index 05247000527c9..619c8a39a1c8f 100644 --- a/Framework/Core/include/Framework/ASoA.h +++ b/Framework/Core/include/Framework/ASoA.h @@ -63,6 +63,8 @@ void accessingInvalidIndexFor(const char* getter); void dereferenceWithWrongType(const char* getter, const char* target); void missingFilterDeclaration(int hash, int ai); void notBoundTable(const char* tableName); +void parentTableMismatch(const char* tableName); +void incompatibleFilteredRanges(const char* tableName); void* extractCCDBPayload(char* payload, size_t size, TClass const* cl, const char* what); // ASCII-only lowercase. Column labels are plain identifiers, so we deliberately @@ -73,6 +75,16 @@ constexpr inline char asciiToLower(char c) return (c >= 'A' && c <= 'Z') ? static_cast(c + 32) : c; } +// Whether a column label names an arrow field: exactly (the common case: a +// length check and a memcmp) or ignoring the case. +inline bool labelMatches(std::string_view label, std::string_view name) +{ + return label == name || + std::ranges::equal(label, name, [](char c1, char c2) { + return asciiToLower(c1) == asciiToLower(c2); + }); +} + template auto createFieldsFromColumns(framework::pack) { @@ -610,6 +622,21 @@ class ColumnIterator : ChunkingPolicy } mutable unwrap_t const* mCurrent = nullptr; + // TODO(C++23): drop mCurrentPos and mGlobalOffset. They point back into the + // index policy of the enclosing TableIterator, because a column getter, being + // a member of the column base class, cannot name the iterator it is part of; + // TableIterator::bind() has to reset them (and the boundIterators of dynamic + // columns) on every construction and copy. With explicit object parameters + // (deducing this) the getters generated by the column macros can receive the + // whole iterator, e.g. + // template + // decltype(auto) pt(this Self const& self) { return self.Pt::mColumnIterator.at(self.mRowIndex + self.mOffset); } + // and read the position from it directly. That makes every ColumnIterator two + // pointers smaller and TableIterator copyable without bind(), which matters for + // slices of wide tables. Postponed until O2 switches to C++23: under C++20 + // Apple clang rejects explicit object parameters, and GCC 14 only accepts them + // with a -Wc++23-extensions warning. Getters becoming templates also breaks + // code that takes their address. int64_t const* mCurrentPos = nullptr; uint64_t const* mGlobalOffset = nullptr; mutable unwrap_t const* mLast = nullptr; @@ -1062,6 +1089,23 @@ struct TableIterator : IP, C... { this->limitRange(this->rangeStart(), this->rangeEnd()); } + /// Construct with a new index policy, copying the column iterators of + /// another, already constructed, iterator on the same arrow table instead + /// of creating them from the ChunkedArrays. Columns the other iterator does + /// not have (e.g. dynamic columns added by Attach) are made from columnData. + template + TableIterator(arrow::ChunkedArray* columnData[sizeof...(C)], IP&& policy, Other const& other) + : IP{policy}, + C(columnFrom(columnData, other))... + { + if (this->size() != 0) { + bind(); + } + if constexpr (has_index) { + this->limitRange(this->rangeStart(), this->rangeEnd()); + } + } + TableIterator() = default; TableIterator(self_t const& other) : IP{static_cast(other)}, @@ -1072,10 +1116,24 @@ struct TableIterator : IP, C... { } } - TableIterator& operator=(TableIterator other) + /// The columns are assigned directly from other and bound once. A move + /// would do the same: the iterator owns nothing, and the columns have to be + /// bound to the new object in any case. + TableIterator& operator=(self_t const& other) { IP::operator=(static_cast(other)); - (void(static_cast(*this) = static_cast(other)), ...); + (void(static_cast(*this) = static_cast(other)), ...); + if (this->size() != 0) { + bind(); + } + return *this; + } + + TableIterator& operator=(TableIterator const& other) + requires std::same_as + { + IP::operator=(IP{static_cast(other)}); + (void(static_cast(*this) = static_cast(other)), ...); if (this->size() != 0) { bind(); } @@ -1210,6 +1268,16 @@ struct TableIterator : IP, C... { } private: + template + static CC columnFrom(arrow::ChunkedArray* columnData[sizeof...(C)], Other const& other) + { + if constexpr (std::is_base_of_v) { + return static_cast(other); + } else { + return CC(columnData[framework::has_type_at_v(all_columns{})]); + } + } + /// Helper to move at the end of columns which actually have an iterator. template void doMoveToEnd(framework::pack) @@ -1522,9 +1590,52 @@ static consteval auto extractBindings(framework::pack) SelectionVector selectionToVector(gandiva::Selection const& sel); +/// Whether the columns of Prefix are the first columns of Full, in the same order +template +consteval bool isColumnPrefix() +{ + if constexpr (framework::pack_size(Prefix{}) > framework::pack_size(Full{})) { + return false; + } else { + return [](std::index_sequence) { + return (std::same_as, framework::pack_element_t> && ...); + }(std::make_index_sequence{}); + } +} + +/// Make a table of type R on (a range of) the arrow table of parent. When the +/// columns of R start with the columns of parent, R reuses the column pointers +/// parent has already resolved; otherwise R resolves them from the arrow schema. +template +R makeTableOn(ArrowTableRef ref, P const& parent, Args&&... args) +{ + // ref is moved along to the table, so that the shared_ptr to the arrow + // table is not copied (and its reference count updated) at every step + if constexpr (std::constructible_from) { + return R(std::move(ref), parent, std::forward(args)...); + } else if constexpr (std::constructible_from) { + return R(std::move(ref), std::forward(args)...); + } else { + return R(std::vector{std::move(ref)}, std::forward(args)...); + } +} + +/// The range of an unsorted slice, which is a selection over the whole table: +/// the full range of ref when the selection has rows, an empty range when it +/// has none, so that an empty slice skips making its iterators, as an empty +/// sorted slice does. An empty unsorted slice therefore has no raw access to +/// the rows of the table. +inline ArrowTableRef unsortedSliceRange(ArrowTableRef const& ref, std::span selection) +{ + return selection.empty() ? ref.makeEmpty() : ref; +} + +// The slicing helpers below that return a named table have explicit return +// types: clang does not apply the named return value optimization in function +// templates with a deduced return type, and would copy the table on return. template requires std::same_as && (o2::soa::is_binding_compatible_v()) -auto doSliceBy(T const* table, o2::framework::PresliceBase const& container, int value) +typename T::self_t doSliceBy(T const* table, o2::framework::PresliceBase const& container, int value) { if constexpr (OPT) { if (container.isMissing()) { @@ -1532,7 +1643,7 @@ auto doSliceBy(T const* table, o2::framework::PresliceBase const } } auto out = container.getSliceFor(value, table->asArrowTableRef()); - auto t = typename T::self_t({out}); + auto t = makeTableOn(std::move(out), *table); if (t.tableSize() != 0) { table->copyIndexBindings(t); t.bindInternalIndicesTo(table); @@ -1541,9 +1652,9 @@ auto doSliceBy(T const* table, o2::framework::PresliceBase const } template -auto doSliceByHelper(T const* table, std::span const& selection) +soa::Filtered doSliceByHelper(T const* table, std::span const& selection) { - auto t = soa::Filtered({table->asArrowTableRef()}, selection); + auto t = makeTableOn>(unsortedSliceRange(table->asArrowTableRef(), selection), *table, selection); if (t.tableSize() != 0) { table->copyIndexBindings(t); t.bindInternalIndicesTo(table); @@ -1554,9 +1665,9 @@ auto doSliceByHelper(T const* table, std::span const& selection) template requires(!soa::is_filtered_table) -auto doSliceByHelper(T const* table, std::span const& selection) +soa::Filtered doSliceByHelper(T const* table, std::span const& selection) { - auto t = soa::Filtered({table->asArrowTableRef()}, selection); + auto t = makeTableOn>(unsortedSliceRange(table->asArrowTableRef(), selection), *table, selection); if (t.tableSize() != 0) { table->copyIndexBindings(t); t.bindInternalIndicesTo(table); @@ -1580,17 +1691,18 @@ auto doSliceBy(T const* table, o2::framework::PresliceBase const SelectionVector sliceSelection(std::span const& mSelectedRows, int64_t nrows, uint64_t offset); template -auto prepareFilteredSlice(T const* table, o2::soa::ArrowTableRef slice) +Filtered prepareFilteredSlice(T const* table, o2::soa::ArrowTableRef slice) { - if (slice.range.offset >= static_cast(table->tableSize())) { - Filtered fresult{{slice}, SelectionVector{}}; + // an empty range selects no rows: skip slicing the selection of the table + if (slice.range.size == 0 || slice.range.offset >= static_cast(table->tableSize())) { + auto fresult = makeTableOn>(std::move(slice), *table, SelectionVector{}); if (fresult.tableSize() != 0) { table->copyIndexBindings(fresult); } return fresult; } auto slicedSelection = sliceSelection(table->getSelectedRows(), slice.range.size, slice.range.offset); - Filtered fresult{{slice}, std::move(slicedSelection)}; + auto fresult = makeTableOn>(std::move(slice), *table, std::move(slicedSelection)); if (fresult.tableSize() != 0) { table->copyIndexBindings(fresult); } @@ -1612,13 +1724,54 @@ auto doFilteredSliceBy(T const* table, o2::framework::PresliceBase originReplacement(header::DataOrigin newOrigin); +/// Key under which the slicing cache remembers the entry position for table T +/// and the index column node: the type id of T and the column's hash template -auto doSliceByCached(T const* table, framework::expressions::BindingNode const& node, int value, o2::framework::SliceCache& cache) +constexpr uint64_t sliceCacheKey(framework::expressions::BindingNode const& node) +{ + return (static_cast(o2::framework::TypeIdHelpers::uniqueId()) << 32) | node.hash; +} + +/// The sorted slicing cache entry of table T for the index column node. The +/// entry stays valid until the cache is updated, so that it can be looked up +/// once and reused for many slices. +template +framework::SliceInfoPtr getSliceInfoFor(framework::expressions::BindingNode const& node, o2::framework::SliceCache& cache) +{ + // the cache entry for a table type and index column does not change during the + // run, so its position is looked up by label once and remembered + auto const key = sliceCacheKey(node); + auto pos = node.hash == 0 ? -1 : cache.ptr->knownPosition(key); + if (pos < 0) { + pos = cache.ptr->locateSorted({"", originReplacement(cache.ptr->newOrigin)(o2::soa::getMatcherFromTypeForKey(node.name)), node.name}); + if (node.hash != 0) { + cache.ptr->rememberPosition(key, pos); + } + } + return cache.ptr->getCacheForPos(pos); +} + +template +framework::SliceInfoUnsortedPtr getSliceInfoUnsortedFor(framework::expressions::BindingNode const& node, o2::framework::SliceCache& cache) +{ + auto const key = sliceCacheKey(node); + auto pos = node.hash == 0 ? -1 : cache.ptr->knownPositionUnsorted(key); + if (pos < 0) { + pos = cache.ptr->locateUnsorted({"", originReplacement(cache.ptr->newOrigin)(o2::soa::getMatcherFromTypeForKey(node.name)), node.name}); + if (node.hash != 0) { + cache.ptr->rememberPositionUnsorted(key, pos); + } + } + return cache.ptr->getCacheUnsortedForPos(pos); +} + +/// Slice of table for the group value, using an already looked up cache entry +template + requires(!soa::is_filtered_table) +typename T::self_t doSliceByCached(T const* table, framework::SliceInfoPtr const& sliceInfo, int value) { - auto localCache = cache.ptr->getCacheFor({"", originReplacement(cache.ptr->newOrigin)(o2::soa::getMatcherFromTypeForKey(node.name)), - node.name}); - auto [offset, count] = localCache.getSliceFor(value); - auto t = typename T::self_t({table->asArrowTableRef().slice({static_cast(offset), count})}); + auto [offset, count] = sliceInfo.getSliceFor(value); + auto t = makeTableOn(table->asArrowTableRef().slice({static_cast(offset), count}), *table); if (t.tableSize() != 0) { table->copyIndexBindings(t); } @@ -1626,28 +1779,38 @@ auto doSliceByCached(T const* table, framework::expressions::BindingNode const& } template -auto doFilteredSliceByCached(T const* table, framework::expressions::BindingNode const& node, int value, o2::framework::SliceCache& cache) +auto doSliceByCached(T const* table, framework::SliceInfoPtr const& sliceInfo, int value) { - auto localCache = cache.ptr->getCacheFor({"", originReplacement(cache.ptr->newOrigin)(o2::soa::getMatcherFromTypeForKey(node.name)), - node.name}); - auto [offset, count] = localCache.getSliceFor(value); + auto [offset, count] = sliceInfo.getSliceFor(value); return prepareFilteredSlice(table, table->asArrowTableRef().slice({static_cast(offset), count})); } template -auto doSliceByCachedUnsorted(T const* table, framework::expressions::BindingNode const& node, int value, o2::framework::SliceCache& cache) +auto doSliceByCached(T const* table, framework::expressions::BindingNode const& node, int value, o2::framework::SliceCache& cache) +{ + return doSliceByCached(table, getSliceInfoFor(node, cache), value); +} + +template +auto doFilteredSliceByCached(T const* table, framework::expressions::BindingNode const& node, int value, o2::framework::SliceCache& cache) +{ + return doSliceByCached(table, getSliceInfoFor(node, cache), value); +} + +template +std::conditional_t, typename T::self_t, Filtered> doSliceByCachedUnsorted(T const* table, framework::expressions::BindingNode const& node, int value, o2::framework::SliceCache& cache) { - auto localCache = cache.ptr->getCacheUnsortedFor({"", originReplacement(cache.ptr->newOrigin)(o2::soa::getMatcherFromTypeForKey(node.name)), - node.name}); + auto localCache = getSliceInfoUnsortedFor(node, cache); + auto selection = localCache.getSliceFor(value); if constexpr (soa::is_filtered_table) { - auto t = typename T::self_t({table->asArrowTableRef()}, localCache.getSliceFor(value)); + auto t = makeTableOn(unsortedSliceRange(table->asArrowTableRef(), selection), *table, selection); if (t.tableSize() != 0) { t.intersectWithSelection(table->getSelectedRows()); table->copyIndexBindings(t); } return t; } else { - auto t = Filtered({table->asArrowTableRef()}, localCache.getSliceFor(value)); + auto t = makeTableOn>(unsortedSliceRange(table->asArrowTableRef(), selection), *table, selection); if (t.tableSize() != 0) { table->copyIndexBindings(t); } @@ -1658,10 +1821,11 @@ auto doSliceByCachedUnsorted(T const* table, framework::expressions::BindingNode template auto select(T const& t, framework::expressions::Filter const& f) { - return Filtered({t.asArrowTableRef()}, selectionToVector(framework::expressions::createSelection(t.asArrowTable(), f))); + return makeTableOn>(t.asArrowTableRef(), t, selectionToVector(framework::expressions::createSelection(t.asArrowTable(), f))); } arrow::ChunkedArray* getIndexFromLabel(arrow::Table* table, std::string_view label); +int getPositionFromLabel(arrow::Table* table, std::string_view label); template consteval auto base_iter(framework::pack&&) -> TableIterator @@ -1758,6 +1922,9 @@ class Table } using columns_t = decltype(getColumns()); + /// Columns in the order of the resolved column pointers (getColumnChunks()), + /// kept here because derived tables may redefine columns_t + using chunk_columns_t = columns_t; static constexpr auto column_hashes = [](framework::pack) consteval { auto hashes = std::array{C::hash...}; @@ -1789,60 +1956,68 @@ class Table { } + template + TableIteratorBase(arrow::ChunkedArray* columnData[framework::pack_size(columns_t{})], IP&& policy, Other const& other) + : base_iterator(columnData, std::forward(policy), other) + { + } + + // The converting assignments and constructors work directly on the base + // iterator of other, without temporary copies of it template - TableIteratorBase& operator=(TableIteratorBase other) + TableIteratorBase& operator=(TableIteratorBase const& other) requires(P::ref.desc_hash == Parent::ref.desc_hash) { - static_cast&>(*this) = static_cast>(other); + static_cast&>(*this) = static_cast const&>(other); return *this; } template - TableIteratorBase& operator=(TableIteratorBase other) + TableIteratorBase& operator=(TableIteratorBase const& other) { - static_cast&>(*this) = static_cast>(other); + static_cast&>(*this) = static_cast const&>(other); return *this; } template - TableIteratorBase& operator=(TableIteratorBase other) + TableIteratorBase& operator=(TableIteratorBase const& other) requires std::same_as { - static_cast&>(*this) = static_cast>(other); + static_cast&>(*this) = static_cast const&>(other); return *this; } template TableIteratorBase(TableIteratorBase const& other) requires(P::ref.desc_hash == Parent::ref.desc_hash) + : base_iterator(static_cast const&>(other)) { - *this = other; } template TableIteratorBase(TableIteratorBase&& other) noexcept requires(P::ref.desc_hash == Parent::ref.desc_hash) + : base_iterator(static_cast const&>(other)) { - *this = other; } template TableIteratorBase(TableIteratorBase const& other) + : base_iterator(static_cast const&>(other)) { - *this = other; } template TableIteratorBase(TableIteratorBase&& other) noexcept + : base_iterator(static_cast const&>(other)) { - *this = other; } template - TableIteratorBase(TableIteratorBase other) + TableIteratorBase(TableIteratorBase const& other) requires std::same_as + : base_iterator(static_cast const&>(other)) { - *this = other; } TableIteratorBase& operator=(RowViewSentinel const& other) @@ -1949,20 +2124,27 @@ class Table using unfiltered_const_iterator = unfiltered_iterator; Table(o2::soa::ArrowTableRef tableRef) - : mArrowTableRef(tableRef), - mEnd{tableRef.range.size} + : mArrowTableRef(std::move(tableRef)), + mEnd{mArrowTableRef.range.size}, + mBegin{lookupColumnsAndMakeBegin()} { - if (mArrowTableRef.tablePtr->num_rows() == 0) { - for (size_t ci = 0; ci < framework::pack_size(columns_t{}); ++ci) { - mColumnChunks[ci] = nullptr; - } - mBegin = mEnd; - } else { - auto lookups = [this](framework::pack) -> std::array { return {lookupColumn()...}; }(columns_t{}); - for (size_t ci = 0; ci < framework::pack_size(columns_t{}); ++ci) { - mColumnChunks[ci] = lookups[ci]; - } - mBegin = unfiltered_iterator{mColumnChunks, {mEnd.index, mArrowTableRef.range.offset}}; + if (mEnd.index != 0) { + mBegin.bindInternalIndices(this); + } + } + + /// Construct on (a range of) the arrow table of a parent table whose columns + /// are the first columns of this one, reusing the column pointers the parent + /// has already resolved instead of looking them up by label. Columns past the + /// parent's (e.g. dynamic columns added by Attach) have no backing array. + template + requires(isColumnPrefix()) + Table(o2::soa::ArrowTableRef tableRef, P const& parent) + : mArrowTableRef(std::move(tableRef)), + mEnd{mArrowTableRef.range.size}, + mBegin{inheritColumnsAndMakeBegin(parent)} + { + if (mEnd.index != 0) { mBegin.bindInternalIndices(this); } } @@ -2042,9 +2224,26 @@ class Table // is held by the table, so we are safe passing the bare pointer. If it does it // means that the iterator on a table is outliving the table itself, which is // a bad idea. + if (hasCachedBegin()) { + return filtered_iterator(mColumnChunks, {selection, mArrowTableRef.tablePtr->num_rows(), mArrowTableRef.range.offset}, mBegin); + } return filtered_iterator(mColumnChunks, {selection, mArrowTableRef.tablePtr->num_rows(), mArrowTableRef.range.offset}); } + /// Whether the cached begin iterator holds constructed column iterators, + /// which is the case for every table with a non-empty range + [[nodiscard]] bool hasCachedBegin() const + { + return mEnd.index != 0; + } + + /// The cached begin iterator over all rows of the range, also for filtered + /// tables, which override cached_begin() + [[nodiscard]] auto const& cachedUnfilteredBegin() const + { + return mBegin; + } + iterator iteratorAt(uint64_t i) const { return rawIteratorAt(i); @@ -2078,10 +2277,18 @@ class Table return mArrowTableRef.tablePtr->Slice(mArrowTableRef.range.offset, mArrowTableRef.range.size); } - [[nodiscard]] ArrowTableRef asArrowTableRef() const + /// The arrow table and range of this table; copy it to keep it beyond the + /// lifetime of the table + [[nodiscard]] ArrowTableRef const& asArrowTableRef() const { return mArrowTableRef; } + + /// Column pointers resolved for the arrow table, in the order of chunk_columns_t + [[nodiscard]] std::span getColumnChunks() const + { + return std::span{mColumnChunks}; + } /// Return offset auto offset() const { @@ -2176,12 +2383,12 @@ class Table auto rawSlice(uint64_t start, uint64_t end) const { - return self_t{mArrowTableRef.slice({start, static_cast(end - start + 1)})}; + return makeTableOn(mArrowTableRef.slice({start, static_cast(end - start + 1)}), *this); } auto emptySlice() const { - return self_t{mArrowTableRef.makeEmpty()}; + return makeTableOn(mArrowTableRef.makeEmpty(), *this); } void setPointerReconstructor(framework::PointerReconstructor const& pointerReconstructor) @@ -2199,7 +2406,65 @@ class Table template arrow::ChunkedArray* lookupColumn() { - return getIndexFromLabel(mArrowTableRef.tablePtr.get(), T::columnLabel()); + // Schemas do not change during a run: try the position the column had in + // the last arrow table this type was made from, and look it up by label + // only when the field there has a different name. + static thread_local int position = -1; + auto* table = mArrowTableRef.tablePtr.get(); + if (position < 0 || position >= table->num_columns() || !labelMatches(T::columnLabel(), table->schema()->field(position)->name())) { + position = getPositionFromLabel(table, T::columnLabel()); + } + return table->column(position).get(); + } + + // mBegin is made in the constructors' initializer lists by the helpers below, + // which also fill mColumnChunks (declared before it), so that it is + // constructed once, in place, instead of being default-initialized (which + // zero-fills every column) and then assigned. + + /// The begin iterator of an empty range: at the end, with no column bound + iterator makeEmptyBegin() const + { + iterator it; + it = mEnd; + return it; + } + + /// Look up the column arrays by label and make the begin iterator + iterator lookupColumnsAndMakeBegin() + { + if (mArrowTableRef.tablePtr->num_rows() == 0) { + std::fill(std::begin(mColumnChunks), std::end(mColumnChunks), nullptr); + return makeEmptyBegin(); + } + auto lookups = [this](framework::pack) -> std::array { return {lookupColumn()...}; }(columns_t{}); + std::ranges::copy(lookups, std::begin(mColumnChunks)); + if (mEnd.index == 0) { + // empty range: nothing to iterate, begin is already at the end + return makeEmptyBegin(); + } + return unfiltered_iterator{mColumnChunks, {mEnd.index, mArrowTableRef.range.offset}}; + } + + /// Take the column arrays from the parent and make the begin iterator, + /// copying the parent's column iterators when it has them + template + iterator inheritColumnsAndMakeBegin(P const& parent) + { + if (O2_BUILTIN_UNLIKELY(mArrowTableRef.tablePtr != parent.asArrowTableRef().tablePtr)) { + parentTableMismatch(o2::aod::label()); + } + auto inheritedEnd = std::ranges::copy(parent.getColumnChunks(), std::begin(mColumnChunks)).out; + std::fill(inheritedEnd, std::end(mColumnChunks), nullptr); + if (mEnd.index == 0) { + // empty range: nothing to iterate, begin is already at the end + return makeEmptyBegin(); + } + if (parent.hasCachedBegin()) { + // copy the parent's column iterators and only position the copy on the range + return unfiltered_iterator{mColumnChunks, {mEnd.index, mArrowTableRef.range.offset}, parent.cachedUnfilteredBegin()}; + } + return unfiltered_iterator{mColumnChunks, {mEnd.index, mArrowTableRef.range.offset}}; } ArrowTableRef mArrowTableRef; @@ -3416,6 +3681,16 @@ struct Join : Table, o2::aod::Hash<"JOIN/0"_h>, o2::aod: } } + template + requires(std::constructible_from) + Join(ArrowTableRef table, P const& parent) + : base{std::move(table), parent} + { + if (this->tableSize() != 0) { + bindInternalIndicesTo(this); + } + } + using base::bindExternalIndices; using base::bindInternalIndicesTo; static constexpr const uint32_t binding_origin = base::binding_origin; @@ -3485,12 +3760,12 @@ struct Join : Table, o2::aod::Hash<"JOIN/0"_h>, o2::aod: auto rawSlice(uint64_t start, uint64_t end) const { - return self_t{{this->asArrowTableRef().slice({start, static_cast(end - start + 1)})}}; + return makeTableOn(this->asArrowTableRef().slice({start, static_cast(end - start + 1)}), *this); } auto emptySlice() const { - return self_t{{this->asArrowTableRef().slice({0, 0})}}; + return makeTableOn(this->asArrowTableRef().slice({0, 0}), *this); } template @@ -3517,7 +3792,7 @@ struct Concat : Table, o2::aod::Hash<"CONC/0"_h>, o2::ao using self_t = Concat; Concat(ArrowTableRef table) - : base{table} + : base{std::move(table)} { bindInternalIndicesTo(this); } @@ -3595,10 +3870,23 @@ class FilteredBase : public T FilteredBase(std::vector&& tables, is_a_selection auto selection) : T{std::move(tables)} { - adoptSelection(selection); - if (this->tableSize() != 0) { - mFilteredBegin = table_t::filtered_begin(mSelectedRows); - } + // a SelectionVector is this table's own copy: it is moved in instead of + // being copied again (other selections are only viewed, see adoptSelection) + adoptSelection(std::move(selection)); + T::bindInternalIndicesTo(this); + resetRanges(); + mFilteredBegin.bindInternalIndices(this); + } + + template + requires(std::constructible_from) + FilteredBase(ArrowTableRef table, P const& parent, is_a_selection auto selection) + : T{std::move(table), parent} + { + // a SelectionVector is this table's own copy: it is moved in instead of + // being copied again (other selections are only viewed, see adoptSelection) + adoptSelection(std::move(selection)); + T::bindInternalIndicesTo(this); resetRanges(); mFilteredBegin.bindInternalIndices(this); } @@ -3613,16 +3901,18 @@ class FilteredBase : public T return const_iterator(mFilteredBegin); } + /// Access by row number in the range. The unfiltered iterator holds the + /// bindings, so this works also when no row is selected. unfiltered_iterator rawIteratorAt(uint64_t i) const { - auto it = unfiltered_iterator{mFilteredBegin}; + auto it = unfiltered_iterator{this->cachedUnfilteredBegin()}; it.setCursor(i); return it; } [[nodiscard]] RowViewSentinel end() const { - return RowViewSentinel{*mFilteredEnd}; + return RowViewSentinel{mFilteredEnd}; } auto& cached_begin() @@ -3660,12 +3950,12 @@ class FilteredBase : public T SelectionVector newSelection; newSelection.resize(static_cast(end - start + 1)); std::iota(newSelection.begin(), newSelection.end(), start); - return self_t{{this->asArrowTableRef()}, std::move(newSelection)}; + return makeTableOn(this->asArrowTableRef(), *this, std::move(newSelection)); } auto emptySlice() const { - return self_t{{this->asArrowTableRef()}, SelectionVector{}}; + return makeTableOn(this->asArrowTableRef(), *this, SelectionVector{}); } static inline auto getSpan(gandiva::Selection const& sel) @@ -3681,21 +3971,25 @@ class FilteredBase : public T /// Bind the columns which refer to other tables /// to the associated tables. + /// The bindings are held by the unfiltered iterator, from which the filtered + /// one is made, and are also set on the filtered one in case it is built void bindExternalIndicesRaw(std::vector&& ptrs) { - mFilteredBegin.bindExternalIndicesRaw(std::forward>(ptrs)); + mFilteredBegin.bindExternalIndicesRaw(std::vector{ptrs}); + T::bindExternalIndicesRaw(std::forward>(ptrs)); } template void bindInternalIndicesTo(I const* ptr) { + T::bindInternalIndicesTo(ptr); mFilteredBegin.bindInternalIndices(ptr); } template void doCopyIndexBindings(framework::pack, T1& dest) const { - dest.bindExternalIndicesRaw(mFilteredBegin.getIndexBindings()); + dest.bindExternalIndicesRaw(this->cachedUnfilteredBegin().getIndexBindings()); } template @@ -3775,6 +4069,7 @@ class FilteredBase : public T void setPointerReconstructor(framework::PointerReconstructor const& pointerReconstructor) { + T::setPointerReconstructor(pointerReconstructor); mFilteredBegin.setPointerReconstructor(pointerReconstructor); } @@ -3784,22 +4079,25 @@ class FilteredBase : public T if (mCached) { mSelectedRows = std::span{mSelectedRowsCache}; } - mFilteredEnd.reset(new RowViewSentinel{static_cast(mSelectedRows.size())}); + mFilteredEnd = static_cast(mSelectedRows.size()); if (tableSize() == 0) { - mFilteredBegin = *mFilteredEnd; - } else { + mFilteredBegin = RowViewSentinel{mFilteredEnd}; + } else if (mFilteredBeginBuilt) { mFilteredBegin.resetSelection(mSelectedRows); + } else if (!mSelectedRows.empty()) { + // made from the unfiltered iterator, with its bindings, once rows are selected + mFilteredBegin = table_t::filtered_begin(mSelectedRows); + mFilteredBeginBuilt = true; } + // with no rows selected and no built iterator, begin is already at the end } - template - inline void adoptSelection(S) - { - } - + // A gandiva::Selection is not adopted, only viewed through a span, so it is + // taken by reference: the constructor's parameter keeps it alive while the + // table is set up, even when the constructor passes it on with std::move. template requires(std::same_as, gandiva::Selection>) - inline void adoptSelection(S selection) + inline void adoptSelection(S const& selection) { mSelectedRows = getSpan(selection); mCached = false; @@ -3825,8 +4123,11 @@ class FilteredBase : public T std::span mSelectedRows; SelectionVector mSelectedRowsCache; bool mCached = false; + /// whether mFilteredBegin has been made; it is not while no row is selected + bool mFilteredBeginBuilt = false; iterator mFilteredBegin; - std::shared_ptr mFilteredEnd; + /// the number of selected rows, which end() returns as a sentinel + int64_t mFilteredEnd = 0; }; template @@ -3855,6 +4156,11 @@ class Filtered : public FilteredBase Filtered(std::vector&& tables, is_a_selection auto selection) : FilteredBase{std::move(tables), std::forward(selection)} {} + template + requires(std::constructible_from) + Filtered(ArrowTableRef table, P const& parent, is_a_selection auto selection) + : FilteredBase{std::move(table), parent, std::forward(selection)} {} + Filtered operator+(is_a_selection auto selection) { Filtered copy(*this); @@ -3903,7 +4209,7 @@ class Filtered : public FilteredBase unfiltered_iterator rawIteratorAt(uint64_t i) const { - auto it = unfiltered_iterator{this->cached_begin()}; + auto it = unfiltered_iterator{this->cachedUnfilteredBegin()}; it.setCursor(i); return it; } @@ -3915,12 +4221,12 @@ class Filtered : public FilteredBase SelectionVector newSelection; newSelection.resize(static_cast(end - start + 1)); std::iota(newSelection.begin(), newSelection.end(), start); - return self_t{{this->asArrowTableRef()}, std::move(newSelection)}; + return makeTableOn(this->asArrowTableRef(), *this, std::move(newSelection)); } auto emptySlice() const { - return self_t{{this->asArrowTableRef()}, SelectionVector{}}; + return makeTableOn(this->asArrowTableRef(), *this, SelectionVector{}); } template @@ -3982,14 +4288,21 @@ class Filtered> : public FilteredBase return const_iterator(this->cached_begin()); } + /// The result is the rows of the first table that pass the selections of + /// all the tables, so it reuses the columns the first table has resolved. Filtered(std::vector>&& tables, is_a_selection auto selection) - : FilteredBase(std::move(extractTablesFromFiltered(tables)), std::forward(selection)) + : FilteredBase(commonTable(tables), tables.front(), std::forward(selection)) { for (auto& table : tables) { *this *= table; } } + template + requires(std::constructible_from) + Filtered(ArrowTableRef table, P const& parent, is_a_selection auto selection) + : FilteredBase{std::move(table), parent, std::forward(selection)} {} + Filtered> operator+(is_a_selection auto selection) { Filtered> copy(*this); @@ -4038,7 +4351,7 @@ class Filtered> : public FilteredBase unfiltered_iterator rawIteratorAt(uint64_t i) const { - auto it = unfiltered_iterator{this->cached_begin()}; + auto it = unfiltered_iterator{this->cachedUnfilteredBegin()}; it.setCursor(i); return it; } @@ -4048,12 +4361,12 @@ class Filtered> : public FilteredBase SelectionVector newSelection; newSelection.resize(static_cast(end - start + 1)); std::iota(newSelection.begin(), newSelection.end(), start); - return self_t{{this->asArrowTableRef()}, std::move(newSelection)}; + return makeTableOn(this->asArrowTableRef(), *this, std::move(newSelection)); } auto emptySlice() const { - return self_t{{this->asArrowTableRef()}, SelectionVector{}}; + return makeTableOn(this->asArrowTableRef(), *this, SelectionVector{}); } auto sliceByCached(framework::expressions::BindingNode const& node, int value, o2::framework::SliceCache& cache) const @@ -4079,13 +4392,17 @@ class Filtered> : public FilteredBase } private: - std::vector extractTablesFromFiltered(std::vector>& tables) - { - std::vector outTables; - for (auto& table : tables) { - outTables.push_back(table.asArrowTableRef()); + /// The arrow table of the first table, which all the tables have to share + /// the range of for their selections to be combined + static ArrowTableRef commonTable(std::vector> const& tables) + { + auto ref = tables.front().asArrowTableRef(); + for (auto const& table : tables) { + if (table.asArrowTableRef().range != ref.range) { + incompatibleFilteredRanges(o2::aod::label()); + } } - return outTables; + return ref; } }; @@ -4120,7 +4437,7 @@ struct IndexTable : Table { } IndexTable(ArrowTableRef table) - : base_t{table} {} + : base_t{std::move(table)} {} /// FIXME: this is a compatiblity for a generic constructor call with a vector /// there has to be a safer way @@ -4144,7 +4461,12 @@ struct SmallGroupsBase : public Filtered { static constexpr bool applyFilters = APPLY; SmallGroupsBase(std::vector&& tables, is_a_selection auto selection) - : Filtered(std::move(tables), selection) {} + : Filtered(std::move(tables), std::move(selection)) {} + + template + requires(std::constructible_from) + SmallGroupsBase(ArrowTableRef table, P const& parent, is_a_selection auto selection) + : Filtered(std::move(table), parent, std::move(selection)) {} }; template diff --git a/Framework/Core/include/Framework/ASoAHelpers.h b/Framework/Core/include/Framework/ASoAHelpers.h index 0449bdfdc2a0c..2ff7b19dedd84 100644 --- a/Framework/Core/include/Framework/ASoAHelpers.h +++ b/Framework/Core/include/Framework/ASoAHelpers.h @@ -1156,6 +1156,10 @@ struct CombinationsGenerator { using CombinationType = typename P::CombinationType; public: + /// End-of-iteration marker: the iterator itself knows when it is exhausted + struct CombinationsSentinel { + }; + struct CombinationsIterator : public P { public: using reference = CombinationType&; @@ -1195,38 +1199,39 @@ struct CombinationsGenerator { { return (lh.mIsEnd && rh.mIsEnd) || (lh.mCurrent == rh.mCurrent); } + bool operator==(CombinationsSentinel) const + { + return this->mIsEnd; + } }; using iterator = CombinationsIterator; using const_iterator = CombinationsIterator; + using sentinel = CombinationsSentinel; inline iterator begin() { return iterator(mBegin); } - inline iterator end() + inline sentinel end() { - return iterator(mEnd); + return {}; } inline const_iterator begin() const { return iterator(mBegin); } - inline const_iterator end() const + inline sentinel end() const { - return iterator(mEnd); + return {}; } CombinationsGenerator() = delete; - CombinationsGenerator(const P& policy) : mBegin(policy), mEnd(policy) - { - mEnd.moveToEnd(); - } + CombinationsGenerator(const P& policy) : mBegin(policy) {} ~CombinationsGenerator() = default; private: iterator mBegin; - iterator mEnd; }; template diff --git a/Framework/Core/include/Framework/AnalysisHelpers.h b/Framework/Core/include/Framework/AnalysisHelpers.h index 6071e8291e387..44b370ed56860 100644 --- a/Framework/Core/include/Framework/AnalysisHelpers.h +++ b/Framework/Core/include/Framework/AnalysisHelpers.h @@ -964,7 +964,7 @@ auto getTableFromFilter(soa::is_filtered_table auto const& table, soa::Selection auto getTableFromFilter(soa::is_not_filtered_table auto const& table, soa::SelectionVector&& selection) { - return std::make_unique>>(std::vector{table.asArrowTableRef()}, std::forward(selection)); + return std::make_unique>>(o2::soa::makeTableOn>>(table.asArrowTableRef(), table, std::forward(selection))); } void initializePartitionCaches(std::span hashes, std::shared_ptr const& schema, expressions::Filter const& filter, gandiva::NodePtr& tree, gandiva::FilterPtr& gfilter); @@ -1104,12 +1104,15 @@ auto Extend(T const& table) } /// Template function to attach dynamic columns on-the-fly (e.g. inside -/// process() function). Dynamic columns need to be compatible with the table. +/// process() function). Dynamic columns need to be compatible with the table +/// and must not be in it already. The result reuses the columns the table has +/// resolved, as the attached columns follow them and have no backing arrays. template + requires((!framework::has_type_v && ...)) auto Attach(T const& table) { using output_t = Join, o2::aod::Hash<"JOIN/0"_h>, o2::aod::Hash<"JOIN"_h>, Cs...>>; - return output_t{{table.asArrowTableRef()}}; + return output_t{table.asArrowTableRef(), table}; } } // namespace o2::soa diff --git a/Framework/Core/include/Framework/AnalysisTask.h b/Framework/Core/include/Framework/AnalysisTask.h index bfd67a03ecbc1..8ccb382370e94 100644 --- a/Framework/Core/include/Framework/AnalysisTask.h +++ b/Framework/Core/include/Framework/AnalysisTask.h @@ -25,6 +25,7 @@ #include "Framework/GroupSlicer.h" #include "Framework/StructToTuple.h" #include "Framework/TypeIdHelpers.h" +#include "Framework/VariantHelpers.h" #include "Framework/ArrowTableSlicingCache.h" #include "Framework/AnalysisDataModel.h" #include "Framework/DanglingEdgesContext.h" @@ -398,29 +399,31 @@ struct AnalysisDataProcessorBuilder { if constexpr (soa::is_iterator) { auto slicer = GroupSlicer(groupingTable, associatedTables, slices, newOrigin); for (auto& slice : slicer) { - auto associatedSlices = slice.associatedTables(); - std::apply([&pointerReconstructor](auto&... table) { - (table.setPointerReconstructor(pointerReconstructor), ...); - }, - associatedSlices); - - overwriteInternalIndices(associatedSlices, associatedTables); - std::apply( - [&binder](auto&... x) mutable { - (binder(x), ...); + // the slices are passed as prvalues and bound to the parameters + // directly, so that they are not copied on their way to the process function + [&](auto&&... associatedSlices) { + auto prepareSlice = framework::overloaded{ + [&](S&& t) + requires(!std::is_lvalue_reference_v) + { + t.setPointerReconstructor(pointerReconstructor); + t.bindInternalIndicesTo(&std::get>(associatedTables)); + binder(t); + }, + // tables not related to the grouping table are passed as references to + // the full tables, which got the same bindings before the slicer was made + [](auto&) {}}; + (prepareSlice(std::forward(associatedSlices)), ...); + + // bind partitions and grouping table + homogeneous_apply_refs_sized([&groupingTable](auto& x) { + analysis_task_parsers::bindExternalIndicesPartition(x, &groupingTable); + return true; }, - associatedSlices); - - // bind partitions and grouping table - homogeneous_apply_refs_sized([&groupingTable](auto& x) { - analysis_task_parsers::bindExternalIndicesPartition(x, &groupingTable); - return true; - }, - task); + task); - [](Task& task, void (Task::*processingFunction)(Grouping, Associated...), Grouping g, std::tuple...>& at) { - std::invoke(processingFunction, task, g, std::get>(at)...); - }(task, processingFunction, slice.groupingElement(), associatedSlices); + std::invoke(processingFunction, task, slice.groupingElement(), associatedSlices...); + }(slice.template prepareArgument>()...); } } else { // bind partitions and grouping table diff --git a/Framework/Core/include/Framework/ArrowTableSlicingCache.h b/Framework/Core/include/Framework/ArrowTableSlicingCache.h index 9b27480024674..fd89f61e054c9 100644 --- a/Framework/Core/include/Framework/ArrowTableSlicingCache.h +++ b/Framework/Core/include/Framework/ArrowTableSlicingCache.h @@ -101,6 +101,19 @@ struct ArrowTableSlicingCache { int getCachePosSortedFor(Entry const& bindingKey) const; int getCachePosUnsortedFor(Entry const& bindingKey) const; + // locate an enabled entry of the given kind; throws if the key is in the other + // cache, in neither, or disabled + int locateSorted(Entry const& bindingKey) const; + int locateUnsorted(Entry const& bindingKey) const; + + // positions already located, by a key the caller makes from the table type + // and the index column (see soa::getSliceInfoFor); -1 if not known yet. The + // entry lists only change in setCaches, which forgets them. + int knownPosition(uint64_t key) const; + int knownPositionUnsorted(uint64_t key) const; + void rememberPosition(uint64_t key, int pos) const; + void rememberPositionUnsorted(uint64_t key, int pos) const; + // get slice from cache for a given value SliceInfoPtr getCacheFor(Entry const& bindingKey) const; SliceInfoUnsortedPtr getCacheUnsortedFor(Entry const& bindingKey) const; @@ -114,6 +127,10 @@ struct ArrowTableSlicingCache { std::pair> emptySlice{nullptr, nullptr}; static void validateOrder(Entry const& bindingKey, std::shared_ptr const& input); + + private: + mutable std::vector> mKnownPositions; + mutable std::vector> mKnownPositionsUnsorted; }; } // namespace o2::framework diff --git a/Framework/Core/include/Framework/GroupSlicer.h b/Framework/Core/include/Framework/GroupSlicer.h index f06cd6a0cd916..aa6fe2c42939d 100644 --- a/Framework/Core/include/Framework/GroupSlicer.h +++ b/Framework/Core/include/Framework/GroupSlicer.h @@ -160,11 +160,10 @@ struct GroupSlicer { return *this; } - auto associatedTables() - { - return std::make_tuple(prepareArgument()...); - } - + /// The associated table A1 for the current grouping element: a slice for + /// tables related to the grouping table, otherwise the full table. Slices are + /// returned as prvalues, so that the caller can bind them without a copy; + /// their internal indices still need to be bound to the full table. template requires(o2::soa::relatedByIndex, std::decay_t>() && soa::is_filtered_table) auto prepareArgument() @@ -179,24 +178,22 @@ struct GroupSlicer { } // generic split auto selection = sliceInfosUnsorted[index].getSliceFor(pos); - // intersect selections - o2::soa::SelectionVector s; - if (selections[index]->empty()) { - if (!selection.empty()) { - std::copy(selection.begin(), selection.end(), std::back_inserter(s)); - } - } else { - if (!selection.empty()) { - if constexpr (std::decay_t::applyFilters) { + if constexpr (std::decay_t::applyFilters) { + // a selection of sorted, unique rows that is as long as the full table + // selects every row: the intersection is then the group itself + if (!selections[index]->empty() && std::ssize(*selections[index]) != originalTable.tableSize()) { + // intersect with the filter of the full table: the result is a new selection + o2::soa::SelectionVector s; + if (!selection.empty()) { std::set_intersection(selection.begin(), selection.end(), selections[index]->begin(), selections[index]->end(), std::back_inserter(s)); - } else { - std::copy(selection.begin(), selection.end(), std::back_inserter(s)); } + auto range = soa::unsortedSliceRange(originalTable.asArrowTableRef(), s); + return soa::makeTableOn>(std::move(range), originalTable, std::move(s)); } } - std::decay_t typedTable{{originalTable.asArrowTableRef()}, std::move(s)}; - typedTable.bindInternalIndicesTo(&originalTable); - return typedTable; + // no filter to apply, or one that selects every row: view the rows of the group in the slicing cache, + // which lives throughout the process call, instead of copying them + return soa::makeTableOn>(soa::unsortedSliceRange(originalTable.asArrowTableRef(), selection), originalTable, selection); } template @@ -219,6 +216,10 @@ struct GroupSlicer { uint64_t offset = oc.first; auto count = oc.second; auto groupedElementsTable = originalTable.asArrowTableRef().slice({offset, count}); + if (count == 0) { + // an empty group selects no rows; starts[index] stays valid for the next groups + return soa::makeTableOn>(std::move(groupedElementsTable), originalTable, soa::SelectionVector{}); + } // for each grouping element we need to slice the selection vector auto start_iterator = std::lower_bound(starts[index], selections[index]->end(), offset); @@ -230,9 +231,7 @@ struct GroupSlicer { return idx - static_cast(offset); }); - std::decay_t typedTable{{groupedElementsTable}, std::move(slicedSelection)}; - typedTable.bindInternalIndicesTo(&originalTable); - return typedTable; + return soa::makeTableOn>(std::move(groupedElementsTable), originalTable, std::move(slicedSelection)); } template @@ -252,14 +251,14 @@ struct GroupSlicer { } // optimized split auto [offset, count] = sliceInfos[index].getSliceFor(pos); - auto groupedElementsTable = originalTable.rawSlice(offset, offset + count - 1); - groupedElementsTable.bindInternalIndicesTo(&originalTable); - return groupedElementsTable; + return soa::makeTableOn>(originalTable.asArrowTableRef().slice({static_cast(offset), static_cast(count)}), originalTable); } + /// Tables not related to the grouping table are the same for every grouping + /// element, so the full table is returned by reference instead of a copy. template requires(!o2::soa::relatedByIndex, std::decay_t>() && !soa::is_smallgroups) - auto prepareArgument() + A1& prepareArgument() { return std::get(*mAt); } diff --git a/Framework/Core/include/Framework/GroupedCombinations.h b/Framework/Core/include/Framework/GroupedCombinations.h index d8c6aea44f31d..49f8c769cf4a0 100644 --- a/Framework/Core/include/Framework/GroupedCombinations.h +++ b/Framework/Core/include/Framework/GroupedCombinations.h @@ -21,19 +21,6 @@ namespace o2::framework { -// Create an instance of a tuple interleaved from given tuples -template -auto interleaveTuplesImpl(std::tuple& t1, std::tuple& t2, std::index_sequence) -{ - return std::tuple_cat(std::make_tuple(std::get(t1), std::get(t2))...); -} - -template -auto interleaveTuples(std::tuple& t1, std::tuple& t2) -{ - return interleaveTuplesImpl(t1, t2, std::index_sequence_for()); -} - template using is_index_to_g_t = typename std::conditional(), std::true_type, std::false_type>::type; @@ -47,6 +34,20 @@ expressions::BindingNode getMatchingIndexNode() return expressions::BindingNode{index_column_t::mLabel, o2::framework::TypeIdHelpers::uniqueId(), expressions::selectArrowType()}; } +namespace detail +{ +/// Makes a T when converted to it. An element of a tuple (or of a tuple in an +/// optional) initialized from it is made in place by the conversion function, +/// instead of being moved from a temporary T. This is the resolution of +/// CWG 2327 that clang and GCC implement; with a compiler that does not, the +/// element is moved, as it would be from a T. +template +struct MakeOnConversion { + F make; + operator T() const { return make(); } +}; +} // namespace detail + template requires(sizeof...(As) > 0) struct GroupedCombinationsGenerator { @@ -56,6 +57,10 @@ struct GroupedCombinationsGenerator { using GroupedIteratorType = pack_to_tuple_t, pack>>; + /// End-of-iteration marker: the iterator itself knows when it is exhausted + struct GroupedSentinel { + }; + struct GroupedIterator : public GroupingPolicy { public: using reference = GroupedIteratorType&; @@ -70,17 +75,17 @@ struct GroupedCombinationsGenerator { template GroupedIterator(const GroupingPolicy& groupingPolicy, const G& grouping, const std::tuple& associated, SliceCache* cache_) : GroupingPolicy(groupingPolicy), - mGrouping{std::make_shared(std::vector{grouping.asArrowTableRef()})}, mAssociated{std::make_shared>(std::make_tuple(std::get(pack{})>(associated)...))}, mIndexColumns{getMatchingIndexNode()...}, cache{cache_} { if constexpr (soa::is_filtered_table>) { - mGrouping = std::make_shared(std::vector{grouping.asArrowTableRef()}, grouping.getSelectedRows()); + mGrouping = std::make_shared(soa::makeTableOn(grouping.asArrowTableRef(), grouping, grouping.getSelectedRows())); } else { - mGrouping = std::make_shared(std::vector{grouping.asArrowTableRef()}); + mGrouping = std::make_shared(soa::makeTableOn(grouping.asArrowTableRef(), grouping)); } setMultipleGroupingTables(grouping); + updateSliceInfos(std::make_index_sequence()); if (!this->mIsEnd) { setCurrentGroupedCombination(); } @@ -94,12 +99,13 @@ struct GroupedCombinationsGenerator { void setTables(const G& grouping, const std::tuple& associated) { if constexpr (soa::is_filtered_table>) { - mGrouping = std::make_shared(std::vector{grouping.asArrowTableRef()}, grouping.getSelectedRows()); + mGrouping = std::make_shared(soa::makeTableOn(grouping.asArrowTableRef(), grouping, grouping.getSelectedRows())); } else { - mGrouping = std::make_shared(std::vector{grouping.asArrowTableRef()}); + mGrouping = std::make_shared(soa::makeTableOn(grouping.asArrowTableRef(), grouping)); } mAssociated = std::make_shared>(std::make_tuple(std::get(pack{})>(associated)...)); setMultipleGroupingTables(grouping); + updateSliceInfos(std::make_index_sequence()); if (!this->mIsEnd) { setCurrentGroupedCombination(); } @@ -149,17 +155,23 @@ struct GroupedCombinationsGenerator { { return !(*this == rh); } - - private: - std::tuple getAssociatedTables() + bool operator==(GroupedSentinel) const { - return doGetAssociatedTables(std::make_index_sequence()); + return this->mIsEnd; } + private: + /// Look up the slicing cache entries of the associated tables once per + /// set of tables, instead of once per slice template - std::tuple doGetAssociatedTables(std::index_sequence) + void updateSliceInfos(std::index_sequence) { - return std::make_tuple(getAssociatedTable()...); + ([this]() { + if (std::get(*mAssociated).size() != 0) { + mSliceInfos[Is] = soa::getSliceInfoFor>>>(mIndexColumns[Is], *cache); + } + }(), + ...); } template @@ -169,49 +181,67 @@ struct GroupedCombinationsGenerator { if (std::get(*mAssociated).size() == 0) { return std::get(*mAssociated); } - return std::get(*mAssociated).sliceByCached(mIndexColumns[I], ind, *cache); + return soa::doSliceByCached(&std::get(*mAssociated), mSliceInfos[I], ind); } void setCurrentGroupedCombination() { if (!this->mIsEnd) { - auto& currentGrouping = GroupingPolicy::mCurrent; - mSlices.emplace(getAssociatedTables()); - mCurrentGrouped.emplace(interleaveTuples(currentGrouping, *mSlices)); + emplaceCurrentGrouped(std::make_index_sequence()); } } + /// Make the current combination: the grouping elements interleaved with the + /// slices of the associated tables. Each slice is made by a conversion + /// function when its element of the combination is initialized, so that it + /// is made in place rather than moved there. + template + void emplaceCurrentGrouped(std::index_sequence) + { + std::apply([this](auto&&... elements) { mCurrentGrouped.emplace(std::forward(elements)...); }, + std::tuple_cat(std::forward_as_tuple(std::get(GroupingPolicy::mCurrent), + makeSliceOnConversion())...)); + } + + template + auto makeSliceOnConversion() + { + using slice_t = std::tuple_element_t<2 * I + 1, GroupedIteratorType>; + auto make = [this]() { return getAssociatedTable(); }; + return detail::MakeOnConversion{make}; + } + std::array mIndexColumns; + std::array mSliceInfos; std::shared_ptr mGrouping; std::shared_ptr> mAssociated; - std::optional> mSlices; std::optional mCurrentGrouped; SliceCache* cache = nullptr; }; using iterator = GroupedIterator; using const_iterator = GroupedIterator; + using sentinel = GroupedSentinel; inline iterator begin() { return iterator(mBegin); } - inline iterator end() + inline sentinel end() { - return iterator(mEnd); + return {}; } inline const_iterator begin() const { return iterator(mBegin); } - inline const_iterator end() const + inline sentinel end() const { - return iterator(mEnd); + return {}; } GroupedCombinationsGenerator(const BP& binningPolicy, int catNeighbours, const T1& outsider, SliceCache* cache) - : mBegin(GroupingPolicy(binningPolicy, catNeighbours, outsider), cache), - mEnd(GroupingPolicy(binningPolicy, catNeighbours, outsider), cache) {} + : mBegin(GroupingPolicy(binningPolicy, catNeighbours, outsider), cache) {} template GroupedCombinationsGenerator(const BP& binningPolicy, int catNeighbours, const T1& outsider, const G& grouping, const std::tuple& associated, SliceCache* cache) : GroupedCombinationsGenerator(binningPolicy, catNeighbours, outsider, cache) @@ -226,13 +256,10 @@ struct GroupedCombinationsGenerator { void setTables(const G& grouping, const std::tuple& associated) { mBegin.setTables(grouping, associated); - mEnd.setTables(grouping, associated); - mEnd.moveToEnd(); } private: iterator mBegin; - iterator mEnd; }; template @@ -240,7 +267,8 @@ concept is_combinations_generator = requires(T t, typename T::g_t const& g, pack typename T::GroupedIterator; t.setTables(g, a); { t.begin() } -> std::same_as; - { t.end() } -> std::same_as; + { t.end() } -> std::same_as; + { t.begin() != t.end() } -> std::convertible_to; }; // Aliases for 2-particle correlations diff --git a/Framework/Core/src/ASoA.cxx b/Framework/Core/src/ASoA.cxx index 9c0821dbd0462..558d1a496d80b 100644 --- a/Framework/Core/src/ASoA.cxx +++ b/Framework/Core/src/ASoA.cxx @@ -216,22 +216,30 @@ o2::soa::ArrowTableRef ArrowHelpers::concatTables(std::vector(resultFields), columns)}; } -arrow::ChunkedArray* getIndexFromLabel(arrow::Table* table, std::string_view label) +int getPositionFromLabel(arrow::Table* table, std::string_view label) { - // Take the exact-match common case first (string_view comparison checks length - // then memcmp), and fall back to a case-insensitive scan only when the labels - // differ in case. auto field = std::ranges::find_if(table->schema()->fields(), [label](std::shared_ptr const& f) { - std::string_view name = f->name(); - return label == name || - std::ranges::equal(label, name, [](char c1, char c2) { - return asciiToLower(c1) == asciiToLower(c2); - }); + return labelMatches(label, f->name()); }); if (field == table->schema()->fields().end()) { o2::framework::throw_error(o2::framework::runtime_error_f("Unable to find column with label %s.", label)); } - return table->column(std::distance(table->schema()->fields().begin(), field)).get(); + return static_cast(std::distance(table->schema()->fields().begin(), field)); +} + +arrow::ChunkedArray* getIndexFromLabel(arrow::Table* table, std::string_view label) +{ + return table->column(getPositionFromLabel(table, label)).get(); +} + +void parentTableMismatch(const char* tableName) +{ + throw o2::framework::runtime_error_f("Table %s can only reuse the columns of a parent table that refers to the same arrow table.", tableName); +} + +void incompatibleFilteredRanges(const char* tableName) +{ + throw o2::framework::runtime_error_f("Filtered %s tables cover different row ranges and their selections cannot be combined.", tableName); } void notBoundTable(const char* tableName) diff --git a/Framework/Core/src/ArrowTableSlicingCache.cxx b/Framework/Core/src/ArrowTableSlicingCache.cxx index 7b96b7c0c0e85..54dcbff8bf1dd 100644 --- a/Framework/Core/src/ArrowTableSlicingCache.cxx +++ b/Framework/Core/src/ArrowTableSlicingCache.cxx @@ -111,6 +111,8 @@ void ArrowTableSlicingCache::setCaches(Cache&& bsks, Cache&& bsksUnsorted) valuesUnsorted.resize(bindingsKeysUnsorted.size()); groups.clear(); groups.resize(bindingsKeysUnsorted.size()); + mKnownPositions.clear(); + mKnownPositionsUnsorted.clear(); } arrow::Status ArrowTableSlicingCache::updateCacheEntry(int pos, std::shared_ptr const& table) @@ -235,7 +237,7 @@ int ArrowTableSlicingCache::getCachePosUnsortedFor(Entry const& bindingKey) cons } return -1; } -SliceInfoPtr ArrowTableSlicingCache::getCacheFor(Entry const& bindingKey) const +int ArrowTableSlicingCache::locateSorted(Entry const& bindingKey) const { auto [p, s] = getCachePos(bindingKey); if (!s) { @@ -244,11 +246,10 @@ SliceInfoPtr ArrowTableSlicingCache::getCacheFor(Entry const& bindingKey) const if (!bindingsKeys[p].enabled) { throw runtime_error_f("Disabled cache %s/%s is requested", bindingKey.binding.c_str(), bindingKey.key.c_str()); } - - return getCacheForPos(p); + return p; } -SliceInfoUnsortedPtr ArrowTableSlicingCache::getCacheUnsortedFor(const Entry& bindingKey) const +int ArrowTableSlicingCache::locateUnsorted(Entry const& bindingKey) const { auto [p, s] = getCachePos(bindingKey); if (s) { @@ -257,8 +258,50 @@ SliceInfoUnsortedPtr ArrowTableSlicingCache::getCacheUnsortedFor(const Entry& bi if (!bindingsKeysUnsorted[p].enabled) { throw runtime_error_f("Disabled unsorted cache (%s) %s/%s is requested", DataSpecUtils::describe(bindingKey.matcher).c_str(), bindingKey.binding.c_str(), bindingKey.key.c_str()); } + return p; +} + +namespace +{ +int findKnown(std::vector> const& known, uint64_t key) +{ + for (auto const& [k, p] : known) { + if (k == key) { + return p; + } + } + return -1; +} +} // namespace + +int ArrowTableSlicingCache::knownPosition(uint64_t key) const +{ + return findKnown(mKnownPositions, key); +} - return getCacheUnsortedForPos(p); +int ArrowTableSlicingCache::knownPositionUnsorted(uint64_t key) const +{ + return findKnown(mKnownPositionsUnsorted, key); +} + +void ArrowTableSlicingCache::rememberPosition(uint64_t key, int pos) const +{ + mKnownPositions.emplace_back(key, pos); +} + +void ArrowTableSlicingCache::rememberPositionUnsorted(uint64_t key, int pos) const +{ + mKnownPositionsUnsorted.emplace_back(key, pos); +} + +SliceInfoPtr ArrowTableSlicingCache::getCacheFor(Entry const& bindingKey) const +{ + return getCacheForPos(locateSorted(bindingKey)); +} + +SliceInfoUnsortedPtr ArrowTableSlicingCache::getCacheUnsortedFor(const Entry& bindingKey) const +{ + return getCacheUnsortedForPos(locateUnsorted(bindingKey)); } SliceInfoPtr ArrowTableSlicingCache::getCacheForPos(int pos) const diff --git a/Framework/Core/test/benchmark_ASoA.cxx b/Framework/Core/test/benchmark_ASoA.cxx index 4001e2a725a15..c83f7b5829265 100644 --- a/Framework/Core/test/benchmark_ASoA.cxx +++ b/Framework/Core/test/benchmark_ASoA.cxx @@ -15,6 +15,7 @@ #include #include #include +#include using namespace o2::framework; using namespace arrow; @@ -33,6 +34,13 @@ DECLARE_SOA_DYNAMIC_COLUMN(SumFreeArgs, sumFreeArgs, [](float x, float y, float } // namespace test DECLARE_SOA_TABLE(TestTable, "AOD", "TESTTBL", test::X, test::Y, test::Z, test::Sum); + +namespace test +{ +DECLARE_SOA_COLUMN_FULL(W, w, float, "w"); +} // namespace test + +DECLARE_SOA_TABLE(TestTableW, "AOD", "TESTTBLW", test::W); } // namespace o2::aod #ifdef __APPLE__ @@ -377,4 +385,111 @@ static void BM_ASoADynamicColumnCallGetGetterByLabel(benchmark::State& state) } BENCHMARK(BM_ASoADynamicColumnCallGetGetterByLabel)->Range(8, 8 << maxrange); +// Copies of table iterators: a wide table, as each column of an iterator is copied and bound +namespace +{ +std::shared_ptr makeTracks(int64_t n) +{ + std::default_random_engine e1(1234567891); + std::uniform_real_distribution uniform_dist(0, 1); + TableBuilder builder; + auto rowWriter = builder.cursor(); + for (auto i = 0; i < n; ++i) { + rowWriter(0, i, 0, uniform_dist(e1), uniform_dist(e1), uniform_dist(e1), + uniform_dist(e1), uniform_dist(e1), uniform_dist(e1), uniform_dist(e1)); + } + return builder.finalize(); +} + +SelectionVector allRows(int64_t n) +{ + SelectionVector rows(n); + std::iota(rows.begin(), rows.end(), 0); + return rows; +} +} // namespace + +// Copy assignment of an iterator +static void BM_ASoAIteratorAssign(benchmark::State& state) +{ + o2::aod::StoredTracks tracks{makeTracks(state.range(0))}; + auto target = tracks.begin(); + auto source = tracks.begin(); + + for (auto _ : state) { + float sum = 0; + for (auto i = 0; i < state.range(0); ++i) { + source.setCursor(i); + target = source; + sum += target.x(); + } + benchmark::DoNotOptimize(sum); + } + state.SetItemsProcessed(state.iterations() * state.range(0)); +} + +BENCHMARK(BM_ASoAIteratorAssign)->Arg(1 << 14); + +// Assignment of a filtered iterator to an unfiltered one +static void BM_ASoAFilteredToUnfilteredAssign(benchmark::State& state) +{ + auto table = makeTracks(state.range(0)); + o2::aod::StoredTracks tracks{table}; + Filtered filtered{{table}, allRows(state.range(0))}; + auto target = tracks.begin(); + + for (auto _ : state) { + float sum = 0; + for (auto const& row : filtered) { + target = row; + sum += target.x(); + } + benchmark::DoNotOptimize(sum); + } + state.SetItemsProcessed(state.iterations() * state.range(0)); +} + +BENCHMARK(BM_ASoAFilteredToUnfilteredAssign)->Arg(1 << 14); + +// Access by row number to a filtered table, as for an index to it +static void BM_ASoAFilteredRawIteratorAt(benchmark::State& state) +{ + auto table = makeTracks(state.range(0)); + Filtered filtered{{table}, allRows(state.range(0))}; + + for (auto _ : state) { + float sum = 0; + for (auto i = 0; i < state.range(0); ++i) { + sum += filtered.rawIteratorAt(i).x(); + } + benchmark::DoNotOptimize(sum); + } + state.SetItemsProcessed(state.iterations() * state.range(0)); +} + +BENCHMARK(BM_ASoAFilteredRawIteratorAt)->Arg(1 << 14); + +// The begin iterator of a join +static void BM_ASoAJoinBegin(benchmark::State& state) +{ + auto table = makeTracks(state.range(0)); + TableBuilder builder; + auto rowWriter = builder.cursor(); + for (auto i = 0; i < state.range(0); ++i) { + rowWriter(0, 1.f); + } + Join joined{{ArrowTableRef{table}, ArrowTableRef{builder.finalize()}}}; + + for (auto _ : state) { + float sum = 0; + for (auto i = 0; i < state.range(0); ++i) { + sum += joined.begin().x(); + } + benchmark::DoNotOptimize(sum); + } + state.SetItemsProcessed(state.iterations() * state.range(0)); +} + +BENCHMARK(BM_ASoAJoinBegin)->Arg(1 << 14); + BENCHMARK_MAIN(); diff --git a/Framework/Core/test/benchmark_EventMixing.cxx b/Framework/Core/test/benchmark_EventMixing.cxx index 0e7e6839ee35e..986b7e756048b 100644 --- a/Framework/Core/test/benchmark_EventMixing.cxx +++ b/Framework/Core/test/benchmark_EventMixing.cxx @@ -14,6 +14,7 @@ #include "Framework/TableBuilder.h" #include "Framework/AnalysisDataModel.h" #include +#include #include #include #include @@ -66,11 +67,18 @@ static void BM_EventMixingTraditional(benchmark::State& state) } auto tableCol = colBuilder.finalize(); o2::aod::Collisions collisions{tableCol}; - std::uniform_int_distribution uniform_dist_col_ind(0, collisions.size()); + std::uniform_int_distribution uniform_dist_col_ind(0, collisions.size() - 1); + + // the slice cache requires tracks sorted by collision index + std::vector colIndices(numTracksPerEvent * state.range(0)); + for (auto& colIndex : colIndices) { + colIndex = uniform_dist_col_ind(e1); + } + std::sort(colIndices.begin(), colIndices.end()); auto rowWriterTrack = trackBuilder.cursor(); - for (auto i = 0; i < numTracksPerEvent * state.range(0); ++i) { - rowWriterTrack(0, uniform_dist_col_ind(e1), 0, + for (auto colIndex : colIndices) { + rowWriterTrack(0, colIndex, 0, uniform_dist(e1), uniform_dist(e1), uniform_dist(e1), uniform_dist(e1), uniform_dist(e1), uniform_dist(e1), uniform_dist(e1)); @@ -158,11 +166,18 @@ static void BM_EventMixingCombinations(benchmark::State& state) } auto tableCol = colBuilder.finalize(); o2::aod::Collisions collisions{tableCol}; - std::uniform_int_distribution uniform_dist_col_ind(0, collisions.size()); + std::uniform_int_distribution uniform_dist_col_ind(0, collisions.size() - 1); + + // the slice cache requires tracks sorted by collision index + std::vector colIndices(numTracksPerEvent * state.range(0)); + for (auto& colIndex : colIndices) { + colIndex = uniform_dist_col_ind(e1); + } + std::sort(colIndices.begin(), colIndices.end()); auto rowWriterTrack = trackBuilder.cursor(); - for (auto i = 0; i < numTracksPerEvent * state.range(0); ++i) { - rowWriterTrack(0, uniform_dist_col_ind(e1), 0, + for (auto colIndex : colIndices) { + rowWriterTrack(0, colIndex, 0, uniform_dist(e1), uniform_dist(e1), uniform_dist(e1), uniform_dist(e1), uniform_dist(e1), uniform_dist(e1), uniform_dist(e1)); @@ -172,7 +187,7 @@ static void BM_EventMixingCombinations(benchmark::State& state) int64_t count = 0; int64_t colCount = 0; - std::string key = "fIndex" + getLabelFromType(); + std::string key = "fIndex" + cutString(getLabelFromType()); ArrowTableSlicingCache atscache{{{getLabelFromType(), getMatcherFromTypeForKey(key), key}}}; auto s = atscache.updateCacheEntry(0, tableTrack); SliceCache cache{&atscache}; @@ -200,4 +215,84 @@ static void BM_EventMixingCombinations(benchmark::State& state) BENCHMARK(BM_EventMixingCombinations)->RangeMultiplier(2)->Range(4, 8 << maxPairsRange); +// Overhead of the grouped generator alone: many collisions, few tracks and no +// track pairs, so that setTables() and the per-step iterator cost dominate. +// ExplicitLoop compares against end() on every step, as many analyses do. +template +static void BM_EventMixingGeneratorOnly(benchmark::State& state) +{ + constexpr int numTracksPerEventSmall = 2; + std::default_random_engine e1(1234567891); + std::uniform_real_distribution uniform_dist(0.f, 1.f); + std::uniform_real_distribution uniform_dist_x(-0.065f, 0.073f); + std::uniform_real_distribution uniform_dist_y(-0.320f, 0.360f); + std::uniform_int_distribution uniform_dist_int(0, 5); + + std::vector xBins{VARIABLE_WIDTH, -0.064, -0.062, -0.060, 0.066, 0.068, 0.070, 0.072}; + std::vector yBins{VARIABLE_WIDTH, -0.320, -0.301, -0.300, 0.330, 0.340, 0.350, 0.360}; + using BinningType = ColumnBinningPolicy; + BinningType binningOnPositions{{xBins, yBins}, true}; + + TableBuilder colBuilder, trackBuilder; + auto rowWriterCol = colBuilder.cursor(); + for (auto i = 0; i < state.range(0); ++i) { + float x = uniform_dist_x(e1); + float y = uniform_dist_y(e1); + rowWriterCol(0, uniform_dist_int(e1), + x, y, uniform_dist(e1), + uniform_dist(e1), uniform_dist(e1), uniform_dist(e1), + uniform_dist(e1), uniform_dist(e1), uniform_dist(e1), + uniform_dist_int(e1), uniform_dist(e1), + uniform_dist_int(e1), + uniform_dist(e1), uniform_dist(e1)); + } + auto tableCol = colBuilder.finalize(); + o2::aod::Collisions collisions{tableCol}; + + auto rowWriterTrack = trackBuilder.cursor(); + for (auto colIndex = 0; colIndex < collisions.size(); ++colIndex) { + for (auto j = 0; j < numTracksPerEventSmall; ++j) { + rowWriterTrack(0, colIndex, 0, + uniform_dist(e1), uniform_dist(e1), uniform_dist(e1), + uniform_dist(e1), uniform_dist(e1), uniform_dist(e1), + uniform_dist(e1)); + } + } + auto tableTrack = trackBuilder.finalize(); + o2::aod::StoredTracks tracks{tableTrack}; + + std::string key = "fIndex" + cutString(getLabelFromType()); + ArrowTableSlicingCache atscache{{{getLabelFromType(), getMatcherFromTypeForKey(key), key}}}; + auto s = atscache.updateCacheEntry(0, tableTrack); + SliceCache cache{&atscache}; + + int64_t colCount = 0; + int64_t trackCount = 0; + for (auto _ : state) { + colCount = 0; + trackCount = 0; + auto tracksTuple = std::make_tuple(tracks); + SameKindPair pair{binningOnPositions, numEventsToMix - 1, -1, collisions, tracksTuple, &cache}; + if constexpr (ExplicitLoop) { + for (auto it = pair.begin(); it != pair.end(); ++it) { + auto& [c1, tracks1, c2, tracks2] = *it; + trackCount += tracks1.size() + tracks2.size(); + colCount++; + } + } else { + for (auto& [c1, tracks1, c2, tracks2] : pair) { + trackCount += tracks1.size() + tracks2.size(); + colCount++; + } + } + benchmark::DoNotOptimize(colCount); + benchmark::DoNotOptimize(trackCount); + } + state.counters["Mixed collision pairs"] = colCount; + state.counters["Pairs/s"] = benchmark::Counter(static_cast(colCount) * state.iterations(), benchmark::Counter::kIsRate); +} + +BENCHMARK_TEMPLATE(BM_EventMixingGeneratorOnly, false)->RangeMultiplier(4)->Range(256, 4096); +BENCHMARK_TEMPLATE(BM_EventMixingGeneratorOnly, true)->RangeMultiplier(4)->Range(256, 4096); + BENCHMARK_MAIN(); diff --git a/Framework/Core/test/benchmark_SparseSlicing.cxx b/Framework/Core/test/benchmark_SparseSlicing.cxx new file mode 100644 index 0000000000000..2dc894dc19770 --- /dev/null +++ b/Framework/Core/test/benchmark_SparseSlicing.cxx @@ -0,0 +1,504 @@ +// Copyright 2019-2020 CERN and copyright holders of ALICE O2. +// See https://alice-o2.web.cern.ch/copyright for details of the copyright holders. +// All rights not expressly granted are reserved. +// +// This software is distributed under the terms of the GNU General Public +// License v3 (GPL Version 3), copied verbatim in the file "COPYING". +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include "Framework/ASoAHelpers.h" +#include "Framework/GroupedCombinations.h" +#include "Framework/GroupSlicer.h" +#include "Framework/TableBuilder.h" +#include "Framework/AnalysisDataModel.h" +#include +#include +#include + +namespace o2::aod +{ +// A table with no index to collisions, so GroupSlicer passes it whole +namespace unrelated +{ +DECLARE_SOA_COLUMN(A, a, float); +DECLARE_SOA_COLUMN(B, b, float); +DECLARE_SOA_COLUMN(C, c, float); +DECLARE_SOA_COLUMN(D, d, float); +DECLARE_SOA_COLUMN(E, e, float); +DECLARE_SOA_COLUMN(F, f, float); +DECLARE_SOA_COLUMN(G, g, float); +DECLARE_SOA_COLUMN(H, h, float); +} // namespace unrelated +DECLARE_SOA_TABLE(Unrelated, "AOD", "UNRELATED", unrelated::A, unrelated::B, unrelated::C, unrelated::D, + unrelated::E, unrelated::F, unrelated::G, unrelated::H); +} // namespace o2::aod + +using namespace o2::framework; +using namespace o2::soa; + +// Derived-data-like input: many collisions, and tracks in only a few of them. +// Per-collision slicing then produces mostly empty tables, so the cost of +// making a table dominates over the cost of iterating its rows. + +namespace +{ +constexpr int64_t defaultCollisionsPerTrack = 100; // 1% of the collisions have a track + +using BinningType = ColumnBinningPolicy; + +struct SparseData { + std::shared_ptr collisionTable; + std::shared_ptr trackTable; + std::shared_ptr unrelatedTable; + ArrowTableSlicingCache slicingCache; + SliceCache cache{nullptr}; + // The same index registered as unsorted: a key can be in only one of the + // lists of a cache, as the sorted list is searched first + ArrowTableSlicingCache unsortedSlicingCache; + SliceCache unsortedCache{nullptr}; + + explicit SparseData(int64_t nCollisions, int64_t collisionsPerTrack = defaultCollisionsPerTrack) + : slicingCache{{{getLabelFromType(), + getMatcherFromTypeForKey(key()), key()}}}, + unsortedSlicingCache{{}, {{getLabelFromType(), getMatcherFromTypeForKey(key()), key()}}} + { + std::default_random_engine e1(1234567891); + std::uniform_real_distribution uniform_dist(0.f, 1.f); + std::uniform_real_distribution uniform_dist_x(-0.065f, 0.073f); + std::uniform_real_distribution uniform_dist_y(-0.320f, 0.360f); + std::uniform_int_distribution uniform_dist_int(0, 5); + + TableBuilder colBuilder; + auto rowWriterCol = colBuilder.cursor(); + for (auto i = 0; i < nCollisions; ++i) { + rowWriterCol(0, uniform_dist_int(e1), + uniform_dist_x(e1), uniform_dist_y(e1), uniform_dist(e1), + uniform_dist(e1), uniform_dist(e1), uniform_dist(e1), + uniform_dist(e1), uniform_dist(e1), uniform_dist(e1), + uniform_dist_int(e1), uniform_dist(e1), + uniform_dist_int(e1), + uniform_dist(e1), uniform_dist(e1)); + } + collisionTable = colBuilder.finalize(); + + TableBuilder trackBuilder; + auto rowWriterTrack = trackBuilder.cursor(); + for (auto colIndex = 0; colIndex < nCollisions; colIndex += collisionsPerTrack) { + rowWriterTrack(0, colIndex, 0, + uniform_dist(e1), uniform_dist(e1), uniform_dist(e1), + uniform_dist(e1), uniform_dist(e1), uniform_dist(e1), + uniform_dist(e1)); + } + trackTable = trackBuilder.finalize(); + + TableBuilder unrelatedBuilder; + auto rowWriterUnrelated = unrelatedBuilder.cursor(); + for (auto i = 0; i < 100; ++i) { + rowWriterUnrelated(0, uniform_dist(e1), uniform_dist(e1), uniform_dist(e1), uniform_dist(e1), + uniform_dist(e1), uniform_dist(e1), uniform_dist(e1), uniform_dist(e1)); + } + unrelatedTable = unrelatedBuilder.finalize(); + + auto s = slicingCache.updateCacheEntry(0, trackTable); + cache = SliceCache{&slicingCache}; + auto su = unsortedSlicingCache.updateCacheEntryUnsorted(0, trackTable); + unsortedCache = SliceCache{&unsortedSlicingCache}; + } + + static std::string key() + { + return "fIndex" + cutString(getLabelFromType()); + } +}; + +void setCounters(benchmark::State& state, int64_t slices, int64_t rows) +{ + state.counters["Slices"] = static_cast(slices); + state.counters["Rows"] = static_cast(rows); + state.counters["Slices/s"] = benchmark::Counter(static_cast(slices) * state.iterations(), benchmark::Counter::kIsRate); +} +} // namespace + +// The path of a process(Collision const&, Tracks const&) signature: the slices +// are passed to the invoked function directly, as AnalysisTask does +static void BM_SparseGroupSlicer(benchmark::State& state) +{ + SparseData data(state.range(0)); + o2::aod::Collisions collisions{data.collisionTable}; + o2::aod::StoredTracks tracks{data.trackTable}; + auto associated = std::make_tuple(tracks); + + int64_t slices = 0; + int64_t rows = 0; + for (auto _ : state) { + slices = 0; + rows = 0; + GroupSlicer slicer(collisions, associated, data.slicingCache); + for (auto& slice : slicer) { + [&](auto&&... tables) { + (tables.bindInternalIndicesTo(&std::get>(associated)), ...); + rows += (tables.size() + ...); + }(slice.template prepareArgument()); + ++slices; + } + benchmark::DoNotOptimize(rows); + } + setCounters(state, slices, rows); +} + +BENCHMARK(BM_SparseGroupSlicer)->RangeMultiplier(8)->Range(1 << 10, 1 << 16); + +// The same with a second associated table that has no index to collisions, +// as in process(Collision const&, Tracks const&, Unrelated const&): GroupSlicer +// passes that table whole for every collision +static void BM_SparseGroupSlicerUnrelated(benchmark::State& state) +{ + SparseData data(state.range(0)); + o2::aod::Collisions collisions{data.collisionTable}; + o2::aod::StoredTracks tracks{data.trackTable}; + o2::aod::Unrelated unrelated{data.unrelatedTable}; + auto associated = std::make_tuple(tracks, unrelated); + + int64_t slices = 0; + int64_t rows = 0; + for (auto _ : state) { + slices = 0; + rows = 0; + GroupSlicer slicer(collisions, associated, data.slicingCache); + for (auto& slice : slicer) { + [&](auto&&... tables) { + (tables.bindInternalIndicesTo(&std::get>(associated)), ...); + rows += (tables.size() + ...); + }(slice.template prepareArgument(), slice.template prepareArgument()); + ++slices; + } + benchmark::DoNotOptimize(rows); + } + setCounters(state, slices, rows); +} + +BENCHMARK(BM_SparseGroupSlicerUnrelated)->RangeMultiplier(8)->Range(1 << 10, 1 << 16); + +// The path of a process(Collision const&, SmallGroups const&) signature: +// the tracks are sliced through the unsorted cache. All tracks are selected, so +// the slices view the rows of each group in the slicing cache. +// The second argument is the number of collisions per track: 100 is the sparse +// case, 1 gives every collision a track, so that every group has rows. +template +void runGroupSlicerSmallGroups(benchmark::State& state, T const& tracks, SparseData& data) +{ + o2::aod::Collisions collisions{data.collisionTable}; + auto associated = std::make_tuple(tracks); + + int64_t slices = 0; + int64_t rows = 0; + for (auto _ : state) { + slices = 0; + rows = 0; + GroupSlicer slicer(collisions, associated, data.unsortedSlicingCache); + for (auto& slice : slicer) { + [&](auto&&... tables) { + (tables.bindInternalIndicesTo(&std::get>(associated)), ...); + rows += (tables.size() + ...); + }(slice.template prepareArgument()); + ++slices; + } + benchmark::DoNotOptimize(rows); + } + setCounters(state, slices, rows); +} + +static void BM_SparseGroupSlicerSmallGroups(benchmark::State& state) +{ + SparseData data(state.range(0), state.range(1)); + SelectionVector all(data.trackTable->num_rows()); + std::iota(all.begin(), all.end(), 0); + SmallGroups tracks{{data.trackTable}, std::move(all)}; + runGroupSlicerSmallGroups(state, tracks, data); +} + +BENCHMARK(BM_SparseGroupSlicerSmallGroups)->ArgsProduct({benchmark::CreateRange(1 << 10, 1 << 16, 8), {defaultCollisionsPerTrack, 1}}); + +// The same with a filter that rejects every other track: the rows of each group +// are intersected with the selection of the full table into a new selection +static void BM_SparseGroupSlicerSmallGroupsPartial(benchmark::State& state) +{ + SparseData data(state.range(0), state.range(1)); + SelectionVector half; + for (int64_t i = 0; i < data.trackTable->num_rows(); i += 2) { + half.push_back(i); + } + SmallGroups tracks{{data.trackTable}, std::move(half)}; + runGroupSlicerSmallGroups(state, tracks, data); +} + +BENCHMARK(BM_SparseGroupSlicerSmallGroupsPartial)->ArgsProduct({benchmark::CreateRange(1 << 10, 1 << 16, 8), {defaultCollisionsPerTrack, 1}}); + +// The same with SmallGroupsUnfiltered, or SmallGroups with no selection on the +// full table: the slices view the rows of each group in the slicing cache +static void BM_SparseGroupSlicerSmallGroupsUnfiltered(benchmark::State& state) +{ + SparseData data(state.range(0), state.range(1)); + SmallGroupsUnfiltered tracks{{data.trackTable}, SelectionVector{}}; + runGroupSlicerSmallGroups(state, tracks, data); +} + +BENCHMARK(BM_SparseGroupSlicerSmallGroupsUnfiltered)->ArgsProduct({benchmark::CreateRange(1 << 10, 1 << 16, 8), {defaultCollisionsPerTrack, 1}}); + +static void BM_SparseSliceByCached(benchmark::State& state) +{ + SparseData data(state.range(0)); + o2::aod::Collisions collisions{data.collisionTable}; + o2::aod::StoredTracks tracks{data.trackTable}; + + int64_t slices = 0; + int64_t rows = 0; + for (auto _ : state) { + slices = 0; + rows = 0; + for (auto const& collision : collisions) { + auto slice = tracks.sliceByCached(o2::aod::track::collisionId, collision.globalIndex(), data.cache); + rows += slice.size(); + ++slices; + } + benchmark::DoNotOptimize(rows); + } + setCounters(state, slices, rows); +} + +BENCHMARK(BM_SparseSliceByCached)->RangeMultiplier(8)->Range(1 << 10, 1 << 16); + +static void BM_SparseFilteredSliceByCached(benchmark::State& state) +{ + SparseData data(state.range(0)); + o2::aod::Collisions collisions{data.collisionTable}; + SelectionVector all(data.trackTable->num_rows()); + std::iota(all.begin(), all.end(), 0); + Filtered tracks{{data.trackTable}, std::move(all)}; + + int64_t slices = 0; + int64_t rows = 0; + for (auto _ : state) { + slices = 0; + rows = 0; + for (auto const& collision : collisions) { + auto slice = tracks.sliceByCached(o2::aod::track::collisionId, collision.globalIndex(), data.cache); + rows += slice.size(); + ++slices; + } + benchmark::DoNotOptimize(rows); + } + setCounters(state, slices, rows); +} + +BENCHMARK(BM_SparseFilteredSliceByCached)->RangeMultiplier(8)->Range(1 << 10, 1 << 16); + +// Slicing with a sorted Preslice, as a task does with sliceBy +static void BM_SparseSliceBy(benchmark::State& state) +{ + SparseData data(state.range(0)); + o2::aod::Collisions collisions{data.collisionTable}; + o2::aod::StoredTracks tracks{data.trackTable}; + Preslice perCollision = o2::aod::track::collisionId; + perCollision.updateSliceInfo(data.slicingCache.getCacheFor(perCollision.getBindingKey())); + + int64_t slices = 0; + int64_t rows = 0; + for (auto _ : state) { + slices = 0; + rows = 0; + for (auto const& collision : collisions) { + auto slice = tracks.sliceBy(perCollision, collision.globalIndex()); + rows += slice.size(); + ++slices; + } + benchmark::DoNotOptimize(rows); + } + setCounters(state, slices, rows); +} + +BENCHMARK(BM_SparseSliceBy)->RangeMultiplier(8)->Range(1 << 10, 1 << 16); + +static void BM_SparseFilteredSliceBy(benchmark::State& state) +{ + SparseData data(state.range(0)); + o2::aod::Collisions collisions{data.collisionTable}; + SelectionVector all(data.trackTable->num_rows()); + std::iota(all.begin(), all.end(), 0); + Filtered tracks{{data.trackTable}, std::move(all)}; + Preslice perCollision = o2::aod::track::collisionId; + perCollision.updateSliceInfo(data.slicingCache.getCacheFor(perCollision.getBindingKey())); + + int64_t slices = 0; + int64_t rows = 0; + for (auto _ : state) { + slices = 0; + rows = 0; + for (auto const& collision : collisions) { + auto slice = tracks.sliceBy(perCollision, collision.globalIndex()); + rows += slice.size(); + ++slices; + } + benchmark::DoNotOptimize(rows); + } + setCounters(state, slices, rows); +} + +BENCHMARK(BM_SparseFilteredSliceBy)->RangeMultiplier(8)->Range(1 << 10, 1 << 16); + +// Slicing with an unsorted Preslice: the slices are filtered tables +static void BM_SparseSliceByUnsorted(benchmark::State& state) +{ + SparseData data(state.range(0)); + o2::aod::Collisions collisions{data.collisionTable}; + o2::aod::StoredTracks tracks{data.trackTable}; + PresliceUnsorted perCollision = o2::aod::track::collisionId; + perCollision.updateSliceInfo(data.unsortedSlicingCache.getCacheUnsortedFor(perCollision.getBindingKey())); + + int64_t slices = 0; + int64_t rows = 0; + for (auto _ : state) { + slices = 0; + rows = 0; + for (auto const& collision : collisions) { + auto slice = tracks.sliceBy(perCollision, collision.globalIndex()); + rows += slice.size(); + ++slices; + } + benchmark::DoNotOptimize(rows); + } + setCounters(state, slices, rows); +} + +BENCHMARK(BM_SparseSliceByUnsorted)->RangeMultiplier(8)->Range(1 << 10, 1 << 16); + +static void BM_SparseFilteredSliceByUnsorted(benchmark::State& state) +{ + SparseData data(state.range(0)); + o2::aod::Collisions collisions{data.collisionTable}; + SelectionVector all(data.trackTable->num_rows()); + std::iota(all.begin(), all.end(), 0); + Filtered tracks{{data.trackTable}, std::move(all)}; + PresliceUnsorted perCollision = o2::aod::track::collisionId; + perCollision.updateSliceInfo(data.unsortedSlicingCache.getCacheUnsortedFor(perCollision.getBindingKey())); + + int64_t slices = 0; + int64_t rows = 0; + for (auto _ : state) { + slices = 0; + rows = 0; + for (auto const& collision : collisions) { + auto slice = tracks.sliceBy(perCollision, collision.globalIndex()); + rows += slice.size(); + ++slices; + } + benchmark::DoNotOptimize(rows); + } + setCounters(state, slices, rows); +} + +BENCHMARK(BM_SparseFilteredSliceByUnsorted)->RangeMultiplier(8)->Range(1 << 10, 1 << 16); + +static void BM_SparseSliceByCachedUnsorted(benchmark::State& state) +{ + SparseData data(state.range(0)); + o2::aod::Collisions collisions{data.collisionTable}; + o2::aod::StoredTracks tracks{data.trackTable}; + + int64_t slices = 0; + int64_t rows = 0; + for (auto _ : state) { + slices = 0; + rows = 0; + for (auto const& collision : collisions) { + auto slice = tracks.sliceByCachedUnsorted(o2::aod::track::collisionId, collision.globalIndex(), data.unsortedCache); + rows += slice.size(); + ++slices; + } + benchmark::DoNotOptimize(rows); + } + setCounters(state, slices, rows); +} + +BENCHMARK(BM_SparseSliceByCachedUnsorted)->RangeMultiplier(8)->Range(1 << 10, 1 << 16); + +static void BM_SparseFilteredSliceByCachedUnsorted(benchmark::State& state) +{ + SparseData data(state.range(0)); + o2::aod::Collisions collisions{data.collisionTable}; + SelectionVector all(data.trackTable->num_rows()); + std::iota(all.begin(), all.end(), 0); + Filtered tracks{{data.trackTable}, std::move(all)}; + + int64_t slices = 0; + int64_t rows = 0; + for (auto _ : state) { + slices = 0; + rows = 0; + for (auto const& collision : collisions) { + auto slice = tracks.sliceByCachedUnsorted(o2::aod::track::collisionId, collision.globalIndex(), data.unsortedCache); + rows += slice.size(); + ++slices; + } + benchmark::DoNotOptimize(rows); + } + setCounters(state, slices, rows); +} + +BENCHMARK(BM_SparseFilteredSliceByCachedUnsorted)->RangeMultiplier(8)->Range(1 << 10, 1 << 16); + +// Event mixing: every collision pair slices the tracks of both collisions +static void BM_SparseMixedPairs(benchmark::State& state) +{ + constexpr int numEventsToMix = 5; + std::vector xBins{VARIABLE_WIDTH, -0.064, -0.062, -0.060, 0.066, 0.068, 0.070, 0.072}; + std::vector yBins{VARIABLE_WIDTH, -0.320, -0.301, -0.300, 0.330, 0.340, 0.350, 0.360}; + BinningType binningOnPositions{{xBins, yBins}, true}; + + SparseData data(state.range(0)); + o2::aod::Collisions collisions{data.collisionTable}; + o2::aod::StoredTracks tracks{data.trackTable}; + + int64_t slices = 0; + int64_t rows = 0; + for (auto _ : state) { + slices = 0; + rows = 0; + auto tracksTuple = std::make_tuple(tracks); + SameKindPair pairs{binningOnPositions, numEventsToMix - 1, -1, collisions, tracksTuple, &data.cache}; + for (auto& [c1, tracks1, c2, tracks2] : pairs) { + rows += tracks1.size() + tracks2.size(); + slices += 2; + } + benchmark::DoNotOptimize(rows); + } + setCounters(state, slices, rows); +} + +BENCHMARK(BM_SparseMixedPairs)->RangeMultiplier(8)->Range(1 << 10, 1 << 13); + +// A table made directly from an arrow table, as for the inputs of every timeframe +static void BM_TableFromArrow(benchmark::State& state) +{ + SparseData data(1 << 10); + int64_t tables = 0; + int64_t rows = 0; + for (auto _ : state) { + tables = 0; + rows = 0; + for (auto i = 0; i < state.range(0); ++i) { + o2::aod::StoredTracks tracks{data.trackTable}; + rows += tracks.size(); + ++tables; + } + benchmark::DoNotOptimize(rows); + } + state.counters["Tables/s"] = benchmark::Counter(static_cast(tables) * state.iterations(), benchmark::Counter::kIsRate); +} + +BENCHMARK(BM_TableFromArrow)->Arg(1 << 12); + +BENCHMARK_MAIN(); diff --git a/Framework/Core/test/test_ASoA.cxx b/Framework/Core/test/test_ASoA.cxx index 40d6e71893a9b..31bc2126d5304 100644 --- a/Framework/Core/test/test_ASoA.cxx +++ b/Framework/Core/test/test_ASoA.cxx @@ -867,7 +867,9 @@ TEST_CASE("TestAdvancedIndices") using Flt = o2::soa::Filtered; expressions::Filter fltx = (o2::aod::test::x <= -6); - Flt f{{tpts1}, expressions::createSelection(tpts1, fltx)}; + // a Filtered table only views a gandiva::Selection: keep it alive while the table is used + auto selectionx = expressions::createSelection(tpts1, fltx); + Flt f{{tpts1}, selectionx}; prt.bindExternalIndices(&f); auto it2 = prt.begin(); diff --git a/Framework/Core/test/test_ASoAHelpers.cxx b/Framework/Core/test/test_ASoAHelpers.cxx index 701dc0bbced50..51b32a44df325 100644 --- a/Framework/Core/test/test_ASoAHelpers.cxx +++ b/Framework/Core/test/test_ASoAHelpers.cxx @@ -72,7 +72,9 @@ TEST_CASE("IteratorTuple") REQUIRE(*(static_cast(std::get<1>(maxOffset2)).getIterator().mCurrentPos) == 8); expressions::Filter filter = test::x > 3; - auto filtered = Filtered{{tests.asArrowTableRef()}, o2::framework::expressions::createSelection(tests.asArrowTable(), filter)}; + // a Filtered table only views a gandiva::Selection: keep it alive while the table is used + auto selection = o2::framework::expressions::createSelection(tests.asArrowTable(), filter); + auto filtered = Filtered{{tests.asArrowTableRef()}, selection}; std::tuple, Filtered> filteredTuple = std::make_tuple(filtered, filtered); auto it1 = std::get<0>(filteredTuple).begin(); @@ -154,7 +156,12 @@ TEST_CASE("CombinationsGeneratorConstruction") REQUIRE(!(comb2.begin() == comb2.end())); - auto endCombination = *(comb2.end()); + // Tested below: a normal iterator moved to the end with moveToEnd(), not end(). + // end() returns a sentinel, which carries no row positions and cannot be dereferenced. + auto endIt = comb2.begin(); + endIt.moveToEnd(); + REQUIRE(endIt == comb2.end()); + auto endCombination = *endIt; REQUIRE(!(static_cast(std::get<0>(endCombination)).getIterator().mCurrentPos == nullptr)); REQUIRE(*(static_cast(std::get<0>(endCombination)).getIterator().mCurrentPos) == 8); REQUIRE(static_cast(std::get<0>(endCombination)).getIterator().mCurrentChunk == 0); @@ -189,7 +196,12 @@ TEST_CASE("CombinationsGeneratorConstruction") REQUIRE(!(comb2Filter.begin() == comb2Filter.end())); - auto endFilterCombination = *(comb2Filter.end()); + // Tested below: a normal iterator moved to the end with moveToEnd(), not end(). + // end() returns a sentinel, which carries no row positions and cannot be dereferenced. + auto endFilterIt = comb2Filter.begin(); + endFilterIt.moveToEnd(); + REQUIRE(endFilterIt == comb2Filter.end()); + auto endFilterCombination = *endFilterIt; REQUIRE(!(static_cast(std::get<0>(endFilterCombination)).getIterator().mCurrentPos == nullptr)); REQUIRE(*(static_cast(std::get<0>(endFilterCombination)).getIterator().mCurrentPos) == -1); REQUIRE(static_cast(std::get<0>(endFilterCombination)).getIterator().mCurrentChunk == 0); @@ -214,7 +226,12 @@ TEST_CASE("CombinationsGeneratorConstruction") // Looks that mCurrentChunk is reset to 0 if an iterator goes too far // (the iterators before the end() have correct chunk numbers) - auto endConcatCombination = *(comb2Concat.end()); + // Tested below: a normal iterator moved to the end with moveToEnd(), not end(). + // end() returns a sentinel, which carries no row positions and cannot be dereferenced. + auto endConcatIt = comb2Concat.begin(); + endConcatIt.moveToEnd(); + REQUIRE(endConcatIt == comb2Concat.end()); + auto endConcatCombination = *endConcatIt; REQUIRE(!(static_cast(std::get<0>(endConcatCombination)).getIterator().mCurrentPos == nullptr)); REQUIRE(*(static_cast(std::get<0>(endConcatCombination)).getIterator().mCurrentPos) == 12); REQUIRE(static_cast(std::get<0>(endConcatCombination)).getIterator().mCurrentChunk == 0); @@ -237,7 +254,12 @@ TEST_CASE("CombinationsGeneratorConstruction") REQUIRE(!(comb2Diff.begin() == comb2Diff.end())); - auto endDiffCombination = *(comb2Diff.end()); + // Tested below: a normal iterator moved to the end with moveToEnd(), not end(). + // end() returns a sentinel, which carries no row positions and cannot be dereferenced. + auto endDiffIt = comb2Diff.begin(); + endDiffIt.moveToEnd(); + REQUIRE(endDiffIt == comb2Diff.end()); + auto endDiffCombination = *endDiffIt; REQUIRE(!(static_cast(std::get<0>(endDiffCombination)).getIterator().mCurrentPos == nullptr)); REQUIRE(*(static_cast(std::get<0>(endDiffCombination)).getIterator().mCurrentPos) == 8); REQUIRE(static_cast(std::get<0>(endDiffCombination)).getIterator().mCurrentChunk == 0); @@ -270,7 +292,12 @@ TEST_CASE("CombinationsGeneratorConstruction") // REQUIRE(comb2Bad.begin() == comb2Bad.end());; - auto endBadCombination = *(comb2Bad.end()); + // Tested below: a normal iterator moved to the end with moveToEnd(), not end(). + // end() returns a sentinel, which carries no row positions and cannot be dereferenced. + auto endBadIt = comb2Bad.begin(); + endBadIt.moveToEnd(); + REQUIRE(endBadIt == comb2Bad.end()); + auto endBadCombination = *endBadIt; REQUIRE(!(static_cast(std::get<0>(endBadCombination)).getIterator().mCurrentPos == nullptr)); REQUIRE(*(static_cast(std::get<0>(endBadCombination)).getIterator().mCurrentPos) == 4); REQUIRE(static_cast(std::get<0>(endBadCombination)).getIterator().mCurrentChunk == 0); @@ -302,7 +329,12 @@ TEST_CASE("CombinationsGeneratorConstruction") REQUIRE(!(combBlock.begin() == combBlock.end())); - auto endBlockCombination = *(combBlock.end()); + // Tested below: a normal iterator moved to the end with moveToEnd(), not end(). + // end() returns a sentinel, which carries no row positions and cannot be dereferenced. + auto endBlockIt = combBlock.begin(); + endBlockIt.moveToEnd(); + REQUIRE(endBlockIt == combBlock.end()); + auto endBlockCombination = *endBlockIt; REQUIRE(!(static_cast(std::get<0>(endBlockCombination)).getIterator().mCurrentPos == nullptr)); REQUIRE(*(static_cast(std::get<0>(endBlockCombination)).getIterator().mCurrentPos) == 8); REQUIRE(static_cast(std::get<0>(endBlockCombination)).getIterator().mCurrentChunk == 0); diff --git a/Framework/Core/test/test_GroupSlicer.cxx b/Framework/Core/test/test_GroupSlicer.cxx index c81acb6c7c85c..c8c420dca4870 100644 --- a/Framework/Core/test/test_GroupSlicer.cxx +++ b/Framework/Core/test/test_GroupSlicer.cxx @@ -123,10 +123,9 @@ TEST_CASE("GroupSlicerOneAssociated") auto count = 0; for (auto& slice : g) { - auto as = slice.associatedTables(); auto gg = slice.groupingElement(); REQUIRE(gg.globalIndex() == count); - auto trks = std::get(as); + auto trks = slice.prepareArgument(); REQUIRE(trks.size() == 10); for (auto& trk : trks) { REQUIRE(trk.eventId() == count); @@ -202,14 +201,13 @@ TEST_CASE("GroupSlicerSeveralAssociated") auto count = 0; for (auto& slice : g) { - auto as = slice.associatedTables(); auto gg = slice.groupingElement(); REQUIRE(gg.globalIndex() == count); - auto trksx = std::get(as); - auto trksy = std::get(as); - auto trksz = std::get(as); + auto trksx = slice.prepareArgument(); + auto trksy = slice.prepareArgument(); + auto trksz = slice.prepareArgument(); - auto trksu = std::get(as); + auto trksu = slice.prepareArgument(); REQUIRE(trksx.size() == 10); REQUIRE(trksy.size() == 20); @@ -263,10 +261,9 @@ TEST_CASE("GroupSlicerMismatchedGroups") o2::framework::GroupSlicer g(e, tt, slices); for (auto& slice : g) { - auto as = slice.associatedTables(); auto gg = slice.groupingElement(); REQUIRE(gg.globalIndex() == (int64_t)slice.position); - auto trks = std::get(as); + auto trks = slice.prepareArgument(); if (slice.position == 3 || slice.position == 10 || slice.position == 12 || slice.position == 16 || slice.position == 19) { REQUIRE(trks.size() == 0); } else { @@ -321,10 +318,9 @@ TEST_CASE("GroupSlicerMismatchedUnassignedGroups") auto count = 0; for (auto& slice : g) { - auto as = slice.associatedTables(); auto gg = slice.groupingElement(); REQUIRE(gg.globalIndex() == count); - auto trks = std::get(as); + auto trks = slice.prepareArgument(); if (count == 3 || count == 10 || count == 12 || count == 16 || count == 19) { REQUIRE(trks.size() == 0); } else { @@ -373,10 +369,9 @@ TEST_CASE("GroupSlicerMismatchedFilteredGroups") auto count = 0; for (auto& slice : g) { - auto as = slice.associatedTables(); auto gg = slice.groupingElement(); REQUIRE(gg.globalIndex() == rows[count]); - auto trks = std::get(as); + auto trks = slice.prepareArgument(); if (rows[count] == 3 || rows[count] == 10 || rows[count] == 12 || rows[count] == 16) { REQUIRE(trks.size() == 0); } else { @@ -435,10 +430,9 @@ TEST_CASE("GroupSlicerMismatchedUnsortedFilteredGroups") unsigned int count = 0; for (auto& slice : g) { - auto as = slice.associatedTables(); auto gg = slice.groupingElement(); REQUIRE(gg.globalIndex() == rows[count]); - auto trks = std::get>(as); + auto trks = slice.prepareArgument>(); if (rows[count] == 3 || rows[count] == 10 || rows[count] == 12 || rows[count] == 16) { REQUIRE(trks.size() == 0); } else { @@ -457,10 +451,9 @@ TEST_CASE("GroupSlicerMismatchedUnsortedFilteredGroups") count = 0; for (auto& slice : ge) { - auto as = slice.associatedTables(); auto gg = slice.groupingElement(); REQUIRE(gg.globalIndex() == rows[count]); - auto trks = std::get>(as); + auto trks = slice.prepareArgument>(); REQUIRE(trks.size() == 0); ++count; } @@ -471,10 +464,9 @@ TEST_CASE("GroupSlicerMismatchedUnsortedFilteredGroups") count = 0; for (auto& slice : gu) { - auto as = slice.associatedTables(); auto gg = slice.groupingElement(); REQUIRE(gg.globalIndex() == rows[count]); - auto trks = std::get>(as); + auto trks = slice.prepareArgument>(); if (rows[count] == 3 || rows[count] == 10 || rows[count] == 12 || rows[count] == 16) { REQUIRE(trks.size() == 0); } else { @@ -563,10 +555,9 @@ TEST_CASE("GroupSlicerMismatchedUnsortedFilteredGroupsWithSelfIndex") // For a grouped case, the recursive access of a slice-self index of a filtered table should have consistent types for (auto& slice : g) { - auto as = slice.associatedTables(); auto gg = slice.groupingElement(); - overwriteInternalIndices(as, associatedTuple); - auto& ts = std::get<1>(as); + auto ts = slice.prepareArgument(); + ts.bindInternalIndicesTo(&std::get(associatedTuple)); ts.bindExternalIndices(&e, &std::get<0>(associatedTuple)); for (auto& thing : ts) { if (thing.has_part()) { @@ -620,9 +611,8 @@ TEST_CASE("EmptySliceables") unsigned int count = 0; for (auto& slice : g) { - auto as = slice.associatedTables(); auto gg = slice.groupingElement(); - auto trks = std::get(as); + auto trks = slice.prepareArgument(); REQUIRE(gg.globalIndex() == count); REQUIRE(trks.size() == 0); ++count;