7#include <GaudiKernel/ConcurrencyFlags.h>
10#include <boost/core/demangle.hpp>
15#include <range/v3/algorithm/stable_sort.hpp>
16#include <range/v3/to_container.hpp>
17#include <range/v3/view.hpp>
26namespace rv = ranges::views;
33 : base_class(name, svc),
59 ATH_MSG_ERROR(
"Failed to create background event selector context");
60 return StatusCode::FAILURE;
65 SmartIF<IProxyProviderSvc> proxyProviderSvc{
66 serviceLocator()->service(std::format(
"ProxyProviderSvc/BkgPPSvc_{}", name()))
72 if (!addressProvider) {
74 "Could not cast background event selector to IAddressProvider");
76 proxyProviderSvc->addProvider(addressProvider);
79 SmartIF<IAddressProvider> athPoolAP{
80 serviceLocator()->service(std::format(
"AthenaPoolAddressProviderSvc/BkgAPAPSvc_{}", name()))
84 "Could not cast AthenaPoolAddressProviderSvc to IAddressProvider");
86 proxyProviderSvc->addProvider(athPoolAP);
89 SmartIF<IAddressProvider> addRemapAP{
90 serviceLocator()->service(std::format(
"AddressRemappingSvc/BkgARSvc_{}", name()))
93 ATH_MSG_WARNING(
"Could not cast AddressRemappingSvc to IAddressProvider");
95 proxyProviderSvc->addProvider(addRemapAP);
102 auto& sgs =
m_empty_caches.emplace_back(std::make_unique<SGHandleArray>());
103 sgs->reserve(mbBatchSize);
104 for (
int j = 0; j < mbBatchSize; ++j) {
106 auto& sg = sgs->emplace_back(
107 std::format(
"StoreGateSvc/StoreGate_{}_{}_{}", name(), i, j), name());
110 sg->setProxyProviderSvc(proxyProviderSvc);
120 auto skipEvent_callback = [
this, mbBatchSize](
123 using namespace std::chrono_literals;
124 auto evts = ranges::make_subrange(begin, end);
125 ATH_MSG_INFO(
"Skipping " << end - begin <<
" HS events.");
130 std::vector<std::tuple<int, int>> batches_with_counts{};
132 for (
int batch : batches_all) {
134 if (batches_with_counts.empty()) {
135 batches_with_counts.emplace_back(batch, 1);
139 auto& last_entry = batches_with_counts.back();
140 if (batch == std::get<0>(last_entry)) {
141 std::get<1>(last_entry) += 1;
144 batches_with_counts.emplace_back(batch, 1);
152 for (
const auto& [batch,
count] : batches_with_counts) {
153 if (
m_cache.count(batch) != 0) {
160 std::this_thread::sleep_for(50ms);
173 return StatusCode::FAILURE;
180 return StatusCode::SUCCESS;
185 return StatusCode::SUCCESS;
189 const EventContext& ctx) {
194 bool sf_updated_throwaway;
195 const float beam_lumi_sf =
197 ctx.eventID().lumi_block(),
198 sf_updated_throwaway)
200 std::vector<float> avg_num_mb_by_bunch(n_bunches,
210 avg_num_mb_by_bunch[idx] *=
m_beamInt->normFactor(bunch);
215 num_mb_by_bunch.clear();
216 num_mb_by_bunch.resize(n_bunches);
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);
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));
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);
234 if (num_mb > mbBatchSize) {
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;
241 good && num_mb_by_bunch[idx] > 0;
244 ranges::to<std::vector>;
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));
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) {
262 ATH_MSG_ERROR(
"We need " << num_mb <<
" events but the batch size is "
263 << mbBatchSize <<
". Restricting to "
264 << mbBatchSize <<
" events!");
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");
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);
288 if (
m_cache.count(batch) != 0) {
293 return StatusCode::SUCCESS;
297 ATH_MSG_INFO(
"Waiting to prevent out-of-order loading of batches");
298 order_wait_start = std::chrono::steady_clock::now();
300 std::this_thread::sleep_for(50ms);
302 auto wait_time = std::chrono::steady_clock::now() - order_wait_start;
304 "Waited {:%M:%S} to prevent out-of-order loading", wait_time));
310 if (empty_caches_lock.owns_lock()) {
313 empty_caches_lock.unlock();
317 cache_wait_start = std::chrono::steady_clock::now();
320 std::this_thread::sleep_for(100ms);
324 auto wait_time = std::chrono::steady_clock::now() - cache_wait_start;
326 std::format(
"Waited {:%M:%S} for a free cache", wait_time));
330 ATH_MSG_INFO(
"Reading next batch in event " << ctx.evt() <<
", slot "
331 << ctx.slot() <<
" (hs_id "
334 auto start_time = std::chrono::system_clock::now();
339 for (
auto&& sg : *
m_cache[batch]) {
342 SG::CurrentEventStore::Push reader_sg_ces(sg.get());
347 return StatusCode::FAILURE;
349 IOpaqueAddress* addr =
nullptr;
353 return StatusCode::FAILURE;
355 if (addr ==
nullptr) {
357 return StatusCode::FAILURE;
363 for (
const auto* proxy_ptr : sg->proxies()) {
364 if (!proxy_ptr->isValid()) {
369 sg->proxy_exact(proxy_ptr->sgkey())->accessData();
377 "Reading {} events took {:%OMm %OSs}",
m_cache[batch]->
size(),
378 std::chrono::system_clock::now() - start_time));
381 return StatusCode::SUCCESS;
384 return StatusCode::SUCCESS;
388 std::uint64_t mb_id) {
389 const std::int64_t hs_id =
get_hs_id(ctx);
398 throw std::logic_error(std::format(
399 "Tried to request bunch {} which is outside the range [{}, {}]", bunch,
406 using namespace std::chrono_literals;
407 const std::int64_t hs_id =
get_hs_id(ctx);
414 std::unique_ptr temp = std::move(
m_cache[batch]);
416 for (
auto&& sg : *temp) {
422 ATH_MSG_DEBUG(
"BATCH " << batch <<
": " << uses <<
" uses out of "
426 return StatusCode::SUCCESS;
#define ATH_CHECK
Evaluate an expression and check for errors.
#define ATH_MSG_WARNING(x)
std::string CLIDToString(const CLID &clid)
uint32_t CLID
The Class ID type.
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.
int count(std::string s, const std::string ®x)
count how many occurances of a regx are in a string