7#include <GaudiKernel/ConcurrencyFlags.h>
10#include <boost/core/demangle.hpp>
15#include <range/v3/algorithm/stable_sort.hpp>
16#include <range/v3/numeric/accumulate.hpp>
17#include <range/v3/to_container.hpp>
18#include <range/v3/view.hpp>
27namespace rv = ranges::views;
34 : base_class(name, svc),
60 ATH_MSG_ERROR(
"Failed to create background event selector context");
61 return StatusCode::FAILURE;
66 SmartIF<IProxyProviderSvc> proxyProviderSvc{
67 serviceLocator()->service(std::format(
"ProxyProviderSvc/BkgPPSvc_{}", name()))
73 if (!addressProvider) {
75 "Could not cast background event selector to IAddressProvider");
77 proxyProviderSvc->addProvider(addressProvider);
80 SmartIF<IAddressProvider> athPoolAP{
81 serviceLocator()->service(std::format(
"AthenaPoolAddressProviderSvc/BkgAPAPSvc_{}", name()))
85 "Could not cast AthenaPoolAddressProviderSvc to IAddressProvider");
87 proxyProviderSvc->addProvider(athPoolAP);
90 SmartIF<IAddressProvider> addRemapAP{
91 serviceLocator()->service(std::format(
"AddressRemappingSvc/BkgARSvc_{}", name()))
94 ATH_MSG_WARNING(
"Could not cast AddressRemappingSvc to IAddressProvider");
96 proxyProviderSvc->addProvider(addRemapAP);
103 auto& sgs =
m_empty_caches.emplace_back(std::make_unique<SGHandleArray>());
104 sgs->reserve(mbBatchSize);
105 for (
int j = 0; j < mbBatchSize; ++j) {
107 auto& sg = sgs->emplace_back(
108 std::format(
"StoreGateSvc/StoreGate_{}_{}_{}", name(), i, j), name());
111 sg->setProxyProviderSvc(proxyProviderSvc);
121 auto skipEvent_callback = [
this, mbBatchSize](
124 using namespace std::chrono_literals;
125 auto evts = ranges::make_subrange(begin, end);
126 ATH_MSG_INFO(
"Skipping " << end - begin <<
" HS events.");
131 std::vector<std::tuple<int, int>> batches_with_counts{};
133 for (
int batch : batches_all) {
135 if (batches_with_counts.empty()) {
136 batches_with_counts.emplace_back(batch, 1);
140 auto& last_entry = batches_with_counts.back();
141 if (batch == std::get<0>(last_entry)) {
142 std::get<1>(last_entry) += 1;
145 batches_with_counts.emplace_back(batch, 1);
153 for (
const auto& [batch,
count] : batches_with_counts) {
154 if (
m_cache.count(batch) != 0) {
161 std::this_thread::sleep_for(50ms);
174 return StatusCode::FAILURE;
181 return StatusCode::SUCCESS;
186 return StatusCode::SUCCESS;
190 const EventContext& ctx) {
195 bool sf_updated_throwaway;
196 const float beam_lumi_sf =
198 ctx.eventID().lumi_block(),
199 sf_updated_throwaway)
201 std::vector<float> avg_num_mb_by_bunch(n_bunches,
211 avg_num_mb_by_bunch[idx] *=
m_beamInt->normFactor(bunch);
216 num_mb_by_bunch.clear();
217 num_mb_by_bunch.resize(n_bunches);
220 std::transform(avg_num_mb_by_bunch.begin(), avg_num_mb_by_bunch.end(),
221 num_mb_by_bunch.begin(), [&prng](
float avg) {
222 return std::poisson_distribution<std::uint64_t>(avg)(prng);
225 std::transform(avg_num_mb_by_bunch.begin(), avg_num_mb_by_bunch.end(),
226 num_mb_by_bunch.begin(), [](
float f) {
227 return static_cast<std::uint64_t>(std::round(f));
231 std::uint64_t num_mb = ranges::accumulate(num_mb_by_bunch, 0UL);
232 std::vector<std::uint64_t>& index_array = *
m_idx_lists.get(ctx);
235 if (num_mb > mbBatchSize) {
238 rv::iota(0ULL, num_mb_by_bunch.size()) |
239 rv::filter([center_bunch, &num_mb_by_bunch](
int idx) {
240 bool good = idx != center_bunch;
242 good && num_mb_by_bunch[idx] > 0;
245 ranges::to<std::vector>;
247 ranges::stable_sort(indices, std::greater{},
248 [center_bunch](std::size_t idx) {
249 return std::size_t(std::abs(
int(idx) - center_bunch));
252 for (
auto idx : indices) {
253 const std::uint64_t max_to_subtract = num_mb - mbBatchSize;
254 const std::uint64_t num_subtracted =
255 std::min(max_to_subtract, num_mb_by_bunch[idx]);
256 num_mb_by_bunch[idx] -= num_subtracted;
257 num_mb -= num_subtracted;
258 if (num_mb <= mbBatchSize) {
263 ATH_MSG_ERROR(
"We need " << num_mb <<
" events but the batch size is "
264 << mbBatchSize <<
". Restricting to "
265 << mbBatchSize <<
" events!");
267 index_array = rv::ints(0,
int(mbBatchSize)) | rv::sample(num_mb, prng) |
268 ranges::to<std::vector<std::uint64_t>>;
269 ranges::shuffle(index_array, prng);
270 ATH_MSG_DEBUG(
"HS ID " << hs_id <<
" uses " << num_mb <<
" events");
280 using namespace std::chrono_literals;
281 bool first_wait =
true;
282 std::chrono::steady_clock::time_point cache_wait_start{};
283 std::chrono::steady_clock::time_point order_wait_start{};
284 const std::int64_t hs_id =
get_hs_id(ctx);
289 if (
m_cache.count(batch) != 0) {
294 return StatusCode::SUCCESS;
298 ATH_MSG_INFO(
"Waiting to prevent out-of-order loading of batches");
299 order_wait_start = std::chrono::steady_clock::now();
301 std::this_thread::sleep_for(50ms);
303 auto wait_time = std::chrono::steady_clock::now() - order_wait_start;
305 "Waited {:%M:%S} to prevent out-of-order loading", wait_time));
311 if (empty_caches_lock.owns_lock()) {
314 empty_caches_lock.unlock();
318 cache_wait_start = std::chrono::steady_clock::now();
321 std::this_thread::sleep_for(100ms);
325 auto wait_time = std::chrono::steady_clock::now() - cache_wait_start;
327 std::format(
"Waited {:%M:%S} for a free cache", wait_time));
331 ATH_MSG_INFO(
"Reading next batch in event " << ctx.evt() <<
", slot "
332 << ctx.slot() <<
" (hs_id "
335 auto start_time = std::chrono::system_clock::now();
340 for (
auto&& sg : *
m_cache[batch]) {
343 SG::CurrentEventStore::Push reader_sg_ces(sg.get());
348 return StatusCode::FAILURE;
350 IOpaqueAddress* addr =
nullptr;
354 return StatusCode::FAILURE;
356 if (addr ==
nullptr) {
358 return StatusCode::FAILURE;
364 for (
const auto* proxy_ptr : sg->proxies()) {
365 if (!proxy_ptr->isValid()) {
370 sg->proxy_exact(proxy_ptr->sgkey())->accessData();
378 "Reading {} events took {:%OMm %OSs}",
m_cache[batch]->
size(),
379 std::chrono::system_clock::now() - start_time));
382 return StatusCode::SUCCESS;
385 return StatusCode::SUCCESS;
389 std::uint64_t mb_id) {
390 const std::int64_t hs_id =
get_hs_id(ctx);
399 throw std::logic_error(std::format(
400 "Tried to request bunch {} which is outside the range [{}, {}]", bunch,
407 using namespace std::chrono_literals;
408 const std::int64_t hs_id =
get_hs_id(ctx);
415 std::unique_ptr temp = std::move(
m_cache[batch]);
417 for (
auto&& sg : *temp) {
423 ATH_MSG_DEBUG(
"BATCH " << batch <<
": " << uses <<
" uses out of "
427 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