diff --git a/Framework/Core/CMakeLists.txt b/Framework/Core/CMakeLists.txt index 437dc5ee6478c..219a5d73de7dd 100644 --- a/Framework/Core/CMakeLists.txt +++ b/Framework/Core/CMakeLists.txt @@ -189,6 +189,7 @@ target_include_directories(${targetName} PUBLIC $(); auto sendHistos = [deviceSpec, &context](HistogramRegistry const& self, TNamed* obj) mutable { + // Compact sparse histograms are sent as the equivalent THnSparse, so the output files and + // whatever reads or merges them are unchanged. One at a time, each compact histogram + // freed before its THnSparse is serialised, to keep the memory peak low. + if (auto* compact = dynamic_cast(obj)) { + std::unique_ptr sparse{compact->toTHnSparse()}; + compact->Reset(); + TNamed* named = sparse.get(); + context.outputs().snapshot(self.ref(deviceSpec.inputTimesliceId, deviceSpec.maxInputTimeslices), *named); + return; + } context.outputs().snapshot(self.ref(deviceSpec.inputTimesliceId, deviceSpec.maxInputTimeslices), *obj); }; hr.apply(sendHistos); diff --git a/Framework/Core/include/Framework/BlockSparseArray.h b/Framework/Core/include/Framework/BlockSparseArray.h new file mode 100644 index 0000000000000..4aeccdbc9741b --- /dev/null +++ b/Framework/Core/include/Framework/BlockSparseArray.h @@ -0,0 +1,441 @@ +// Copyright 2019-2026 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. + +#ifndef O2_FRAMEWORK_BLOCKSPARSEARRAY_H_ +#define O2_FRAMEWORK_BLOCKSPARSEARRAY_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace o2::framework +{ + +/// Sparse storage of histogram bin contents (and optionally sum of squared +/// weights), keyed by a linear bin index. +/// +/// The key space is cut into blocks of 2^blockBits consecutive keys. A block +/// keeps its filled bins either +/// - sparse: sorted 16-bit offsets with the contents (and sumw2) alongside, or +/// - dense: the full arrays of the block plus a bitmap of filled bins. +/// A block turns dense once that costs at most `denseFactor` times its sparse +/// form, which bounds the memory per filled bin in both regimes. The blocks in +/// use are found through an open-addressing hash table of block ids, so there +/// is no per-bin hash table: a filled bin in a sparse block costs sizeof(T) + 2 +/// bytes (+8 with sumw2), plus ~32 bytes per block in use for its descriptor. +template +class BlockSparseArray +{ + public: + /// Pointers to the content and sumw2 (nullptr without sumw2) of one bin. + /// Valid until the next insertion of a bin. + struct Ref { + T* v = nullptr; + double* s = nullptr; + explicit operator bool() const { return v != nullptr; } + }; + + /// Position of an iteration over the filled bins (see next()). + struct Cursor { + std::vector ids; // block ids in use, sorted + size_t index = 0; + uint32_t pos = 0; + bool started = false; + }; + + /// keyBits: keys are < 2^keyBits. blockBits in [6, 16]. + /// The default block size, 2^12 keys, keeps the shift of a sorted block on inserting a + /// new bin short (at most ~700 bins before the block turns dense), so filling in random + /// order stays within ~1.5x of THnSparse; larger blocks save little memory. + static constexpr int kDefaultBlockBits = 12; + + explicit BlockSparseArray(int keyBits, int blockBits = kDefaultBlockBits, bool sumw2 = false, double denseFactor = 4.) + : mKeyBits(keyBits), mBlockBits(blockBits), mBlockSize(1u << blockBits), mMask((1u << blockBits) - 1), mSumw2(sumw2), mDenseFactor(denseFactor) + { + if (blockBits < 6 || blockBits > 16) { + throw std::invalid_argument("BlockSparseArray: blockBits must be in [6, 16]"); + } + if (keyBits < 0 || keyBits > 64) { + throw std::invalid_argument("BlockSparseArray: keys must fit in 64 bits"); + } + mPerBin = sizeof(T) + sizeof(uint16_t) + (mSumw2 ? sizeof(double) : 0); + mDenseBytes = size_t(mBlockSize) * (sizeof(T) + (mSumw2 ? sizeof(double) : 0)) + mBlockSize / 8; + mDenseAt = uint32_t(mDenseBytes / (denseFactor * mPerBin)) + 1; + mDenseAt = std::min(std::max(mDenseAt, 8), mBlockSize); + } + BlockSparseArray(const BlockSparseArray&) = delete; + BlockSparseArray& operator=(const BlockSparseArray&) = delete; + ~BlockSparseArray() { clear(); } + + /// content[key] += w, sumw2[key] += w2 (if kept). Keys out of range are ignored. + void add(uint64_t key, T w, double w2) + { + if (Ref r = ref(key, true)) { + *r.v += w; + if (r.s) { + *r.s += w2; + } + } + } + void add(uint64_t key, T w = 1) { add(key, w, double(w) * double(w)); } + + /// The bin `key`: inserted (zero) if `create`, otherwise an empty Ref when not + /// filled. Always an empty Ref for a key out of range. + Ref ref(uint64_t key, bool create) + { + if (!inRange(key)) { + return {}; + } + Block* b = create ? &block(key >> mBlockBits) : findBlock(key >> mBlockBits); + if (!b) { + return {}; + } + uint32_t off = uint32_t(key & mMask); + if (b->cap == kDense) { + uint64_t* bits = denseBits(*b); + uint64_t m = uint64_t(1) << (off & 63); + if (!(bits[off >> 6] & m)) { + if (!create) { + return {}; + } + bits[off >> 6] |= m; + ++b->n; + ++mFilled; + } + return {vals(*b) + off, mSumw2 ? sw2(*b) + off : nullptr}; + } + uint32_t i = b->n ? uint32_t(std::lower_bound(offs(*b), offs(*b) + b->n, uint16_t(off)) - offs(*b)) : 0; + if (i < b->n && offs(*b)[i] == off) { + return {vals(*b) + i, mSumw2 ? sw2(*b) + i : nullptr}; + } + if (!create) { + return {}; + } + if (b->n == b->cap) { + if (b->n + 1 >= mDenseAt) { + densify(*b); + return ref(key, true); + } + grow(*b); + } + uint16_t* o = offs(*b); + T* v = vals(*b); + std::memmove(o + i + 1, o + i, (b->n - i) * sizeof(uint16_t)); + std::memmove(v + i + 1, v + i, (b->n - i) * sizeof(T)); + o[i] = uint16_t(off); + v[i] = T(0); + double* s = nullptr; + if (mSumw2) { + s = sw2(*b); + std::memmove(s + i + 1, s + i, (b->n - i) * sizeof(double)); + s[i] = 0.; + s += i; + } + ++b->n; + ++mFilled; + return {v + i, s}; + } + + /// Content of a bin (0 if not filled or out of range). + T get(uint64_t key) const + { + Ref r = const_cast(this)->ref(key, false); + return r ? *r.v : T(0); + } + /// Sum of squared weights of a bin (0 if not filled, not kept or out of range). + double getSumw2(uint64_t key) const + { + Ref r = const_cast(this)->ref(key, false); + return r.s ? *r.s : 0.; + } + + /// Next filled bin after `c`, in increasing key order. False at the end. + /// No bin may be inserted while iterating. + bool next(Cursor& c, uint64_t& key, T& v, double& s) const + { + if (!c.started) { + c.ids.reserve(mUsed); + for (const auto& slot : mSlots) { + if (slot.id != kEmpty) { + c.ids.push_back(slot.id); + } + } + std::sort(c.ids.begin(), c.ids.end()); + c.started = true; + } + for (; c.index < c.ids.size(); ++c.index, c.pos = 0) { + uint64_t id = c.ids[c.index]; + const Block* b = const_cast(this)->findBlock(id); + if (b->cap == kDense) { + const uint64_t* bits = denseBits(*b); + for (uint32_t off = c.pos; off < mBlockSize;) { + uint64_t m = bits[off >> 6] >> (off & 63); + if (!m) { + off = (off | 63) + 1; + continue; + } + off += uint32_t(std::countr_zero(m)); + key = (id << mBlockBits) + off; + v = vals(*b)[off]; + s = mSumw2 ? sw2(*b)[off] : double(v); + c.pos = off + 1; + return true; + } + } else if (c.pos < b->n) { + key = (id << mBlockBits) + offs(*b)[c.pos]; + v = vals(*b)[c.pos]; + s = mSumw2 ? sw2(*b)[c.pos] : double(v); + ++c.pos; + return true; + } + } + return false; + } + + /// f(key, content, sumw2) for every filled bin, in increasing key order. + /// Without sumw2 the content is passed as sumw2 (Poisson errors). + template + void forEach(F&& f) const + { + Cursor c; + uint64_t k; + T v; + double s; + while (next(c, k, v, s)) { + f(k, v, s); + } + } + + /// this += other (same layout). + void merge(const BlockSparseArray& other) + { + if (other.mBlockBits != mBlockBits || other.mKeyBits != mKeyBits) { + throw std::invalid_argument("BlockSparseArray::merge: incompatible layout"); + } + other.forEach([this](uint64_t k, T v, double s) { add(k, v, s); }); + } + + /// Start keeping sum of squared weights, initialised to the contents (as THnSparse::Sumw2()). + void enableSumw2() + { + if (mSumw2) { + return; + } + BlockSparseArray tmp(mKeyBits, mBlockBits, true, mDenseFactor); + forEach([&tmp](uint64_t k, T v, double) { tmp.add(k, v, double(v)); }); + swap(tmp); + } + + bool hasSumw2() const { return mSumw2; } + bool inRange(uint64_t key) const { return mKeyBits >= 64 || (key >> mKeyBits) == 0; } + uint64_t filledBins() const { return mFilled; } + /// Bytes allocated (blocks and block table), excluding malloc overhead. + size_t bytes() const { return mBytes + mSlots.capacity() * sizeof(Slot); } + size_t denseBlocks() const { return mDenseBlocks; } + + void clear() + { + for (auto& slot : mSlots) { + if (slot.id != kEmpty) { + std::free(slot.b.buf); + } + } + mSlots.clear(); + mSlots.shrink_to_fit(); + mUsed = 0; + mFilled = mBytes = mDenseBlocks = 0; + } + + void swap(BlockSparseArray& o) noexcept + { + std::swap(mKeyBits, o.mKeyBits); + std::swap(mBlockBits, o.mBlockBits); + std::swap(mBlockSize, o.mBlockSize); + std::swap(mMask, o.mMask); + std::swap(mSumw2, o.mSumw2); + std::swap(mDenseFactor, o.mDenseFactor); + std::swap(mPerBin, o.mPerBin); + std::swap(mDenseBytes, o.mDenseBytes); + std::swap(mDenseAt, o.mDenseAt); + mSlots.swap(o.mSlots); + std::swap(mUsed, o.mUsed); + std::swap(mFilled, o.mFilled); + std::swap(mBytes, o.mBytes); + std::swap(mDenseBlocks, o.mDenseBlocks); + } + + private: + static constexpr uint32_t kDense = 0xffffffffu; + static constexpr uint64_t kEmpty = ~uint64_t(0); // no block id reaches it: ids are < 2^(64 - blockBits) + + // Layout of buf: sparse [sumw2 (double) x cap][contents (T) x cap][offsets (uint16) x cap] + // dense [sumw2 (double) x S ][contents (T) x S ][bitmap (uint64) x S/64] + struct Block { + void* buf = nullptr; + uint32_t n = 0; // filled bins + uint32_t cap = 0; // capacity in bins, kDense when dense + }; + struct Slot { + uint64_t id = kEmpty; + Block b; + }; + + uint32_t slots(const Block& b) const { return b.cap == kDense ? mBlockSize : b.cap; } + double* sw2(const Block& b) const { return static_cast(b.buf); } + T* vals(const Block& b) const + { + return reinterpret_cast(static_cast(b.buf) + (mSumw2 ? slots(b) * sizeof(double) : 0)); + } + uint16_t* offs(const Block& b) const { return reinterpret_cast(vals(b) + b.cap); } + // 2^blockBits T's (a multiple of 64 of them) keep the bitmap 8-byte aligned + uint64_t* denseBits(const Block& b) const { return reinterpret_cast(vals(b) + mBlockSize); } + + static size_t hash(uint64_t x) + { + x ^= x >> 33; + x *= 0xff51afd7ed558ccdULL; + x ^= x >> 33; + return size_t(x); + } + Block* findBlock(uint64_t id) + { + if (mSlots.empty()) { + return nullptr; + } + size_t mask = mSlots.size() - 1; + for (size_t i = hash(id) & mask;; i = (i + 1) & mask) { + if (mSlots[i].id == id) { + return &mSlots[i].b; + } + if (mSlots[i].id == kEmpty) { + return nullptr; + } + } + } + /// The block `id`, created empty if needed. Rehashing moves descriptors, so + /// a Block reference is valid only until the next block is created. + Block& block(uint64_t id) + { + if (Block* b = findBlock(id)) { + return *b; + } + if ((mUsed + 1) * 4 > mSlots.size() * 3) { + rehash(mSlots.empty() ? 16 : 2 * mSlots.size()); + } + size_t mask = mSlots.size() - 1; + size_t i = hash(id) & mask; + while (mSlots[i].id != kEmpty) { + i = (i + 1) & mask; + } + mSlots[i].id = id; + ++mUsed; + return mSlots[i].b; + } + void rehash(size_t size) + { + std::vector old(size); + old.swap(mSlots); + size_t mask = size - 1; + for (const auto& slot : old) { + if (slot.id != kEmpty) { + size_t i = hash(slot.id) & mask; + while (mSlots[i].id != kEmpty) { + i = (i + 1) & mask; + } + mSlots[i] = slot; + } + } + } + + void* allocate(size_t bytes) + { + void* p = std::calloc(1, bytes); + if (!p) { + throw std::bad_alloc(); + } + mBytes += bytes; + return p; + } + void release(Block& b, size_t bytes) + { + std::free(b.buf); + mBytes -= bytes; + } + size_t sparseBytes(uint32_t cap) const { return size_t(cap) * mPerBin; } + + // Capacity grows 1, 2, 3, 4, 6, 9, ...: a block with a single bin (bins + // scattered over many blocks) costs one bin, not a minimum chunk. + void grow(Block& b) + { + uint32_t cap = std::min(std::max(b.cap + b.cap / 2, b.cap + 1), mDenseAt); + Block nb; + nb.cap = cap; + nb.n = b.n; + nb.buf = allocate(sparseBytes(cap)); + if (b.n) { + std::memcpy(vals(nb), vals(b), b.n * sizeof(T)); + std::memcpy(offs(nb), offs(b), b.n * sizeof(uint16_t)); + if (mSumw2) { + std::memcpy(sw2(nb), sw2(b), b.n * sizeof(double)); + } + } + if (b.buf) { + release(b, sparseBytes(b.cap)); + } + b = nb; + } + + void densify(Block& b) + { + Block nb; + nb.cap = kDense; + nb.n = b.n; + nb.buf = allocate(mDenseBytes); + T* v = vals(nb); + double* s = mSumw2 ? sw2(nb) : nullptr; + uint64_t* bits = denseBits(nb); + const uint16_t* o = offs(b); + for (uint32_t i = 0; i < b.n; ++i) { + v[o[i]] = vals(b)[i]; + if (s) { + s[o[i]] = sw2(b)[i]; + } + bits[o[i] >> 6] |= uint64_t(1) << (o[i] & 63); + } + release(b, sparseBytes(b.cap)); + b = nb; + ++mDenseBlocks; + } + + int mKeyBits; + int mBlockBits; + uint32_t mBlockSize; + uint32_t mMask; + bool mSumw2; + double mDenseFactor; + size_t mPerBin = 0; + size_t mDenseBytes = 0; + uint32_t mDenseAt = 0; + std::vector mSlots; // open addressing, size a power of 2, load <= 3/4 + size_t mUsed = 0; + uint64_t mFilled = 0; + size_t mBytes = 0, mDenseBlocks = 0; +}; + +} // namespace o2::framework + +#endif // O2_FRAMEWORK_BLOCKSPARSEARRAY_H_ diff --git a/Framework/Core/include/Framework/CompactTHnSparse.h b/Framework/Core/include/Framework/CompactTHnSparse.h new file mode 100644 index 0000000000000..1f16dc0c3b1ff --- /dev/null +++ b/Framework/Core/include/Framework/CompactTHnSparse.h @@ -0,0 +1,574 @@ +// Copyright 2019-2026 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. + +#ifndef O2_FRAMEWORK_COMPACTTHNSPARSE_H_ +#define O2_FRAMEWORK_COMPACTTHNSPARSE_H_ + +// A sparse n-dimensional histogram with the THnBase interface and a fraction of +// the memory of THnSparse. +// +// THnSparse spends ~60 of its ~70 bytes per filled bin on a hash table from +// bin coordinates to bin index, and briefly needs about three times its size +// whenever that table grows. Here the filled bins are kept in a +// BlockSparseArray keyed by the linear bin index: sizeof(T) + 2 bytes per filled +// bin in sparse regions (+8 with Sumw2), dense arrays where the bins are dense. +// +// Bin indices are linear indices over all cells, under/overflow included (as in +// THn), so GetBinContent(bin) works for any bin; GetNbins() is the number of +// filled bins (as in THnSparse). Everything else (Fill, Add, Merge, Scale, +// projections, statistics) comes from THnBase. toTHnSparse() gives the +// equivalent THnSparse, with the same bins, errors and statistics. +// +// It is meant to be filled and written out (the HistogramRegistry writes it as +// the equivalent THnSparse). Reading it back by bin number is where it differs +// from THnSparse, whose bin numbers count the filled bins: loops over +// i < GetNbins() with GetBinContent(i, coord) visit cells, not filled bins (use +// THnIter instead), and the THnBase functions built on that numbering +// (ComputeIntegral, GetRandom, PrintEntries, Print("c"), Fit) throw here. + +#include "Framework/BlockSparseArray.h" +#include "Framework/RuntimeError.h" + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +/// Type-independent interface, used by the HistogramRegistry +class CompactTHnSparse : public THnBase +{ + public: + /// The equivalent THnSparse (THnSparseF for float contents, THnSparseD for double), owned by the caller. + virtual THnSparse* toTHnSparse(const char* name = nullptr) const = 0; + /// Bytes of bin storage (blocks and block tables, excluding malloc overhead) + virtual size_t storageBytes() const = 0; + /// Size of one bin content in bytes + virtual int contentSize() const = 0; + + // THnBase implements these (non-virtual) with THnSparse's numbering of the filled bins + // 0..GetNbins()-1, which is not the bin numbering here: they would use the wrong bins + // (ComputeIntegral would write out of bounds). Read the written THnSparse instead. + Double_t ComputeIntegral() { unsupported("ComputeIntegral"); } + void GetRandom(Double_t*, Bool_t = kTRUE) { unsupported("GetRandom"); } + void PrintEntries(Long64_t = 0, Long64_t = -1, Option_t* = nullptr) const { unsupported("PrintEntries"); } + TFitResultPtr Fit(TF1*, Option_t* = "", Option_t* = "") { unsupported("Fit"); } + void Print(Option_t* option = "") const override + { + if (option && (std::strchr(option, 'c') || std::strchr(option, 'C'))) { + unsupported("Print with the bin contents"); + } + THnBase::Print(option); + } + + protected: + CompactTHnSparse() = default; + using THnBase::THnBase; + + private: + [[noreturn]] void unsupported(const char* what) const + { + throw o2::framework::runtime_error_f("%s is not supported by %s (%s): convert it with toTHnSparse() first", what, IsA()->GetName(), GetName()); + } + + ClassDefOverride(CompactTHnSparse, 1); // Interface of the sparse n-dimensional histograms with compact bin storage +}; + +template +class CompactTHnSparseT : public CompactTHnSparse +{ + public: + CompactTHnSparseT() = default; + CompactTHnSparseT(const char* name, const char* title, Int_t dim, const Int_t* nbins, + const Double_t* xmin = nullptr, const Double_t* xmax = nullptr, Int_t blockBits = o2::framework::BlockSparseArray::kDefaultBlockBits) + : CompactTHnSparse(name, title, dim, nbins, xmin, xmax), mBlockBits(blockBits) + { + InitStorage(const_cast(nbins), 0); + } + CompactTHnSparseT(const char* name, const char* title, const std::vector& axes, Int_t blockBits = o2::framework::BlockSparseArray::kDefaultBlockBits) + : CompactTHnSparse(name, title, axes), mBlockBits(blockBits) + { + std::vector nbins; + for (auto& a : axes) { + nbins.push_back(a.GetNbins()); + } + InitStorage(nbins.data(), 0); + } + ~CompactTHnSparseT() override = default; + + ROOT::Internal::THnBaseBinIter* CreateIter(Bool_t respectAxisRange) const override; + /// Number of filled bins + Long64_t GetNbins() const override { return mStore ? Long64_t(mStore->filledBins()) : 0; } + + /// Linear bin index of the bin coordinates, -1 if one is outside [0, nbins + 1] + Long64_t GetBin(const Int_t* idx) const override + { + Long64_t bin = 0; + for (Int_t d = 0; d < fNdimensions; ++d) { + if (idx[d] < 0 || idx[d] > GetAxis(d)->GetNbins() + 1) { + return -1; + } + bin += Long64_t(idx[d]) * mStride[d]; + } + return bin; + } + Long64_t GetBin(const Double_t* x) const override + { + Long64_t bin = 0; // FindBin of a value is always in [0, nbins + 1] + for (Int_t d = 0; d < fNdimensions; ++d) { + bin += Long64_t(GetAxis(d)->FindBin(x[d])) * mStride[d]; + } + return bin; + } + Long64_t GetBin(const char* name[]) const override + { + Long64_t bin = 0; + for (Int_t d = 0; d < fNdimensions; ++d) { + Int_t i = GetAxis(d)->FindBin(name[d]); + if (i < 0) { + return -1; // unknown label + } + bin += Long64_t(i) * mStride[d]; + } + return bin; + } + Long64_t GetBin(const Int_t* idx, Bool_t /*allocate*/ = kTRUE) override { return std::as_const(*this).GetBin(idx); } + Long64_t GetBin(const Double_t* x, Bool_t /*allocate*/ = kTRUE) override { return std::as_const(*this).GetBin(x); } + Long64_t GetBin(const char* name[], Bool_t /*allocate*/ = kTRUE) override { return std::as_const(*this).GetBin(name); } + + // Contents are summed in double and stored as T, as THnSparse does, so both give identical bins + void FillBin(Long64_t bin, Double_t w) override + { + if (!isValid(bin)) { + return; + } + auto r = mStore->ref(uint64_t(bin), true); + *r.v = T(Double_t(*r.v) + w); + if (r.s) { + *r.s += w * w; + } + FillBinBase(w); + } + + using THnBase::SetBinContent; + void SetBinContent(Long64_t bin, Double_t v) override + { + if (isValid(bin)) { + *mStore->ref(uint64_t(bin), true).v = T(v); + } + } + void SetBinError2(Long64_t bin, Double_t e2) override + { + if (!isValid(bin)) { + return; + } + if (!GetCalculateErrors()) { + Sumw2(); + } + *mStore->ref(uint64_t(bin), true).s = e2; + } + using THnBase::AddBinContent; + void AddBinContent(Long64_t bin, Double_t v = 1.) override + { + if (!isValid(bin)) { + return; + } + if (auto r = mStore->ref(uint64_t(bin), v != 0.)) { // adding 0 does not make a bin filled + *r.v = T(Double_t(*r.v) + v); + } + } + void AddBinError2(Long64_t bin, Double_t e2) override + { + if (!isValid(bin)) { + return; + } + if (!GetCalculateErrors()) { + Sumw2(); + } + if (auto r = mStore->ref(uint64_t(bin), e2 != 0.)) { + *r.s += e2; + } + } + using THnBase::GetBinContent; + /// Content of the bin with linear index `bin`; its coordinates in `idx` if given + Double_t GetBinContent(Long64_t bin, Int_t* idx = nullptr) const override + { + if (!isValid(bin)) { + return 0.; + } + if (idx) { + coordinates(bin, idx); + } + return mStore->get(uint64_t(bin)); + } + Double_t GetBinError2(Long64_t bin) const override + { + if (!isValid(bin)) { + return 0.; + } + return GetCalculateErrors() ? mStore->getSumw2(uint64_t(bin)) : mStore->get(uint64_t(bin)); + } + + void Sumw2() override + { + if (GetCalculateErrors()) { + return; + } + fTsumw2 = 0.; + mStore->enableSumw2(); + } + void Reset(Option_t* option = "") override + { + ResetBase(option); + makeStore(); + } + + /// Whether `bin` is a linear bin index of this histogram (0 <= bin < number of cells) + bool isValid(Long64_t bin) const { return mStore && bin >= 0 && bin < mCells; } + /// Coordinates (bin numbers per axis) of the linear bin index `bin` + void coordinates(Long64_t bin, Int_t* idx) const + { + for (Int_t d = 0; d < fNdimensions; ++d) { + idx[d] = Int_t(bin / mStride[d]); + bin %= mStride[d]; + } + } + + THnSparse* toTHnSparse(const char* name = nullptr) const override; + size_t storageBytes() const override { return mStore ? mStore->bytes() : 0; } + int contentSize() const override { return sizeof(T); } + const o2::framework::BlockSparseArray& storage() const { return *mStore; } + + protected: + void InitStorage(Int_t* nbins, Int_t /*chunkSize*/) override; + + private: + void makeStore(); + + Int_t mBlockBits = o2::framework::BlockSparseArray::kDefaultBlockBits; + std::vector mStride; ///> mStore = nullptr; /// CompactTHnSparseF; +typedef CompactTHnSparseT CompactTHnSparseD; + +namespace o2::framework::detail +{ +/// Iterates over the filled bins of a CompactTHnSparseT in increasing bin index +template +class CompactTHnSparseIter : public ROOT::Internal::THnBaseBinIter +{ + public: + CompactTHnSparseIter(Bool_t respectAxisRange, const CompactTHnSparseT* hist) + : ROOT::Internal::THnBaseBinIter(respectAxisRange), mHist(hist), mCoord(hist->GetNdimensions(), -1) {} + + Int_t GetCoord(Int_t dim) const override { return mCoord[dim]; } + Long64_t Next(Int_t* coord = nullptr) override + { + uint64_t key; + T v; + double s; + while (mHist && mHist->storage().next(mCursor, key, v, s)) { + mHist->coordinates(Long64_t(key), mCoord.data()); + if (RespectsAxisRange() && !mHist->IsInRange(mCoord.data())) { + fHaveSkippedBin = kTRUE; + continue; + } + if (coord) { + std::copy(mCoord.begin(), mCoord.end(), coord); + } + return Long64_t(key); + } + mHist = nullptr; + return -1; + } + + private: + const CompactTHnSparseT* mHist; + std::vector mCoord; + typename o2::framework::BlockSparseArray::Cursor mCursor; +}; +} // namespace o2::framework::detail + +template +ROOT::Internal::THnBaseBinIter* CompactTHnSparseT::CreateIter(Bool_t respectAxisRange) const +{ + return new o2::framework::detail::CompactTHnSparseIter(respectAxisRange, this); +} + +template +void CompactTHnSparseT::InitStorage(Int_t* nbins, Int_t /*chunkSize*/) +{ + // last axis fastest, as in THn + constexpr uint64_t maxCells = uint64_t(1) << 62; + mStride.assign(fNdimensions, 1); + uint64_t cells = 1; + for (Int_t d = fNdimensions - 1; d >= 0; --d) { + mStride[d] = Long64_t(cells); + uint64_t n = uint64_t(nbins[d]) + 2; + if (cells > maxCells / n) { + Fatal("InitStorage", "%s: the %d axes have more than 2^62 cells (under/overflow included), which do not fit a 64-bit bin index; use THnSparse", GetName(), fNdimensions); + } + cells *= n; + } + mCells = Long64_t(cells); + mKeyBits = 0; + while (mKeyBits < 64 && (uint64_t(1) << mKeyBits) < cells) { + ++mKeyBits; + } + makeStore(); +} + +template +void CompactTHnSparseT::makeStore() +{ + mStore = std::make_unique>(mKeyBits, mBlockBits, GetCalculateErrors()); +} + +namespace o2::framework::detail +{ +// Builds a THnSparse from bins given in any order without its hash table from coordinates to +// bin index, which takes ~85 of THnSparse's ~95 bytes per bin here and is never written out: +// THnSparse rebuilds it from the bin chunks on the first lookup (FillExMap), as for a +// THnSparse read from a file. A subclass only to reach THnSparse's protected chunk functions +// and THnBase's statistics; it adds no members and no ClassDef, so IsA() and what is written +// out are those of THnSparseT. +template +class THnSparseBuilder : public THnSparseT +{ + public: + THnSparseBuilder(const char* name, const char* title, const std::vector& axes, THnBase const& source) + : THnSparseT(name, title, axes) + { + // THnSparse's compact coordinates: per axis the bits of nbins + 2, packed from the first + // axis up (THnSparseCoordCompression in THnSparse.cxx; the format of fCoordinates on file) + Int_t shift = 0; + for (Int_t d = 0; d < this->fNdimensions; ++d) { + mBitOffsets.push_back(shift); + shift += numBits(this->GetAxis(d)->GetNbins() + 2); + } + mBufferSize = (shift + 7) / 8; + mBuffer.assign(std::max(mBufferSize, Int_t(sizeof(ULong64_t))), 0); + if (source.GetCalculateErrors()) { + this->Sumw2(); + } + } + + /// appends the bin with these (per-axis) coordinates; each bin must be appended only once + void append(const Int_t* coord, Double_t content, Double_t error2) + { + pack(coord); + THnSparseArrayChunk* chunk = this->GetNChunks() ? this->GetChunk(this->GetNChunks() - 1) : nullptr; + if (!chunk || chunk->GetEntries() == this->GetChunkSize()) { + chunk = this->AddChunk(); + if (chunk->fSingleCoordinateSize != mBufferSize) { + throw runtime_error_f("THnSparseBuilder: coordinate size %d, THnSparse's is %d", mBufferSize, chunk->fSingleCoordinateSize); + } + } + Int_t i = chunk->GetEntries(); + chunk->AddBin(i, mBuffer.data()); + chunk->fContent->SetAt(content, i); + if (chunk->fSumw2) { + chunk->fSumw2->SetAt(error2, i); + } + this->SetFilledBins(this->GetNbins() + 1); + } + + void copyStatistics(THnBase const& source) + { + this->fEntries = source.GetEntries(); + this->fTsumw = source.GetSumw(); + this->fTsumw2 = source.GetSumw2(); + for (Int_t d = 0; d < this->fNdimensions; ++d) { + this->fTsumwx[d] = source.GetSumwx(d); + this->fTsumwx2[d] = source.GetSumwx2(d); + } + } + + private: + static Int_t numBits(Int_t n) + { + Int_t r = (n > 0); + while (n /= 2) { + ++r; + } + return r; + } + + // as THnSparseCoordCompression::SetBufferFromCoord + void pack(const Int_t* coord) + { + if (mBufferSize <= 8) { + ULong64_t l64buf = 0; + for (Int_t d = 0; d < this->fNdimensions; ++d) { + l64buf += ((ULong64_t)((UInt_t)coord[d])) << mBitOffsets[d]; + } + std::memcpy(mBuffer.data(), &l64buf, sizeof(ULong64_t)); + return; + } + std::memset(mBuffer.data(), 0, mBufferSize); + for (Int_t d = 0; d < this->fNdimensions; ++d) { + ULong64_t val = coord[d]; + Char_t* pbuf = mBuffer.data() + mBitOffsets[d] / 8; + const Int_t bitShift = mBitOffsets[d] % 8; + *pbuf += 0xff & (val << bitShift); + val = val >> (8 - bitShift); + while (val) { + ++pbuf; + *pbuf += 0xff & val; + val = val >> 8; + } + } + } + + std::vector mBitOffsets; + Int_t mBufferSize = 0; + std::vector mBuffer; +}; +} // namespace o2::framework::detail + +template +THnSparse* CompactTHnSparseT::toTHnSparse(const char* name) const +{ + std::vector axes; + for (Int_t d = 0; d < fNdimensions; ++d) { + axes.push_back(*GetAxis(d)); + } + using Array = std::conditional_t, TArrayF, TArrayD>; + auto h = std::make_unique>(name ? name : GetName(), GetTitle(), axes, *this); + // every stored bin, zero-content ones included: THnSparse keeps those once allocated too + std::vector idx(fNdimensions); + mStore->forEach([&](uint64_t k, T v, double s) { + coordinates(Long64_t(k), idx.data()); + h->append(idx.data(), v, s); + }); + h->copyStatistics(*this); + return h.release(); +} + +// The filled bins are written as (bin index, content[, sumw2]) arrays after the THnBase part. +namespace o2::framework::detail +{ +// TBuffer's array functions take an Int_t count +template +void readArray(TBuffer& b, V* p, Long64_t n) +{ + for (Long64_t done = 0; done < n;) { + Int_t k = Int_t(std::min(n - done, std::numeric_limits::max())); + b.ReadFastArray(p + done, k); + done += k; + } +} +template +void writeArray(TBuffer& b, const V* p, Long64_t n) +{ + for (Long64_t done = 0; done < n;) { + Int_t k = Int_t(std::min(n - done, std::numeric_limits::max())); + b.WriteFastArray(p + done, k); + done += k; + } +} +} // namespace o2::framework::detail + +template +void CompactTHnSparseT::Streamer(TBuffer& b) +{ + using namespace o2::framework::detail; + if (b.IsReading()) { + UInt_t start, count; + b.ReadVersion(&start, &count); + THnBase::Streamer(b); + b >> mBlockBits; + if (mBlockBits < 6 || mBlockBits > 16) { + Error("Streamer", "invalid block size 2^%d, using 2^%d", mBlockBits, o2::framework::BlockSparseArray::kDefaultBlockBits); + mBlockBits = o2::framework::BlockSparseArray::kDefaultBlockBits; + } + std::vector nbins(fNdimensions); + for (Int_t d = 0; d < fNdimensions; ++d) { + nbins[d] = GetAxis(d)->GetNbins(); + } + InitStorage(nbins.data(), 0); + Long64_t n; + b >> n; + if (n < 0 || n > mCells) { + Error("Streamer", "%s: invalid number of filled bins %lld", GetName(), n); + b.CheckByteCount(start, count, IsA()); + return; + } + std::vector keys(n); + std::vector vals(n); + std::vector sumw2; + readArray(b, keys.data(), n); + readArray(b, vals.data(), n); + if (GetCalculateErrors()) { + sumw2.resize(n); + readArray(b, sumw2.data(), n); + } + Long64_t bad = 0; + for (Long64_t i = 0; i < n; ++i) { + if (!isValid(keys[i])) { + ++bad; + continue; + } + mStore->add(uint64_t(keys[i]), vals[i], sumw2.empty() ? 0. : sumw2[i]); + } + if (bad) { + Error("Streamer", "%s: %lld bin indices out of range were dropped", GetName(), bad); + } + b.CheckByteCount(start, count, IsA()); + } else { + UInt_t count = b.WriteVersion(IsA(), kTRUE); + THnBase::Streamer(b); + b << mBlockBits; + Long64_t n = GetNbins(); + std::vector keys; + std::vector vals; + std::vector sumw2; + keys.reserve(n); + vals.reserve(n); + if (GetCalculateErrors()) { + sumw2.reserve(n); + } + if (mStore) { + mStore->forEach([&](uint64_t k, T v, double s) { + keys.push_back(Long64_t(k)); + vals.push_back(v); + if (GetCalculateErrors()) { + sumw2.push_back(s); + } + }); + } + b << n; + writeArray(b, keys.data(), n); + writeArray(b, vals.data(), n); + if (GetCalculateErrors()) { + writeArray(b, sumw2.data(), n); + } + b.SetByteCount(count, kTRUE); + } +} + +#endif // O2_FRAMEWORK_COMPACTTHNSPARSE_H_ diff --git a/Framework/Core/include/Framework/HistogramRegistry.h b/Framework/Core/include/Framework/HistogramRegistry.h index a09a9988fb576..9bb041759809d 100644 --- a/Framework/Core/include/Framework/HistogramRegistry.h +++ b/Framework/Core/include/Framework/HistogramRegistry.h @@ -337,6 +337,13 @@ double HistFiller::getSize(std::shared_ptr hist, double fillFraction) // relates the compact bin coordinates (or a hash thereof) to a linear index // this index determines in which chunk and therein at which position to find / store bin coordinate and content size += nBinsFilled * 3 * sizeof(Long64_t); // hash, key, value; not sure why 3 are needed here... + } else if constexpr (std::is_base_of_v) { + // filled bins in sparse blocks cost the content + a 16-bit offset (+ sumw2); dense blocks are never larger than 4x that + double nBinsTotal = 1.; + for (int d = 0; d < hist->GetNdimensions(); ++d) { + nBinsTotal *= hist->GetAxis(d)->GetNbins() + 2; + } + size = fillFraction * nBinsTotal * (hist->contentSize() + sizeof(uint16_t) + ((hist->GetSumw2() != -1.) ? sizeof(double) : 0.)); } return size / 1048576.; } @@ -450,6 +457,7 @@ extern template HistPtr HistogramRegistry::insertClone(const HistName&, const st extern template HistPtr HistogramRegistry::insertClone(const HistName&, const std::shared_ptr); extern template HistPtr HistogramRegistry::insertClone(const HistName&, const std::shared_ptr); extern template HistPtr HistogramRegistry::insertClone(const HistName&, const std::shared_ptr); +extern template HistPtr HistogramRegistry::insertClone(const HistName&, const std::shared_ptr); extern template std::shared_ptr HistogramRegistry::add(char const* const name, char const* const title, const HistogramConfigSpec& histConfigSpec, bool callSumw2); extern template std::shared_ptr HistogramRegistry::add(char const* const name, char const* const title, HistType histType, const std::vector& axes, bool callSumw2); @@ -469,6 +477,8 @@ extern template std::shared_ptr HistogramRegistry::add(cha extern template std::shared_ptr HistogramRegistry::add(char const* const name, char const* const title, HistType histType, const std::vector& axes, bool callSumw2); extern template std::shared_ptr HistogramRegistry::add(char const* const name, char const* const title, const HistogramConfigSpec& histConfigSpec, bool callSumw2); extern template std::shared_ptr HistogramRegistry::add(char const* const name, char const* const title, HistType histType, const std::vector& axes, bool callSumw2); +extern template std::shared_ptr HistogramRegistry::add(char const* const name, char const* const title, const HistogramConfigSpec& histConfigSpec, bool callSumw2); +extern template std::shared_ptr HistogramRegistry::add(char const* const name, char const* const title, HistType histType, const std::vector& axes, bool callSumw2); template void HistogramRegistry::fill(const HistName& histName, const T& table, const o2::framework::expressions::Filter& filter) diff --git a/Framework/Core/include/Framework/HistogramSpec.h b/Framework/Core/include/Framework/HistogramSpec.h index 47c3d7f1c6170..475c086c1a331 100644 --- a/Framework/Core/include/Framework/HistogramSpec.h +++ b/Framework/Core/include/Framework/HistogramSpec.h @@ -21,6 +21,7 @@ #include "Framework/Configurable.h" #include "Framework/StepTHn.h" +#include "Framework/CompactTHnSparse.h" #include #include #include @@ -69,11 +70,14 @@ enum HistType : unsigned int { kTProfile2D, kTProfile3D, kStepTHnF, - kStepTHnD + kStepTHnD, + kCompactTHnSparseF, // THnSparse with ~8x less memory per filled bin, written out as THnSparseF; for filling only: + // bin numbers differ from THnSparse's, see CompactTHnSparse.h + kCompactTHnSparseD // same, written out as THnSparseD }; // variant of all possible root pointers; here we use only the interface types since the underlying data representation (int,float,double,long,char) is irrelevant -using HistPtr = std::variant, std::shared_ptr, std::shared_ptr, std::shared_ptr, std::shared_ptr, std::shared_ptr, std::shared_ptr, std::shared_ptr, std::shared_ptr>; +using HistPtr = std::variant, std::shared_ptr, std::shared_ptr, std::shared_ptr, std::shared_ptr, std::shared_ptr, std::shared_ptr, std::shared_ptr, std::shared_ptr, std::shared_ptr>; //************************************************************************************************** /** @@ -257,7 +261,9 @@ DECLAREEXT(TProfile); DECLAREEXT(TProfile2D); DECLAREEXT(TProfile3D); DECLAREEXT(StepTHnF); -DECLAREEXT(StepTHnD) +DECLAREEXT(StepTHnD); +DECLAREEXT(CompactTHnSparseF); +DECLAREEXT(CompactTHnSparseD) #undef DECLAREEXT } // namespace o2::framework diff --git a/Framework/Core/src/HistogramRegistry.cxx b/Framework/Core/src/HistogramRegistry.cxx index 87b92f058cb5d..a3d90731168bf 100644 --- a/Framework/Core/src/HistogramRegistry.cxx +++ b/Framework/Core/src/HistogramRegistry.cxx @@ -211,7 +211,7 @@ void HistogramRegistry::print(bool showAxisDetails) if (hist) { using T = std::decay_t; bool isSparse{}; - if (hist->InheritsFrom(THnSparse::Class())) { + if (hist->InheritsFrom(THnSparse::Class()) || hist->InheritsFrom(CompactTHnSparse::Class())) { isSparse = true; containsSparseHist = true; } @@ -386,6 +386,7 @@ template HistPtr HistogramRegistry::insertClone(const HistName&, const std::shar template HistPtr HistogramRegistry::insertClone(const HistName&, const std::shared_ptr); template HistPtr HistogramRegistry::insertClone(const HistName&, const std::shared_ptr); template HistPtr HistogramRegistry::insertClone(const HistName&, const std::shared_ptr); +template HistPtr HistogramRegistry::insertClone(const HistName&, const std::shared_ptr); template std::shared_ptr HistogramRegistry::add(char const* const name, char const* const title, const HistogramConfigSpec& histConfigSpec, bool callSumw2) @@ -427,5 +428,7 @@ template std::shared_ptr HistogramRegistry::add(char const template std::shared_ptr HistogramRegistry::add(char const* const name, char const* const title, HistType histType, const std::vector& axes, bool callSumw2); template std::shared_ptr HistogramRegistry::add(char const* const name, char const* const title, const HistogramConfigSpec& histConfigSpec, bool callSumw2); template std::shared_ptr HistogramRegistry::add(char const* const name, char const* const title, HistType histType, const std::vector& axes, bool callSumw2); +template std::shared_ptr HistogramRegistry::add(char const* const name, char const* const title, const HistogramConfigSpec& histConfigSpec, bool callSumw2); +template std::shared_ptr HistogramRegistry::add(char const* const name, char const* const title, HistType histType, const std::vector& axes, bool callSumw2); } // namespace o2::framework diff --git a/Framework/Core/src/HistogramSpec.cxx b/Framework/Core/src/HistogramSpec.cxx index 282b3de18674b..565c33ac20631 100644 --- a/Framework/Core/src/HistogramSpec.cxx +++ b/Framework/Core/src/HistogramSpec.cxx @@ -240,6 +240,8 @@ HistPtr HistFactory::createHistVariant(const HistogramSpec& histSpec) CREATE_HIST_CASE(StepTHnF, StepTHn) CREATE_HIST_CASE(StepTHnD, StepTHn) + CREATE_HIST_CASE(CompactTHnSparseF, CompactTHnSparse) + CREATE_HIST_CASE(CompactTHnSparseD, CompactTHnSparse) default: throw runtime_error("Histogram type was not specified."); } @@ -301,7 +303,9 @@ EXPIMPL(TProfile); EXPIMPL(TProfile2D); EXPIMPL(TProfile3D); EXPIMPL(StepTHnF); -EXPIMPL(StepTHnD) +EXPIMPL(StepTHnD); +EXPIMPL(CompactTHnSparseF); +EXPIMPL(CompactTHnSparseD) #undef EXPIMPL } // namespace o2::framework diff --git a/Framework/Core/src/StepTHnLinkDef.h b/Framework/Core/src/StepTHnLinkDef.h index 550daa56a8b9d..0421db6fbd05b 100644 --- a/Framework/Core/src/StepTHnLinkDef.h +++ b/Framework/Core/src/StepTHnLinkDef.h @@ -18,3 +18,9 @@ #pragma link C++ class StepTHnT < TArrayD> + ; #pragma link C++ typedef StepTHnF; #pragma link C++ typedef StepTHnD; + +#pragma link C++ class CompactTHnSparse + ; +#pragma link C++ class CompactTHnSparseT < Float_t> - ; +#pragma link C++ class CompactTHnSparseT < Double_t> - ; +#pragma link C++ typedef CompactTHnSparseF; +#pragma link C++ typedef CompactTHnSparseD; diff --git a/Framework/Core/test/test_CompactTHnSparse.cxx b/Framework/Core/test/test_CompactTHnSparse.cxx new file mode 100644 index 0000000000000..b0693a775d859 --- /dev/null +++ b/Framework/Core/test/test_CompactTHnSparse.cxx @@ -0,0 +1,409 @@ +// Copyright 2019-2026 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/CompactTHnSparse.h" +#include "Framework/HistogramRegistry.h" + +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include + +namespace +{ +constexpr int kDim = 5; +// a variable-width axis, a fine axis that makes dense regions, out-of-range fills (under/overflow) +const Int_t kBins[kDim] = {8, 20, 16, 9, 110}; +const Double_t kMin[kDim] = {0., -2., -1.6, 0., -1.05}; +const Double_t kMax[kDim] = {8., 2., 4.8, 9., 1.05}; +const Double_t kEdges0[9] = {0., 0.2, 0.5, 1., 2., 3., 5., 10., 100.}; + +template +void setAxes(H& h) +{ + h.SetBinEdges(0, kEdges0); + h.GetAxis(1)->SetTitle("#Delta#eta"); +} + +// Correlated values, so some cells are dense and most of the space stays empty +void draw(TRandom3& r, Double_t* x) +{ + Double_t c = r.Gaus(0., 1.); + x[0] = std::abs(r.Exp(1.5)); + x[1] = 0.8 * c + r.Gaus(0., 0.3); + x[2] = r.Uniform(-1.6, 4.8); + x[3] = r.Uniform(-0.5, 9.5); // under- and overflow + x[4] = 0.6 * c + r.Gaus(0., 0.4); +} + +// Every filled bin of `ref` has the same content and error in `h`, and the statistics agree. +// Errors are compared to 1e-14: where the compiler fuses w * w + sumw2 into one FMA in one of +// the two fill paths but not the other (GCC on aarch64), they differ in the last bit. +void compare(const THnSparse& ref, const THnBase& h) +{ + REQUIRE(h.GetNbins() == ref.GetNbins()); + REQUIRE(h.GetEntries() == ref.GetEntries()); + REQUIRE(h.GetCalculateErrors() == ref.GetCalculateErrors()); + REQUIRE(h.GetSumw() == Catch::Approx(ref.GetSumw()).epsilon(1e-12)); + REQUIRE(h.GetSumw2() == Catch::Approx(ref.GetSumw2()).epsilon(1e-12)); + for (int d = 0; d < kDim; ++d) { + REQUIRE(h.GetSumwx(d) == Catch::Approx(ref.GetSumwx(d)).epsilon(1e-12)); + REQUIRE(h.GetSumwx2(d) == Catch::Approx(ref.GetSumwx2(d)).epsilon(1e-12)); + REQUIRE(h.GetAxis(d)->GetNbins() == ref.GetAxis(d)->GetNbins()); + REQUIRE(h.GetAxis(d)->GetXmin() == ref.GetAxis(d)->GetXmin()); + REQUIRE(h.GetAxis(d)->GetXmax() == ref.GetAxis(d)->GetXmax()); + } + Int_t coord[kDim]; + long bad = 0; + for (Long64_t i = 0; i < ref.GetNbins(); ++i) { + Double_t v = ref.GetBinContent(i, coord); + Long64_t b = h.GetBin(coord); + bad += h.GetBinContent(b) != v || h.GetBinError2(b) != Catch::Approx(ref.GetBinError2(i)).epsilon(1e-14); + } + REQUIRE(bad == 0); +} + +struct Pair { + THnSparseF ref{"ref", "ref", kDim, kBins, kMin, kMax}; + CompactTHnSparseF h{"h", "h", kDim, kBins, kMin, kMax}; + Pair() + { + setAxes(ref); + setAxes(h); + } + void fill(TRandom3& r, int n, bool weighted) + { + Double_t x[kDim]; + for (int i = 0; i < n; ++i) { + draw(r, x); + Double_t w = weighted ? r.Uniform(0.1, 3.) : 1.; + ref.Fill(x, w); + h.Fill(x, w); + } + } +}; +} // namespace + +TEST_CASE("CompactTHnSparseFillLikeTHnSparse") +{ + TRandom3 r(1); + Pair p; + p.fill(r, 200000, false); + compare(p.ref, p.h); + REQUIRE(p.h.storage().denseBlocks() > 0); // both block layouts are exercised + + // Errors switched on part way: earlier bins get sumw2 = content, as in THnSparse + p.ref.Sumw2(); + p.h.Sumw2(); + p.fill(r, 100000, true); + compare(p.ref, p.h); + + // Variadic fill from THnBase + p.ref.Fill(0.3, 0.1, 0.2, 4.5, 0.01, 2.5); + p.h.Fill(0.3, 0.1, 0.2, 4.5, 0.01, 2.5); + compare(p.ref, p.h); + + // Far less memory than THnSparse needs for its hash table alone + REQUIRE(p.h.storageBytes() < 30 * size_t(p.h.GetNbins())); +} + +TEST_CASE("CompactTHnSparseToTHnSparse") +{ + TRandom3 r(2); + Pair p; + p.ref.Sumw2(); + p.h.Sumw2(); + p.fill(r, 100000, true); + std::unique_ptr s(p.h.toTHnSparse("converted")); + REQUIRE(s->IsA() == THnSparseF::Class()); + REQUIRE(std::string(s->GetName()) == "converted"); + REQUIRE(s->GetAxis(0)->GetXbins()->GetSize() == 9); + REQUIRE(std::string(s->GetAxis(1)->GetTitle()) == "#Delta#eta"); + compare(p.ref, *s); +} + +TEST_CASE("CompactTHnSparseMerge") +{ + TRandom3 r(3); + Pair all; + CompactTHnSparseF h1("h1", "h1", kDim, kBins, kMin, kMax); + CompactTHnSparseF h2("h2", "h2", kDim, kBins, kMin, kMax); + setAxes(h1); + setAxes(h2); + Double_t x[kDim]; + for (int i = 0; i < 100000; ++i) { + draw(r, x); + all.ref.Fill(x); + (i % 2 ? h1 : h2).Fill(x); + } + TList l; + l.Add(&h2); + h1.Merge(&l); + l.Clear("nodelete"); + compare(all.ref, h1); +} + +TEST_CASE("CompactTHnSparseStreamer") +{ + TRandom3 r(4); + Pair p; + p.ref.Sumw2(); + p.h.Sumw2(); + p.fill(r, 50000, true); + + TBufferFile buf(TBuffer::kWrite); + buf.WriteObjectAny(&p.h, CompactTHnSparseF::Class()); + buf.SetReadMode(); + buf.SetBufferOffset(0); + std::unique_ptr back(static_cast(buf.ReadObjectAny(CompactTHnSparseF::Class()))); + REQUIRE(back); + compare(p.ref, *back); + + // Clone goes through the streamer too + std::unique_ptr clone(static_cast(p.h.Clone("clone"))); + compare(p.ref, *clone); +} + +TEST_CASE("CompactTHnSparseProjectionAndRange") +{ + TRandom3 r(5); + Pair p; + p.fill(r, 50000, false); + std::unique_ptr pr(p.ref.Projection(4)); + std::unique_ptr ph(p.h.Projection(4)); + REQUIRE(ph->GetNbinsX() == pr->GetNbinsX()); + for (int b = 0; b <= pr->GetNbinsX() + 1; ++b) { + REQUIRE(ph->GetBinContent(b) == pr->GetBinContent(b)); + } + // Axis ranges are respected by projections (through the bin iterator) + p.ref.GetAxis(3)->SetRange(2, 5); + p.h.GetAxis(3)->SetRange(2, 5); + pr.reset(p.ref.Projection(1)); + ph.reset(p.h.Projection(1)); + REQUIRE(ph->GetEntries() == pr->GetEntries()); + for (int b = 0; b <= pr->GetNbinsX() + 1; ++b) { + REQUIRE(ph->GetBinContent(b) == pr->GetBinContent(b)); + } +} + +TEST_CASE("CompactTHnSparseReset") +{ + TRandom3 r(6); + Pair p; + p.fill(r, 1000, true); + p.h.Reset(); + REQUIRE(p.h.GetNbins() == 0); + REQUIRE(p.h.GetEntries() == 0); + Int_t c[kDim] = {1, 1, 1, 1, 1}; + REQUIRE(p.h.GetBinContent(p.h.GetBin(c)) == 0); +} + +TEST_CASE("CompactTHnSparseInHistogramRegistry") +{ + using namespace o2::framework; + std::vector edges0(std::begin(kEdges0), std::end(kEdges0)); + std::vector axes{{edges0, "p_{T}"}, {20, -2., 2., "#Delta#eta"}, {16, -1.6, 4.8}, {9, 0., 9.}, {110, -1.05, 1.05}}; + HistogramRegistry registry{"registry"}; + registry.add("ref", "ref", kTHnSparseF, axes, true); + registry.add("compact/h", "compact", kCompactTHnSparseF, axes, true); + auto ref = registry.get(HIST("ref")); + auto compact = registry.get(HIST("compact/h")); + REQUIRE(compact->IsA() == CompactTHnSparseF::Class()); + REQUIRE(std::string(compact->GetAxis(0)->GetTitle()) == "p_{T}"); + REQUIRE_THROWS(registry.get(HIST("compact/h"))); + + TRandom3 r(7); + Double_t x[kDim]; + for (int i = 0; i < 50000; ++i) { + draw(r, x); + Double_t w = r.Uniform(0.1, 3.); + registry.fill(HIST("ref"), x[0], x[1], x[2], x[3], x[4], w); + registry.fill(HIST("compact/h"), x[0], x[1], x[2], x[3], x[4], w); + } + compare(*ref, *compact); + REQUIRE(registry.getSize(HIST("compact/h"), 0.01) < registry.getSize(HIST("ref"), 0.01)); + + registry.addClone("compact/", "copy/"); + compare(*ref, *registry.get(HIST("copy/h"))); + + // What postRunOutput sends for a compact histogram: the equivalent THnSparse, same name + int converted = 0; + registry.apply([&](HistogramRegistry const&, TNamed* obj) { + if (auto* c = dynamic_cast(obj)) { + std::unique_ptr s{c->toTHnSparse()}; + REQUIRE(s->IsA() == THnSparseF::Class()); + REQUIRE(std::string(s->GetName()) == c->GetName()); + compare(*ref, *s); + ++converted; + } + }); + REQUIRE(converted == 2); +} + +TEST_CASE("CompactTHnSparseOutOfRange") +{ + Pair p; + Int_t bad[kDim] = {1, 1, 1, 1, kBins[4] + 2}; // past the overflow bin of the last axis + REQUIRE(p.h.GetBin(bad) == -1); + Int_t neg[kDim] = {-1, 1, 1, 1, 1}; + REQUIRE(p.h.GetBin(neg) == -1); + for (Long64_t bin : {Long64_t(-1), Long64_t(1) << 40, std::numeric_limits::max()}) { + p.h.FillBin(bin, 1.); + p.h.SetBinContent(bin, 2.); + p.h.AddBinContent(bin, 3.); + p.h.SetBinError2(bin, 4.); + REQUIRE(p.h.GetBinContent(bin) == 0.); + REQUIRE(p.h.GetBinError2(bin) == 0.); + } + REQUIRE(p.h.GetNbins() == 0); + + CompactTHnSparseF empty; // as created by ROOT I/O before reading + REQUIRE(empty.GetBinContent(Long64_t(0)) == 0.); + REQUIRE(empty.GetNbins() == 0); +} + +TEST_CASE("CompactTHnSparseToTHnSparseWideCoordinates") +{ + // 6 axes of 1030 bins: 66 bits of THnSparse coordinates (11 per axis), more than 8 bytes, yet + // ~1.2e18 cells, which fit CompactTHnSparse's 64-bit bin index; and more bins + // than one THnSparse chunk. The converted histogram has no hash table until its first + // lookup; it must find every bin, survive streaming and take further fills like THnSparse. + constexpr int nd = 6; + Int_t nbins[nd]; + Double_t lo[nd], hi[nd]; + for (int d = 0; d < nd; ++d) { + nbins[d] = 1030; + lo[d] = -1.; + hi[d] = 1.; + } + THnSparseD ref("ref", "ref", nd, nbins, lo, hi); + CompactTHnSparseD h("h", "h", nd, nbins, lo, hi); + ref.Sumw2(); + h.Sumw2(); + TRandom3 r(11); + Double_t x[nd]; + auto fill = [&](THnBase& a, THnBase& b, int n) { + for (int i = 0; i < n; ++i) { + for (int d = 0; d < nd; ++d) { + x[d] = r.Gaus(0., 0.6); // some under/overflow + } + Double_t w = r.Uniform(0.5, 2.); + a.Fill(x, w); + b.Fill(x, w); + } + }; + fill(ref, h, 50000); + auto check = [&](const THnSparse& s) { + REQUIRE(s.GetNbins() == ref.GetNbins()); + REQUIRE(s.GetEntries() == ref.GetEntries()); + REQUIRE(s.GetSumw() == Catch::Approx(ref.GetSumw()).epsilon(1e-12)); + REQUIRE(s.GetSumw2() == Catch::Approx(ref.GetSumw2()).epsilon(1e-12)); + Int_t coord[nd]; + long bad = 0; + for (Long64_t i = 0; i < ref.GetNbins(); ++i) { + Double_t v = ref.GetBinContent(i, coord); + Long64_t b = s.GetBin(coord); + bad += b < 0 || s.GetBinContent(b) != v || s.GetBinError2(b) != ref.GetBinError2(i); + } + REQUIRE(bad == 0); + }; + std::unique_ptr s(h.toTHnSparse()); + REQUIRE(s->IsA() == THnSparseD::Class()); + REQUIRE(s->GetNChunks() > 1); + check(*s); + + TBufferFile buf(TBuffer::kWrite); + buf.WriteObject(s.get()); + buf.SetReadMode(); + buf.SetBufferOffset(0); + std::unique_ptr back(static_cast(buf.ReadObject(THnSparseD::Class()))); + REQUIRE(back); + REQUIRE(back->IsA() == THnSparseD::Class()); + check(*back); + + // further fills of the converted histogram: new bins and existing ones + fill(ref, *s, 20000); + check(*s); +} + +TEST_CASE("CompactTHnSparseZeroWeightFills") +{ + // THnSparse keeps a bin allocated by a fill of weight 0; the conversion must too + for (bool errors : {false, true}) { + TRandom3 r(8); + Pair p; + if (errors) { + p.ref.Sumw2(); + p.h.Sumw2(); + } + p.fill(r, 1000, true); + Double_t x[kDim]; + for (int i = 0; i < 100; ++i) { + draw(r, x); + p.ref.Fill(x, 0.); + p.h.Fill(x, 0.); + } + std::unique_ptr s(p.h.toTHnSparse()); + compare(p.ref, *s); + } +} + +TEST_CASE("BlockSparseArrayScatteredKeys") +{ + // Bins scattered over the whole key space, one per block (the worst case): the block + // table must stay proportional to the bins filled, whatever the size of the key space, + // and below THnSparse's ~70 B per filled bin (8-20 B when bins cluster) + for (int keyBits : {30, 40, 50, 62}) { + o2::framework::BlockSparseArray a(keyBits); + TRandom3 r(9); + const int n = 100000; + for (int i = 0; i < n; ++i) { + uint64_t k = (uint64_t(r.Integer(0xffffffff)) << 32 | r.Integer(0xffffffff)) >> (64 - keyBits); + a.add(k, 1.f); + } + REQUIRE(a.filledBins() > 0.99 * n); + REQUIRE(a.bytes() < 80 * a.filledBins()); + uint64_t count = 0, last = 0; + bool ordered = true; + a.forEach([&](uint64_t k, float, double) { ordered = ordered && (count == 0 || k > last); last = k; ++count; }); + REQUIRE(count == a.filledBins()); + REQUIRE(ordered); + } +} + +TEST_CASE("CompactTHnSparseReadByBinNumberUnsupported") +{ + // THnBase functions built on THnSparse's numbering of filled bins throw instead of using wrong bins + TRandom3 r(10); + Pair p; + p.fill(r, 1000, false); + Double_t x[kDim]; + REQUIRE_THROWS(p.h.ComputeIntegral()); + REQUIRE_THROWS(p.h.GetRandom(x)); + REQUIRE_THROWS(p.h.PrintEntries()); + REQUIRE_THROWS(p.h.Print("c")); + REQUIRE_THROWS(p.h.Fit(nullptr)); + REQUIRE_NOTHROW(p.h.Print("as")); + // the same through the registry's interface type + CompactTHnSparse& base = p.h; + REQUIRE_THROWS(base.GetRandom(x)); + // reading the converted THnSparse works + std::unique_ptr s(p.h.toTHnSparse()); + REQUIRE(s->ComputeIntegral() > 0.); +}