The Gaudi Framework  v30r3 (a5ef0a68)
RCWNTupleCnv.cpp
Go to the documentation of this file.
1 #define ROOTHISTCNV_RCWNTUPLECNV_CPP
2 
3 // Include files
6 #include "GaudiKernel/NTuple.h"
7 
8 // Compiler include files
9 #include <cstdio>
10 #include <cstring>
11 #include <list>
12 #include <utility>
13 #include <vector>
14 
15 #include "RCWNTupleCnv.h"
16 
17 #include "TLeafD.h"
18 #include "TLeafF.h"
19 #include "TLeafI.h"
20 #include "TTree.h"
21 
22 namespace
23 {
24  template <typename T>
25  size_t saveItem( char* target, const NTuple::_Data<T>& src )
26  {
27  static_assert( std::is_trivially_copyable<T>::value, "T must be trivally copyable" );
28  std::memcpy( target, src.buffer(), sizeof( T ) * src.length() );
29  return sizeof( T ) * src.length();
30  }
31 
32  template <typename T>
33  size_t loadItem( const char* src, NTuple::_Data<T>& target )
34  {
35  static_assert( std::is_trivially_copyable<T>::value, "T must be trivally copyable" );
36  std::memcpy( const_cast<void*>( target.buffer() ), src, sizeof( T ) * target.length() );
37  return sizeof( T ) * target.length();
38  }
39 
40  template <typename POD>
41  decltype( auto ) downcast_item( const INTupleItem& i )
42  {
43  return dynamic_cast<const NTuple::_Data<POD>&>( i );
44  }
45  template <typename POD>
46  decltype( auto ) downcast_item( INTupleItem& i )
47  {
48  return dynamic_cast<NTuple::_Data<POD>&>( i );
49  }
50  template <typename POD, typename T>
51  void downcast_item( T&& ) = delete;
52 
53  template <typename Item, typename F>
54  decltype( auto ) visit( Item& i, F&& f )
55  {
56  switch ( i.type() ) {
57  case DataTypeInfo::INT:
58  return f( downcast_item<int>( i ) );
59  case DataTypeInfo::CHAR:
60  return f( downcast_item<char>( i ) );
62  return f( downcast_item<short>( i ) );
63  case DataTypeInfo::LONG:
64  return f( downcast_item<long>( i ) );
66  return f( downcast_item<long long>( i ) );
68  return f( downcast_item<unsigned char>( i ) );
70  return f( downcast_item<unsigned short>( i ) );
71  case DataTypeInfo::UINT:
72  return f( downcast_item<unsigned int>( i ) );
74  return f( downcast_item<unsigned long>( i ) );
76  return f( downcast_item<unsigned long long>( i ) );
78  return f( downcast_item<double>( i ) );
80  return f( downcast_item<float>( i ) );
81  case DataTypeInfo::BOOL:
82  return f( downcast_item<bool>( i ) );
83  }
84  throw std::runtime_error( "RCWNTupleCnv::visit: unknown INTupleItem::type()" );
85  }
86 
87  //-----------------------------------------------------------------------------
88  template <class T>
89  void analyzeItem( std::string typ, const NTuple::_Data<T>* it, std::string& desc, std::string& block_name,
90  std::string& var_name, long& lowerRange, long& upperRange, long& size )
91  //-----------------------------------------------------------------------------
92  {
93 
94  RootHistCnv::parseName( it->name(), block_name, var_name );
95 
96  // long item_size = (sizeof(T) < 4) ? 4 : sizeof(T);
97  long item_size = sizeof( T );
98  long dimension = it->length();
99  long ndim = it->ndim() - 1;
100  desc += var_name;
101  if ( it->hasIndex() || it->length() > 1 ) {
102  desc += '[';
103  }
104  if ( it->hasIndex() ) {
105  std::string ind_blk, ind_var;
106  RootHistCnv::parseName( it->index(), ind_blk, ind_var );
107  if ( ind_blk != block_name ) {
108  std::cerr << "ERROR: Index for CWNT variable " << ind_var << " is in a different block: " << ind_blk
109  << std::endl;
110  }
111  desc += ind_var;
112  } else if ( it->dim( ndim ) > 1 ) {
113  desc += std::to_string( it->dim( ndim ) );
114  }
115 
116  for ( int i = ndim - 1; i >= 0; i-- ) {
117  desc += "][";
118  desc += std::to_string( it->dim( i ) );
119  }
120  if ( it->hasIndex() || it->length() > 1 ) {
121  desc += ']';
122  }
123 
124  if ( it->range().lower() != it->range().min() && it->range().upper() != it->range().max() ) {
125  lowerRange = it->range().lower();
126  upperRange = it->range().upper();
127  } else {
128  lowerRange = 0;
129  upperRange = -1;
130  }
131  desc += typ;
132  size += item_size * dimension;
133  }
134 }
135 
136 //-----------------------------------------------------------------------------
138 //-----------------------------------------------------------------------------
139 {
140  MsgStream log( msgSvc(), "RCWNTupleCnv" );
141  rtree = new TTree( desc.c_str(), nt->title().c_str() );
142  log << MSG::VERBOSE << "created tree id: " << rtree->GetName() << " title: " << nt->title() << " desc: " << desc
143  << endmsg;
144 
145  // Loop over the items
146 
147  std::string block_name, var_name;
148  long lowerRange, upperRange;
149  long size = 0;
150  long cursize, oldsize = 0;
151  std::vector<std::string> item_fullname;
152  // std::vector<long> item_size,item_size2;
153  std::vector<long> item_buf_pos, item_buf_len, item_buf_end;
154  std::vector<long> item_range_lower, item_range_upper;
156 
157  for ( const auto& i : nt->items() ) {
158  std::string item;
159 
160  visit( *i, [&]( const auto& data ) {
161  analyzeItem( this->rootVarType( data.type() ), &data, item, block_name, var_name, lowerRange, upperRange, size );
162  } );
163 
164  item_name.emplace_back( block_name, item );
165  cursize = size - oldsize;
166 
167  log << MSG::VERBOSE << "item: " << item << " type " << i->type() << " blk: " << block_name << " var: " << var_name
168  << " rng: " << lowerRange << " " << upperRange << " sz: " << size << " " << cursize
169  << " buf_pos: " << size - cursize << endmsg;
170 
171  item_fullname.push_back( var_name );
172  item_buf_pos.push_back( size - cursize );
173  item_buf_len.push_back( cursize );
174  item_buf_end.push_back( size );
175  item_range_lower.push_back( lowerRange );
176  item_range_upper.push_back( upperRange );
177 
178  oldsize = size;
179  }
180 
181  // Make a new buffer, and tell the ntuple where it is
182  char* buff = nt->setBuffer( new char[size] );
183 
184  log << MSG::VERBOSE << "Created buffer size: " << size << " at " << (void*)buff << endmsg;
185 
186  // Zero out the buffer to make ROOT happy
187  std::fill_n( buff, size, 0 );
188 
189  char* buf_pos = buff;
190 
191  auto end = item_name.cend();
192 
193  // Loop over items, creating a new branch for each one;
194  unsigned int i_item = 0;
195  for ( auto itr = item_name.cbegin(); itr != end; ++itr, ++i_item ) {
196 
197  buf_pos = buff + item_buf_pos[i_item];
198 
199 // log << MSG::WARNING << "adding TBranch " << i_item << " "
200 // << item_fullname[i_item]
201 // << " format: " << itr->second.c_str() << " at "
202 // << (void*) buf_pos << " (" << (void*) buff << "+"
203 // << (void*)item_buf_pos[i_item] << ")"
204 // << endmsg;
205 
206 #if ROOT_VERSION_CODE >= ROOT_VERSION( 5, 15, 0 )
207  auto br = new TBranch( rtree,
208 #else
209  TBranch* br = new TBranch(
210 #endif
211  item_fullname[i_item].c_str(), buf_pos, itr->second.c_str() );
212 
213  if ( itr->first != "AUTO_BLK" ) {
214  std::string tit = itr->first;
215  tit = itr->first + "::" + br->GetTitle();
216  br->SetTitle( tit.c_str() );
217  }
218 
219  log << MSG::DEBUG << "adding TBranch " << br->GetTitle() << " at " << (void*)buf_pos << endmsg;
220 
221  // for index items with a limited range. Must be a TLeafI!
222  if ( item_range_lower[i_item] < item_range_upper[i_item] ) {
223  // log << MSG::VERBOSE << "\"" << item_fullname[i_item]
224  // << "\" is range limited " << item_range_lower[i_item] << " "
225  // << item_range_upper[i_item] << endmsg;
226  TLeafI* index = nullptr;
227  TObject* tobj = br->GetListOfLeaves()->FindObject( item_fullname[i_item].c_str() );
228  if ( tobj->IsA()->InheritsFrom( "TLeafI" ) ) {
229  index = dynamic_cast<TLeafI*>( tobj );
230 
231  if ( index ) {
232  index->SetMaximum( item_range_upper[i_item] );
233  // FIXME -- add for next version of ROOT
234  // index->SetMinimum( item_range_lower[i_item] );
235  } else {
236  log << MSG::ERROR << "Could dynamic cast to TLeafI: " << item_fullname[i_item] << endmsg;
237  }
238  }
239  }
240 
241  rtree->GetListOfBranches()->Add( br );
242  }
243 
244  log << MSG::INFO << "Booked TTree with ID: " << desc << " \"" << nt->title() << "\" in directory " << getDirectory()
245  << endmsg;
246 
247  return StatusCode::SUCCESS;
248 }
249 
250 // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
251 
252 //-----------------------------------------------------------------------------
254 //-----------------------------------------------------------------------------
255 {
256  // Fill the tree;
257  const auto& items = nt->items();
258  std::accumulate( begin( items ), end( items ), nt->buffer(), []( char* dest, const INTupleItem* i ) {
259  return dest + visit( *i, [dest]( const auto& item ) { return saveItem( dest, item ); } );
260  } );
261 
262  rtree->Fill();
263  nt->reset();
264  return StatusCode::SUCCESS;
265 }
266 
267 //-----------------------------------------------------------------------------
268 StatusCode RootHistCnv::RCWNTupleCnv::readData( TTree* rtree, INTuple* ntup, long ievt )
269 //-----------------------------------------------------------------------------
270 {
271  if ( ievt >= rtree->GetEntries() ) {
272  MsgStream log( msgSvc(), "RCWNTupleCnv::readData" );
273  log << MSG::ERROR << "no more entries in tree to read. max: " << rtree->GetEntries() << " current: " << ievt
274  << endmsg;
275  return StatusCode::FAILURE;
276  }
277 
278  rtree->GetEvent( ievt );
279  ievt++;
280 
281  // copy data from ntup->buffer() to ntup->items()->buffer()
282  auto& items = ntup->items();
283  std::accumulate( begin( items ), end( items ), const_cast<const char*>( ntup->buffer() ),
284  []( const char* src, INTupleItem* i ) {
285  return src + visit( *i, [src]( auto& item ) { return loadItem( src, item ); } );
286  } );
287 
288  return StatusCode::SUCCESS;
289 }
290 
291 //-----------------------------------------------------------------------------
293 //-----------------------------------------------------------------------------
294 {
295  MsgStream log( msgSvc(), "RCWNTupleCnv::load" );
296 
297  StatusCode status;
298 
299  NTuple::Tuple* pObj = nullptr;
300 
301  std::string title = tree->GetTitle();
302  log << MSG::VERBOSE << "loading CWNT " << title << " at: " << tree << endmsg;
303 
304  status = m_ntupleSvc->create( CLID_ColumnWiseTuple, title, pObj );
305  INTuple* ntup = dynamic_cast<INTuple*>( pObj );
306 
307  INTupleItem* item = nullptr;
308 
309  std::string itemName, indexName, item_type, itemTitle, blockName;
310  // long numEnt, numVar;
311  long size, totsize = 0;
313 
314  // numEnt = (int)tree->GetEntries();
315  // numVar = tree->GetNbranches();
316 
317  // loop over all branches (==leaves)
318  TObjArray* lbr = tree->GetListOfBranches();
319  TIter bitr( lbr );
320  while ( TObject* tobjb = bitr() ) {
321 
322  TBranch* br = (TBranch*)tobjb;
323  itemTitle = br->GetTitle();
324 
325  int ipos = itemTitle.find( "::" );
326  if ( ipos >= 0 ) {
327  blockName = itemTitle.substr( 0, ipos );
328  } else {
329  blockName = "";
330  }
331 
332  TObjArray* lf = br->GetListOfLeaves();
333 
334  TIter litr( lf );
335  while ( TObject* tobj = litr() ) {
336 
337  bool hasRange = false;
338  int indexRange = 0;
339  int itemSize;
340  item = nullptr;
341 
342  // TLeaf* tl = (TLeaf*)tobj;
343  TLeaf* tl = dynamic_cast<TLeaf*>( tobj );
344  itemName = tl->GetName();
345 
346  // char* buf_pos = (char*)tl->GetValuePointer();
347  // cout << " " << itemName << " " << blockName << " "
348  // << (void*)buf_pos;
349 
350  if ( blockName != "" ) {
351  log << MSG::DEBUG << "loading NTuple item " << blockName << "/" << itemName;
352  } else {
353  log << MSG::DEBUG << "loading NTuple item " << itemName;
354  }
355 
356  int arraySize;
357  TLeaf* indexLeaf = tl->GetLeafCounter( arraySize );
358 
359  if ( arraySize == 0 ) {
360  log << MSG::ERROR << "TLeaf counter size = 0. This should not happen!" << endmsg;
361  }
362 
363  if ( indexLeaf ) {
364  // index Arrays and Matrices
365 
366  indexName = indexLeaf->GetName();
367  // indexRange = tl->GetNdata();
368  indexRange = indexLeaf->GetMaximum();
369  itemSize = indexRange * tl->GetLenType() * arraySize;
370 
371  log << "[" << indexName;
372 
373  // Just for Matrices
374  if ( arraySize != 1 ) {
375  log << "][" << arraySize;
376  }
377  log << "]";
378 
379  } else {
380  itemSize = tl->GetLenType() * arraySize;
381 
382  indexName = "";
383 
384  if ( arraySize == 1 ) {
385  // Simple items
386  } else {
387  // Arrays of constant size
388  log << "[" << arraySize << "]";
389  }
390  }
391 
392  log << endmsg;
393 
394  // cout << " index: " << indexName << endl;
395 
396  // size = tl->GetNdata() * tl->GetLenType();
397  size = itemSize;
398  totsize += size;
399 
400  hasRange = tl->IsRange();
401 
402  itemList.emplace_back( tl, itemSize );
403 
404  // Integer
405  if ( tobj->IsA()->InheritsFrom( "TLeafI" ) ) {
406 
407  TLeafI* tli = dynamic_cast<TLeafI*>( tobj );
408  if ( tli->IsUnsigned() ) {
409  unsigned long min = 0, max = 0;
410  if ( hasRange ) {
411  min = tli->GetMinimum();
412  max = tli->GetMaximum();
413  }
414 
415  item = createNTupleItem( itemName, blockName, indexName, indexRange, arraySize, min, max, ntup );
416  } else {
417  long min = 0, max = 0;
418  if ( hasRange ) {
419  min = tli->GetMinimum();
420  max = tli->GetMaximum();
421  }
422 
423  item = createNTupleItem( itemName, blockName, indexName, indexRange, arraySize, min, max, ntup );
424  }
425 
426  // Float
427  } else if ( tobj->IsA()->InheritsFrom( "TLeafF" ) ) {
428  float min = 0., max = 0.;
429 
430  TLeafF* tlf = dynamic_cast<TLeafF*>( tobj );
431  if ( hasRange ) {
432  min = float( tlf->GetMinimum() );
433  max = float( tlf->GetMaximum() );
434  }
435 
436  item = createNTupleItem( itemName, blockName, indexName, indexRange, arraySize, min, max, ntup );
437 
438  // Double
439  } else if ( tobj->IsA()->InheritsFrom( "TLeafD" ) ) {
440  double min = 0., max = 0.;
441 
442  TLeafD* tld = dynamic_cast<TLeafD*>( tobj );
443  if ( hasRange ) {
444  min = tld->GetMinimum();
445  max = tld->GetMaximum();
446  }
447 
448  item = createNTupleItem( itemName, blockName, indexName, indexRange, arraySize, min, max, ntup );
449 
450  } else {
451  log << MSG::ERROR << "Uknown data type" << endmsg;
452  }
453 
454  if ( item ) {
455  ntup->add( item );
456  } else {
457  log << MSG::ERROR << "Unable to create ntuple item \"" << itemName << "\"" << endmsg;
458  }
459 
460  } // end litr
461  } // end bitr
462 
463  log << MSG::DEBUG << "Total buffer size of NTuple: " << totsize << " Bytes." << endmsg;
464 
465  char* buf = ntup->setBuffer( new char[totsize] );
466  char* bufpos = buf;
467 
468  int ts = 0;
469  for ( const auto& iitr : itemList ) {
470  TLeaf* leaf = iitr.first;
471  int isize = iitr.second;
472 
473  log << MSG::VERBOSE << "setting TBranch " << leaf->GetBranch()->GetName() << " buffer at " << (void*)bufpos
474  << endmsg;
475 
476  leaf->GetBranch()->SetAddress( (void*)bufpos );
477 
478  // //testing
479  // if (leaf->IsA()->InheritsFrom("TLeafI")) {
480  // for (int ievt=0; ievt<5; ievt++) {
481  // leaf->GetBranch()->GetEvent(ievt);
482  // int *idat = (int*)bufpos;
483  // log << MSG::WARNING << leaf->GetName() << ": " << ievt << " "
484  // << *idat << endmsg;
485 
486  // }
487  // }
488 
489  ts += isize;
490 
491  bufpos += isize;
492  }
493 
494  if ( totsize != ts ) {
495  log << MSG::ERROR << "buffer size mismatch: " << ts << " " << totsize << endmsg;
496  }
497 
498  refpObject = ntup;
499 
500  return StatusCode::SUCCESS;
501 }
502 
503 // Instantiation of a static factory class used by clients to create
504 // instances of this service
std::string getDirectory()
Definition: RConverter.cpp:153
virtual const std::string & name() const =0
Access _Item name.
constexpr static const auto FAILURE
Definition: StatusCode.h:88
Definition of the MsgStream class used to transmit messages.
Definition: MsgStream.h:24
virtual const ItemRange & range() const =0
Access the range if specified.
bool parseName(const std::string &full, std::string &blk, std::string &var)
Definition: RNTupleCnv.cpp:245
T to_string(T...args)
virtual StatusCode add(INTupleItem *item)=0
Add an item row to the N tuple.
T endl(T...args)
SmartIF< IMessageSvc > & msgSvc() const
Retrieve pointer to message service.
Definition: Converter.cpp:102
#define DECLARE_CONVERTER(x)
Definition: Converter.h:155
T cend(T...args)
Converter of Column-wise NTuple into ROOT format.
Definition: RCWNTupleCnv.h:21
StatusCode book(const std::string &desc, INTuple *pObject, TTree *&tree) override
Book the N tuple.
constexpr auto size(const C &c) noexcept(noexcept(c.size())) -> decltype(c.size())
STL class.
NTuple interface class definition.
Definition: INTuple.h:82
virtual void reset()=0
Reset all entries to their default values.
T push_back(T...args)
virtual long ndim() const =0
Dimension.
NTuple interface class definition.
Definition: INTuple.h:27
T memcpy(T...args)
virtual long length() const =0
Access the buffer length.
virtual const char * buffer() const =0
Access data buffer (CONST)
virtual StatusCode create(const CLID &typ, const std::string &title, NTuple::Tuple *&refpTuple)=0
Create requested N tuple (Hide constructor)
This class is used for returning status codes from appropriate routines.
Definition: StatusCode.h:51
StatusCode load(TTree *tree, INTuple *&refpObject) override
Create the transient representation of an object.
Abstract class describing basic data in an Ntuple.
Definition: NTuple.h:39
constexpr static const auto SUCCESS
Definition: StatusCode.h:87
Abstract base class which allows the user to interact with the actual N tuple implementation.
Definition: NTuple.h:407
StatusCode readData(TTree *rtree, INTuple *pObject, long ievt) override
Read N tuple data.
virtual const void * buffer() const =0
Access data buffer (CONST)
T find(T...args)
T cbegin(T...args)
virtual char * setBuffer(char *buff)=0
Attach data buffer.
virtual const std::string & index() const =0
Access the index _Item.
T c_str(T...args)
T fill_n(T...args)
T substr(T...args)
virtual long dim(long i) const =0
Access individual dimensions.
INTupleItem * createNTupleItem(std::string itemName, std::string blockName, std::string indexName, int indexRange, int arraySize, TYP min, TYP max, INTuple *ntup)
Add an item of a given type to the N tuple.
Definition: RNTupleCnv.cpp:272
virtual ItemContainer & items()=0
Access item container.
AttribStringParser::Iterator begin(const AttribStringParser &parser)
virtual bool hasIndex() const =0
Is the tuple have an index item?
T accumulate(T...args)
SmartIF< INTupleSvc > m_ntupleSvc
Reference to N tuple service.
Definition: RNTupleCnv.h:56
virtual const std::string & title() const =0
Object title.
MsgStream & endmsg(MsgStream &s)
MsgStream Modifier: endmsg. Calls the output method of the MsgStream.
Definition: MsgStream.h:209
virtual std::string rootVarType(int)
Return ROOT type info:
Definition: RNTupleCnv.cpp:208
StatusCode writeData(TTree *rtree, INTuple *pObject) override
Write N tuple data.
T emplace_back(T...args)