Project
Loading...
Searching...
No Matches
ASoA.cxx
Go to the documentation of this file.
1// Copyright 2019-2020 CERN and copyright holders of ALICE O2.
2// See https://alice-o2.web.cern.ch/copyright for details of the copyright holders.
3// All rights not expressly granted are reserved.
4//
5// This software is distributed under the terms of the GNU General Public
6// License v3 (GPL Version 3), copied verbatim in the file "COPYING".
7//
8// In applying this license CERN does not waive the privileges and immunities
9// granted to it by virtue of its status as an Intergovernmental Organization
10// or submit itself to any jurisdiction.
11
12#include "Framework/ASoA.h"
13#include "ArrowDebugHelpers.h"
15#include <arrow/util/key_value_metadata.h>
16#include <arrow/util/config.h>
17#include <TMemFile.h>
18#include <TClass.h>
19#include <TTree.h>
20#include <TH1.h>
21#include <TError.h>
22
23namespace o2::soa
24{
25void accessingInvalidIndexFor(const char* getter)
26{
27 throw o2::framework::runtime_error_f("Accessing invalid index for %s", getter);
28}
29void dereferenceWithWrongType(const char* getter, const char* target)
30{
31 throw o2::framework::runtime_error_f("Trying to dereference index with a wrong type in %s_as<T> for base target \"%s\". Note that if you have several compatible index targets in your process() signature, the last one will be the one actually bound.", getter, target);
32}
34{
35 throw o2::framework::runtime_error_f("Null selection for %d (arg %d), missing Filter declaration?", hash, ai);
36}
37
38void getterNotFound(const char* targetColumnLabel)
39{
40 throw o2::framework::runtime_error_f("Getter for \"%s\" not found", targetColumnLabel);
41}
42
44{
45 throw framework::runtime_error("columnLabel: must not be empty");
46}
47
49{
51 rows.resize(sel->GetNumSlots());
52 for (auto i = 0; i < sel->GetNumSlots(); ++i) {
53 rows[i] = sel->GetIndex(i);
54 }
55 return rows;
56}
57
58SelectionVector sliceSelection(std::span<int64_t const> const& mSelectedRows, int64_t nrows, uint64_t offset)
59{
60 auto start = offset;
61 auto end = start + nrows;
62 auto start_iterator = std::lower_bound(mSelectedRows.begin(), mSelectedRows.end(), start);
63 auto stop_iterator = std::lower_bound(start_iterator, mSelectedRows.end(), end);
64 SelectionVector slicedSelection{start_iterator, stop_iterator};
65 std::ranges::transform(slicedSelection.begin(), slicedSelection.end(), slicedSelection.begin(),
66 [&start](int64_t idx) {
67 return idx - static_cast<int64_t>(start);
68 });
69 return slicedSelection;
70}
71
72namespace
73{
74template <typename T>
75 requires(std::same_as<T, std::string>)
76auto makeString(T const& str)
77{
78 return str.c_str();
79}
80template <typename T>
81 requires(std::same_as<T, const char*>)
82auto makeString(T const& str)
83{
84 return str;
85}
86
87template <typename T>
88void canNotJoin(std::vector<std::shared_ptr<arrow::Table>> const& tables, std::span<T> labels)
89{
90 for (auto i = 0U; i < tables.size() - 1; ++i) {
91 if (tables[i]->num_rows() != tables[i + 1]->num_rows()) {
92 throw o2::framework::runtime_error_f("Tables %s and %s have different sizes (%d vs %d) and cannot be joined!",
93 makeString(labels[i]), makeString(labels[i + 1]), tables[i]->num_rows(), tables[i + 1]->num_rows());
94 }
95 }
96}
97
98template <typename T>
99void IncompatibleRanges(std::vector<ArrowTableRef> const& tables, std::span<T> labels)
100{
101 auto loc = std::ranges::adjacent_find(tables, [](auto const& l, auto const& r) { return l.range != r.range; });
102 if (loc != std::ranges::cend(tables)) {
103 auto pos = std::distance(tables.begin(), loc);
104 auto next = loc + 1;
105 if (labels.empty()) {
106 throw o2::framework::runtime_error_f("Incompatible ranges at %d: (%zu, %z) vs. (%zu, %z)", pos, loc->range.offset, loc->range.size, next->range.offset, next->range.size);
107 } else {
108 throw o2::framework::runtime_error_f("Incompatible ranges at %d between %s and %s: (%zu, %z) vs. (%zu, %z)", pos, makeString(labels[pos]), makeString(labels[pos + 1]), loc->range.offset, loc->range.size, next->range.offset, next->range.size);
109 }
110 }
111}
112
113std::shared_ptr<arrow::Table> joinTablesImpl(std::ranges::input_range auto tables)
114{
115 std::vector<std::shared_ptr<arrow::Field>> fields;
116 std::vector<std::shared_ptr<arrow::ChunkedArray>> columns;
117 bool notEmpty = (tables.front()->num_rows() != 0);
118 std::ranges::for_each(tables, [&fields, &columns, notEmpty](auto const& t) {
119 std::ranges::copy(t->fields(), std::back_inserter(fields));
120 if (notEmpty) {
121 std::ranges::copy(t->columns(), std::back_inserter(columns));
122 }
123 });
124 auto schema = std::make_shared<arrow::Schema>(fields);
125 return arrow::Table::Make(schema, columns);
126}
127
128template <typename T>
129ArrowTableRef joinTablesImpl(std::ranges::input_range auto tables, std::span<T> labels)
130{
131 if (tables.size() == 1) {
132 return tables.front();
133 }
134 IncompatibleRanges(tables, labels);
135 ArrowRange commonRange{tables.front().range};
136 return {joinTablesImpl(tables), commonRange};
137}
138} // namespace
139
140o2::soa::ArrowTableRef ArrowHelpers::joinTables(std::vector<std::shared_ptr<arrow::Table>>&& tables)
141{
142 std::vector<ArrowTableRef> refs;
143 std::ranges::transform(tables, std::back_inserter(refs), [](auto const& table) { return ArrowTableRef{table}; });
144 return joinTablesImpl(refs, std::span<const char* const>());
145}
146
147o2::soa::ArrowTableRef ArrowHelpers::joinTables(std::vector<o2::soa::ArrowTableRef>&& tables)
148{
149 return joinTablesImpl(tables, std::span<const char* const>());
150}
151
152o2::soa::ArrowTableRef ArrowHelpers::joinTables(std::vector<o2::soa::ArrowTableRef>&& tables, std::span<const char* const> labels)
153{
154 return joinTablesImpl(tables, labels);
155}
156
157o2::soa::ArrowTableRef ArrowHelpers::joinTables(std::vector<o2::soa::ArrowTableRef>&& tables, std::span<const std::string> labels)
158{
159 return joinTablesImpl(tables, labels);
160}
161
162o2::soa::ArrowTableRef ArrowHelpers::joinTables(std::vector<std::shared_ptr<arrow::Table>>&& tables, std::span<const char* const> labels)
163{
164 canNotJoin(tables, labels);
165 return o2::soa::ArrowTableRef{joinTablesImpl(tables)};
166}
167
168o2::soa::ArrowTableRef ArrowHelpers::joinTables(std::vector<std::shared_ptr<arrow::Table>>&& tables, std::span<const std::string> labels)
169{
170 canNotJoin(tables, labels);
171 return o2::soa::ArrowTableRef{joinTablesImpl(tables)};
172}
173
174o2::soa::ArrowTableRef ArrowHelpers::concatTables(std::vector<o2::soa::ArrowTableRef>&& tables)
175{
176 if (tables.size() == 1) {
177 return tables.front();
178 }
179 std::vector<std::shared_ptr<arrow::ChunkedArray>> columns;
180 std::vector<std::shared_ptr<arrow::Field>> resultFields = tables.front()->schema()->fields();
181 auto compareFields = [](std::shared_ptr<arrow::Field> const& f1, std::shared_ptr<arrow::Field> const& f2) {
182 // Let's do this with stable sorting.
183 return (!f1->Equals(f2)) && (f1->name() < f2->name());
184 };
185
186 for (auto i = 1; i < tables.size(); ++i) {
187 auto const& fields = tables[i]->fields();
188 std::vector<std::shared_ptr<arrow::Field>> intersection;
189 std::ranges::set_intersection(resultFields, fields, std::back_inserter(intersection), compareFields);
190 resultFields.swap(intersection);
191 }
192
193 for (auto const& field : resultFields) {
194 arrow::ArrayVector chunks;
195 for (auto const& table : tables) {
196 auto ci = table->schema()->GetFieldIndex(field->name());
197 if (ci == -1) {
198 throw framework::runtime_error_f("Unable to find field {}", field->name().c_str());
199 }
200 auto column = table->column(ci);
201 auto otherChunks = column->chunks();
202 chunks.insert(chunks.end(), otherChunks.begin(), otherChunks.end());
203 }
204 columns.push_back(std::make_shared<arrow::ChunkedArray>(chunks));
205 }
206
207 return {arrow::Table::Make(std::make_shared<arrow::Schema>(resultFields), columns)};
208}
209
210arrow::ChunkedArray* getIndexFromLabel(arrow::Table* table, std::string_view label)
211{
212 // Take the exact-match common case first (string_view comparison checks length
213 // then memcmp), and fall back to a case-insensitive scan only when the labels
214 // differ in case.
215 auto field = std::ranges::find_if(table->schema()->fields(), [label](std::shared_ptr<arrow::Field> const& f) {
216 std::string_view name = f->name();
217 return label == name ||
218 std::ranges::equal(label, name, [](char c1, char c2) {
219 return asciiToLower(c1) == asciiToLower(c2);
220 });
221 });
222 if (field == table->schema()->fields().end()) {
223 o2::framework::throw_error(o2::framework::runtime_error_f("Unable to find column with label %s.", label));
224 }
225 return table->column(std::distance(table->schema()->fields().begin(), field)).get();
226}
227
228void notBoundTable(const char* tableName)
229{
230 throw o2::framework::runtime_error_f("Index pointing to %s is not bound! Did you subscribe to the table?", tableName);
231}
232
233void notFoundColumn(const char* label, const char* key)
234{
235 throw o2::framework::runtime_error_f(R"(Preslice not valid: table "%s" (or join based on it) does not have column "%s")", label, key);
236}
237
238void missingOptionalPreslice(const char* label, const char* key)
239{
240 throw o2::framework::runtime_error_f(R"(Optional Preslice with missing binding used: table "%s" (or join based on it) does not have column "%s")", label, key);
241}
242
243void* extractCCDBPayload(char* payload, size_t size, TClass const* cl, const char* what)
244{
245 Int_t previousErrorLevel = gErrorIgnoreLevel;
246 gErrorIgnoreLevel = kFatal;
247 // does it have a flattened headers map attached in the end?
248 TMemFile file("name", (char*)payload, size, "READ");
249 gErrorIgnoreLevel = previousErrorLevel;
250 if (file.IsZombie()) {
251 return nullptr;
252 }
253
254 if (!cl) {
255 return nullptr;
256 }
257 auto object = file.GetObjectChecked(what, cl);
258 if (!object) {
259 // it could be that object was stored with previous convention
260 // where the classname was taken as key
261 std::string objectName(cl->GetName());
262 objectName.erase(std::find_if(objectName.rbegin(), objectName.rend(), [](unsigned char ch) {
263 return !std::isspace(ch);
264 }).base(),
265 objectName.end());
266 objectName.erase(objectName.begin(), std::find_if(objectName.begin(), objectName.end(), [](unsigned char ch) {
267 return !std::isspace(ch);
268 }));
269
270 object = file.GetObjectChecked(objectName.c_str(), cl);
271 LOG(warn) << "Did not find object under expected name " << what;
272 if (!object) {
273 return nullptr;
274 }
275 LOG(warn) << "Found object under deprecated name " << cl->GetName();
276 }
277 auto result = object;
278 // We need to handle some specific cases as ROOT ties them deeply
279 // to the file they are contained in
280 if (cl->InheritsFrom("TObject")) {
281 // make a clone
282 // detach from the file
283 auto tree = dynamic_cast<TTree*>((TObject*)object);
284 if (tree) {
285 tree->LoadBaskets(0x1L << 32); // make tree memory based
286 tree->SetDirectory(nullptr);
287 result = tree;
288 } else {
289 auto h = dynamic_cast<TH1*>((TObject*)object);
290 if (h) {
291 h->SetDirectory(nullptr);
292 result = h;
293 }
294 }
295 }
296 return result;
297}
298
300{
301 return [newOrigin](framework::ConcreteDataMatcher&& m) {
302 if ((m.origin == header::DataOrigin{"AOD"}) && (newOrigin != header::DataOrigin{"AOD"})) {
303 m.origin = newOrigin;
304 }
305 return m;
306 };
307}
308
309} // namespace o2::soa
310
311namespace o2::framework
312{
313std::string cutString(std::string&& str)
314{
315 auto pos = str.find('_');
316 if (pos != std::string::npos) {
317 str.erase(pos);
318 }
319 return str;
320}
321
322std::string strToUpper(std::string&& str)
323{
324 std::transform(str.begin(), str.end(), str.begin(), [](unsigned char c) { return std::toupper(c); });
325 return str;
326}
327
329{
330 return binding == "[MISSING]";
331}
332
334{
335 return bindingKey;
336}
337
342
347
349{
350 auto [offset_, count] = this->sliceInfo.getSliceFor(value);
351 return input.slice({static_cast<uint64_t>(offset_), count});
352}
353
354std::span<const int64_t> PreslicePolicyGeneral::getSliceFor(int value) const
355{
356 return this->sliceInfo.getSliceFor(value);
357}
358} // namespace o2::framework
std::vector< std::string > labels
uint32_t hash
std::shared_ptr< arrow::Schema > schema
std::vector< std::shared_ptr< arrow::Field > > fields
int32_t i
uint16_t pos
Definition RawData.h:3
uint32_t c
Definition RawData.h:2
StringRef key
Class for time synchronization of RawReader instances.
const GLfloat * m
Definition glcorearb.h:4066
GLint GLsizei count
Definition glcorearb.h:399
GLuint64EXT * result
Definition glcorearb.h:5662
GLsizeiptr size
Definition glcorearb.h:659
GLuint GLuint end
Definition glcorearb.h:469
GLdouble f
Definition glcorearb.h:310
GLsizei const GLfloat * value
Definition glcorearb.h:819
GLenum target
Definition glcorearb.h:1641
GLintptr offset
Definition glcorearb.h:660
GLuint GLsizei const GLchar * label
Definition glcorearb.h:2519
GLuint object
Definition glcorearb.h:4041
GLboolean r
Definition glcorearb.h:1233
GLuint start
Definition glcorearb.h:469
std::shared_ptr< gandiva::SelectionVector > Selection
Definition Expressions.h:46
Defining ITS Vertex explicitly as messageable.
Definition Cartesian.h:288
RuntimeErrorRef runtime_error(const char *)
void throw_error(RuntimeErrorRef)
std::string strToUpper(std::string &&str)
Definition ASoA.cxx:322
RuntimeErrorRef runtime_error_f(const char *,...)
std::string cutString(std::string &&str)
Definition ASoA.cxx:313
void * extractCCDBPayload(char *payload, size_t size, TClass const *cl, const char *what)
Definition ASoA.cxx:243
SelectionVector selectionToVector(gandiva::Selection const &sel)
Definition ASoA.cxx:48
void notBoundTable(const char *tableName)
Definition ASoA.cxx:228
SelectionVector sliceSelection(std::span< int64_t const > const &mSelectedRows, int64_t nrows, uint64_t offset)
Definition ASoA.cxx:58
std::vector< int64_t > SelectionVector
Definition ASoA.h:444
void missingFilterDeclaration(int hash, int ai)
Definition ASoA.cxx:33
void accessingInvalidIndexFor(const char *getter)
Definition ASoA.cxx:25
void dereferenceWithWrongType(const char *getter, const char *target)
Definition ASoA.cxx:29
void emptyColumnLabel()
Definition ASoA.cxx:43
void getterNotFound(const char *targetColumnLabel)
Definition ASoA.cxx:38
void missingOptionalPreslice(const char *label, const char *key)
Definition ASoA.cxx:238
std::function< framework::ConcreteDataMatcher(framework::ConcreteDataMatcher &&)> originReplacement(header::DataOrigin newOrigin)
Definition ASoA.cxx:299
arrow::ChunkedArray * getIndexFromLabel(arrow::Table *table, std::string_view label)
Definition ASoA.cxx:210
void notFoundColumn(const char *label, const char *key)
Definition ASoA.cxx:233
const std::string binding
Definition ASoA.h:1424
Entry const & getBindingKey() const
Definition ASoA.cxx:333
SliceInfoUnsortedPtr sliceInfo
Definition ASoA.h:1441
std::span< const int64_t > getSliceFor(int value) const
Definition ASoA.cxx:354
void updateSliceInfo(SliceInfoUnsortedPtr &&si)
Definition ASoA.cxx:343
o2::soa::ArrowTableRef getSliceFor(int value, o2::soa::ArrowTableRef const &input) const
Definition ASoA.cxx:348
void updateSliceInfo(SliceInfoPtr &&si)
Definition ASoA.cxx:338
std::pair< int64_t, int64_t > getSliceFor(int value) const
std::span< int64_t const > getSliceFor(int value) const
static o2::soa::ArrowTableRef joinTables(std::vector< std::shared_ptr< arrow::Table > > &&tables)
Definition ASoA.cxx:140
static o2::soa::ArrowTableRef concatTables(std::vector< o2::soa::ArrowTableRef > &&tables)
Definition ASoA.cxx:174
ArrowTableRef slice(ArrowRange newRange) const
Definition ArrowTypes.h:52
LOG(info)<< "Compressed in "<< sw.CpuTime()<< " s"
std::unique_ptr< TTree > tree((TTree *) flIn.Get(std::string(o2::base::NameConf::CTFTREENAME).c_str()))
std::vector< ReadoutWindowData > rows
const std::string str