ATLAS Offline Software
Loading...
Searching...
No Matches
BatchedMinbiasSvc.cxx
Go to the documentation of this file.
1/*
2 Copyright (C) 2002-2026 CERN for the benefit of the ATLAS collaboration
3*/
4
5#include "BatchedMinbiasSvc.h"
6
7#include <GaudiKernel/ConcurrencyFlags.h>
8
9#include <algorithm>
10#include <boost/core/demangle.hpp>
11#include <chrono>
12#include <cmath>
13#include <format>
14#include <random>
15#include <range/v3/algorithm/stable_sort.hpp>
16#include <range/v3/to_container.hpp>
17#include <range/v3/view.hpp>
18#include <thread>
19
25
26namespace rv = ranges::views;
27
28inline std::string CLIDToString(const CLID& clid) {
29 return boost::core::demangle(CLIDRegistry::CLIDToTypeinfo(clid)->name());
30}
31
32BatchedMinbiasSvc::BatchedMinbiasSvc(const std::string& name, ISvcLocator* svc)
33 : base_class(name, svc),
34 m_bkg_evt_sel_ctx(nullptr),
36
38
39int BatchedMinbiasSvc::event_to_batch(std::int64_t hs_id) {
40 return int(hs_id / m_HSBatchSize.value());
41}
42
44 ATH_CHECK(m_skipEventIdxSvc.retrieve());
45 ATH_CHECK(m_beamInt.retrieve());
46 ATH_CHECK(m_beamLumi.retrieve());
47
48 m_cache.clear();
49 m_empty_caches.clear();
50 m_batch_use_count.clear();
51 m_batch_use_count.reserve(m_actualNHSEventsPerBatch.value().size());
52 for (std::size_t i = 0; i < m_actualNHSEventsPerBatch.value().size(); ++i) {
53 m_batch_use_count.emplace_back(std::make_unique<std::atomic_int>(0));
54 }
55 ATH_CHECK(m_bkgEventSelector.retrieve());
56 ATH_CHECK(m_activeStoreSvc.retrieve());
57 // Setup context
58 if (!m_bkgEventSelector->createContext(m_bkg_evt_sel_ctx).isSuccess()) {
59 ATH_MSG_ERROR("Failed to create background event selector context");
60 return StatusCode::FAILURE;
61 }
62 ATH_CHECK(SmartIF<IService>(m_bkgEventSelector.get())->start());
63
64 // Setup proxy provider
65 SmartIF<IProxyProviderSvc> proxyProviderSvc{
66 serviceLocator()->service(std::format("ProxyProviderSvc/BkgPPSvc_{}", name()))
67 };
68 ATH_CHECK(proxyProviderSvc.isValid());
69
70 // Setup Address Providers
71 SmartIF<IAddressProvider> addressProvider{m_bkgEventSelector.get()};
72 if (!addressProvider) {
74 "Could not cast background event selector to IAddressProvider");
75 } else {
76 proxyProviderSvc->addProvider(addressProvider);
77 }
78 // AthenaPoolAddressProviderSvc
79 SmartIF<IAddressProvider> athPoolAP{
80 serviceLocator()->service(std::format("AthenaPoolAddressProviderSvc/BkgAPAPSvc_{}", name()))
81 };
82 if (!athPoolAP) {
84 "Could not cast AthenaPoolAddressProviderSvc to IAddressProvider");
85 } else {
86 proxyProviderSvc->addProvider(athPoolAP);
87 }
88 // AddressRemappingSvc
89 SmartIF<IAddressProvider> addRemapAP{
90 serviceLocator()->service(std::format("AddressRemappingSvc/BkgARSvc_{}", name()))
91 };
92 if (!addRemapAP) {
93 ATH_MSG_WARNING("Could not cast AddressRemappingSvc to IAddressProvider");
94 } else {
95 proxyProviderSvc->addProvider(addRemapAP);
96 }
97
98 int mbBatchSize = m_MBBatchSize.value();
99 // setup NSimultaneousBatches vectors of MBBatchSize StoreGates in
100 // m_empty_caches
101 for (int i = 0; i < m_NSimultaneousBatches.value(); ++i) {
102 auto& sgs = m_empty_caches.emplace_back(std::make_unique<SGHandleArray>());
103 sgs->reserve(mbBatchSize);
104 for (int j = 0; j < mbBatchSize; ++j) {
105 // creates / retrieves a different StoreGateSvc for each slot
106 auto& sg = sgs->emplace_back(
107 std::format("StoreGateSvc/StoreGate_{}_{}_{}", name(), i, j), name());
108 ATH_CHECK(sg.retrieve());
109 sg->setStoreID(StoreID::PILEUP_STORE);
110 sg->setProxyProviderSvc(proxyProviderSvc);
111 }
112 }
113
114 // Setup the spare store for event skipping
115 ATH_CHECK(m_spare_store.retrieve());
117 m_spare_store->setProxyProviderSvc(proxyProviderSvc);
118
119 // Setup the callback for event skipping
120 auto skipEvent_callback = [this, mbBatchSize](
122 ISkipEventIdxSvc::EvtIter end) -> StatusCode {
123 using namespace std::chrono_literals;
124 auto evts = ranges::make_subrange(begin, end);
125 ATH_MSG_INFO("Skipping " << end - begin << " HS events.");
126 auto batches_all =
127 evts | rv::transform([this](const ISkipEventIdxSvc::EvtId& evt) {
128 return event_to_batch(evt.evtIdx);
129 });
130 std::vector<std::tuple<int, int>> batches_with_counts{};
131 // Produce a list of batches, and how many times they appear
132 for (int batch : batches_all) {
133 // First entry
134 if (batches_with_counts.empty()) {
135 batches_with_counts.emplace_back(batch, 1);
136 continue;
137 }
138 // Subsequent entries
139 auto& last_entry = batches_with_counts.back();
140 if (batch == std::get<0>(last_entry)) {
141 std::get<1>(last_entry) += 1;
142 continue;
143 }
144 batches_with_counts.emplace_back(batch, 1);
145 }
146
147 // Discard batches
148 const int hs_batch_size = m_HSBatchSize.value();
149 auto* const old_store = m_activeStoreSvc->activeStore();
150 m_activeStoreSvc->setStore(m_spare_store.get());
151 ATH_CHECK(m_spare_store->clearStore());
152 for (const auto& [batch, count] : batches_with_counts) {
153 if (m_cache.count(batch) != 0) {
154 // batch is currently loaded, just update the use count
155 m_batch_use_count[batch]->fetch_add(count);
156 continue;
157 }
158 // force ordering in background stream
159 while (m_last_loaded_batch < batch - 1) {
160 std::this_thread::sleep_for(50ms);
161 }
162 // if we aren't skipping all the hardscatters in the batch, do nothing
163 if ((m_batch_use_count[batch]->fetch_add(count) + count) <
164 hs_batch_size) {
165 continue;
166 }
167 // otherwise discard the batch
168 ATH_MSG_INFO("Discarding batch " << batch);
169 std::unique_lock lck{m_reading_batch_mtx};
170 if (!m_bkgEventSelector->next(*m_bkg_evt_sel_ctx, mbBatchSize)
171 .isSuccess()) {
172 ATH_MSG_INFO("Ran out of background events");
173 return StatusCode::FAILURE;
174 }
175 // increment counters
176 m_last_loaded_batch.fetch_add(1);
177 }
178 ATH_CHECK(m_spare_store->clearStore());
179 m_activeStoreSvc->setStore(old_store);
180 return StatusCode::SUCCESS;
181 };
182
183 // register callback
184 ATH_CHECK(m_skipEventIdxSvc->registerCallback(skipEvent_callback));
185 return StatusCode::SUCCESS;
186}
187
188std::size_t BatchedMinbiasSvc::calcMBRequired(std::int64_t hs_id,
189 const EventContext& ctx) {
190 const int n_bunches = m_latestDeltaBC.value() - m_earliestDeltaBC.value() + 1;
191 FastReseededPRNG prng{m_seed.value(), hs_id};
192
193 // First apply the beam luminosity SF
194 bool sf_updated_throwaway;
195 const float beam_lumi_sf =
196 m_useBeamLumi ? m_beamLumi->scaleFactor(ctx.eventID().run_number(),
197 ctx.eventID().lumi_block(),
198 sf_updated_throwaway)
199 : 1.f;
200 std::vector<float> avg_num_mb_by_bunch(n_bunches,
201 beam_lumi_sf * m_nPerBunch.value());
202 // Now update using beam intensities
203 if (m_useBeamInt) {
204 // Supposed to be once per event, but ends up running once per minbias type
205 // per event now
206 m_beamInt->selectT0(ctx);
207 for (int bunch = m_earliestDeltaBC.value();
208 bunch <= m_latestDeltaBC.value(); ++bunch) {
209 std::size_t idx = bunch - m_earliestDeltaBC.value();
210 avg_num_mb_by_bunch[idx] *= m_beamInt->normFactor(bunch);
211 }
212 }
213
214 std::vector<std::uint64_t>& num_mb_by_bunch = *m_num_mb_by_bunch.get(ctx);
215 num_mb_by_bunch.clear();
216 num_mb_by_bunch.resize(n_bunches);
217
218 if (m_usePoisson) {
219 std::transform(avg_num_mb_by_bunch.begin(), avg_num_mb_by_bunch.end(),
220 num_mb_by_bunch.begin(), [&prng](float avg) {
221 return std::poisson_distribution<std::uint64_t>(avg)(prng);
222 });
223 } else {
224 std::transform(avg_num_mb_by_bunch.begin(), avg_num_mb_by_bunch.end(),
225 num_mb_by_bunch.begin(), [](float f) {
226 return static_cast<std::uint64_t>(std::round(f));
227 });
228 }
229
230 std::uint64_t num_mb = std::accumulate(num_mb_by_bunch.begin(), num_mb_by_bunch.end(), std::uint64_t{0});
231 std::vector<std::uint64_t>& index_array = *m_idx_lists.get(ctx);
232 const std::uint64_t mbBatchSize = m_MBBatchSize.value();
233 // Prevent running out of events
234 if (num_mb > mbBatchSize) {
235 const int center_bunch = -m_earliestDeltaBC.value();
236 auto indices =
237 rv::iota(0ULL, num_mb_by_bunch.size()) |
238 rv::filter([center_bunch, &num_mb_by_bunch](int idx) {
239 bool good = idx != center_bunch; // filter out the central bunch
240 good =
241 good && num_mb_by_bunch[idx] > 0; // filter out unfilled bunches
242 return good;
243 }) |
244 ranges::to<std::vector>;
245 // sort by distance from central bunch
246 ranges::stable_sort(indices, std::greater{},
247 [center_bunch](std::size_t idx) {
248 return std::size_t(std::abs(int(idx) - center_bunch));
249 });
250 // subtract from bunches until we aren't using too many events
251 for (auto idx : indices) {
252 const std::uint64_t max_to_subtract = num_mb - mbBatchSize;
253 const std::uint64_t num_subtracted =
254 std::min(max_to_subtract, num_mb_by_bunch[idx]);
255 num_mb_by_bunch[idx] -= num_subtracted;
256 num_mb -= num_subtracted;
257 if (num_mb <= mbBatchSize) {
258 break;
259 }
260 }
261 // Print an error anyway so we can fix the job
262 ATH_MSG_ERROR("We need " << num_mb << " events but the batch size is "
263 << mbBatchSize << ". Restricting to "
264 << mbBatchSize << " events!");
265 }
266 index_array = rv::ints(0, int(mbBatchSize)) | rv::sample(num_mb, prng) |
267 ranges::to<std::vector<std::uint64_t>>;
268 ranges::shuffle(index_array, prng);
269 ATH_MSG_DEBUG("HS ID " << hs_id << " uses " << num_mb << " events");
270 // Disabled until C++ 23 range formatting can be used
271 // if (m_HSBatchSize <= 1) {
272 // ATH_MSG_DEBUG(fmt::format("\t\tBy bunch: [{}]\n", fmt::join(num_mb_by_bunch, ", "))
273 // << fmt::format("\t\tOrder: [{}]", fmt::join(index_array, ", ")));
274 // }
275 return num_mb;
276}
277
278StatusCode BatchedMinbiasSvc::beginHardScatter(const EventContext& ctx) {
279 using namespace std::chrono_literals;
280 bool first_wait = true;
281 std::chrono::steady_clock::time_point cache_wait_start{};
282 std::chrono::steady_clock::time_point order_wait_start{};
283 const std::int64_t hs_id = get_hs_id(ctx);
284 const int batch = event_to_batch(hs_id);
285 calcMBRequired(hs_id, ctx); // don't need the total, only need to populate the arrays
286
287 while (true) {
288 if (m_cache.count(batch) != 0) {
289 // batch already loaded
290 // mutex prevents returning when batch is partially loaded
291 m_cache_mtxs[batch].lock();
292 m_cache_mtxs[batch].unlock();
293 return StatusCode::SUCCESS;
294 }
295 // prevent batches loading out-of-order
296 if (m_last_loaded_batch < (batch - 1)) {
297 ATH_MSG_INFO("Waiting to prevent out-of-order loading of batches");
298 order_wait_start = std::chrono::steady_clock::now();
299 while (m_last_loaded_batch < (batch - 1)) {
300 std::this_thread::sleep_for(50ms);
301 }
302 auto wait_time = std::chrono::steady_clock::now() - order_wait_start;
303 ATH_MSG_INFO(std::format(
304 "Waited {:%M:%S} to prevent out-of-order loading", wait_time));
305 }
306 // See if there are any free caches
307 // Using try_lock here to avoid reading same batch twice
308 std::unique_lock<std::mutex> empty_caches_lock (m_empty_caches_mtx,
309 std::try_to_lock);
310 if (empty_caches_lock.owns_lock()) {
311 if (m_empty_caches.empty()) {
312 // Unlock mutex if we got the lock but there were no free caches
313 empty_caches_lock.unlock();
314 if (first_wait) {
315 ATH_MSG_INFO("Waiting for a free cache");
316 first_wait = false;
317 cache_wait_start = std::chrono::steady_clock::now();
318 }
319 // Wait 100ms then try again
320 std::this_thread::sleep_for(100ms);
321 continue;
322 }
323 if (!first_wait) {
324 auto wait_time = std::chrono::steady_clock::now() - cache_wait_start;
326 std::format("Waited {:%M:%S} for a free cache", wait_time));
327 }
328 std::scoped_lock reading{m_cache_mtxs[batch], m_reading_batch_mtx};
329 if (m_HSBatchSize != 0) {
330 ATH_MSG_INFO("Reading next batch in event " << ctx.evt() << ", slot "
331 << ctx.slot() << " (hs_id "
332 << hs_id << ")");
333 }
334 auto start_time = std::chrono::system_clock::now();
335 m_cache[batch] = std::move(m_empty_caches.front());
336 m_empty_caches.pop_front();
337 // Remember old store to reset later
338 auto* old_store = m_activeStoreSvc->activeStore();
339 for (auto&& sg : *m_cache[batch]) {
340 // Change active store
341 m_activeStoreSvc->setStore(sg.get());
342 SG::CurrentEventStore::Push reader_sg_ces(sg.get());
343 // Read next event
344 ATH_CHECK(sg->clearStore(true));
345 if (!(m_bkgEventSelector->next(*m_bkg_evt_sel_ctx)).isSuccess()) {
346 ATH_MSG_FATAL("Ran out of minbias events");
347 return StatusCode::FAILURE;
348 }
349 IOpaqueAddress* addr = nullptr;
350 if (!m_bkgEventSelector->createAddress(*m_bkg_evt_sel_ctx, addr)
351 .isSuccess()) {
352 ATH_MSG_WARNING("Failed to create address. No more events?");
353 return StatusCode::FAILURE;
354 }
355 if (addr == nullptr) {
356 ATH_MSG_WARNING("createAddress returned nullptr. No more events?");
357 return StatusCode::FAILURE;
358 }
359 ATH_CHECK(sg->recordAddress(addr));
360 ATH_CHECK(sg->loadEventProxies());
361 // Read data now if desired
362 if (!m_onDemandMB) {
363 for (const auto* proxy_ptr : sg->proxies()) {
364 if (!proxy_ptr->isValid()) {
365 continue;
366 }
367
368 // Sort of a const_cast, then ->accessData()
369 sg->proxy_exact(proxy_ptr->sgkey())->accessData();
370 }
371 }
372 }
373 // Reset active store
374 m_activeStoreSvc->setStore(old_store);
375 if (m_HSBatchSize != 0) {
376 ATH_MSG_INFO(std::format(
377 "Reading {} events took {:%OMm %OSs}", m_cache[batch]->size(),
378 std::chrono::system_clock::now() - start_time));
379 }
380 m_last_loaded_batch.exchange(batch);
381 return StatusCode::SUCCESS;
382 }
383 }
384 return StatusCode::SUCCESS;
385}
386
388 std::uint64_t mb_id) {
389 const std::int64_t hs_id = get_hs_id(ctx);
390 const std::size_t index = m_idx_lists.get(ctx)->at(mb_id);
391 const int batch = event_to_batch(hs_id);
392 return m_cache[batch]->at(index).get();
393}
394
395std::size_t BatchedMinbiasSvc::getNumForBunch(const EventContext& ctx,
396 int bunch) const {
397 if (bunch < m_earliestDeltaBC.value() || bunch > m_latestDeltaBC.value()) {
398 throw std::logic_error(std::format(
399 "Tried to request bunch {} which is outside the range [{}, {}]", bunch,
400 m_earliestDeltaBC.value(), m_latestDeltaBC.value()));
401 }
402 return m_num_mb_by_bunch.get(ctx)->at(bunch - m_earliestDeltaBC.value());
403}
404
405StatusCode BatchedMinbiasSvc::endHardScatter(const EventContext& ctx) {
406 using namespace std::chrono_literals;
407 const std::int64_t hs_id = get_hs_id(ctx);
408 const int batch = event_to_batch(hs_id);
409 const int uses = m_batch_use_count[batch]->fetch_add(1) + 1;
410
411 // If we're done with every event in the batch, clear the stores and return
412 // them
413 if (uses == m_HSBatchSize.value()) {
414 std::unique_ptr temp = std::move(m_cache[batch]);
415 m_cache.erase(batch);
416 for (auto&& sg : *temp) {
417 ATH_CHECK(sg->clearStore());
418 }
419 std::lock_guard lg{m_empty_caches_mtx};
420 m_empty_caches.emplace_back(std::move(temp));
421 } else {
422 ATH_MSG_DEBUG("BATCH " << batch << ": " << uses << " uses out of "
423 << m_HSBatchSize << " "
425 }
426 return StatusCode::SUCCESS;
427}
#define ATH_CHECK
Evaluate an expression and check for errors.
#define ATH_MSG_ERROR(x)
#define ATH_MSG_FATAL(x)
#define ATH_MSG_INFO(x)
#define ATH_MSG_WARNING(x)
#define ATH_MSG_DEBUG(x)
std::string CLIDToString(const CLID &clid)
uint32_t CLID
The Class ID type.
Hold a pointer to the current event store.
size_t size() const
Number of registered mappings.
StatusCode initialize() override
AthService initialize.
ServiceHandle< IEvtSelector > m_bkgEventSelector
Gaudi::Property< std::uint64_t > m_seed
Gaudi::Property< float > m_nPerBunch
Gaudi::Property< bool > m_useBeamLumi
std::map< int, std::unique_ptr< SGHandleArray > > m_cache
ServiceHandle< IBeamIntensity > m_beamInt
~BatchedMinbiasSvc()
Destructor.
Gaudi::Property< std::vector< int > > m_actualNHSEventsPerBatch
Gaudi::Property< bool > m_onDemandMB
int event_to_batch(std::int64_t hs_id)
StoreGateSvc * getMinbias(const EventContext &ctx, std::uint64_t mb_id) override
Gaudi::Property< int > m_earliestDeltaBC
std::vector< std::unique_ptr< std::atomic_int > > m_batch_use_count
Gaudi::Property< bool > m_usePoisson
ServiceHandle< ActiveStoreSvc > m_activeStoreSvc
Gaudi::Property< int > m_latestDeltaBC
std::deque< std::unique_ptr< SGHandleArray > > m_empty_caches
std::mutex m_reading_batch_mtx
std::size_t getNumForBunch(const EventContext &ctx, int bunch) const override
StatusCode endHardScatter(const EventContext &ctx) override
SG::SlotSpecificObj< std::vector< std::uint64_t > > m_idx_lists
Gaudi::Property< bool > m_useBeamInt
std::mutex m_empty_caches_mtx
Gaudi::Property< int > m_MBBatchSize
BatchedMinbiasSvc(const std::string &name, ISvcLocator *svc)
Constructor.
ServiceHandle< ISkipEventIdxSvc > m_skipEventIdxSvc
IEvtSelector::Context * m_bkg_evt_sel_ctx
virtual std::int64_t get_hs_id(const EventContext &ctx) const override
std::size_t calcMBRequired(std::int64_t hs_id, const EventContext &ctx)
SG::SlotSpecificObj< std::vector< std::uint64_t > > m_num_mb_by_bunch
Gaudi::Property< int > m_HSBatchSize
std::map< int, std::mutex > m_cache_mtxs
StatusCode beginHardScatter(const EventContext &ctx) override
std::atomic_int m_last_loaded_batch
ServiceHandle< IBeamLuminosity > m_beamLumi
Gaudi::Property< int > m_NSimultaneousBatches
static const std::type_info * CLIDToTypeinfo(CLID clid)
Translate between CLID and type_info.
std::vector< EvtId >::const_iterator EvtIter
The Athena Transient Store API.
@ PILEUP_STORE
Definition StoreID.h:31
int count(std::string s, const std::string &regx)
count how many occurances of a regx are in a string
Definition hcg.cxx:148
Definition index.py:1