forked from AliceO2Group/AliceO2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEncodedBlocks.h
More file actions
1609 lines (1384 loc) · 70.7 KB
/
EncodedBlocks.h
File metadata and controls
1609 lines (1384 loc) · 70.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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.
/// \file EncodedBlock.h
/// \brief Set of entropy-encoded blocks
/// Used to store a CTF of particular detector. Can be build as a flat buffer which can be directly messaged between DPL devices
#ifndef ALICEO2_ENCODED_BLOCKS_H
#define ALICEO2_ENCODED_BLOCKS_H
// #undef NDEBUG
// #include <cassert>
#include <type_traits>
#include <cstddef>
#include <Rtypes.h>
#include <any>
#include "TTree.h"
#include "CommonUtils/StringUtils.h"
#include "Framework/Logger.h"
#include "DetectorsCommonDataFormats/CTFDictHeader.h"
#include "DetectorsCommonDataFormats/CTFIOSize.h"
#include "DetectorsCommonDataFormats/ANSHeader.h"
#include "DetectorsCommonDataFormats/internal/Packer.h"
#include "DetectorsCommonDataFormats/Metadata.h"
#ifndef __CLING__
#include "DetectorsCommonDataFormats/internal/ExternalEntropyCoder.h"
#include "DetectorsCommonDataFormats/internal/InplaceEntropyCoder.h"
#include "rANS/compat.h"
#include "rANS/histogram.h"
#include "rANS/serialize.h"
#include "rANS/factory.h"
#include "rANS/metrics.h"
#include "rANS/utils.h"
#endif
namespace o2
{
namespace ctf
{
namespace detail
{
template <class, class Enable = void>
struct is_iterator : std::false_type {
};
template <class T>
struct is_iterator<T, std::enable_if_t<
std::is_base_of_v<std::input_iterator_tag, typename std::iterator_traits<T>::iterator_category> ||
std::is_same_v<std::output_iterator_tag, typename std::iterator_traits<T>::iterator_category>>>
: std::true_type {
};
template <class T>
inline constexpr bool is_iterator_v = is_iterator<T>::value;
inline constexpr bool mayEEncode(Metadata::OptStore opt) noexcept
{
return (opt == Metadata::OptStore::EENCODE) || (opt == Metadata::OptStore::EENCODE_OR_PACK);
}
inline constexpr bool mayPack(Metadata::OptStore opt) noexcept
{
return (opt == Metadata::OptStore::PACK) || (opt == Metadata::OptStore::EENCODE_OR_PACK);
}
} // namespace detail
constexpr size_t PackingThreshold = 512;
constexpr size_t Alignment = 16;
constexpr int WrappersSplitLevel = 99;
constexpr int WrappersCompressionLevel = 1;
/// This is the type of the vector to be used for the EncodedBlocks buffer allocation
using BufferType = uint8_t; // to avoid every detector using different types, we better define it here
/// align size to given diven number of bytes
inline size_t alignSize(size_t sizeBytes)
{
auto res = sizeBytes % Alignment;
return res ? sizeBytes + (Alignment - res) : sizeBytes;
}
/// relocate pointer by the difference of addresses
template <class T>
inline T* relocatePointer(const char* oldBase, char* newBase, const T* ptr)
{
return (ptr != nullptr) ? reinterpret_cast<T*>(newBase + (reinterpret_cast<const char*>(ptr) - oldBase)) : nullptr;
}
template <typename source_T, typename dest_T, std::enable_if_t<(sizeof(dest_T) >= sizeof(source_T)), bool> = true>
inline constexpr size_t calculateNDestTElements(size_t nElems) noexcept
{
const size_t srcBufferSize = nElems * sizeof(source_T);
return srcBufferSize / sizeof(dest_T) + (srcBufferSize % sizeof(dest_T) != 0);
};
template <typename source_T, typename dest_T, std::enable_if_t<(sizeof(dest_T) >= sizeof(source_T)), bool> = true>
inline size_t calculatePaddedSize(size_t nElems) noexcept
{
const size_t sizeOfSourceT = sizeof(source_T);
const size_t sizeOfDestT = sizeof(dest_T);
// this is equivalent to (sizeOfSourceT / sizeOfDestT) * std::ceil(sizeOfSourceArray/ sizeOfDestT)
return (sizeOfDestT / sizeOfSourceT) * calculateNDestTElements<source_T, dest_T>(nElems);
};
///>>======================== Auxiliary classes =======================>>
/// registry struct for the buffer start and offsets of writable space
struct Registry {
char* head = nullptr; //! pointer on the head of the CTF
int nFilledBlocks = 0; // number of filled blocks = next block to fill (must be strictly consecutive)
size_t offsFreeStart = 0; //! offset of the start of the writable space (wrt head), in bytes!!!
size_t size = 0; // full size in bytes!!!
/// calculate the pointer of the head of the writable space
char* getFreeBlockStart() const
{
assert(offsFreeStart <= size);
return head + offsFreeStart;
}
/// size in bytes available to fill data
size_t getFreeSize() const
{
return size - offsFreeStart;
}
char* getFreeBlockEnd() const
{
assert(offsFreeStart <= size);
return getFreeBlockStart() + getFreeSize();
}
ClassDefNV(Registry, 1);
};
/// binary blob for single entropy-compressed column: metadata + (optional) dictionary and data buffer + their sizes
template <typename W = uint32_t>
struct Block {
Registry* registry = nullptr; //! non-persistent info for in-memory ops
int nDict = 0; // dictionary length (if any)
int nData = 0; // length of data
int nLiterals = 0; // length of literals vector (if any)
int nStored = 0; // total length
W* payload = nullptr; //[nStored];
inline const W* getDict() const { return nDict ? payload : nullptr; }
inline const W* getData() const { return nData ? (payload + nDict) : nullptr; }
inline const W* getDataPointer() const { return payload ? (payload + nDict) : nullptr; } // needed when nData is not set yet
inline const W* getLiterals() const { return nLiterals ? (payload + nDict + nData) : nullptr; }
inline const W* getEndOfBlock() const
{
if (!registry) {
return nullptr;
}
// get last legal W*, since unaligned data is undefined behavior!
const size_t delta = reinterpret_cast<uintptr_t>(registry->getFreeBlockEnd()) % sizeof(W);
return reinterpret_cast<const W*>(registry->getFreeBlockEnd() - delta);
}
inline W* getCreatePayload() { return payload ? payload : (registry ? (payload = reinterpret_cast<W*>(registry->getFreeBlockStart())) : nullptr); }
inline W* getCreateDict() { return payload ? payload : getCreatePayload(); }
inline W* getCreateData() { return payload ? (payload + nDict) : getCreatePayload(); }
inline W* getCreateLiterals() { return payload ? payload + (nDict + nData) : getCreatePayload(); }
inline W* getEndOfBlock() { return const_cast<W*>(static_cast<const Block&>(*this).getEndOfBlock()); };
inline auto getOffsDict() { return reinterpret_cast<std::uintptr_t>(getCreateDict()) - reinterpret_cast<std::uintptr_t>(registry->head); }
inline auto getOffsData() { return reinterpret_cast<std::uintptr_t>(getCreateData()) - reinterpret_cast<std::uintptr_t>(registry->head); }
inline auto getOffsLiterals() { return reinterpret_cast<std::uintptr_t>(getCreateLiterals()) - reinterpret_cast<std::uintptr_t>(registry->head); }
inline void setNDict(int _ndict)
{
nDict = _ndict;
nStored += nDict;
}
inline void setNData(int _ndata)
{
nData = _ndata;
nStored += nData;
}
inline void setNLiterals(int _nliterals)
{
nLiterals = _nliterals;
nStored += nLiterals;
}
inline int getNDict() const { return nDict; }
inline int getNData() const { return nData; }
inline int getNLiterals() const { return nLiterals; }
inline int getNStored() const { return nStored; }
~Block()
{
if (!registry) { // this is a standalone block owning its data
delete[] payload;
}
}
/// clear itself
void clear()
{
nDict = 0;
nData = 0;
nLiterals = 0;
nStored = 0;
payload = nullptr;
}
/// estimate free size needed to add new block
static size_t estimateSize(int n)
{
return alignSize(n * sizeof(W));
}
// store a dictionary in an empty block
void storeDict(int _ndict, const W* _dict)
{
if (getNStored() > 0) {
throw std::runtime_error("trying to write in occupied block");
}
size_t sz = estimateSize(_ndict);
assert(registry); // this method is valid only for flat version, which has a registry
assert(sz <= registry->getFreeSize());
assert((_ndict > 0) == (_dict != nullptr));
setNDict(_ndict);
if (nDict) {
memcpy(getCreateDict(), _dict, _ndict * sizeof(W));
realignBlock();
}
};
// store a dictionary to a block which can either be empty or contain a dict.
void storeData(int _ndata, const W* _data)
{
if (getNStored() > getNDict()) {
throw std::runtime_error("trying to write in occupied block");
}
size_t sz = estimateSize(_ndata);
assert(registry); // this method is valid only for flat version, which has a registry
assert(sz <= registry->getFreeSize());
assert((_ndata > 0) == (_data != nullptr));
setNData(_ndata);
if (nData) {
memcpy(getCreateData(), _data, _ndata * sizeof(W));
realignBlock();
}
}
// store a dictionary to a block which can either be empty or contain a dict.
void storeLiterals(int _nliterals, const W* _literals)
{
if (getNStored() > getNDict() + getNData()) {
throw std::runtime_error("trying to write in occupied block");
}
size_t sz = estimateSize(_nliterals);
assert(registry); // this method is valid only for flat version, which has a registry
assert(sz <= registry->getFreeSize());
// assert((_nliterals > 0) == (_literals != nullptr));
setNLiterals(_nliterals);
if (nLiterals) {
memcpy(getCreateLiterals(), _literals, _nliterals * sizeof(W));
realignBlock();
}
}
// resize block and free up unused buffer space.
void realignBlock()
{
if (payload) {
size_t sz = estimateSize(getNStored());
registry->offsFreeStart = (reinterpret_cast<char*>(payload) - registry->head) + sz;
}
}
/// store binary blob data (buffer filled from head to tail)
void store(int _ndict, int _ndata, int _nliterals, const W* _dict, const W* _data, const W* _literals)
{
size_t sz = estimateSize(_ndict + _ndata + _nliterals);
assert(registry); // this method is valid only for flat version, which has a registry
assert(sz <= registry->getFreeSize());
assert((_ndict > 0) == (_dict != nullptr));
assert((_ndata > 0) == (_data != nullptr));
// assert(_literals == _data + _nliterals);
setNDict(_ndict);
setNData(_ndata);
setNLiterals(_nliterals);
getCreatePayload(); // do this even for empty block!!!
if (getNStored()) {
payload = reinterpret_cast<W*>(registry->getFreeBlockStart());
if (getNDict()) {
memcpy(getCreateDict(), _dict, _ndict * sizeof(W));
}
if (getNData()) {
memcpy(getCreateData(), _data, _ndata * sizeof(W));
}
if (getNLiterals()) {
memcpy(getCreateLiterals(), _literals, _nliterals * sizeof(W));
}
}
realignBlock();
}
/// relocate to different head position
void relocate(const char* oldHead, char* newHeadData, char* newHeadRegistry)
{
payload = relocatePointer(oldHead, newHeadData, payload);
registry = relocatePointer(oldHead, newHeadRegistry, registry);
}
ClassDefNV(Block, 1);
}; // namespace ctf
///<<======================== Auxiliary classes =======================<<
template <typename H, int N, typename W = uint32_t>
class EncodedBlocks
{
public:
typedef EncodedBlocks<H, N, W> base;
#ifndef __CLING__
template <typename source_T>
using dictionaryType = std::variant<rans::RenormedSparseHistogram<source_T>, rans::RenormedDenseHistogram<source_T>>;
#endif
void setHeader(const H& h)
{
mHeader = h;
}
const H& getHeader() const { return mHeader; }
H& getHeader() { return mHeader; }
std::shared_ptr<H> cloneHeader() const { return std::shared_ptr<H>(new H(mHeader)); } // for dictionary creation
const auto& getRegistry() const { return mRegistry; }
const auto& getMetadata() const { return mMetadata; }
auto& getMetadata(int i) const
{
assert(i < N);
return mMetadata[i];
}
auto& getBlock(int i) const
{
assert(i < N);
return mBlocks[i];
}
#ifndef __CLING__
template <typename source_T>
dictionaryType<source_T> getDictionary(int i, ANSHeader ansVersion = ANSVersionUnspecified) const
{
const auto& block = getBlock(i);
const auto& metadata = getMetadata(i);
ansVersion = checkANSVersion(ansVersion);
assert(static_cast<int64_t>(std::numeric_limits<source_T>::min()) <= static_cast<int64_t>(metadata.max));
assert(static_cast<int64_t>(std::numeric_limits<source_T>::max()) >= static_cast<int64_t>(metadata.min));
// check consistency of metadata and type
[&]() {
const int64_t sourceMin = std::numeric_limits<source_T>::min();
const int64_t sourceMax = std::numeric_limits<source_T>::max();
auto view = rans::trim(rans::HistogramView{block.getDict(), block.getDict() + block.getNDict(), metadata.min});
const int64_t dictMin = view.getMin();
const int64_t dictMax = view.getMax();
assert(dictMin >= metadata.min);
assert(dictMax <= metadata.max);
if ((dictMin < sourceMin) || (dictMax > sourceMax)) {
if (ansVersion == ANSVersionCompat && mHeader.majorVersion == 1 && mHeader.minorVersion == 0 && mHeader.dictTimeStamp < 1653192000000) {
LOGP(warn, "value range of dictionary and target datatype are incompatible: target type [{},{}] vs dictionary [{},{}], tolerate in compat mode for old dictionaries", sourceMin, sourceMax, dictMin, dictMax);
} else {
throw std::runtime_error(fmt::format("value range of dictionary and target datatype are incompatible: target type [{},{}] vs dictionary [{},{}]", sourceMin, sourceMax, dictMin, dictMax));
}
}
}();
if (ansVersion == ANSVersionCompat) {
rans::DenseHistogram<source_T> histogram{block.getDict(), block.getDict() + block.getNDict(), metadata.min};
return rans::compat::renorm(std::move(histogram), metadata.probabilityBits);
} else if (ansVersion == ANSVersion1) {
// dictionary is loaded from an explicit dict file and is stored densly
if (getANSHeader() == ANSVersionUnspecified) {
rans::DenseHistogram<source_T> histogram{block.getDict(), block.getDict() + block.getNDict(), metadata.min};
size_t renormingBits = rans::utils::sanitizeRenormingBitRange(metadata.probabilityBits);
LOG_IF(debug, renormingBits != metadata.probabilityBits)
<< fmt::format("While reading metadata from external dictionary, rANSV1 is rounding renorming precision from {} to {}", metadata.probabilityBits, renormingBits);
return rans::renorm(std::move(histogram), renormingBits, rans::RenormingPolicy::ForceIncompressible);
} else {
// dictionary is elias-delta coded inside the block
if constexpr (sizeof(source_T) > 2) {
return rans::readRenormedSetDictionary(block.getDict(), block.getDict() + block.getNDict(),
static_cast<source_T>(metadata.min), static_cast<source_T>(metadata.max),
metadata.probabilityBits);
} else {
return rans::readRenormedDictionary(block.getDict(), block.getDict() + block.getNDict(),
static_cast<source_T>(metadata.min), static_cast<source_T>(metadata.max),
metadata.probabilityBits);
}
}
} else {
throw std::runtime_error(fmt::format("Failed to load serialized Dictionary. Unsupported ANS Version: {}", static_cast<std::string>(ansVersion)));
}
};
#endif
void setANSHeader(const ANSHeader& h)
{
mANSHeader = h;
}
const ANSHeader& getANSHeader() const { return mANSHeader; }
ANSHeader& getANSHeader() { return mANSHeader; }
static constexpr int getNBlocks() { return N; }
static size_t getMinAlignedSize() { return alignSize(sizeof(base)); }
/// cast arbitrary buffer head to container class. Head is supposed to respect the alignment
static auto get(void* head) { return reinterpret_cast<EncodedBlocks*>(head); }
static auto get(const void* head) { return reinterpret_cast<const EncodedBlocks*>(head); }
/// get const image of the container wrapper, with pointers in the image relocated to new head
static auto getImage(const void* newHead);
/// create container from arbitrary buffer of predefined size (in bytes!!!). Head is supposed to respect the alignment
static auto create(void* head, size_t sz);
/// create container from vector. Head is supposed to respect the alignment
template <typename VD>
static auto create(VD& v);
/// estimate free size needed to add new block
static size_t estimateBlockSize(int n) { return Block<W>::estimateSize(n); }
/// check if empty and valid
bool empty() const { return (mRegistry.offsFreeStart == alignSize(sizeof(*this))) && (mRegistry.size >= mRegistry.offsFreeStart); }
/// check if flat and valid
bool flat() const { return mRegistry.size > 0 && (mRegistry.size >= mRegistry.offsFreeStart) && (mBlocks[0].registry == &mRegistry) && (mBlocks[N - 1].registry == &mRegistry); }
/// clear itself
void clear();
/// Compactify by eliminating empty space
size_t compactify() { return (mRegistry.size = estimateSize()); }
/// total allocated size in bytes
size_t size() const { return mRegistry.size; }
/// size remaining for additional data
size_t getFreeSize() const { return mRegistry.getFreeSize(); }
/// expand the storage to new size in bytes
template <typename buffer_T>
static auto expand(buffer_T& buffer, size_t newsizeBytes);
/// copy itself to flat buffer created on the fly from the vector
template <typename V>
void copyToFlat(V& vec);
/// copy itself to flat buffer created on the fly at the provided pointer. The destination block should be at least of size estimateSize()
void copyToFlat(void* base) { fillFlatCopy(create(base, estimateSize())); }
/// attach to tree
size_t appendToTree(TTree& tree, const std::string& name) const;
/// read from tree to non-flat object
void readFromTree(TTree& tree, const std::string& name, int ev = 0);
/// read from tree to destination buffer vector
template <typename VD>
static void readFromTree(VD& vec, TTree& tree, const std::string& name, int ev = 0);
/// encode vector src to bloc at provided slot
template <typename VE, typename buffer_T>
inline o2::ctf::CTFIOSize encode(const VE& src, int slot, uint8_t symbolTablePrecision, Metadata::OptStore opt, buffer_T* buffer = nullptr, const std::any& encoderExt = {}, float memfc = 1.f)
{
return encode(std::begin(src), std::end(src), slot, symbolTablePrecision, opt, buffer, encoderExt, memfc);
}
/// encode vector src to bloc at provided slot
template <typename input_IT, typename buffer_T>
o2::ctf::CTFIOSize encode(const input_IT srcBegin, const input_IT srcEnd, int slot, uint8_t symbolTablePrecision, Metadata::OptStore opt, buffer_T* buffer = nullptr, const std::any& encoderExt = {}, float memfc = 1.f);
/// decode block at provided slot to destination vector (will be resized as needed)
template <class container_T, class container_IT = typename container_T::iterator>
o2::ctf::CTFIOSize decode(container_T& dest, int slot, const std::any& decoderExt = {}) const;
/// decode block at provided slot to destination pointer, the needed space assumed to be available
template <typename D_IT, std::enable_if_t<detail::is_iterator_v<D_IT>, bool> = true>
o2::ctf::CTFIOSize decode(D_IT dest, int slot, const std::any& decoderExt = {}) const;
#ifndef __CLING__
/// create a special EncodedBlocks containing only dictionaries made from provided vector of frequency tables
static std::vector<char> createDictionaryBlocks(const std::vector<rans::DenseHistogram<int32_t>>& vfreq, const std::vector<Metadata>& prbits);
#endif
/// print itself
void print(const std::string& prefix = "", int verbosity = 1) const;
void dump(const std::string& prefix = "", int ncol = 20) const;
protected:
static_assert(N > 0, "number of encoded blocks < 1");
Registry mRegistry; //
ANSHeader mANSHeader; // ANS header
H mHeader; // detector specific header
std::array<Metadata, N> mMetadata; // compressed block's details
std::array<Block<W>, N> mBlocks; //! this is in fact stored, but to overcome TBuffer limits we have to define the branches per block!!!
inline static constexpr Metadata::OptStore FallbackStorageType{Metadata::OptStore::NONE};
/// setup internal structure and registry for given buffer size (in bytes!!!)
void init(size_t sz);
/// relocate to different head position, newHead points on start of the dynamic buffer holding the data.
/// the address of the static part might be actually different (wrapper). This different newHead and
/// wrapper addresses must be used when the buffer pointed by newHead is const (e.g. received from the
/// DPL input), in this case we create a wrapper, which points on these const data
static void relocate(const char* oldHead, char* newHead, char* wrapper, size_t newsize = 0);
/// Estimate size of the buffer needed to store all compressed data in a contiguous block of memory, accounting for the alignment
/// This method is to be called after reading object from the tree as a non-flat object!
size_t estimateSize() const;
/// do the same using metadata info
size_t estimateSizeFromMetadata() const;
/// Create its own flat copy in the destination empty flat object
void fillFlatCopy(EncodedBlocks& dest) const;
/// add and fill single branch
template <typename D>
static size_t fillTreeBranch(TTree& tree, const std::string& brname, D& dt, int compLevel, int splitLevel = 99);
/// read single branch
template <typename D>
static bool readTreeBranch(TTree& tree, const std::string& brname, D& dt, int ev = 0);
template <typename T>
auto expandStorage(size_t slot, size_t nElemets, T* buffer = nullptr) -> decltype(auto);
inline ANSHeader checkANSVersion(ANSHeader ansVersion) const
{
auto ctfANSHeader = getANSHeader();
ANSHeader ret{ANSVersionUnspecified};
const bool isEqual{ansVersion == ctfANSHeader};
const bool isHeaderUnspecified{ctfANSHeader == ANSVersionUnspecified};
if (isEqual) {
if (isHeaderUnspecified) {
throw std::runtime_error{fmt::format("Missmatch of ANSVersions, trying to encode/decode CTF with ANS Version Header {} with ANS Version {}",
static_cast<std::string>(ctfANSHeader),
static_cast<std::string>(ansVersion))};
} else {
ret = ctfANSHeader;
}
} else {
if (isHeaderUnspecified) {
ret = ansVersion;
} else {
ret = ctfANSHeader;
}
}
return ret;
};
template <typename input_IT, typename buffer_T>
o2::ctf::CTFIOSize entropyCodeRANSCompat(const input_IT srcBegin, const input_IT srcEnd, int slot, uint8_t symbolTablePrecision, buffer_T* buffer = nullptr, const std::any& encoderExt = {}, float memfc = 1.f);
template <typename input_IT, typename buffer_T>
o2::ctf::CTFIOSize entropyCodeRANSV1(const input_IT srcBegin, const input_IT srcEnd, int slot, Metadata::OptStore opt, buffer_T* buffer = nullptr, const std::any& encoderExt = {}, float memfc = 1.f);
template <typename input_IT, typename buffer_T>
o2::ctf::CTFIOSize encodeRANSV1External(const input_IT srcBegin, const input_IT srcEnd, int slot, const std::any& encoderExt, buffer_T* buffer = nullptr, double_t sizeEstimateSafetyFactor = 1);
template <typename input_IT, typename buffer_T>
o2::ctf::CTFIOSize encodeRANSV1Inplace(const input_IT srcBegin, const input_IT srcEnd, int slot, Metadata::OptStore opt, buffer_T* buffer = nullptr, double_t sizeEstimateSafetyFactor = 1);
#ifndef __CLING__
template <typename input_IT, typename buffer_T>
o2::ctf::CTFIOSize pack(const input_IT srcBegin, const input_IT srcEnd, int slot, rans::Metrics<typename std::iterator_traits<input_IT>::value_type> metrics, buffer_T* buffer = nullptr);
template <typename input_IT, typename buffer_T>
inline o2::ctf::CTFIOSize pack(const input_IT srcBegin, const input_IT srcEnd, int slot, buffer_T* buffer = nullptr)
{
using source_type = typename std::iterator_traits<input_IT>::value_type;
rans::Metrics<source_type> metrics{};
metrics.getDatasetProperties().numSamples = std::distance(srcBegin, srcEnd);
if (metrics.getDatasetProperties().numSamples != 0) {
const auto [minIter, maxIter] = std::minmax_element(srcBegin, srcEnd);
metrics.getDatasetProperties().min = *minIter;
metrics.getDatasetProperties().max = *maxIter;
// special case: if min === max, the range is 0 and the data can be reconstructed just via the metadata.
metrics.getDatasetProperties().alphabetRangeBits =
rans::utils::getRangeBits(metrics.getDatasetProperties().min,
metrics.getDatasetProperties().max);
}
return pack(srcBegin, srcEnd, slot, metrics, buffer);
}
#endif
template <typename input_IT, typename buffer_T>
o2::ctf::CTFIOSize store(const input_IT srcBegin, const input_IT srcEnd, int slot, Metadata::OptStore opt, buffer_T* buffer = nullptr);
// decode
template <typename dst_IT>
CTFIOSize decodeCompatImpl(dst_IT dest, int slot, const std::any& decoderExt) const;
template <typename dst_IT>
CTFIOSize decodeRansV1Impl(dst_IT dest, int slot, const std::any& decoderExt) const;
template <typename dst_IT>
CTFIOSize decodeUnpackImpl(dst_IT dest, int slot) const;
template <typename dst_IT>
CTFIOSize decodeCopyImpl(dst_IT dest, int slot) const;
ClassDefNV(EncodedBlocks, 3);
}; // namespace ctf
///_____________________________________________________________________________
/// read from tree to non-flat object
template <typename H, int N, typename W>
void EncodedBlocks<H, N, W>::readFromTree(TTree& tree, const std::string& name, int ev)
{
readTreeBranch(tree, o2::utils::Str::concat_string(name, "_wrapper."), *this, ev);
for (int i = 0; i < N; i++) {
readTreeBranch(tree, o2::utils::Str::concat_string(name, "_block.", std::to_string(i), "."), mBlocks[i], ev);
}
}
///_____________________________________________________________________________
/// read from tree to destination buffer vector
template <typename H, int N, typename W>
template <typename VD>
void EncodedBlocks<H, N, W>::readFromTree(VD& vec, TTree& tree, const std::string& name, int ev)
{
auto tmp = create(vec);
if (!readTreeBranch(tree, o2::utils::Str::concat_string(name, "_wrapper."), *tmp, ev)) {
throw std::runtime_error(fmt::format("Failed to read CTF header for {}", name));
}
tmp = tmp->expand(vec, tmp->estimateSizeFromMetadata());
const auto& meta = tmp->getMetadata();
for (int i = 0; i < N; i++) {
Block<W> bl;
readTreeBranch(tree, o2::utils::Str::concat_string(name, "_block.", std::to_string(i), "."), bl, ev);
assert(meta[i].nDictWords == bl.getNDict());
assert(meta[i].nDataWords == bl.getNData());
assert(meta[i].nLiteralWords == bl.getNLiterals());
tmp->mBlocks[i].store(bl.getNDict(), bl.getNData(), bl.getNLiterals(), bl.getDict(), bl.getData(), bl.getLiterals());
}
}
///_____________________________________________________________________________
/// attach to tree
template <typename H, int N, typename W>
size_t EncodedBlocks<H, N, W>::appendToTree(TTree& tree, const std::string& name) const
{
long s = 0;
s += fillTreeBranch(tree, o2::utils::Str::concat_string(name, "_wrapper."), const_cast<base&>(*this), WrappersCompressionLevel, WrappersSplitLevel);
for (int i = 0; i < N; i++) {
int compression = mMetadata[i].opt == Metadata::OptStore::ROOTCompression ? 1 : 0;
s += fillTreeBranch(tree, o2::utils::Str::concat_string(name, "_block.", std::to_string(i), "."), const_cast<Block<W>&>(mBlocks[i]), compression);
}
tree.SetEntries(tree.GetEntries() + 1);
return s;
}
///_____________________________________________________________________________
/// read single branch
template <typename H, int N, typename W>
template <typename D>
bool EncodedBlocks<H, N, W>::readTreeBranch(TTree& tree, const std::string& brname, D& dt, int ev)
{
auto* br = tree.GetBranch(brname.c_str());
if (!br) {
LOG(debug) << "Branch " << brname << " is absent";
return false;
}
auto* ptr = &dt;
br->SetAddress(&ptr);
br->GetEntry(ev);
br->ResetAddress();
return true;
}
///_____________________________________________________________________________
/// add and fill single branch
template <typename H, int N, typename W>
template <typename D>
inline size_t EncodedBlocks<H, N, W>::fillTreeBranch(TTree& tree, const std::string& brname, D& dt, int compLevel, int splitLevel)
{
auto* br = tree.GetBranch(brname.c_str());
if (!br) {
br = tree.Branch(brname.c_str(), &dt, 512, splitLevel);
br->SetCompressionLevel(compLevel);
}
return br->Fill();
}
///_____________________________________________________________________________
/// Create its own flat copy in the destination empty flat object
template <typename H, int N, typename W>
void EncodedBlocks<H, N, W>::fillFlatCopy(EncodedBlocks& dest) const
{
assert(dest.empty() && dest.mRegistry.getFreeSize() < estimateSize());
dest.mANSHeader = mANSHeader;
dest.mHeader = mHeader;
dest.mMetadata = mMetadata;
for (int i = 0; i < N; i++) {
dest.mBlocks[i].store(mBlocks[i].getNDict(), mBlocks[i].getNData(), mBlocks[i].getDict(), mBlocks[i].getData());
}
}
///_____________________________________________________________________________
/// Copy itself to flat buffer created on the fly from the vector
template <typename H, int N, typename W>
template <typename V>
void EncodedBlocks<H, N, W>::copyToFlat(V& vec)
{
auto vtsz = sizeof(typename std::remove_reference<decltype(vec)>::type::value_type), sz = estimateSize();
vec.resize(sz / vtsz);
copyToFlat(vec.data());
}
///_____________________________________________________________________________
/// Estimate size of the buffer needed to store all compressed data in a contiguos block of memory, accounting for alignment
/// This method is to be called after reading object from the tree as a non-flat object!
template <typename H, int N, typename W>
size_t EncodedBlocks<H, N, W>::estimateSize() const
{
size_t sz = 0;
sz += alignSize(sizeof(*this));
for (int i = 0; i < N; i++) {
sz += alignSize(mBlocks[i].nStored * sizeof(W));
}
return sz;
}
///_____________________________________________________________________________
/// Estimate size from metadata
/// This method is to be called after reading object from the tree as a non-flat object!
template <typename H, int N, typename W>
size_t EncodedBlocks<H, N, W>::estimateSizeFromMetadata() const
{
size_t sz = alignSize(sizeof(*this));
for (int i = 0; i < N; i++) {
sz += alignSize((mMetadata[i].nDictWords + mMetadata[i].nDataWords + mMetadata[i].nLiteralWords) * sizeof(W));
}
return sz;
}
///_____________________________________________________________________________
/// expand the storage to new size in bytes
template <typename H, int N, typename W>
template <typename buffer_T>
auto EncodedBlocks<H, N, W>::expand(buffer_T& buffer, size_t newsizeBytes)
{
auto buftypesize = sizeof(typename std::remove_reference<decltype(buffer)>::type::value_type);
auto* oldHead = get(buffer.data())->mRegistry.head;
buffer.resize(alignSize(newsizeBytes) / buftypesize);
relocate(oldHead, reinterpret_cast<char*>(buffer.data()), reinterpret_cast<char*>(buffer.data()), newsizeBytes);
return get(buffer.data());
}
///_____________________________________________________________________________
/// relocate to different head position, newHead points on start of the dynamic buffer holding the data.
/// the address of the static part might be actually different (wrapper). This different newHead and
/// wrapper addresses must be used when the buffer pointed by newHead is const (e.g. received from the
/// DPL input), in this case we create a wrapper, which points on these const data
template <typename H, int N, typename W>
void EncodedBlocks<H, N, W>::relocate(const char* oldHead, char* newHead, char* wrapper, size_t newsize)
{
auto newStr = get(wrapper);
for (int i = 0; i < N; i++) {
newStr->mBlocks[i].relocate(oldHead, newHead, wrapper);
}
newStr->mRegistry.head = newHead; // newHead points on the real data
// if asked, update the size
if (newsize) { // in bytes!!!
assert(newStr->estimateSize() <= newsize);
newStr->mRegistry.size = newsize;
}
}
///_____________________________________________________________________________
/// setup internal structure and registry for given buffer size (in bytes!!!)
template <typename H, int N, typename W>
void EncodedBlocks<H, N, W>::init(size_t sz)
{
mRegistry.head = reinterpret_cast<char*>(this);
mRegistry.size = sz;
mRegistry.offsFreeStart = alignSize(sizeof(*this));
for (int i = 0; i < N; i++) {
mMetadata[i].clear();
mBlocks[i].registry = &mRegistry;
mBlocks[i].clear();
}
}
///_____________________________________________________________________________
/// clear itself
template <typename H, int N, typename W>
void EncodedBlocks<H, N, W>::clear()
{
for (int i = 0; i < N; i++) {
mBlocks[i].clear();
mMetadata[i].clear();
}
mRegistry.offsFreeStart = alignSize(sizeof(*this));
}
///_____________________________________________________________________________
/// get const image of the container wrapper, with pointers in the image relocated to new head
template <typename H, int N, typename W>
auto EncodedBlocks<H, N, W>::getImage(const void* newHead)
{
assert(newHead);
auto image(*get(newHead)); // 1st make a shalow copy
// now fix its pointers
// we don't modify newHead, but still need to remove constness for relocation interface
relocate(image.mRegistry.head, const_cast<char*>(reinterpret_cast<const char*>(newHead)), reinterpret_cast<char*>(&image));
return image;
}
///_____________________________________________________________________________
/// create container from arbitrary buffer of predefined size (in bytes!!!). Head is supposed to respect the alignment
template <typename H, int N, typename W>
inline auto EncodedBlocks<H, N, W>::create(void* head, size_t sz)
{
const H defh;
auto b = get(head);
b->init(sz);
b->setHeader(defh);
return b;
}
///_____________________________________________________________________________
/// create container from arbitrary buffer of predefined size (in bytes!!!). Head is supposed to respect the alignment
template <typename H, int N, typename W>
template <typename VD>
inline auto EncodedBlocks<H, N, W>::create(VD& v)
{
size_t vsz = sizeof(typename std::remove_reference<decltype(v)>::type::value_type); // size of the element of the buffer
auto baseSize = getMinAlignedSize() / vsz;
if (v.size() < baseSize) {
v.resize(baseSize);
}
return create(v.data(), v.size() * vsz);
}
///_____________________________________________________________________________
/// print itself
template <typename H, int N, typename W>
void EncodedBlocks<H, N, W>::print(const std::string& prefix, int verbosity) const
{
if (verbosity > 0) {
LOG(info) << prefix << "Container of " << N << " blocks, size: " << size() << " bytes, unused: " << getFreeSize();
for (int i = 0; i < N; i++) {
LOG(info) << "Block " << i << " for " << static_cast<uint32_t>(mMetadata[i].messageLength) << " message words of "
<< static_cast<uint32_t>(mMetadata[i].messageWordSize) << " bytes |"
<< " NDictWords: " << mBlocks[i].getNDict() << " NDataWords: " << mBlocks[i].getNData()
<< " NLiteralWords: " << mBlocks[i].getNLiterals();
}
} else if (verbosity == 0) {
size_t inpSize = 0, ndict = 0, ndata = 0, nlit = 0;
for (int i = 0; i < N; i++) {
inpSize += mMetadata[i].messageLength * mMetadata[i].messageWordSize;
ndict += mBlocks[i].getNDict();
ndata += mBlocks[i].getNData();
nlit += mBlocks[i].getNLiterals();
}
LOG(info) << prefix << N << " blocks, input size: " << inpSize << ", output size: " << size()
<< " NDictWords: " << ndict << " NDataWords: " << ndata << " NLiteralWords: " << nlit;
}
}
///_____________________________________________________________________________
template <typename H, int N, typename W>
template <class container_T, class container_IT>
inline o2::ctf::CTFIOSize EncodedBlocks<H, N, W>::decode(container_T& dest, // destination container
int slot, // slot of the block to decode
const std::any& decoderExt) const // optional externally provided decoder
{
dest.resize(mMetadata[slot].messageLength); // allocate output buffer
return decode(std::begin(dest), slot, decoderExt);
}
///_____________________________________________________________________________
template <typename H, int N, typename W>
template <typename D_IT, std::enable_if_t<detail::is_iterator_v<D_IT>, bool>>
CTFIOSize EncodedBlocks<H, N, W>::decode(D_IT dest, // iterator to destination
int slot, // slot of the block to decode
const std::any& decoderExt) const // optional externally provided decoder
{
// get references to the right data
const auto& ansVersion = getANSHeader();
const auto& block = mBlocks[slot];
const auto& md = mMetadata[slot];
LOGP(debug, "Slot{} | NStored={} Ndict={} nData={}, MD: messageLength:{} opt:{} min:{} max:{} offs:{} width:{} ", slot, block.getNStored(), block.getNDict(), block.getNData(), md.messageLength, (int)md.opt, md.min, md.max, md.literalsPackingOffset, md.literalsPackingWidth);
constexpr size_t word_size = sizeof(W);
if (ansVersion == ANSVersionCompat) {
if (!block.getNStored()) {
return {0, md.getUncompressedSize(), md.getCompressedSize() * word_size};
}
if (md.opt == Metadata::OptStore::EENCODE) {
return decodeCompatImpl(dest, slot, decoderExt);
} else {
return decodeCopyImpl(dest, slot);
}
} else if (ansVersion == ANSVersion1) {
if (md.opt == Metadata::OptStore::PACK) {
return decodeUnpackImpl(dest, slot);
}
if (!block.getNStored()) {
return {0, md.getUncompressedSize(), md.getCompressedSize() * word_size};
}
if (md.opt == Metadata::OptStore::EENCODE) {
return decodeRansV1Impl(dest, slot, decoderExt);
} else {
return decodeCopyImpl(dest, slot);
}
} else {
throw std::runtime_error("unsupported ANS Version");
}
};
#ifndef __CLING__
template <typename H, int N, typename W>
template <typename dst_IT>
CTFIOSize EncodedBlocks<H, N, W>::decodeCompatImpl(dst_IT dstBegin, int slot, const std::any& decoderExt) const
{
// get references to the right data
const auto& block = mBlocks[slot];
const auto& md = mMetadata[slot];
using dst_type = typename std::iterator_traits<dst_IT>::value_type;
using decoder_type = typename rans::compat::decoder_type<dst_type>;
std::optional<decoder_type> inplaceDecoder{};
if (md.nDictWords > 0) {
inplaceDecoder = decoder_type{std::get<rans::RenormedDenseHistogram<dst_type>>(this->getDictionary<dst_type>(slot))};
} else if (!decoderExt.has_value()) {
throw std::runtime_error("neither dictionary nor external decoder provided");
}
auto getDecoder = [&]() -> const decoder_type& {
if (inplaceDecoder.has_value()) {
return inplaceDecoder.value();
} else {
return std::any_cast<const decoder_type&>(decoderExt);
}
};
const size_t NDecoderStreams = rans::compat::defaults::CoderPreset::nStreams;
if (block.getNLiterals()) {
auto* literalsEnd = reinterpret_cast<const dst_type*>(block.getLiterals()) + md.nLiterals;
getDecoder().process(block.getData() + block.getNData(), dstBegin, md.messageLength, NDecoderStreams, literalsEnd);
} else {
getDecoder().process(block.getData() + block.getNData(), dstBegin, md.messageLength, NDecoderStreams);
}
return {0, md.getUncompressedSize(), md.getCompressedSize() * sizeof(W)};
};
template <typename H, int N, typename W>
template <typename dst_IT>