Belle II Software  release-08-01-10
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 
34 using namespace std;
35 using namespace Belle2;
36 
37 //-----------------------------------------------------------------
38 // Register module
39 //-----------------------------------------------------------------
40 
41 REG_MODULE(BeamBkgHitRateMonitor);
42 
43 //-----------------------------------------------------------------
44 // Implementation
45 //-----------------------------------------------------------------
46 
47 BeamBkgHitRateMonitorModule::BeamBkgHitRateMonitorModule() : Module()
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"));
64  addParam("trgTypes", m_trgTypes,
65  "trigger types for event selection (see TRGSummary.h for definitions). "
66  "Empty list means all trigger types.",
67  m_trgTypes);
68  addParam("writeEmptyTimeStamps", m_writeEmptyTimeStamps,
69  "if true, write to ntuple also empty time stamps", false);
70  addParam("topTimeOffset", m_topTimeOffset,
71  "TOP: time offset of hits (to be subtracted) [ns]", 25.0);
72  addParam("topTimeWindow", m_topTimeWindow,
73  "TOP: time window in which to count hits [ns]", 100.0);
74  addParam("svdShaperDigitsName", m_svdShaperDigitsName,
75  "SVDShaperDigits collection name", string(""));
76  addParam("svdThrCharge", m_svdThrCharge,
77  "Energy cur on SVD Cluster charge in electrons", 15000.);
78  addParam("svdIgnoreHotStripsPayload", m_svdIgnoreHotStripsPayload,
79  "If true, also SVD hot strips are counted as active", false);
80  addParam("svdIgnoreMaskedStripsPayload", m_svdIgnoreMaskedStripsPayload,
81  "If true, also SVD FADC-masked strips are counted as active", false);
82  addParam("additionalDataDescription", m_additionalDataDescription,
83  "Additional dictionary of "
84  "name->value pairs to be added to the file metadata to describe the data",
86  addParam("cdcTimeWindowLowerEdgeSmallCell", m_cdcTimeWindowLowerEdgeSmallCell,
87  "CDC: lower edge of the time window for small cells [tdc count = ns]",
88  4550);
89  addParam("cdcTimeWindowUpperEdgeSmallCell", m_cdcTimeWindowUpperEdgeSmallCell,
90  "CDC: upper edge of the time window for small cells [tdc count = ns]",
91  5050);
92  addParam("cdcTimeWindowLowerEdgeNormalCell", m_cdcTimeWindowLowerEdgeNormalCell,
93  "CDC: lower edge of the time window for normal cells [tdc count = ns]",
94  4200);
95  addParam("cdcTimeWindowUpperEdgeNormalCell", m_cdcTimeWindowUpperEdgeNormalCell,
96  "CDC: upper edge of the time window for normal cells [tdc count = ns]",
97  5050);
98  addParam("cdcEnableBadWireTreatment", m_cdcEnableBadWireTreatment,
99  "CDC: flag to enable the bad wire treatment", true);
100  addParam("cdcEnableBackgroundHitFilter", m_cdcEnableBackgroundHitFilter,
101  "CDC: flag to enable the CDC background hit (crosstakl, noise) filter", true);
102  addParam("cdcEnableMarkBackgroundHit", m_cdcEnableMarkBackgroundHit,
103  "CDC: flag to enable to mark background flag on CDCHit (set 0x100 bit for CDCHit::m_status).", false);
104 
105 }
106 
108 {
109  for (auto& monitor : m_monitors) {
110  if (monitor) delete monitor;
111  }
112 }
113 
115 {
116  // collections registration
117  m_eventMetaData.isRequired();
118  if (m_trgTypes.empty()) {
119  m_trgSummary.isOptional(); // enables to run the module when TRGSummary is absent
120  } else {
121  m_trgSummary.isRequired();
122  }
123  m_fileMetaData.isOptional(); // enables to run the module with simulation
124 
125  // create, set and append hit rate monitoring classes
126  auto* pxd = new Background::PXDHitRateCounter();
127  m_monitors.push_back(pxd);
131  m_monitors.push_back(svd);
136  m_monitors.push_back(cdc);
138  m_monitors.push_back(top);
139  auto* arich = new Background::ARICHHitRateCounter();
140  m_monitors.push_back(arich);
141  auto* ecl = new Background::ECLHitRateCounter();
142  m_monitors.push_back(ecl);
143  auto* klm = new Background::KLMHitRateCounter();
144  m_monitors.push_back(klm);
145 
146  // open output root file
147  m_file = TFile::Open(m_outputFileName.c_str(), "RECREATE");
148  if (not m_file) {
149  B2FATAL("Cannot open output file '" << m_outputFileName << "' for writing");
150  }
151 
152  // create tree
153  m_tree = new TTree(m_treeName.c_str(), "hit rates of selected events");
154 
155  // create persistent tree to store fileMetaData
156  m_persistent = new TTree("persistent", "persistent data");
157  m_persistent->Branch("FileMetaData", &m_outputFileMetaData);
158 
159  // set tree branches
160  m_tree->Branch("run", &m_run, "run/I");
161  m_tree->Branch("numEvents", &m_numEvents, "numEvents/I");
162  m_tree->Branch("timeStamp", &m_timeStamp, "timeStamp/i");
163  m_tree->Branch("time", &m_time, "time/I");
164  for (auto& monitor : m_monitors) {
165  monitor->initialize(m_tree);
166  }
167 
168  // control histograms
169  m_trgAll = new TH1F("trgAll", "trigger types of all events", 16, -0.5, 15.5);
170  m_trgAll->SetXTitle("type of trigger timing source");
171  m_trgSel = new TH1F("trgSel", "trigger types of selected events", 16, -0.5, 15.5);
172  m_trgSel->SetXTitle("type of trigger timing source");
173 
174 }
175 
177 {
178  // clear buffers
179  for (auto& monitor : m_monitors) {
180  monitor->clear();
181  }
182  m_eventCounts.clear();
183 
184  // clear counters
186  m_trgTypesCount.clear();
187 
188  // set run number
189  m_run = m_eventMetaData->getRun();
190 
191  // set unix time of the first event in the run
192  unsigned utime = m_eventMetaData->getTime() / 1000000000;
193  m_utimeFirst = utime;
194  m_utimeMin = utime;
195  m_utimeMax = utime + 1;
196 
197 }
198 
200 {
201  // get unix time of the event
202  unsigned utime = m_eventMetaData->getTime() / 1000000000;
203  m_utimeMin = std::min(m_utimeMin, utime);
204  m_utimeMax = std::max(m_utimeMax, utime + 1);
205 
206  // collect file meta data
208 
209  // event selection
210  if (not isEventSelected()) return;
212 
213  // accumulate
214  for (auto& monitor : m_monitors) {
215  monitor->accumulate(utime);
216  }
217  m_eventCounts[utime] += 1;
218 
219 }
220 
222 {
223  // fill ntuple
224  for (unsigned utime = m_utimeMin; utime < m_utimeMax; utime++) {
225  if (not m_writeEmptyTimeStamps) {
226  if (m_eventCounts.find(utime) == m_eventCounts.end()) continue;
227  }
228  m_numEvents = m_eventCounts[utime];
229  m_timeStamp = utime;
230  m_time = utime - m_utimeMin;
231  for (auto& monitor : m_monitors) {
232  monitor->normalize(utime);
233  }
234  m_tree->Fill();
235  }
236 
237  // count selected events in all runs
239 
240  // print a summary for this run
241  std::string trigs;
242  for (const auto& trgType : m_trgTypesCount) {
243  trigs += " trigger type " + std::to_string(trgType.first) + ": " +
244  std::to_string(trgType.second) + " events\n";
245  }
246  B2INFO("Run " << m_run << ": " << m_numEventsSelected
247  << " events selected for beam background hit rate monitoring.\n"
248  << trigs
249  << LogVar("first event utime ", m_utimeMin)
250  << LogVar("start utime ", m_utimeMin)
251  << LogVar("stop utime ", m_utimeMax)
252  << LogVar("duration [seconds]", m_utimeMax - m_utimeMin)
253  );
254 }
255 
257 {
258  setFileMetaData();
259  m_persistent->Fill();
260 
261  // write to file and close
262  m_file->cd();
263  m_file->Write();
264  m_file->Close();
265 
266  B2INFO("Output file: " << m_outputFileName);
267 }
268 
270 {
271  auto trgType = TRGSummary::TTYP_NONE;
272  if (m_trgSummary.isValid()) trgType = m_trgSummary->getTimType();
273  m_trgAll->Fill(trgType);
274 
275  if (m_trgTypes.empty()) {
276  m_trgTypesCount[trgType] += 1;
277  m_trgSel->Fill(trgType);
278  return true;
279  }
280  for (auto type : m_trgTypes) {
281  if (trgType == type) {
282  m_trgTypesCount[trgType] += 1;
283  m_trgSel->Fill(trgType);
284  return true;
285  }
286  }
287  return false;
288 }
289 
290 
292 {
293  // add file name to the list
294  if (m_fileMetaData.isValid()) {
295  std::string lfn = m_fileMetaData->getLfn();
296  if (not lfn.empty() and (m_parentLfns.empty() or (m_parentLfns.back() != lfn))) {
297  m_parentLfns.push_back(lfn);
298  }
299  }
300 
301  // low and high experiment, run and event numbers
302  unsigned long experiment = m_eventMetaData->getExperiment();
303  unsigned long run = m_eventMetaData->getRun();
304  unsigned long event = m_eventMetaData->getEvent();
305  if (m_experimentLow > m_experimentHigh) { //starting condition
306  m_experimentLow = m_experimentHigh = experiment;
307  m_runLow = m_runHigh = run;
309  } else {
310  if ((experiment < m_experimentLow) or ((experiment == m_experimentLow) and ((run < m_runLow) or ((run == m_runLow)
311  and (event < m_eventLow))))) {
312  m_experimentLow = experiment;
313  m_runLow = run;
314  m_eventLow = event;
315  }
316  if ((experiment > m_experimentHigh) or ((experiment == m_experimentHigh) and ((run > m_runHigh) or ((run == m_runHigh)
317  and (event > m_eventHigh))))) {
318  m_experimentHigh = experiment;
319  m_runHigh = run;
320  m_eventHigh = event;
321  }
322  }
323 
324 }
325 
326 
328 {
329 
330  if (m_fileMetaData.isValid() and not m_fileMetaData->isMC()) {
332  }
333 
335 
337  // starting condition so apparently no events at all
338  m_outputFileMetaData.setLow(-1, -1, 0);
339  m_outputFileMetaData.setHigh(-1, -1, 0);
340  } else {
343  }
344 
349  auto mcEvents = Environment::Instance().getNumberOfMCEvents();
352 
353  for (const auto& item : m_additionalDataDescription) {
354  m_outputFileMetaData.setDataDescription(item.first, item.second);
355  }
356 
357  std::string lfn = m_file->GetName();
358  lfn = std::filesystem::absolute(lfn).string();
359  std::string format = EnvironmentVariables::get("BELLE2_LFN_FORMATSTRING", "");
360  if (!format.empty()) {
361  auto format_filename = boost::python::import("B2Tools.format").attr("format_filename");
362  lfn = boost::python::extract<std::string>(format_filename(format, m_outputFileName, m_outputFileMetaData.getJsonStr()));
363  }
365 
366 }
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.
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:94
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_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.