ATLAS Offline Software
Loading...
Searching...
No Matches
TreeBranchHelpers.cxx
Go to the documentation of this file.
1/*
2 Copyright (C) 2002-2025 CERN for the benefit of the ATLAS collaboration
3*/
4
5//
6// includes
7//
8
10
11// EDM include(s):
19
20// ROOT include(s):
21#include <TClass.h>
22#include <TTree.h>
23#include <TBranch.h>
24#include <TVirtualCollectionProxy.h>
25
26// System include(s):
27#include <regex>
28#include <algorithm>
29#include <functional>
30#include <sstream>
31
32//
33// method implementations
34//
35
36namespace {
37
38
39class TempInterface
40 : public SG::AuxVectorData
41{
42public:
43 TempInterface (size_t size) : m_size (size) {}
44 TempInterface (size_t size, SG::auxid_t auxid, void* ptr) :
45 m_size (size)
46 {
47 setCache (auxid, ptr);
48 }
49
50 using AuxVectorData::setStore;
51
52 virtual size_t size_v() const { return m_size; }
53 virtual size_t capacity_v() const { return m_size; }
54
55private:
56 size_t m_size;
57};
58
59
60} // anonymous namespace
61
62
63namespace {
64
65#ifdef XAOD_STANDALONE
66
79 const SG::AuxVectorBase* getVector( const std::string& key,
80 asg::SgTEvent& evtStore,
81 bool allowMissing,
82 const TClass*& cl,
83 MsgStream& msg ) {
84 if( allowMissing &&
85 ( ! evtStore.contains< const SG::AuxVectorBase >( key ) ) ) {
86 return nullptr;
87 }
88 const SG::AuxVectorBase* c = nullptr;
89 if( ! evtStore.retrieve( c, key ).isSuccess() ) {
90 msg << MSG::ERROR << "Couldn't retrieve container with key \"" << key
91 << "\"" << endmsg;
92 return nullptr;
93 }
94 const xAOD::THolder* holder = evtStore.tds()->holder( key );
95 if( holder != nullptr ) {
96 // If the object is in the transient store, get the type of it from
97 // the transient store itself. So that ConstDataVector types would be
98 // handled correctly.
99 const std::type_info* ti = holder->getTypeInfo();
100 cl = TClass::GetClass( *ti );
101 } else {
102 // If the object is not in the transient store, let's just use its
103 // "actual type".
104 cl = TClass::GetClass( typeid( *c ) );
105 }
106 if( ( allowMissing == false ) && ( cl == nullptr ) ) {
107 msg << MSG::ERROR
108 << "Couldn't find TClass dictionary for container \"" << key
109 << "\"" << endmsg;
110 return nullptr;
111 }
112
113 // Return the vector object.
114 return c;
115 }
116
128 const SG::AuxElement* getElement( const std::string& key,
129 asg::SgTEvent& evtStore,
130 bool allowMissing,
131 MsgStream& msg ) {
132 if( allowMissing &&
133 ( ! evtStore.contains< const SG::AuxElement >( key ) ) ) {
134 return nullptr;
135 }
136 const SG::AuxElement* e = nullptr;
137 if( ! evtStore.retrieve( e, key ).isSuccess() ) {
138 msg << MSG::ERROR << "Couldn't retrieve object with key \"" << key
139 << "\"" << endmsg;
140 return nullptr;
141 }
142 return e;
143 }
144
145#else
146
148 class ProxyWithName {
149 public:
151 typedef const SG::DataProxy* argument_type;
153 ProxyWithName( const std::string& name ) : m_name( name ) {}
155 bool operator()( argument_type proxy ) const {
156 return ( proxy->name() == m_name );
157 }
158 private:
159 std::string m_name;
160 }; // class ProxyWithName
161
174 const SG::AuxVectorBase* getVector ATLAS_NOT_CONST_THREAD_SAFE ( const std::string& key,
175 IProxyDict& evtStore,
176 bool allowMissing,
177 const TClass*& cl,
178 MsgStream& msg ) {
179
180 // Find all proxies with this key:
181 auto proxies = evtStore.proxies();
182 proxies.erase( std::remove_if( proxies.begin(), proxies.end(),
183 std::not_fn( ProxyWithName( key ) ) ),
184 proxies.end() );
185 // Now iterate over them:
186 for( const SG::DataProxy* proxy : proxies ) {
187 // We need a non-const version of it... :-(
188 SG::DataProxy* proxy_nc = const_cast< SG::DataProxy* >( proxy );
189 // Try to get the right object out of it.
190 DataBucketBase* bucket =
191 dynamic_cast< DataBucketBase* >( proxy_nc->accessData() );
192 if( ! bucket ) {
193 // This is a big problem in the job. Return right away.
194 msg << MSG::ERROR
195 << "Couldn't access data object as a data bucket?!?" << endmsg;
196 return nullptr;
197 }
198 // Get the dictionary for the type:
199 cl = TClass::GetClass( bucket->tinfo() );
200 if( ! cl ) {
201 if( msg.level() <= MSG::VERBOSE ) {
202 msg << MSG::VERBOSE << "No dictionary found for: "
203 << bucket->tinfo().name() << endmsg;
204 }
205 continue;
206 }
207 // Check whether the object inherits from AuxVectorBase:
208 if( ! cl->InheritsFrom( "SG::AuxVectorBase" ) ) {
209 if( msg.level() <= MSG::VERBOSE ) {
210 msg << MSG::VERBOSE << "Object \"" << key << "/" << cl->GetName()
211 << "\" does not inherit from SG::AuxVectorBase" << endmsg;
212 }
213 continue;
214 }
215 // If all is well, just assume that the inheritance is direct/simple:
217 reinterpret_cast< const SG::AuxVectorBase* >( bucket->object() );
218 return result;
219 }
220
221 // Apparently we failed...
222 if( ! allowMissing ) {
223 msg << MSG::ERROR << "Couldn't retrieve object \"" << key
224 << "\" as SG::AuxVectorBase" << endmsg;
225 }
226 return nullptr;
227 }
228
240 const SG::AuxElement* getElement ATLAS_NOT_CONST_THREAD_SAFE ( const std::string& key,
241 StoreGateSvc& evtStore,
242 bool allowMissing,
243 MsgStream& msg ) {
244
245
246 const SG::AuxElement* e = nullptr;
247 if( !evtStore.retrieve( e, key ).isSuccess() ) {
248 if(!allowMissing) {
249 msg << MSG::ERROR << "Couldn't retrieve object with key \"" << key
250 << "\"" << endmsg;
251 }
252 return nullptr;
253 }
254 return e;
255
256 }
257#endif // XAOD_STANDALONE
258
267 char rootType( char typeidType, MsgStream& msg ) {
268
269 // Do the hard-coded translation:
270 switch( typeidType ) {
271
272 case 'c':
273 return 'B';
274 break;
275 case 'h':
276 return 'b';
277 break;
278 case 's':
279 return 'S';
280 break;
281 case 't':
282 return 's';
283 break;
284 case 'i':
285 return 'I';
286 break;
287 case 'j':
288 return 'i';
289 break;
290 case 'f':
291 return 'F';
292 break;
293 case 'd':
294 return 'D';
295 break;
296 case 'x':
297 return 'L';
298 break;
299 case 'y':
300 case 'm': // Not sure how platform-independent this one is...
301 return 'l';
302 break;
303 case 'b':
304 return 'O';
305 break;
306 default:
307 // If we didn't find this type:
308 msg << MSG::ERROR << "Received an unknown type: " << typeidType
309 << endmsg;
310 return '\0';
311 break;
312 }
313 }
314} // private namespace
315
316namespace CP
317{
318 namespace TreeBranchHelpers
319 {
320 StatusCode BranchConfig ::
321 parse (const std::string& branchDecl, MsgStream& msg)
322 {
323 // The regular expression used to extract the needed info. The logic
324 // is supposed to be:
325 //
326 // (match[1]).(match[2])<any whitespace>-><any whitespace>(match[3])[<any whitespace>type=(match[5])][<any whitespace>metTerm=(match[7])]
327 //
328 // Like:
329 // "Electrons.eta -> el_eta"
330 // "Electrons.eta -> el_eta type=float"
331 // "MissingET.px -> met_px metTerm=Final"
332 static const std::regex
333 re( "\\s*([\\w%]+)\\.([\\w%]+)\\s*->\\s*([\\w%]+)(\\s+type=([\\w%]+))?(\\s+metTerm=([\\w%]+))?" );
334
335 // Interpret this branch declaration.
336 std::smatch match;
337 if( ! std::regex_match( branchDecl, match, re ) ) {
338 msg << MSG::ERROR << "Expression \"" << branchDecl << "\" doesn't match \"<object>.<variable> -> <branch>\"" << endmsg;
339 return StatusCode::FAILURE;
340 }
341 this->branchDecl = branchDecl;
342 sgName = match[ 1 ];
343 auxName = match[ 2 ];
344 branchName = match[ 3 ];
345 typeName = match[ 5 ];
346 metTermName = match[ 7 ];
347 return StatusCode::SUCCESS;
348 }
349
350
351
352 StatusCode BranchConfig ::
353 configureTypes (std::set<std::string>& decosWithoutType, MsgStream& msg)
354 {
355 std::string nominalAuxName = auxName;
356 if (auto pos = nominalAuxName.find ("%SYS%"); pos != std::string::npos)
357 nominalAuxName.replace (pos, 5, "NOSYS");
358 if (!typeName.empty())
359 {
360 if (typeName == "char")
361 SG::ConstAccessor<char> {nominalAuxName};
362 else if (typeName == "float")
363 SG::ConstAccessor<float> {nominalAuxName};
364 else if (typeName == "int")
365 SG::ConstAccessor<int> {nominalAuxName};
366 else if (typeName == "unsigned")
367 SG::ConstAccessor<unsigned> {nominalAuxName};
368 else if (typeName == "uint16")
369 SG::ConstAccessor<std::uint16_t> {nominalAuxName};
370 else if (typeName == "uint32")
371 SG::ConstAccessor<std::uint32_t> {nominalAuxName};
372 else
373 {
374 unsigned line = __LINE__ - 2;
375 std::string file = __FILE__;
376 file = file.substr (file.find_last_of("/\\") + 1);
377 msg << MSG::ERROR << "Unknown type requested, please extend " << file << " near line " << line << " for type " << typeName << endmsg;
378 return StatusCode::FAILURE;
379 }
380 }
383 {
384 nominalAuxId = reg.findAuxID (nominalAuxName);
386 {
387 decosWithoutType.insert (nominalAuxName);
388 msg << MSG::DEBUG << "No aux ID found for auxiliary variable: " << nominalAuxName << endmsg;
389 // just returning SUCCESS here, our caller will report failure
390 return StatusCode::SUCCESS;
391 }
392 }
393 if (auxType == nullptr)
394 {
395 auxType = reg.getType (nominalAuxId);
396 if (auxType == nullptr)
397 {
398 msg << MSG::ERROR
399 << "No std::type_info available for aux-store variable: "
400 << nominalAuxName << endmsg;
401 return StatusCode::FAILURE;
402 }
403 }
404 if (auxVecType == nullptr)
405 {
406 auxVecType = reg.getVecType (nominalAuxId);
407 if (auxVecType == nullptr)
408 {
409 msg << MSG::ERROR
410 << "No std::type_info available for aux-store variable: "
411 << nominalAuxName << endmsg;
412 return StatusCode::FAILURE;
413 }
414 }
415 if (auxFactory == nullptr)
416 {
417 auxFactory = reg.getFactory (nominalAuxId);
418 if (auxFactory == nullptr)
419 {
420 msg << MSG::ERROR
421 << "No factory found for auxiliary variable: "
422 << nominalAuxName << endmsg;
423 return StatusCode::FAILURE;
424 }
425 }
426 return StatusCode::SUCCESS;
427 }
428
429
430
431 StatusCode BranchConfig ::
432 configureSystematics (ISystematicsSvc& sysSvc, MsgStream& msg)
433 {
434 if (sgName.find ("%SYS%") == std::string::npos &&
435 auxName.find ("%SYS%") == std::string::npos &&
436 branchName.find ("%SYS%") == std::string::npos)
437 {
438 nominalOnly = true;
439 }
440 if (!nominalOnly)
441 {
442 if (branchName.find ("%SYS%") == std::string::npos)
443 {
444 msg << MSG::ERROR << "Branch with systematics without %SYS% in branch name: "
445 << branchName << endmsg;
446 return StatusCode::FAILURE;
447 }
448 if (sgName.find ("%SYS%") == std::string::npos &&
449 auxName.find ("%SYS%") == std::string::npos)
450 {
451 msg << MSG::ERROR << "Branch with systematics without %SYS% in SG or aux name: "
452 << sgName << "." << auxName << endmsg;
453 return StatusCode::FAILURE;
454 }
455 if (auxName.find ("NOSYS") != std::string::npos)
456 {
457 msg << MSG::ERROR << "Branch with systematics with NOSYS in aux name: "
458 << sgName << "." << auxName << endmsg;
459 return StatusCode::FAILURE;
460 }
461 if (sgName.find ("NOSYS") != std::string::npos && auxName.find ("%SYS%") == std::string::npos)
462 {
463 msg << MSG::ERROR << "Branch with NOSYS in SG name but without %SYS% in aux name: "
464 << sgName << "." << auxName << endmsg;
465 return StatusCode::FAILURE;
466 }
467
468 if (sgName.find ("%SYS%") != std::string::npos)
470
471 if (auxName.find ("%SYS%") != std::string::npos)
472 {
473 if (auto pos = sgName.find ("NOSYS"); pos == std::string::npos)
475 else
476 {
477 // Sometimes while object systematics were applied we are not interested in them,
478 // NOSYS will then be used on the container name.
479 // Decoration systematics however will only be aware of containers with %SYS% included.
480 // Some special handling is needed to translate from NOSYS back to %SYS%.
481 std::string sgNameSys = sgName;
482 sgNameSys.replace (pos, 5, "%SYS%");
483
484 // these will be the object systematics
485 auto objectSys = sysSvc.getObjectSystematics (sgNameSys);
486
487 // these will be all systematics (object+decor)
488 auto allSys = sysSvc.getDecorSystematics (sgNameSys, auxName);
489
490 // we now need to filter-out object systematics
491 for (auto& variation : allSys)
492 {
493 if (objectSys.find (variation) == objectSys.end())
494 auxNameFilterSys.insert (variation);
495 }
496 }
497 }
498
501 if (branchNameFilterSys.empty())
502 nominalOnly = true;
503 }
504
505 return StatusCode::SUCCESS;
506 }
507
508
509
510 StatusCode OutputBranchData ::
511 configureNames (const BranchConfig& branchConfig, const CP::SystematicSet& sys, ISystematicsSvc& sysSvc, MsgStream& msg)
512 {
513 isNominal = true;
514
515 if (branchConfig.sgName.find ("%SYS%") != std::string::npos)
516 {
517 CP::SystematicSet matching;
518 if (SystematicSet::filterForAffectingSystematics (sys, branchConfig.sgNameFilterSys, matching).isFailure())
519 return StatusCode::FAILURE;
520 if (sysSvc.makeSystematicsName (sgName, branchConfig.sgName, matching).isFailure())
521 return StatusCode::FAILURE;
522 if (!matching.empty())
523 isNominal = false;
524 } else
525 sgName = branchConfig.sgName;
526
527 if (branchConfig.auxName.find ("%SYS%") != std::string::npos)
528 {
529 CP::SystematicSet matching;
530 if (SystematicSet::filterForAffectingSystematics (sys, branchConfig.auxNameFilterSys, matching).isFailure())
531 return StatusCode::FAILURE;
532 if (sysSvc.makeSystematicsName (auxName, branchConfig.auxName, matching).isFailure())
533 return StatusCode::FAILURE;
534 if (!matching.empty())
535 isNominal = false;
536 } else
537 auxName = branchConfig.auxName;
538
539 if (branchConfig.branchName.find ("%SYS%") != std::string::npos)
540 {
541 CP::SystematicSet matching;
542 if (SystematicSet::filterForAffectingSystematics (sys, branchConfig.branchNameFilterSys, matching).isFailure())
543 return StatusCode::FAILURE;
544 if (sysSvc.makeSystematicsName (branchName, branchConfig.branchName, matching).isFailure())
545 return StatusCode::FAILURE;
546 if (matching.empty() && !isNominal)
547 {
548 msg << MSG::FATAL << "Branch \"" << branchName << "\" is not affected by any of the requested systematics but is not nominal." << endmsg;
549 return StatusCode::FAILURE;
550 }
551 } else
552 {
553 branchName = branchConfig.branchName;
554 if (!sys.empty())
555 {
556 msg << MSG::FATAL << "Branch \"" << branchName << "\" without systematics is evaluated in a non-nominal context." << endmsg;
557 return StatusCode::FAILURE;
558 }
559 }
560
561 return StatusCode::SUCCESS;
562 }
563
564
565
566 StatusCode
568 setup( TTree& tree, const BranchConfig& branchConfig, OutputBranchData& outputData, MsgStream& msg ) {
569
570 // Remember the branch name.
571 m_branchName = outputData.branchName;
572
573 // Create the accessor.
574 m_acc.reset( new SG::TypelessConstAccessor( *branchConfig.auxType, outputData.auxName ) );
575
576 // Get a pointer to the vector factory.
577 m_factory = branchConfig.auxFactory;
578
579 // Create the data object.
580 m_data = m_factory->create( m_acc->auxid(), 1, 1, false );
581
582 // Pointer to the branch, to be created.
583 TBranch* br = nullptr;
584
585 // Decide whether we're dealing with a "primitive" or an "object" branch.
586 if( strlen( branchConfig.auxType->name() ) == 1 ) {
587
588 // This is a "primitive" variable...
589
590 // Get the type identifier for it that ROOT will understand.
591 const char rType = rootType( branchConfig.auxType->name()[ 0 ], msg );
592 if( rType == '\0' ) {
593 msg << MSG::ERROR << "Type not recognised for variable: "
594 << outputData.branchName << endmsg;
595 return StatusCode::FAILURE;
596 }
597
598 // Construct the type description.
599 std::ostringstream typeDesc;
600 typeDesc << outputData.branchName << "/" << rType;
601
602 // Create the primitive branch.
603 br = tree.Branch( outputData.branchName.c_str(), m_data->toPtr(),
604 typeDesc.str().c_str() );
605
606 } else {
607
608 // This is an "object" variable...
609
610 // Get a proper type name for the variable.
611 const std::string typeName = SG::normalizedTypeinfoName( *branchConfig.auxType );
612
613 // Access the dictionary for the type.
614 TClass* cl = TClass::GetClass( *branchConfig.auxType );
615 if( ! cl ) {
616 cl = TClass::GetClass( typeName.c_str() );
617 }
618 if( ! cl ) {
619 msg << MSG::ERROR << "Couldn't find dictionary for type: "
620 << typeName << endmsg;
621 return StatusCode::FAILURE;
622 }
623 if( ! cl->GetStreamerInfo() ) {
624 msg << MSG::ERROR << "No streamer info available for type: "
625 << cl->GetName() << endmsg;
626 return StatusCode::FAILURE;
627 }
628
629 // Create the object branch.
630 m_dataPtr = m_data->toPtr();
631 br = tree.Branch( outputData.branchName.c_str(), cl->GetName(), &m_dataPtr );
632
633 }
634
635 // Check that the branch creation succeeded.
636 if( ! br ) {
637 msg << MSG::ERROR << "Failed to create branch: " << outputData.branchName
638 << endmsg;
639 return StatusCode::FAILURE;
640 }
641
642 // Return gracefully.
643 return StatusCode::SUCCESS;
644 }
645
646 StatusCode
648 process( const SG::AuxElement& element, MsgStream& msg ) {
649
650 // A security check.
651 if( ( ! m_acc ) || ( ! m_factory ) || ( ! m_data ) ) {
652 msg << MSG::FATAL << "Internal logic error detected" << endmsg;
653 return StatusCode::FAILURE;
654 }
655
656 // Get the data out of the xAOD object.
657 //const void* auxData = ( *m_acc )( element );
658
659 // Copy it into the output variable.
660 TempInterface dstiface (m_data->size(), m_acc->auxid(), m_data->toPtr());
661 m_factory->copy( m_acc->auxid(), dstiface, 0,
662 *element.container(), element.index(), 1 );
663
664 // Return gracefully.
665 return StatusCode::SUCCESS;
666 }
667
669 setup( TTree& tree, const BranchConfig& branchConfig, OutputBranchData& outputData, MsgStream& msg ) {
670
671 // Remember the branch name.
672 m_branchName = outputData.branchName;
673
674 // Create the accessor.
675 m_acc.reset( new SG::TypelessConstAccessor( *branchConfig.auxType, outputData.auxName ) );
676
677 // Get a pointer to the vector factory.
678 m_factory = branchConfig.auxFactory;
679
680 // Create the data object.
681 m_data = m_factory->create( m_acc->auxid(), 0, 0, false );
682
683 // Get a proper type name for the variable.
684 const std::string typeName = SG::normalizedTypeinfoName( *branchConfig.auxVecType );
685
686 // Access the dictionary for the type.
687 TClass* cl = TClass::GetClass( *branchConfig.auxVecType );
688 if( ! cl ) {
689 cl = TClass::GetClass( typeName.c_str() );
690 }
691 if( ! cl ) {
692 msg << MSG::ERROR << "Couldn't find dictionary for type: "
693 << typeName << endmsg;
694 return StatusCode::FAILURE;
695 }
696 if( ! cl->GetStreamerInfo() ) {
697 msg << MSG::ERROR << "No streamer info available for type: "
698 << cl->GetName() << endmsg;
699 return StatusCode::FAILURE;
700 }
701
702 // Create the branch.
703 m_dataPtr = m_data->toVector();
704 TBranch* br = tree.Branch( outputData.branchName.c_str(), cl->GetName(),
705 &m_dataPtr );
706 if( ! br ) {
707 msg << MSG::ERROR << "Failed to create branch: " << outputData.branchName
708 << endmsg;
709 return StatusCode::FAILURE;
710 }
711
712 // Return gracefully.
713 return StatusCode::SUCCESS;
714 }
715
717 resize( size_t size, MsgStream& msg ) {
718
719 // A security check.
720 if( ! m_data ) {
721 msg << MSG::FATAL << "Internal logic error detected" << endmsg;
722 return StatusCode::FAILURE;
723 }
724
725 // Do the deed.
726 m_data->resize( 0 );
727 m_data->resize( size );
728
729 // Return gracefully.
730 return StatusCode::SUCCESS;
731 }
732
734 process( const SG::AuxElement& element, size_t index, MsgStream& msg ) {
735
736 // A security check.
737 if( ( ! m_acc ) || ( ! m_factory ) || ( ! m_data ) ) {
738 msg << MSG::FATAL << "Internal logic error detected" << endmsg;
739 return StatusCode::FAILURE;
740 }
741
742 // Get the data out of the xAOD object.
743 //const void* auxData = ( *m_acc )( element );
744
745 // Copy it into the output variable.
746 TempInterface dstiface (m_data->size(), m_acc->auxid(), m_data->toPtr());
747 m_factory->copy( m_acc->auxid(), dstiface, index,
748 *element.container(), element.index(), 1 );
749
750 // Return gracefully.
751 return StatusCode::SUCCESS;
752 }
753
754
755
756
757
759 : asg::AsgMessaging( ("CP::TreeBranchHelpers::ElementProcessorRegular/" + sgName).c_str() ),
760 m_sgName(sgName) {
761
762 }
763
765 retrieveProcess( StoreType& evtStore ) {
766
767 // Retrieve the object:
768 static const bool ALLOW_MISSING = false;
769 const SG::AuxElement* el = getElement( m_sgName,
770 evtStore,
771 ALLOW_MISSING, msg() );
772 if( ! el ) {
773 ATH_MSG_ERROR( "Failed to retrieve object \"" << m_sgName
774 << "\"" );
775 return StatusCode::FAILURE;
776 }
777 const SG::AuxElement& element = *el;
778
779 // Process all branches.
780 for( auto& p : m_branches ) {
781 ATH_CHECK( p->process( element, msg() ) );
782 }
783
784 // Return gracefully.
785 return StatusCode::SUCCESS;
786 }
787
789 addBranch( TTree& tree, const BranchConfig& branchConfig, OutputBranchData& outputData ) {
790
791 // Set up the new branch.
792 m_branches.emplace_back(std::make_unique<ElementBranchProcessor>());
793 ATH_CHECK( m_branches.back()->setup( tree, branchConfig, outputData, msg() ) );
794
795 // Return gracefully.
796 return StatusCode::SUCCESS;
797 }
798
800 : asg::AsgMessaging( ("CP::TreeBranchHelpers::ContainerProcessorRegular/" + sgName).c_str() ),
801 m_sgName(sgName) {
802
803 }
804
806 retrieveProcess( StoreType& evtStore ) {
807
808 // Retrieve the container:
809 static const bool ALLOW_MISSING = false;
810 const TClass* cl = nullptr;
811 const SG::AuxVectorBase* vec = getVector( m_sgName,
812 evtStore,
813 ALLOW_MISSING, cl, msg() );
814 if( ! vec ) {
815 ATH_MSG_ERROR( "Failed to retrieve container \""
816 << m_sgName << "\"" );
817 return StatusCode::FAILURE;
818 }
820
821 // Get the collection proxy for the type if it's not available yet.
822 if( ! m_collProxy ) {
823
824 // Get the collection proxy from the dictionary.
825 m_collProxy = cl->GetCollectionProxy();
826 if( ! m_collProxy ) {
827 ATH_MSG_ERROR( "No collection proxy provided by type: "
828 << cl->GetName() );
829 return StatusCode::FAILURE;
830 }
831
832 // Get the offset that one needs to use to get from the element
833 // pointers to SG::AuxElement pointers.
834 static const TClass* const auxElementClass =
835 TClass::GetClass( typeid( SG::AuxElement ) );
837 m_collProxy->GetValueClass()->GetBaseClassOffset( auxElementClass );
838 if( m_auxElementOffset < 0 ) {
839 ATH_MSG_ERROR( "Vector element type \""
840 << m_collProxy->GetValueClass()->GetName()
841 << "\" doesn't seem to inherit from \""
842 << auxElementClass->GetName() << "\"" );
843 return StatusCode::FAILURE;
844 }
845 }
846
847 // Set up the iteration over the elements of the container. In a really
848 // low level / ugly way...
849 void* cPtr =
850 const_cast< void* >( static_cast< const void* >( &container ) );
851 TVirtualCollectionProxy::TPushPop helper( m_collProxy, cPtr );
852 const UInt_t cSize = m_collProxy->Size();
853
854 // Tell all branch processors to resize their variables.
855 for( auto& p : m_branches ) {
856 ATH_CHECK( p->resize( cSize, msg() ) );
857 }
858
859 // Now iterate over the container.
860 for( UInt_t i = 0; i < cSize; ++i ) {
861
862 // Get the element.
863 char* elPtr = static_cast< char* >( m_collProxy->At( i ) );
864 if( ! elPtr ) {
865 ATH_MSG_ERROR( "Failed to get element " << i << " from container" );
866 return StatusCode::FAILURE;
867 }
868 const SG::AuxElement* element =
869 reinterpret_cast< const SG::AuxElement* >( elPtr +
871
872 // Execute all branch processors on this element.
873 for( auto& p : m_branches ) {
874 ATH_CHECK( p->process( *element, i, msg() ) );
875 }
876 }
877
878 // Return gracefully.
879 return StatusCode::SUCCESS;
880 }
881
883 addBranch( TTree& tree, const BranchConfig& branchConfig, OutputBranchData& outputData ) {
884
885 // Set up the new branch.
886 m_branches.emplace_back(std::make_unique<ContainerBranchProcessor>());
887 ATH_CHECK( m_branches.back()->setup( tree, branchConfig, outputData, msg() ) );
888
889 // Return gracefully.
890 return StatusCode::SUCCESS;
891 }
892
893 ElementProcessorMet::ElementProcessorMet (const std::string& sgName, const std::string& termName)
894 : asg::AsgMessaging( ("CP::TreeBranchHelpers::ElementProcessorMet/" + sgName).c_str() ),
895 m_sgName(sgName),
896 m_termName(termName) {
897
898 }
899
901 retrieveProcess( StoreType& evtStore ) {
902
903 const xAOD::MissingETContainer *met = nullptr;
904 ANA_CHECK (evtStore.retrieve (met, m_sgName));
905 const SG::AuxElement& element = *(*met)[m_termName];
906 // Process all branches.
907 for( auto& p : m_branches ) {
908 ATH_CHECK( p->process( element, msg() ) );
909 }
910
911 // Return gracefully.
912 return StatusCode::SUCCESS;
913 }
914
916 addBranch( TTree& tree, const BranchConfig& branchConfig, OutputBranchData& outputData ) {
917
918 // Set up the new branch.
919 m_branches.emplace_back(std::make_unique<ElementBranchProcessor>());
920 ATH_CHECK( m_branches.back()->setup( tree, branchConfig, outputData, msg() ) );
921
922 // Return gracefully.
923 return StatusCode::SUCCESS;
924 }
925
926
927
928 StatusCode ProcessorList ::
929 setupTree(const std::vector<std::string>& branches, std::unordered_set<std::string> nonContainers, ISystematicsSvc& sysSvc, TTree& tree) {
930
931 m_nonContainers = std::move (nonContainers);
932
933 std::vector<BranchConfig> branchConfigs;
934 branchConfigs.reserve( branches.size() );
935 for ( const std::string& branchDecl : branches ) {
936 branchConfigs.emplace_back();
937 ATH_CHECK( branchConfigs.back().parse( branchDecl, msg() ) );
938 }
939
940 // This will loop over all branches, collect the name of any
941 // aux-store decorations that have no type and report them at the
942 // end. This allows to get the full list of missing decorations in
943 // a single run, as opposed to having to re-run the job once per
944 // missing decoration.
945 std::set<std::string> decosWithoutType;
946 for (auto& branchConfig : branchConfigs) {
947 ATH_CHECK ( branchConfig.configureTypes (decosWithoutType, msg()) );
948 }
949 if (!decosWithoutType.empty()) {
950 msg() << MSG::ERROR << "The following decorations have no type information:";
951 for (const auto& deco : decosWithoutType) {
952 msg() << " " << deco;
953 }
954 msg() << endmsg;
955 return StatusCode::FAILURE;
956 }
957
958
959 for (auto& branchConfig : branchConfigs) {
960 ATH_CHECK ( branchConfig.configureSystematics (sysSvc, msg()) );
961 }
962
963 auto sysVector = sysSvc.makeSystematicsVector();
964 // Ensure that the nominal systematic is first
965 if (!sysVector.at(0).empty()) {
966 ATH_MSG_ERROR ("The first systematic in the list is not nominal!");
967 return StatusCode::FAILURE;
968 }
969
970 // The branches we intend to write out
971 std::vector<OutputBranchData> outputBranches;
972
973 // All the branches that will be created
974 std::unordered_set<std::string> allBranches;
975
976 // Iterate over the branch specifications.
977 for( const auto& branchConfig : branchConfigs ) {
978
979 // All the branches that will be created for this rule
980 std::unordered_set<std::string> branchesForRule;
981
982 // Consider all systematics but skip the nominal one
983 for( const auto& sys : sysVector ) {
984
985 if (branchConfig.nominalOnly && !sys.empty()) continue;
986 OutputBranchData outputData;
987 outputData.branchConfig = &branchConfig;
988 outputData.sysIndex = &sys - &sysVector.front();
989 ATH_CHECK( outputData.configureNames (branchConfig, sys, sysSvc, msg()) );
990
991 // Skip branches that have already been created for other
992 // systematics for this rule. That's mostly nominal, but for
993 // systematics correlation studies it can also do other things.
994 if (branchesForRule.contains(outputData.branchName))
995 {
996 ANA_MSG_VERBOSE ("Branch \"" << outputData.branchName << "\" for rule \"" << branchConfig.branchDecl << "\" and systematic \"" << sys.name() << "\" already exists, skipping." );
997 continue;
998 }
999 branchesForRule.insert(outputData.branchName);
1000
1001 // If this branch already exists from another rule, report
1002 // it as an error.
1003 if (allBranches.contains(outputData.branchName))
1004 {
1005 ANA_MSG_ERROR ("Branch \"" << outputData.branchName << "\" would be created twice!" );
1006 return StatusCode::FAILURE;
1007 }
1008 allBranches.insert(outputData.branchName);
1009 outputBranches.push_back(outputData);
1010 }
1011 }
1012
1013 // Group all branches by systematic index to ensure that when
1014 // reading a single systematic the branches are contiguous on
1015 // disk.
1016 std::stable_sort (outputBranches.begin(), outputBranches.end(),
1017 [](const OutputBranchData& a, const OutputBranchData& b) {
1018 return a.sysIndex < b.sysIndex; });
1019
1020 for (auto &outputData : outputBranches)
1021 ATH_CHECK( setupBranch( *outputData.branchConfig, outputData, tree ) );
1022
1023 // Return gracefully.
1024 return StatusCode::SUCCESS;
1025 }
1026
1027 StatusCode ProcessorList::setupBranch( const BranchConfig& branchConfig, OutputBranchData& outputData, TTree& tree ) {
1028
1029 ATH_CHECK( getObjectProcessor( branchConfig, outputData.sgName ).addBranch( tree,
1030 branchConfig, outputData ) );
1031 ATH_MSG_DEBUG( "Writing branch \"" << outputData.branchName
1032 << "\" from container/variable \"" << outputData.sgName
1033 << "." << outputData.auxName << "\"" );
1034
1035 // Return gracefully.
1036 return StatusCode::SUCCESS;
1037 }
1038
1039 StatusCode ProcessorList ::
1040 process (StoreType& evtStore)
1041 {
1042 // Process the standalone objects:
1043 for( auto& [name, processor] : m_processors )
1044 {
1045 // Process it:
1046 ATH_CHECK (processor->retrieveProcess (evtStore));
1047 }
1048 return StatusCode::SUCCESS;
1049 }
1050
1051
1052
1053 IObjectProcessor& ProcessorList ::
1054 getObjectProcessor( const BranchConfig& branchConfig, const std::string& sgName )
1055 {
1056 std::string processorName = sgName;
1057 if (!branchConfig.metTermName.empty())
1058 processorName += ":metTerm=" + branchConfig.metTermName;
1059
1060 if (auto iter = m_processors.find(processorName); iter != m_processors.end())
1061 return *iter->second;
1062
1063 if (!branchConfig.metTermName.empty())
1064 return *m_processors.emplace (processorName, std::make_unique<ElementProcessorMet>(sgName, branchConfig.metTermName)).first->second;
1065
1066 if (m_nonContainers.contains(sgName))
1067 return *m_processors.emplace (processorName, std::make_unique<ElementProcessorRegular>(sgName)).first->second;
1068
1069 return *m_processors.emplace (processorName, std::make_unique<ContainerProcessorRegular>(sgName)).first->second;
1070 }
1071 }
1072}
const boost::regex re(r_e)
#define endmsg
#define ATH_CHECK
Evaluate an expression and check for errors.
#define ATH_MSG_ERROR(x)
#define ATH_MSG_DEBUG(x)
Base class for elements of a container that can have aux data.
Manage index tracking and synchronization of auxiliary data.
std::vector< size_t > vec
#define ANA_MSG_ERROR(xmsg)
Macro printing error messages.
#define ANA_MSG_VERBOSE(xmsg)
Macro printing verbose messages.
#define ANA_CHECK(EXP)
check whether the given expression was successful
Interface providing I/O for a generic auxiliary store.
Interface for factory objects that create vectors.
static Double_t a
static HEPVis_BooleanProcessor processor
#define ATLAS_NOT_CONST_THREAD_SAFE
the interface for the central systematics service
virtual CP::SystematicSet getObjectSystematics(const std::string &name) const =0
get the systematics for the given object in the event store
virtual std::vector< CP::SystematicSet > makeSystematicsVector() const =0
get the list of systematics
virtual CP::SystematicSet getDecorSystematics(const std::string &objectName, const std::string &decorName) const =0
get the systematics for the given object in the event store
virtual StatusCode makeSystematicsName(std::string &result, const std::string &name, const CP::SystematicSet &sys) const =0
make the name for the given systematics
Class to wrap a set of SystematicVariations.
bool empty() const
returns: whether the set is empty
static StatusCode filterForAffectingSystematics(const SystematicSet &systConfig, const SystematicSet &affectingSystematics, SystematicSet &filteredSystematics)
description: filter the systematics for the affected systematics returns: success guarantee: strong f...
std::string m_branchName
Name of the branch being written.
StatusCode resize(size_t size, MsgStream &msg)
Function (re)sizing the variable for a new event.
std::unique_ptr< SG::IAuxTypeVector > m_data
The object managing the memory of the written variable.
StatusCode process(const SG::AuxElement &element, size_t index, MsgStream &msg)
Function processing the object, filling the variable.
std::unique_ptr< SG::TypelessConstAccessor > m_acc
Object accessing the variable in question.
StatusCode setup(TTree &tree, const BranchConfig &branchConfig, OutputBranchData &outputData, MsgStream &msg)
Function setting up the object, and the branch.
const SG::IAuxTypeVectorFactory * m_factory
Pointer to the helper object that handles this variable.
void * m_dataPtr
Helper variable, pointing at the object to be written.
TVirtualCollectionProxy * m_collProxy
Collection proxy used for iterating over the container.
std::string m_sgName
Name of the object in the event store.
int m_auxElementOffset
Offset of the element type to SG::AuxElement.
StatusCode retrieveProcess(StoreType &evtStore) override
retrieve and process the object
StatusCode addBranch(TTree &tree, const BranchConfig &branchConfig, OutputBranchData &outputData) override
Add one branch to the output tree.
std::vector< std::unique_ptr< ContainerBranchProcessor > > m_branches
List of branch processors set up for this xAOD object.
ContainerProcessorRegular(const std::string &sgName)
Default constructor.
std::unique_ptr< SG::IAuxTypeVector > m_data
The object managing the memory of the written variable.
void * m_dataPtr
Helper variable, pointing at the object to be written.
const SG::IAuxTypeVectorFactory * m_factory
Pointer to the helper object that handles this variable.
std::string m_branchName
Name of the branch being written.
StatusCode setup(TTree &tree, const BranchConfig &branchConfig, OutputBranchData &outputData, MsgStream &msg)
Function setting up the object, and the branch.
std::unique_ptr< SG::TypelessConstAccessor > m_acc
Object accessing the variable in question.
StatusCode process(const SG::AuxElement &element, MsgStream &msg)
Function processing the object, filling the variable.
std::vector< std::unique_ptr< ElementBranchProcessor > > m_branches
List of branch processors set up for this xAOD object.
std::string m_termName
Name of the MET term to retrieve.
StatusCode addBranch(TTree &tree, const BranchConfig &branchConfig, OutputBranchData &outputData) override
Add one branch to the output tree.
ElementProcessorMet(const std::string &sgName, const std::string &termName)
Default constructor.
StatusCode retrieveProcess(StoreType &evtStore) override
retrieve and process the object
std::string m_sgName
Name of the object in the event store.
StatusCode retrieveProcess(StoreType &evtStore) override
retrieve and process the object
StatusCode addBranch(TTree &tree, const BranchConfig &branchConfig, OutputBranchData &outputData) override
Add one branch to the output tree.
std::string m_sgName
Name of the object in the event store.
ElementProcessorRegular(const std::string &sgName)
Default constructor.
std::vector< std::unique_ptr< ElementBranchProcessor > > m_branches
List of branch processors set up for this xAOD object.
the interface class for classes reading an object from the event store and processing it
virtual StatusCode addBranch(TTree &tree, const BranchConfig &branchConfig, OutputBranchData &outputData)=0
Add one branch to the output tree.
StatusCode setupBranch(const BranchConfig &branchConfig, OutputBranchData &outputData, TTree &tree)
Function setting up an individual branch on the first event.
std::unordered_set< std::string > m_nonContainers
the non-containers
IObjectProcessor & getObjectProcessor(const BranchConfig &branchConfig, const std::string &sgName)
std::unordered_map< std::string, std::unique_ptr< IObjectProcessor > > m_processors
object processors
A non-templated base class for DataBucket, allows to access the transient object address as a void*.
virtual void * object()=0
virtual const std::type_info & tinfo() const =0
Return the type_info for the stored object.
virtual std::vector< const SG::DataProxy * > proxies() const =0
Return the list of all current proxies in store.
Base class for elements of a container that can have aux data.
Definition AuxElement.h:483
const SG::AuxVectorData * container() const
Return the container holding this element.
size_t index() const
Return the index of this element within its container.
Handle mappings between names and auxid_t.
static AuxTypeRegistry & instance()
Return the singleton registry instance.
Manage index tracking and synchronization of auxiliary data.
Manage lookup of vectors of auxiliary data.
Helper class to provide constant type-safe access to aux data.
DataObject * accessData()
Access DataObject on-demand using conversion service.
Helper class to provide const generic access to aux data.
The Athena Transient Store API.
StatusCode retrieve(const T *&ptr) const
Retrieve the default object into a const T*.
MsgStream & msg() const
The standard message stream.
MsgStream & msg() const
The standard message stream.
AsgMessaging(const std::string &name)
Constructor with a name.
Wrapper for TEvent to make it look like StoreGate.
Definition SgTEvent.h:44
bool contains(const std::string &name) const
Check if an object is available for constant access.
T * retrieve(const std::string &name) const
Function retrieving a constant or non-constant object.
xAOD::TStore * tds() const
Return the underlying transient data store.
Definition SgTEvent.cxx:33
This class takes care of holding EDM objects in memory.
Definition THolder.h:35
const std::type_info * getTypeInfo() const
Definition THolder.cxx:412
const THolder * holder(const std::string &key) const
return holder for key
Definition TStore.cxx:50
bool match(std::string s1, std::string s2)
match the individual directories of two strings
Definition hcg.cxx:357
a namespace for helper functions and objects for filling tree branches
StoreGateSvc StoreType
the type of the event store in the current environment
Select isolated Photons, Electrons and Muons.
std::string normalizedTypeinfoName(const std::type_info &info)
Convert a type_info to a normalized string representation (matching the names used in the root dictio...
static const auxid_t null_auxid
To signal no aux data item.
Definition AuxTypes.h:30
size_t auxid_t
Identifier for a particular aux data item.
Definition AuxTypes.h:27
cl
print [x.__class__ for x in toList(dqregion.getSubRegions()) ]
Definition index.py:1
void stable_sort(DataModel_detail::iterator< DVL > beg, DataModel_detail::iterator< DVL > end)
Specialization of stable_sort for DataVector/List.
DataModel_detail::iterator< DVL > remove_if(typename DataModel_detail::iterator< DVL > beg, typename DataModel_detail::iterator< DVL > end, Predicate pred)
Specialization of remove_if for DataVector/List.
char rootType(char typeidType)
This function is used internally in the code when creating primitive dynamic auxiliary branches.
Convert a type_info to a normalized string representation (matching the names used in the root dictio...
the user configuration of an output branch
std::string branchDecl
the original user configuration string
std::string sgName
the SG name of the object to read from
const SG::IAuxTypeVectorFactory * auxFactory
pointer to the aux vector factory
std::string auxName
the aux data variable name to read from
const std::type_info * auxVecType
the vector type of the decoration we read
CP::SystematicSet auxNameFilterSys
the affecting systematics for the auxName
CP::SystematicSet sgNameFilterSys
the affecting systematics for the sgName
CP::SystematicSet branchNameFilterSys
the affecting systematics for the branchName
const std::type_info * auxType
the type of the decoration we read
SG::auxid_t nominalAuxId
the aux-id for the nominal decoration
std::string branchName
the name of the output branch
std::string metTermName
MET ONLY: the name of the MET term to write out.
bool nominalOnly
whether we only want to write out the nominal
std::string typeName
the name of the type (or empty to read from aux-registry)
the data for a single output branch
bool isNominal
whether this is unaffected by systematics (i.e. nominal)
const BranchConfig * branchConfig
the BranchConfig we are based on
std::size_t sysIndex
the index in the systematics list
StatusCode configureNames(const BranchConfig &branchConfig, const CP::SystematicSet &sys, ISystematicsSvc &sysSvc, MsgStream &msg)
configure names for systematics
std::string auxName
the name of the decoration in the aux-store
std::string sgName
the SG name of the object to read from
std::string branchName
the name of the output branch
MsgStream & msg
Definition testRead.cxx:32
TChain * tree
TFile * file