ATLAS Offline Software
Loading...
Searching...
No Matches
TriggerMatchingTool.cxx
Go to the documentation of this file.
1/*
2 Copyright (C) 2002-2025 CERN for the benefit of the ATLAS collaboration
3*/
4
6#include "BuildCombinations.h"
7#include "GaudiKernel/ServiceHandle.h"
8#include "GaudiKernel/IIncidentSvc.h"
12#include <memory>
13#include <algorithm>
17
18namespace {
20 template <typename T>
21 using constAcc_t = SG::AuxElement::ConstAccessor<T>;
22 template <typename T>
23 using acc_t = SG::AuxElement::Accessor<T>;
24 template <typename T>
25 using vecLink_t = std::vector<ElementLink<T>>;
26
27 template <typename T>
28 ElementLink<T> makeLink(typename T::const_value_type element, IProxyDict *proxyDct)
29 {
30 SG::DataProxy *proxy = proxyDct->proxy(element->container());
31 // This will be null if the container isn't in the store. This shouldn't really happen
32 if (!proxy)
33 return {};
34 else
35 return ElementLink<T>(proxy->sgkey(), element->index(), proxyDct);
36 }
37} //> end anonymous namespace
38
39namespace DerivationFramework {
40
42 const std::string& type,
43 const std::string& name,
44 const IInterface* pSvcLocator) :
45 base_class(type, name, pSvcLocator)
46 {
47 declareProperty("ChainNames", m_chainNames,
48 "The list of trigger chains to match.");
49 declareProperty("OnlineParticleTool", m_trigParticleTool,
50 "The tool to retrieve online particles from the navigation.");
51 declareProperty("InputElectrons",
53 "Offline electron candidates for matching.");
54 declareProperty("InputPhotons",
56 "Offline photon candidates for matching.");
57 declareProperty("InputMuons",
59 "Offline muon candidates for matching.");
60 declareProperty("InputTaus",
62 "Offline tau candidates for matching.");
63 declareProperty("DRThreshold", m_drThreshold = 0.1,
64 "The maximum dR between an offline and an online particle to consider "
65 "a match between them.");
66 declareProperty("Rerun", m_rerun = true,
67 "Whether to match triggers in rerun mode.");
68 declareProperty("OutputContainerPrefix", m_outputPrefix="TrigMatch_",
69 "The prefix to add to the output containers.");
70 declareProperty("CheckEmptyChainGroups", m_checkEmptyChainGroups = true,
71 "If set, discard any empty chain groups. Otherwise these will cause "
72 "a job failure.");
73 declareProperty("InputDependentConfig", m_inputDependentConfig=false,
74 "Warn when a trigger is removed (if the configuration is dependent "
75 "on the inputs, removal is not expected).");
76 }
77
79 {
80 ATH_MSG_INFO( "Initializing " << name() );
81
82 // Remove any duplicates from the list of chain names
83 std::sort(m_chainNames.begin(), m_chainNames.end() );
84 m_chainNames.erase(std::unique(m_chainNames.begin(), m_chainNames.end() ), m_chainNames.end() );
85
86 ATH_CHECK( m_trigParticleTool.retrieve() );
87 ATH_CHECK( m_scoreTool.retrieve() );
88 for (auto &p : m_offlineInputs)
89 {
90 ATH_CHECK(p.second.initialize(SG::AllowEmpty));
91 }
92 return StatusCode::SUCCESS;
93 }
94
95 StatusCode TriggerMatchingTool::addBranches(const EventContext& ctx) const
96 {
97 [[maybe_unused]] static const bool firstEvent = [&](){
98 auto itr = m_chainNames.begin();
99 while (itr != m_chainNames.end() ) {
100 const Trig::ChainGroup* cg = m_tdt->getChainGroup(*itr);
101 if (cg->getListOfTriggers().size() == 0){
103 ATH_MSG_WARNING("Removing trigger " << (*itr) << " -- suggests a bad tool configuration (asking for triggers not in the menu)");
104 // We are now modifying the mutable m_chainNames but since it is done
105 // within this static initialization this is thread-safe:
106 itr = m_chainNames.erase(itr);
107 } else
108 ++itr;
109 }
110 return false;
111 }();
112
114
115 // Now, get all the possible offline candidates
116 std::map<xAOD::Type::ObjectType, const xAOD::IParticleContainer *> offlineContainers;
117 std::map<xAOD::Type::ObjectType, particleVec_t> offlineCandidates;
118 for (const auto& p : m_offlineInputs) {
119 // Skip any that may have been disabled by providing an empty string to
120 // the corresponding property
121 if (p.second.empty() )
122 continue;
123 auto handle = SG::makeHandle(p.second, ctx);
124 if (!handle.isValid())
125 {
126 ATH_MSG_ERROR("Failed to retrieve " << p.second);
127 return StatusCode::FAILURE;
128 }
129 offlineContainers[p.first] = handle.ptr();
130 offlineCandidates.emplace(std::make_pair(
131 p.first,
132 particleVec_t(handle->begin(), handle->end() )
133 ) );
134 }
135
136 // Store possible matches from online to offline particles here
137 // We do this as multiple chains may use the same online particles so we can
138 // reuse this information.
139 std::map<const xAOD::IParticle*, particleVec_t> matches;
140
141 // Iterate through the chains to get the matchings
142 for (const std::string& chain : m_chainNames) {
143 // Create the output
144 xAOD::TrigCompositeContainer* container(nullptr);
145 ATH_CHECK( createOutputContainer(container, chain) );
146
147 // Get the list of online combinations
148 std::vector<particleVec_t> onlineCombinations;
149 ATH_CHECK( m_trigParticleTool->retrieveParticles(onlineCombinations, chain, m_rerun) );
150
152 onlineCombinations.size() << " combinations found for chain" << chain);
153
154 // If no combinations were found (because the trigger was not passed) then
155 // we can skip this trigger
156 if (onlineCombinations.size() == 0)
157 continue;
158
160 // Now build up the list of offline combinations;
161 std::vector<particleVec_t> offlineCombinations;
162
163 // Projection operator to use for comparing vectors
164 // of IParticle*. Compare by using the sum of the pts
165 // of all particles in the vector.
166 struct outerproj {
167 double operator() (const particleVec_t& v) const
168 {
169 // Unfortunately std::ranges::accumulate hasn't made it into C++
170 // as of C++23 or we could use that directly.
171 auto r = std::views::transform (v, &xAOD::IParticle::pt);
172 return std::accumulate (std::begin(r), std::end(r), 0);
173 }
174 };
175
176 for (const particleVec_t& combination : onlineCombinations) {
177 // Here we store the possible candidates for the matching. We use the
178 // range type as a lightweight method to carry around a view of a vector
179 // without copying it (the RangedItr is essentially a combination of 3
180 // iterators).
181 std::vector<particleRange_t> matchCandidates;
182 for (const xAOD::IParticle* part : combination) {
183 const particleVec_t& possibleMatches = getCandidateMatchesFor(
184 part, offlineCandidates, matches);
185 matchCandidates.emplace_back(possibleMatches.begin(), possibleMatches.end() );
186 } //> end loop over particles
187 // Get all possible combinations of offline objects that could match to
188 // this particular online combination.
189 auto theseOfflineCombinations =
191 matchCandidates,
193 outerproj());
194 if (msgLvl(MSG::VERBOSE) ) {
195 // Spit out some verbose information
197 "Checking matching for chain " << chain
198 << " with " << matchCandidates.size() << " legs");
199 std::size_t idx = 0;
200 for (const particleRange_t& range : matchCandidates)
201 ATH_MSG_VERBOSE( "Leg #" << idx++ << " has " << range.size()
202 << " offline candidates." );
204 "Matching generated " << theseOfflineCombinations.size()
205 << " offline combinations");
206 }
207 // Now push them back into the output. Use a specialised function for
208 // inserting into a sorted vector that ensures that we only output
209 // unique combinations
210 for (const particleVec_t& vec : theseOfflineCombinations)
211 TriggerMatchingUtils::insertIntoSortedVector(offlineCombinations, vec, outerproj());
212 } //> end loop over combinations
213
214
215 // Decorate the found combinations onto trigger composites.
216 for (const particleVec_t& foundCombination : offlineCombinations) {
217 xAOD::TrigComposite* composite = new xAOD::TrigComposite();
218 container->push_back(composite);
219 static const acc_t<vecLink_t<xAOD::IParticleContainer>> dec_links(
220 "TrigMatchedObjects");
221 vecLink_t<xAOD::IParticleContainer>& links = dec_links(*composite);
222 for (const xAOD::IParticle* part : foundCombination) {
223 const xAOD::IParticleContainer *container = offlineContainers.at(part->type());
224 // If we have an owning container then things are relatively simple:
225 // we can just construct the element link from its SG key and the
226 // index. Otherwise we have to locate the correct proxy from the element
227 if (container->trackIndices())
228 links.emplace_back(
229 m_offlineInputs.at(part->type()).key(),
230 part->index(),
231 extendedCtx.proxy());
232 else
233 links.push_back(makeLink<xAOD::IParticleContainer>(part, extendedCtx.proxy()));
234 }
235 } //> end loop over the found combinations
236 } //> end loop over chains
237 return StatusCode::SUCCESS;
238 }
239
242 const std::string& chain) const
243 {
244 auto uniqueContainer = std::make_unique<xAOD::TrigCompositeContainer>();
245 auto aux = std::make_unique<xAOD::AuxContainerBase>();
246 uniqueContainer->setStore(aux.get() );
247 container = uniqueContainer.get();
248 std::string name = m_outputPrefix+chain;
249 // We have to replace '.' characters with '_' characters so that these are
250 // valid container names...
251 std::replace(name.begin(), name.end(), '.', '_');
252 ATH_CHECK( evtStore()->record(std::move(uniqueContainer), name) );
253 ATH_CHECK( evtStore()->record(std::move(aux), name+"Aux.") );
254 return StatusCode::SUCCESS;
255 }
256
258 const xAOD::IParticle* part,
259 std::map<xAOD::Type::ObjectType, particleVec_t>& offlineParticles,
260 std::map<const xAOD::IParticle*, particleVec_t>& cache) const
261 {
262 // Build up all the possible matches between online and offline particles
263 auto cacheItr = cache.find(part);
264 if (cacheItr == cache.end() ) {
265 xAOD::Type::ObjectType type = part->type();
266 particleVec_t candidates;
268 // If it's a calo cluster then we need to get the cluster from the
269 // egamma types.
270 static const constAcc_t<vecLink_t<xAOD::CaloClusterContainer>> acc_calo("caloClusterLinks");
271 for (xAOD::Type::ObjectType egType : {
273 {
274 for (const xAOD::IParticle* cand : offlineParticles[egType]) {
275 const vecLink_t<xAOD::CaloClusterContainer>& links = acc_calo(*cand);
276 if (links.size() == 0 || !links.at(0).isValid() )
277 continue;
278 const xAOD::CaloCluster* clus = *links.at(0);
279 if (matchParticles(part, clus) )
280 candidates.push_back(cand);
281 }
282 }
283 }
284 else {
285 for (const xAOD::IParticle* cand : offlineParticles[type])
286 if (matchParticles(part, cand) )
287 candidates.push_back(cand);
288 }
289 cacheItr = cache.emplace(
290 std::make_pair(part, std::move(candidates) ) ).first;
291 }
292 return cacheItr->second;
293 }
294
296 const xAOD::IParticle* lhs,
297 const xAOD::IParticle* rhs) const
298 {
299 return m_scoreTool->score(*lhs, *rhs) < m_drThreshold;
300 }
301
302} //> end namespace DerivationFramework
#define ATH_CHECK
Evaluate an expression and check for errors.
#define ATH_MSG_ERROR(x)
#define ATH_MSG_INFO(x)
#define ATH_MSG_VERBOSE(x)
#define ATH_MSG_WARNING(x)
#define ATH_MSG_DEBUG(x)
std::vector< size_t > vec
void operator()(T1)
Handle class for reading from StoreGate.
bool m_checkEmptyChainGroups
If set, discard any triggers with empty chain groups (break the job otherwise).
std::map< xAOD::Type::ObjectType, SG::ReadHandleKey< xAOD::IParticleContainer > > m_offlineInputs
The input containers to use. These are keyed by xAOD object type.
virtual StatusCode addBranches(const EventContext &ctx) const override
Calculate the matchings.
bool matchParticles(const xAOD::IParticle *lhs, const xAOD::IParticle *rhs) const
Check if the dR between two particles is below threshold.
virtual StatusCode initialize() override
Initialize the tool.
const particleVec_t & getCandidateMatchesFor(const xAOD::IParticle *part, std::map< xAOD::Type::ObjectType, particleVec_t > &offlineParticles, std::map< const xAOD::IParticle *, particleVec_t > &cache) const
Get all offline particles that could match a given online one.
std::vector< const xAOD::IParticle * > particleVec_t
Helper typedefs.
std::string m_outputPrefix
The prefix to place at the beginning of the output containers.
ToolHandle< Trig::TrigDecisionTool > m_tdt
The trig decision tool.
StatusCode createOutputContainer(xAOD::TrigCompositeContainer *&container, const std::string &chain) const
Create an output container for the named chain.
bool m_rerun
Whether to match in rerun mode or not.
ToolHandle< Trig::IIParticleRetrievalTool > m_trigParticleTool
The tool to retrieve the online candidates.
TriggerMatchingTool(const std::string &type, const std::string &name, const IInterface *pSvcLocator)
Constructor.
bool m_inputDependentConfig
If using an input-file-dependent config then we warn when triggers are removed.
float m_drThreshold
The DR threshold to use.
ToolHandle< Trig::IMatchScoringTool > m_scoreTool
The pair scoring tool.
utility class that acts wraps a bidirectional iterator.
Definition RangedItr.h:18
virtual SG::DataProxy * proxy(const CLID &id, const std::string &key) const =0
Get proxy with given id and key.
std::vector< std::string > getListOfTriggers() const
Class providing the definition of the 4-vector interface.
virtual double pt() const =0
The transverse momentum ( ) of the particle.
int r
Definition globals.cxx:22
const ExtendedEventContext & getExtendedEventContext(const EventContext &ctx)
Retrieve an extended context from a context object.
std::vector< std::vector< T > > getAllDistinctCombinations(std::vector< RangedItr< typename std::vector< T >::const_iterator > > &inputs, INNERPROJ innerproj={}, OUTERPROJ outerproj={})
Get all valid, unique combinations of distinct elements from the input ranges.
bool insertIntoSortedVector(std::vector< T > &vec, const T &ele, PROJ proj={})
Helper function for inserting an element into a sorted vector.
THE reconstruction tool.
SG::ReadCondHandle< T > makeHandle(const SG::ReadCondHandleKey< T > &key, const EventContext &ctx=Gaudi::Hive::currentContext())
ElementLink< T > makeLink(const SG::View *view, const SG::ReadHandle< T > &handle, size_t index)
Create EL to a collection in view.
Definition ViewHelper.h:309
DataModel_detail::iterator< DVL > unique(typename DataModel_detail::iterator< DVL > beg, typename DataModel_detail::iterator< DVL > end)
Specialization of unique for DataVector/List.
void sort(typename DataModel_detail::iterator< DVL > beg, typename DataModel_detail::iterator< DVL > end)
Specialization of sort for DataVector/List.
ObjectType
Type of objects that have a representation in the xAOD EDM.
Definition ObjectType.h:32
@ Photon
The object is a photon.
Definition ObjectType.h:47
@ CaloCluster
The object is a calorimeter cluster.
Definition ObjectType.h:39
@ Muon
The object is a muon.
Definition ObjectType.h:48
@ Electron
The object is an electron.
Definition ObjectType.h:46
@ Tau
The object is a tau (jet).
Definition ObjectType.h:49
TrigCompositeContainer_v1 TrigCompositeContainer
Declare the latest version of the container.
CaloCluster_v1 CaloCluster
Define the latest version of the calorimeter cluster class.
TrigComposite_v1 TrigComposite
Declare the latest version of the class.
DataVector< IParticle > IParticleContainer
Simple convenience declaration of IParticleContainer.