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