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