ATLAS Offline Software
TrigCompositeUtils.icc
Go to the documentation of this file.
1 /*
2  Copyright (C) 2002-2024 CERN for the benefit of the ATLAS collaboration
3 */
4 
5 #include "AsgMessaging/MessageCheck.h"
6 #include "AsgTools/CurrentContext.h"
7 #include <regex>
8 
9 namespace TrigCompositeUtils {
10 
11  ANA_MSG_HEADER (msgFindLink)
12 
13  /**
14  * @brief Creates and right away records the Container CONT with the key.
15  * No Aux store.
16  * Returns the WriteHandle.
17  * If possible provide the context that comes via an argument to execute otherwise it will default to looking it up which is slower.
18  **/
19  template<class CONT>
20  SG::WriteHandle<CONT> createAndStoreNoAux( const SG::WriteHandleKey<CONT>& key, const EventContext& ctx ) {
21  SG::WriteHandle<CONT> handle( key, ctx );
22  auto data = std::make_unique<CONT>() ;
23  if (handle.record( std::move( data ) ).isFailure()) {
24  throw std::runtime_error( "ERROR in TrigCompositeUtils::createAndStoreNoAux Unable to record " + key.key());
25  }
26  return handle;
27  }
28 
29  /**
30  * @brief Creates and right away records the Container CONT with the key.
31  * With Aux store.
32  * Returns the WriteHandle.
33  * If possible provide the context that comes via an argument to execute otherwise it will default to looking it up which is slower.
34  **/
35  template<class CONT, class AUX>
36  SG::WriteHandle<CONT> createAndStoreWithAux( const SG::WriteHandleKey<CONT>& key, const EventContext& ctx ) {
37  SG::WriteHandle<CONT> handle( key, ctx );
38  auto data = std::make_unique<CONT>() ;
39  auto aux = std::make_unique<AUX>() ;
40  data->setStore( aux.get() );
41  if (handle.record( std::move( data ), std::move( aux ) ).isFailure()) {
42  throw std::runtime_error( "ERROR in TrigCompositeUtils::createAndStoreWithAux Unable to record " + key.key());
43  }
44  return handle;
45  }
46 
47  template<typename T>
48  void
49  findLinks(const Decision* start, const std::string& linkName, std::vector<LinkInfo<T>>& links, unsigned int behaviour, std::set<const Decision*>* fullyExploredFrom) {
50  using namespace msgFindLink;
51  std::vector<ElementLink<T>> featureLinks;
52  if (start->hasObjectCollectionLinks(linkName, ClassID_traits<T>::ID())) {
53  featureLinks = start->objectCollectionLinks<T>(linkName);
54  }
55  if (start->hasObjectLink(linkName, ClassID_traits<T>::ID())) {
56  featureLinks.push_back(start->objectLink<T>(linkName));
57  }
58  const bool linkFound = (featureLinks.size() > 0);
59  const std::vector<DecisionID> &ids = decisionIDs(start);
60  const EventContext& ctx = Gaudi::Hive::currentContext();
61  for (const ElementLink<T>& featureLink : featureLinks) {
62  // Check for duplicates
63  bool duplicate = false;
64  for (LinkInfo<T> &info : links)
65  {
66  if (info.link == featureLink) {
67  const auto A = decisionToElementLink(start, ctx);
68  const auto& B = info.link;
69  if (info.source != start
70  && linkName != initialRoIString() // Allow multiple nodes to reference the same initial ROI
71  && linkName != roiString() // Allow multiple nodes to reference the same updated ROI
72  && linkName != "l2cbroi" // Allow multiple nodes to reference the same l2cb ROI (muon specific use case)
73  && linkName != viewString() // Allow multiple nodes to reference the same view instance (i.e. re-use of EventViews)
74  && A.dataID().find("_probe") == std::string::npos // Allow re-use if one of the two locations is a tag-and-probe style probe component
75  && B.dataID().find("_probe") == std::string::npos
76  ) {
77  ANA_MSG_WARNING ("Found '" << linkName << "' by multiple paths, but "
78  << "the links are coming from different places in the navigation graph. " << std::endl
79  << "From A:" << A.dataID() << ":" << A.index() << " Dump:" << std::endl << *start << std::endl
80  << "From B:" << B.dataID() << ":" << B.index() << " Dump:" << std::endl << *(info.source));
81  }
82  info.decisions.insert(ids.begin(), ids.end());
83  duplicate = true;
84  }
85  }
86  if (!duplicate)
87  links.emplace_back(start, featureLink);
88  }
89  // Early exit
90  if (linkFound && behaviour == TrigDefs::lastFeatureOfType) {
91  return;
92  }
93  // If not Early Exit, then recurse
94  for (const auto& seed : getLinkToPrevious(start)) {
95 #if TRIGCOMPUTILS_ENABLE_EARLY_EXIT == 1
96  if (fullyExploredFrom != nullptr) {
97  // We only need to recursivly explore back from each node in the graph once.
98  // We can keep a record of nodes which we have already explored, these we can safely skip over.
99  if (fullyExploredFrom->count(*seed) == 1) {
100  continue;
101  }
102  }
103 #endif
104  findLinks<T>(*seed, linkName, links, behaviour, fullyExploredFrom);
105  }
106  // Fully explored this node
107  if (fullyExploredFrom != nullptr) {
108  fullyExploredFrom->insert(start);
109  }
110  }
111 
112  template<typename T>
113  std::vector<LinkInfo<T>>
114  findLinks(const Decision* start, const std::string& linkName, unsigned int behaviour) {
115  std::vector<LinkInfo<T>> links;
116  std::set<const Decision*> fullyExploredFrom;
117  findLinks(start, linkName, links, behaviour, &fullyExploredFrom);
118  return links;
119  }
120 
121  template<typename T>
122  LinkInfo<T>
123  findLink(const Decision* start, const std::string& linkName, const bool suppressMultipleLinksWarning) {
124  using namespace msgFindLink;
125  // We use findLink in cases where there is only one link to be found, or if there are multiple then we
126  // only want the most recent.
127  // Hence we can supply TrigDefs::lastFeatureOfType. /--> parent3(link)
128  // We can still have more then one link found if there is a branch in the navigation. E.g. start --> parent1 --> parent2(link)
129  // If both parent2 and parent3 posessed an admisable ElementLink, then the warning below will trigger, and only one of the
130  // links will be returned (whichever of parent2 or parent3 happened to be the first seed of parent1).
131  std::vector<LinkInfo<T>> links = findLinks<T>(start, linkName, TrigDefs::lastFeatureOfType);
132  if (links.size() > 1 && !suppressMultipleLinksWarning) {
133  ANA_MSG_WARNING (links.size() << " links found for " << linkName
134  << " returning the first link, consider using findLinks.");
135  }
136  if (links.size() > 0) {
137  return links.at(0);
138  }
139  return LinkInfo<T>(); // invalid link
140  }
141 
142 
143  template<class CONTAINER>
144  void filterLinkVectorByContainerKey(const std::string& containerSGKey, std::vector<ElementLink<CONTAINER>>& vector) {
145  if (containerSGKey.empty()) {
146  return;
147  }
148  auto it = std::remove_if(vector.begin(), vector.end(), [&](const ElementLink<CONTAINER>& el) {
149  return !std::regex_match( el.dataID(), std::regex(containerSGKey) );
150  });
151  // Collection has been re-ordered to put the bad elements at the end
152  vector.erase(it, vector.end());
153  }
154 
155 
156  template<class CONTAINER>
157  const std::vector< LinkInfo<CONTAINER> > recursiveGetFeaturesOfType(
158  const NavGraph& navGraph,
159  const std::string& containerSGKey,
160  const bool lastFeatureOfType,
161  const std::string& navElementLinkKey,
162  const DecisionIDContainer& chainIDs) {
163 
164  std::vector< LinkInfo<CONTAINER> > features; // The return vector
165  std::set<const NavGraphNode*> fullyExploredFrom; // Lets us navigate more efficiently
166 
167  // For each starting point through the navigation for a given chain-group
168  for (const NavGraphNode* finalNode : navGraph.finalNodes()) {
169  recursiveGetFeaturesOfTypeInternal<CONTAINER>(features,
170  fullyExploredFrom,
171  finalNode,
172  containerSGKey,
173  lastFeatureOfType,
174  navElementLinkKey,
175  chainIDs);
176  }
177 
178  return features;
179  }
180 
181 
182  template<class CONTAINER>
183  void recursiveGetFeaturesOfTypeInternal(
184  std::vector< LinkInfo<CONTAINER> >& features,
185  std::set<const NavGraphNode*>& fullyExploredFrom,
186  const NavGraphNode* navGraphNode,
187  const std::string& containerSGKey,
188  const bool lastFeatureOfType,
189  const std::string& navElementLinkKey,
190  const DecisionIDContainer& chainIDs) {
191 
192 
193 
194  const Decision* decisionObj = navGraphNode->node();
195  const Decision* decisionObjChild = (navGraphNode->children().size() == 1 ? navGraphNode->children().at(0)->node() : nullptr);
196  const std::vector<DecisionID> &ids = decisionIDs(decisionObj);
197  std::vector<ElementLink<CONTAINER>> featureLinks;
198 
199  // Look up what named links are available in the Decision Object
200  std::vector<std::string> availableLinkNames;
201  if (navElementLinkKey == "") {
202  const std::vector<std::string> getSingleLinkNames = decisionObj->getObjectNames<CONTAINER>();
203  const std::vector<std::string> getCollectionLinkNames = decisionObj->getObjectCollectionNames<CONTAINER>();
204  std::copy(getSingleLinkNames.begin(), getSingleLinkNames.end(), std::back_inserter(availableLinkNames));
205  std::copy(getCollectionLinkNames.begin(), getCollectionLinkNames.end(), std::back_inserter(availableLinkNames));
206  } else { // Just looking for an explicitly named feature
207  availableLinkNames.push_back( navElementLinkKey );
208  }
209 
210  // Fetch the named links that we're interested in
211  for (const std::string& featureNameToGet : availableLinkNames) {
212  // This try block protects against ExcCLIDMismatch throws from
213  // features which do not derive from IParticle, when an IParticle interface is requested.
214 #ifndef XAOD_STANDALONE
215  try {
216 #endif
217  // Slices may have added link collections. These links may have been to objects in different containers.
218  if (decisionObj->hasObjectCollectionLinks(featureNameToGet, ClassID_traits< CONTAINER >::ID())) {
219  std::vector<ElementLink<CONTAINER>> collectionLinks = decisionObj->objectCollectionLinks<CONTAINER>( featureNameToGet );
220  filterLinkVectorByContainerKey<CONTAINER>(containerSGKey, collectionLinks);
221  std::copy(collectionLinks.begin(), collectionLinks.end(), std::back_inserter(featureLinks));
222  }
223 #ifndef XAOD_STANDALONE
224  } catch (SG::ExcCLIDMismatch&) {
225  // This is in place to catch the exception caused by non-IParticle features when an IParticle interface is requested.
226  // We're fine to catch this silently and cary on looking at the next Decision object in the graph
227  }
228  try {
229 #endif
230  // Slices may have added single links. Note: the framework-specified "feature" link is always a single link.
231  if (decisionObj->hasObjectLink(featureNameToGet, ClassID_traits< CONTAINER >::ID())) {
232  std::vector<ElementLink<CONTAINER>> singleEntryVector; // Filtering function operates on a vector
233  singleEntryVector.push_back( decisionObj->objectLink<CONTAINER>( featureNameToGet ) );
234  filterLinkVectorByContainerKey<CONTAINER>(containerSGKey, singleEntryVector);
235  std::copy(singleEntryVector.begin(), singleEntryVector.end(), std::back_inserter(featureLinks));
236  }
237 #ifndef XAOD_STANDALONE
238  } catch (SG::ExcCLIDMismatch&) {
239  // Silently. As above.
240  }
241 #endif
242  }
243 
244  // Check if the Decsision object is active for a specific set of Chains-of-interest (as supplied by the TDT)
245  ActiveState state = ActiveState::UNSET;
246  if (chainIDs.size() > 0) {
247  // If we were given a list of chains to consider then we start assuming none passed this decisionObj
248  state = ActiveState::INACTIVE;
249  for (DecisionID id : chainIDs) {
250  if (std::count(decisionObj->decisions().begin(), decisionObj->decisions().end(), id) == 1) {
251  state = ActiveState::ACTIVE;
252  break;
253  }
254  }
255  // But consider also the ComboHypo, this will have run immidiately after the Hypo and could have failed this chain due to combinatorics.
256  // This statement will only activate for the case that we are looking for "feature" edges (which is the default).
257  if (state == ActiveState::ACTIVE && decisionObjChild && decisionObjChild->name() == comboHypoAlgNodeName()) {
258  state = ActiveState::INACTIVE;
259  for (DecisionID id : chainIDs) {
260  if (std::count(decisionObjChild->decisions().begin(), decisionObjChild->decisions().end(), id) == 1) {
261  state = ActiveState::ACTIVE;
262  break;
263  }
264  }
265  }
266  }
267 
268  // Copy the fetched links into the return vector
269  for (const ElementLink<CONTAINER>& featureLink : featureLinks) {
270  typename std::vector<LinkInfo<CONTAINER>>::iterator vecIt = std::find_if(features.begin(), features.end(), [&](const auto& li) { return li.link == featureLink; } );
271  if (vecIt == features.end()) {
272  // Link did not already exist - add it to the output
273  features.emplace_back( decisionObj, featureLink, state);
274  } else {
275  // Link already existed - if the link's state in the return vector is INACTIVE but is ACTIVE here,
276  // then we need to change it to ACTIVE as this denotes one-or-more of the requested chains were active for the object.
277  if (vecIt->state == ActiveState::INACTIVE and state == ActiveState::ACTIVE) {
278  vecIt->state = ActiveState::ACTIVE;
279  }
280  // Update the set of passed IDs
281  vecIt->decisions.insert(ids.begin(), ids.end());
282  }
283  }
284 
285  // Stop processing this path through the navigation if the lastFeatureOfType flag is set
286  if (featureLinks.size() && lastFeatureOfType) {
287  return;
288  }
289 
290  // Recurse to decisionObj's seeds
291  for (const NavGraphNode* seedNavNode : navGraphNode->seeds()) {
292 #if TRIGCOMPUTILS_ENABLE_EARLY_EXIT == 1
293  if (fullyExploredFrom.count(seedNavNode) == 1) {
294  continue; // Already explored down from here
295  }
296 #endif
297  recursiveGetFeaturesOfTypeInternal<CONTAINER>(features,
298  fullyExploredFrom,
299  seedNavNode,
300  containerSGKey,
301  lastFeatureOfType,
302  navElementLinkKey,
303  chainIDs);
304  }
305 
306  // If we encounter this node again in the future, we don't need to explore it again as it's now fully explored.
307 
308  fullyExploredFrom.insert( navGraphNode );
309  return;
310  }
311 
312 
313  template<typename T>
314  DecisionIDContainer passedDecisionIDs( const Decision* d, const T& required ) {
315  DecisionIDContainer passed;
316  for ( DecisionID id : decisionIDs( d ) ) {
317  if ( required.find(id) != required.end() ) {
318  passed.insert(id);
319  }
320  }
321  return passed;
322  }
323 
324 }