Belle II Software development
BeamBkgHitRateMonitorModule.cc
1/**************************************************************************
2 * basf2 (Belle II Analysis Software Framework) *
3 * Author: The Belle II Collaboration *
4 * *
5 * See git log for contributors and copyright holders. *
6 * This file is licensed under LGPL-3.0, see LICENSE.md. *
7 **************************************************************************/
8
9// Own header.
10#include <background/modules/BeamBkgHitRateMonitor/BeamBkgHitRateMonitorModule.h>
11#include <background/modules/BeamBkgHitRateMonitor/PXDHitRateCounter.h>
12#include <background/modules/BeamBkgHitRateMonitor/SVDHitRateCounter.h>
13#include <background/modules/BeamBkgHitRateMonitor/CDCHitRateCounter.h>
14#include <background/modules/BeamBkgHitRateMonitor/TOPHitRateCounter.h>
15#include <background/modules/BeamBkgHitRateMonitor/ARICHHitRateCounter.h>
16#include <background/modules/BeamBkgHitRateMonitor/ECLHitRateCounter.h>
17#include <background/modules/BeamBkgHitRateMonitor/KLMHitRateCounter.h>
18
19// framework aux
20#include <framework/logging/Logger.h>
21
22#include <framework/io/RootIOUtilities.h>
23#include <framework/core/RandomNumbers.h>
24#include <framework/core/Environment.h>
25#include <framework/core/ModuleParam.templateDetails.h>
26#include <framework/database/Database.h>
27#include <framework/utilities/EnvironmentVariables.h>
28
29#include <boost/python.hpp>
30#include <boost/algorithm/string.hpp>
31
32#include <filesystem>
33
34using namespace std;
35using namespace Belle2;
36
37//-----------------------------------------------------------------
38// Register module
39//-----------------------------------------------------------------
40
41REG_MODULE(BeamBkgHitRateMonitor);
42
43//-----------------------------------------------------------------
44// Implementation
45//-----------------------------------------------------------------
46
48
49{
50 // set module description
51 setDescription("A module for off-line monitoring of beam background hit rates.");
52
53 /* No multiprocessing allowed!
54 * setPropertyFlags(c_ParallelProcessingCertified);
55 */
56
57 // Add parameters
58 addParam("outputFileName", m_outputFileName, "output file name",
59 string("beamBkgHitRates.root"));
60 addParam("treeName", m_treeName, "output tree name",
61 string("tree"));
65 addParam("trgTypes", m_trgTypes,
66 "trigger types for event selection (see TRGSummary.h for definitions). "
67 "Empty list means all trigger types.",
69 addParam("writeEmptyTimeStamps", m_writeEmptyTimeStamps,
70 "if true, write to ntuple also empty time stamps", false);
71 addParam("topTimeOffset", m_topTimeOffset,
72 "TOP: time offset of hits (to be subtracted) [ns]", 25.0);
73 addParam("topTimeWindow", m_topTimeWindow,
74 "TOP: time window in which to count hits [ns]", 100.0);
75 addParam("svdShaperDigitsName", m_svdShaperDigitsName,
76 "SVDShaperDigits collection name", string(""));
77 addParam("svdThrCharge", m_svdThrCharge,
78 "Energy cur on SVD Cluster charge in electrons", 15000.);
79 addParam("svdIgnoreHotStripsPayload", m_svdIgnoreHotStripsPayload,
80 "If true, also SVD hot strips are counted as active", false);
81 addParam("svdIgnoreMaskedStripsPayload", m_svdIgnoreMaskedStripsPayload,
82 "If true, also SVD FADC-masked strips are counted as active", false);
83 addParam("additionalDataDescription", m_additionalDataDescription,
84 "Additional dictionary of "
85 "name->value pairs to be added to the file metadata to describe the data",
87 addParam("cdcTimeWindowLowerEdgeSmallCell", m_cdcTimeWindowLowerEdgeSmallCell,
88 "CDC: lower edge of the time window for small cells [tdc count = ns]",
89 4550);
90 addParam("cdcTimeWindowUpperEdgeSmallCell", m_cdcTimeWindowUpperEdgeSmallCell,
91 "CDC: upper edge of the time window for small cells [tdc count = ns]",
92 5050);
93 addParam("cdcTimeWindowLowerEdgeNormalCell", m_cdcTimeWindowLowerEdgeNormalCell,
94 "CDC: lower edge of the time window for normal cells [tdc count = ns]",
95 4200);
96 addParam("cdcTimeWindowUpperEdgeNormalCell", m_cdcTimeWindowUpperEdgeNormalCell,
97 "CDC: upper edge of the time window for normal cells [tdc count = ns]",
98 5050);
99 addParam("cdcEnableBadWireTreatment", m_cdcEnableBadWireTreatment,
100 "CDC: flag to enable the bad wire treatment", true);
101 addParam("cdcEnableBackgroundHitFilter", m_cdcEnableBackgroundHitFilter,
102 "CDC: flag to enable the CDC background hit (crosstakl, noise) filter", true);
103 addParam("cdcEnableMarkBackgroundHit", m_cdcEnableMarkBackgroundHit,
104 "CDC: flag to enable to mark background flag on CDCHit (set 0x100 bit for CDCHit::m_status).", false);
105 addParam("detectors", m_detectors,
106 "Detectors to be included in the output tree, if empty, all detectors are included", m_detectors);
107}
108
110{
111 for (auto& monitor : m_monitors) {
112 if (monitor) delete monitor;
113 }
114}
115
117{
118 // collections registration
119 m_eventMetaData.isRequired();
120 if (m_trgTypes.empty()) {
121 m_trgSummary.isOptional(); // enables to run the module when TRGSummary is absent
122 } else {
123 m_trgSummary.isRequired();
124 }
125 m_fileMetaData.isOptional(); // enables to run the module with simulation
126
127 // create, set and append hit rate monitoring classes
128 std::string detectors;
129 for (const auto& detector : m_detectors) detectors += detector + " ";
130 if (detectors.find("PXD") != string::npos or detectors.empty()) {
131 auto* pxd = new Background::PXDHitRateCounter();
132 m_monitors.push_back(pxd);
133 }
134
135 if (detectors.find("SVD") != string::npos or detectors.empty()) {
139 m_monitors.push_back(svd);
140 }
141
142 if (detectors.find("CDC") != string::npos or detectors.empty()) {
147 m_monitors.push_back(cdc);
148 }
149
150 if (detectors.find("TOP") != string::npos or detectors.empty()) {
152 m_monitors.push_back(top);
153 }
154
155 if (detectors.find("ARICH") != string::npos or detectors.empty()) {
156 auto* arich = new Background::ARICHHitRateCounter();
157 m_monitors.push_back(arich);
158 }
159
160 if (detectors.find("ECL") != string::npos or detectors.empty()) {
161 auto* ecl = new Background::ECLHitRateCounter();
162 m_monitors.push_back(ecl);
163 }
164
165 if (detectors.find("KLM") != string::npos or detectors.empty()) {
166 auto* klm = new Background::KLMHitRateCounter();
167 m_monitors.push_back(klm);
168 }
169
170 // open output root file
171 m_file = TFile::Open(m_outputFileName.c_str(), "RECREATE");
172 if (not m_file) {
173 B2FATAL("Cannot open output file '" << m_outputFileName << "' for writing");
174 }
175
176 // create tree
177 m_tree = new TTree(m_treeName.c_str(), "hit rates of selected events");
178
179 // create persistent tree to store fileMetaData
180 m_persistent = new TTree("persistent", "persistent data");
181 m_persistent->Branch("FileMetaData", &m_outputFileMetaData);
182
183 // set tree branches
184 m_tree->Branch("run", &m_run, "run/I");
185 m_tree->Branch("numEvents", &m_numEvents, "numEvents/I");
186 m_tree->Branch("timeStamp", &m_timeStamp, "timeStamp/i");
187 m_tree->Branch("time", &m_time, "time/I");
188 for (auto& monitor : m_monitors) {
189 monitor->initialize(m_tree);
190 }
191
192 // control histograms
193 m_trgAll = new TH1F("trgAll", "trigger types of all events", 16, -0.5, 15.5);
194 m_trgAll->SetXTitle("type of trigger timing source");
195 m_trgSel = new TH1F("trgSel", "trigger types of selected events", 16, -0.5, 15.5);
196 m_trgSel->SetXTitle("type of trigger timing source");
197
198}
199
201{
202 // clear buffers
203 for (auto& monitor : m_monitors) {
204 monitor->clear();
205 }
206 m_eventCounts.clear();
207
208 // clear counters
210 m_trgTypesCount.clear();
211
212 // set run number
213 m_run = m_eventMetaData->getRun();
214
215 // set unix time of the first event in the run
216 unsigned utime = m_eventMetaData->getTime() / 1000000000;
217 m_utimeFirst = utime;
218 m_utimeMin = utime;
219 m_utimeMax = utime + 1;
220
221}
222
224{
225 // get unix time of the event
226 unsigned utime = m_eventMetaData->getTime() / 1000000000;
227 m_utimeMin = std::min(m_utimeMin, utime);
228 m_utimeMax = std::max(m_utimeMax, utime + 1);
229
230 // collect file meta data
232
233 // event selection
234 if (not isEventSelected()) return;
236
237 // accumulate
238 for (auto& monitor : m_monitors) {
239 monitor->accumulate(utime);
240 }
241 m_eventCounts[utime] += 1;
242
243}
244
246{
247 // fill ntuple
248 for (unsigned utime = m_utimeMin; utime < m_utimeMax; utime++) {
249 if (not m_writeEmptyTimeStamps) {
250 if (m_eventCounts.find(utime) == m_eventCounts.end()) continue;
251 }
252 m_numEvents = m_eventCounts[utime];
253 m_timeStamp = utime;
254 m_time = utime - m_utimeMin;
255 for (auto& monitor : m_monitors) {
256 monitor->normalize(utime);
257 }
258 m_tree->Fill();
259 }
260
261 // count selected events in all runs
263
264 // print a summary for this run
265 std::string trigs;
266 for (const auto& trgType : m_trgTypesCount) {
267 trigs += " trigger type " + std::to_string(trgType.first) + ": " +
268 std::to_string(trgType.second) + " events\n";
269 }
270 B2INFO("Run " << m_run << ": " << m_numEventsSelected
271 << " events selected for beam background hit rate monitoring.\n"
272 << trigs
273 << LogVar("first event utime ", m_utimeMin)
274 << LogVar("start utime ", m_utimeMin)
275 << LogVar("stop utime ", m_utimeMax)
276 << LogVar("duration [seconds]", m_utimeMax - m_utimeMin)
277 );
278}
279
281{
283 m_persistent->Fill();
284
285 // write to file and close
286 m_file->cd();
287 m_file->Write();
288 m_file->Close();
289
290 B2INFO("Output file: " << m_outputFileName);
291}
292
294{
295 auto trgType = TRGSummary::TTYP_NONE;
296 if (m_trgSummary.isValid()) trgType = m_trgSummary->getTimType();
297 m_trgAll->Fill(trgType);
298
299 if (m_trgTypes.empty()) {
300 m_trgTypesCount[trgType] += 1;
301 m_trgSel->Fill(trgType);
302 return true;
303 }
304 for (auto type : m_trgTypes) {
305 if (trgType == type) {
306 m_trgTypesCount[trgType] += 1;
307 m_trgSel->Fill(trgType);
308 return true;
309 }
310 }
311 return false;
312}
313
314
316{
317 // add file name to the list
318 if (m_fileMetaData.isValid()) {
319 std::string lfn = m_fileMetaData->getLfn();
320 if (not lfn.empty() and (m_parentLfns.empty() or (m_parentLfns.back() != lfn))) {
321 m_parentLfns.push_back(lfn);
322 }
323 }
324
325 // low and high experiment, run and event numbers
326 unsigned long experiment = m_eventMetaData->getExperiment();
327 unsigned long run = m_eventMetaData->getRun();
328 unsigned long event = m_eventMetaData->getEvent();
329 if (m_experimentLow > m_experimentHigh) { //starting condition
330 m_experimentLow = m_experimentHigh = experiment;
331 m_runLow = m_runHigh = run;
333 } else {
334 if ((experiment < m_experimentLow) or ((experiment == m_experimentLow) and ((run < m_runLow) or ((run == m_runLow)
335 and (event < m_eventLow))))) {
336 m_experimentLow = experiment;
337 m_runLow = run;
339 }
340 if ((experiment > m_experimentHigh) or ((experiment == m_experimentHigh) and ((run > m_runHigh) or ((run == m_runHigh)
341 and (event > m_eventHigh))))) {
342 m_experimentHigh = experiment;
343 m_runHigh = run;
345 }
346 }
347
348}
349
350
352{
353
354 if (m_fileMetaData.isValid() and not m_fileMetaData->isMC()) {
356 }
357
359
361 // starting condition so apparently no events at all
362 m_outputFileMetaData.setLow(-1, -1, 0);
363 m_outputFileMetaData.setHigh(-1, -1, 0);
364 } else {
367 }
368
373 auto mcEvents = Environment::Instance().getNumberOfMCEvents();
376
377 for (const auto& item : m_additionalDataDescription) {
378 m_outputFileMetaData.setDataDescription(item.first, item.second);
379 }
380
381 std::string lfn = m_file->GetName();
382 lfn = std::filesystem::absolute(lfn).string();
383 std::string format = EnvironmentVariables::get("BELLE2_LFN_FORMATSTRING", "");
384 if (!format.empty()) {
385 auto format_filename = boost::python::import("B2Tools.format").attr("format_filename");
386 lfn = boost::python::extract<std::string>(format_filename(format, m_outputFileName, m_outputFileMetaData.getJsonStr()));
387 }
389
390}
Class for monitoring beam background hit rates of ARICH.
Class for monitoring beam background hit rates of CDC.
Class for monitoring beam background hit rates of ECL.
Class for monitoring beam background hit rates of EKLM.
Class for monitoring beam background hit rates of PXD.
Class for monitoring beam background hit rates of SVD.
Class for monitoring beam background hit rates of TOP.
unsigned m_numEventsSelected
number of selected events in a run
unsigned long m_experimentLow
Lowest experiment number.
unsigned long m_experimentHigh
Highest experiment number.
std::vector< std::string > m_detectors
detectors to be included in the output tree
unsigned long m_eventLow
Lowest event number in lowest run.
int m_cdcTimeWindowLowerEdgeNormalCell
CDC: lower edge of the time window for normal cells [tdc count = ns].
unsigned m_allEventsSelected
number of selected events in all runs
std::string m_svdShaperDigitsName
SVD: name of the SVDShaperDigits collection.
unsigned m_utimeFirst
unix time of the first event in the run input stream
double m_topTimeWindow
TOP: time window in which to count hits [ns].
std::vector< Background::HitRateBase * > m_monitors
rate monitors
virtual void initialize() override
Initialize the Module.
unsigned long m_runLow
Lowest run number.
unsigned m_utimeMax
maximal unix time of events in the run
bool m_cdcEnableMarkBackgroundHit
CDC: flag to enable to mark background flag on CDCHit (set 0x100 bit for CDCHit::m_status).
virtual void event() override
Event processor.
TH1F * m_trgAll
trigger types of all events
bool m_cdcEnableBadWireTreatment
CDC: flag to enable the bad wire treatment.
virtual void endRun() override
End-of-run action.
StoreObjPtr< TRGSummary > m_trgSummary
trigger summary
virtual void terminate() override
Termination action.
FileMetaData m_outputFileMetaData
output file meta data branch
bool m_svdIgnoreHotStripsPayload
SVD: count hot strips as active.
unsigned long m_runHigh
Highest run number.
StoreObjPtr< EventMetaData > m_eventMetaData
event meta data object
int m_numEvents
number of events in the time stamp
std::vector< int > m_trgTypes
trigger types to be selected
int m_cdcTimeWindowUpperEdgeNormalCell
CDC: upper edge of the time window for normal cells [tdc count = ns].
virtual void beginRun() override
Called when entering a new run.
void setFileMetaData()
Set output FileMetaData object.
unsigned m_timeStamp
time stamp (unix time)
double m_svdThrCharge
SVD: energy cut on cluster charge.
bool m_writeEmptyTimeStamps
if true write to ntuple also empty time stamps
int m_time
time in seconds w.r.t the first event of the run
int m_cdcTimeWindowUpperEdgeSmallCell
CDC: upper edge of the time window for small cells [tdc count = ns].
void collectFileMetaData()
Collect file meta data: LFN's, low and high experiment, run and event numbers.
TH1F * m_trgSel
trigger types of selected events
int m_cdcTimeWindowLowerEdgeSmallCell
CDC: lower edge of the time window for small cells [tdc count = ns].
bool m_svdIgnoreMaskedStripsPayload
SVD: count FADC-masked strips as active.
bool m_cdcEnableBackgroundHitFilter
CDC: flag to enable the CDC background hit (crosstakl, noise) filter.
std::map< unsigned, int > m_eventCounts
number of events in time stamps
unsigned long m_eventHigh
Highest event number in highest run.
std::map< std::string, std::string > m_additionalDataDescription
additional metadata description
std::map< TRGSummary::ETimingType, unsigned > m_trgTypesCount
trigger type counters
std::vector< std::string > m_parentLfns
Vector of parent file LFNs.
double m_topTimeOffset
TOP: time offset of hits [ns].
unsigned m_utimeMin
minimal unix time of events in the run
StoreObjPtr< FileMetaData > m_fileMetaData
file metadata
TTree * m_persistent
root tree pointer (for FileMetaData)
unsigned int getNumberOfMCEvents() const
Number of generated events (from EventInfoSetter).
Definition: Environment.h:106
static Environment & Instance()
Static method to get a reference to the Environment instance.
Definition: Environment.cc:28
void setLow(int experiment, int run, unsigned int event)
Lowest experiment, run and event number setter.
Definition: FileMetaData.h:159
void setHigh(int experiment, int run, unsigned int event)
Highest experiment, run and event number setter.
Definition: FileMetaData.h:167
void setRandomSeed(const std::string &seed)
Random seed setter.
Definition: FileMetaData.h:189
void setSteering(const std::string &steering)
Steering file content setter.
Definition: FileMetaData.h:195
void declareRealData()
Declare that this is not generated, but real data.
Definition: FileMetaData.h:294
std::string getJsonStr() const
Get a json representation.
void setDatabaseGlobalTag(const std::string &globalTag)
Set the database global tag used when creating this file.
Definition: FileMetaData.h:208
void setLfn(const std::string &lfn)
Setter for LFN.
Definition: FileMetaData.h:139
void setDataDescription(const std::string &key, const std::string &value)
describe the data, if the key exists contents will be overwritten.
Definition: FileMetaData.h:214
void setNEvents(unsigned int nEvents)
Number of events setter.
Definition: FileMetaData.h:145
void setMcEvents(unsigned int nEvents)
Number of generated events setter.
Definition: FileMetaData.h:201
void setParents(const std::vector< std::string > &parents)
Parents setter.
Definition: FileMetaData.h:173
Base class for Modules.
Definition: Module.h:72
void setDescription(const std::string &description)
Sets the description of the module.
Definition: Module.cc:214
static std::string getSeed()
Get the random number generator seed.
Definition: RandomNumbers.h:92
@ TTYP_DPHY
delayed physics events for background
Definition: TRGSummary.h:65
@ TTYP_POIS
poisson random trigger
Definition: TRGSummary.h:73
@ TTYP_NONE
reserved (not defined yet)
Definition: TRGSummary.h:75
@ TTYP_RAND
random trigger events
Definition: TRGSummary.h:67
Class to store variables with their name which were sent to the logging service.
static std::string get(const std::string &name, const std::string &fallback="")
Get the value of an environment variable or the given fallback value if the variable is not set.
void addParam(const std::string &name, T &paramVariable, const std::string &description, const T &defaultValue)
Adds a new parameter to the module.
Definition: Module.h:560
static Database & Instance()
Instance of a singleton Database.
Definition: Database.cc:42
#define REG_MODULE(moduleName)
Register the given module (without 'Module' suffix) with the framework.
Definition: Module.h:650
void setCreationData(FileMetaData &metadata)
Fill the creation info of a file meta data: site, user, data.
Abstract base class for different kinds of events.
STL namespace.