CMS 3D CMS Logo

SiStripDetVOffTrendPlotter.cc
Go to the documentation of this file.
6 
7 #include <iostream>
8 #include <fstream>
9 #include <sstream>
10 
12 
17 
18 #include <TROOT.h>
19 #include <TSystem.h>
20 #include <TCanvas.h>
21 #include <TFile.h>
22 #include <TLegend.h>
23 #include <TGraph.h>
24 #include <TH1.h>
25 
27 public:
28  const std::vector<Color_t> PLOT_COLORS{kRed, kBlue, kBlack, kOrange, kMagenta};
29 
30  explicit SiStripDetVOffTrendPlotter(const edm::ParameterSet &iConfig);
31  ~SiStripDetVOffTrendPlotter() override;
32  void analyze(const edm::Event &evt, const edm::EventSetup &evtSetup) override;
33  void endJob() override;
34 
35 private:
36  std::string formatIOV(cond::Time_t iov, std::string format = "%Y-%m-%d__%H_%M_%S");
37  void prepGraph(TGraph *gr, TString name, TString title, Color_t color);
38  void dumpCSV(bool isHV);
39 
42  std::vector<std::string> m_plotTags;
43 
44  // Time interval (in hours) to go back for the plotting.
46  // Or manually specify the start/end time. Format: "2002-01-20 23:59:59.000". Set m_interval to non-positive number to use this.
49  // Specify output plot file name. Will use the timestamps if left empty.
51  // Specify output root file name. Leave empty if do not want to save plots in a root file.
53  // Specify output CSV file name. Leave empty if do not want to dump HV/LV counts in a CSV file.
55  TFile *fout;
57 
58  // IOV TAG #HV, #LV
59  std::map<cond::Time_t, std::map<std::string, std::pair<int, int>>> iovMap;
60 };
61 
63  : m_connectionPool(),
64  m_condDb(iConfig.getParameter<std::string>("conditionDatabase")),
65  m_plotTags(iConfig.getParameter<std::vector<std::string>>("plotTags")),
66  m_interval(iConfig.getParameter<int>("timeInterval")),
67  m_startTime(iConfig.getUntrackedParameter<std::string>("startTime", "")),
68  m_endTime(iConfig.getUntrackedParameter<std::string>("endTime", "")),
69  m_outputPlot(iConfig.getUntrackedParameter<std::string>("outputPlot", "")),
70  m_outputRootFile(iConfig.getUntrackedParameter<std::string>("outputRootFile", "")),
71  m_outputCSV(iConfig.getUntrackedParameter<std::string>("outputCSV", "")),
72  fout(nullptr) {
75  if (!m_outputRootFile.empty())
76  fout = new TFile(m_outputRootFile.data(), "RECREATE");
77 }
78 
80  if (fout)
81  fout->Close();
82 }
83 
85  // get total number of modules
86  auto num_modules = detidReader->getAllDetIds().size();
87 
88  // get start and end time for DB query
89  boost::posix_time::ptime p_start, p_end;
90  if (m_interval > 0) {
91  // from m_interval hours ago to now
92  p_end = boost::posix_time::second_clock::universal_time();
93  p_start = p_end - boost::posix_time::hours(m_interval);
94  } else {
95  // use start and end time from config file
96  p_start = boost::posix_time::time_from_string(m_startTime);
97  p_end = boost::posix_time::time_from_string(m_endTime);
98  }
99  cond::Time_t startIov = cond::time::from_boost(p_start);
100  cond::Time_t endIov = cond::time::from_boost(p_end);
101  if (startIov > endIov)
102  throw cms::Exception("endTime must be greater than startTime!");
103  edm::LogInfo("SiStripDetVOffTrendPlotter")
104  << "[SiStripDetVOffTrendPlotter::" << __func__ << "] "
105  << "Set start IOV " << startIov << " (" << boost::posix_time::to_simple_string(p_start) << ")"
106  << "\n ... Set end IOV " << endIov << " (" << boost::posix_time::to_simple_string(p_end) << ")";
107 
108  // open db session
109  edm::LogInfo("SiStripDetVOffTrendPlotter") << "[SiStripDetVOffTrendPlotter::" << __func__ << "] "
110  << "Query the condition database " << m_condDb;
112  condDbSession.transaction().start(true);
113 
114  // loop over all tags to plot
115  std::vector<TGraph *> hvgraphs, lvgraphs;
116  TLegend *leg_hv = new TLegend(0.6, 0.87, 0.99, 0.99);
117  TLegend *leg_lv = new TLegend(0.6, 0.87, 0.99, 0.99);
118  for (unsigned itag = 0; itag < m_plotTags.size(); ++itag) {
119  auto tag = m_plotTags.at(itag);
120  auto color = itag < PLOT_COLORS.size() ? PLOT_COLORS.at(itag) : kGreen + itag;
121 
122  std::vector<double> vTime;
123  std::vector<double> vHVOffPercent, vLVOffPercent;
124 
125  // query the database
126  edm::LogInfo("SiStripDetVOffTrendPlotter") << "[SiStripDetVOffTrendPlotter::" << __func__ << "] "
127  << "Reading IOVs from tag " << tag;
128  cond::persistency::IOVProxy iovProxy = condDbSession.readIov(tag, true); // load all?
129  auto iiov = iovProxy.find(startIov);
130  auto eiov = iovProxy.find(endIov);
131  int niov = 0;
132  while (iiov != iovProxy.end() && (*iiov).since <= (*eiov).since) {
133  // convert cond::Time_t to seconds since epoch
134  if ((*iiov).since < startIov)
135  vTime.push_back(cond::time::unpack(startIov).first);
136  else
137  vTime.push_back(cond::time::unpack((*iiov).since).first);
138  auto payload = condDbSession.fetchPayload<SiStripDetVOff>((*iiov).payloadId);
139  vHVOffPercent.push_back(1.0 * payload->getHVoffCounts() / num_modules);
140  vLVOffPercent.push_back(1.0 * payload->getLVoffCounts() / num_modules);
141  iovMap[(*iiov).since][tag] = {payload->getHVoffCounts(), payload->getLVoffCounts()};
142  // debug
143  std::cout << boost::posix_time::to_simple_string(cond::time::to_boost((*iiov).since)) << " (" << (*iiov).since
144  << ")"
145  << ", # HV Off=" << std::setw(6) << payload->getHVoffCounts() << ", # LV Off=" << std::setw(6)
146  << payload->getLVoffCounts() << std::endl;
147  ++iiov;
148  ++niov;
149  }
150  edm::LogInfo("SiStripDetVOffTrendPlotter")
151  << "[SiStripDetVOffTrendPlotter::" << __func__ << "] "
152  << "Read " << niov << " IOVs from tag " << tag << " in the specified interval.";
153 
154  TGraph *hv = new TGraph(vTime.size(), vTime.data(), vHVOffPercent.data());
155  prepGraph(hv, TString("HVOff_") + tag, ";UTC;Fraction of HV off", color);
156  leg_hv->AddEntry(hv, tag.data(), "LP");
157 
158  TGraph *lv = new TGraph(vTime.size(), vTime.data(), vLVOffPercent.data());
159  prepGraph(lv, TString("LVOff_") + tag, ";UTC;Fraction of LV off", color);
160  leg_lv->AddEntry(lv, tag.data(), "LP");
161 
162  hvgraphs.push_back(hv);
163  lvgraphs.push_back(lv);
164  }
165 
166  condDbSession.transaction().commit();
167 
168  // Make plots
169  TCanvas c("c", "c", 1800, 1200);
170  c.SetTopMargin(0.12);
171  c.SetBottomMargin(0.08);
172  c.SetGridx();
173  c.SetGridy();
174  for (const auto hv : hvgraphs) {
175  if (hv == hvgraphs.front())
176  hv->Draw("ALP");
177  else
178  hv->Draw("LPsame");
179  if (fout) {
180  fout->cd();
181  hv->Write();
182  }
183  }
184  leg_hv->Draw();
185  std::string plot_postfix =
186  !m_outputPlot.empty() ? m_outputPlot : "from_" + formatIOV(startIov) + "_to_" + formatIOV(endIov) + ".png";
187  c.Print(("HVOff_" + plot_postfix).data());
188 
189  c.Clear();
190  for (const auto lv : lvgraphs) {
191  if (lv == lvgraphs.front())
192  lv->Draw("ALP");
193  else
194  lv->Draw("LPsame");
195  if (fout) {
196  fout->cd();
197  lv->Write();
198  }
199  }
200  leg_lv->Draw();
201  c.Print(("LVOff_" + plot_postfix).data());
202 
203  if (!m_outputCSV.empty()) {
204  dumpCSV(true);
205  dumpCSV(false);
206  }
207 }
208 
210 
212  auto facet = new boost::posix_time::time_facet(format.c_str());
213  std::ostringstream stream;
214  stream.imbue(std::locale(stream.getloc(), facet));
215  stream << cond::time::to_boost(iov);
216  return stream.str();
217 }
218 
219 void SiStripDetVOffTrendPlotter::prepGraph(TGraph *gr, TString name, TString title, Color_t color) {
220  gr->SetName(name);
221  gr->SetTitle(title);
222  gr->SetLineColor(color);
223  gr->SetLineWidth(2);
224  gr->SetMarkerStyle(20);
225  gr->SetMarkerSize(1.5);
226  gr->SetMarkerColor(color);
227  gr->GetXaxis()->SetTimeDisplay(1);
228  gr->GetXaxis()->SetLabelOffset(0.02);
229  gr->GetXaxis()->SetTimeFormat("#splitline{%b %d}{%H:%M}");
230  gr->GetXaxis()->SetTimeOffset(0, "gmt");
231  gr->GetXaxis()->SetLabelSize(0.025);
232  gr->GetXaxis()->SetTitleSize(0.025);
233  gr->GetXaxis()->SetTitleOffset(1.6);
234  gr->GetYaxis()->SetRangeUser(0, 1.05);
235 }
236 
238  // get total number of modules
239  auto num_modules = detidReader->getAllDetIds().size();
240 
241  std::string outCSV = isHV ? "HVOff_table_" + m_outputCSV : "LVOff_table_" + m_outputCSV;
242  std::ofstream csv;
243  csv.open(outCSV);
244  csv << "IOV,Timestamp(UTC),";
245  for (const auto &tag : m_plotTags)
246  csv << tag << ",";
247  csv << std::endl;
248 
249  csv << std::fixed << std::setprecision(1);
250 
251  for (const auto &v : iovMap) {
252  auto iov = v.first;
253  auto timestamp = boost::posix_time::to_simple_string(cond::time::to_boost(iov));
254  csv << iov << "," << timestamp << ",";
255  for (const auto &tag : m_plotTags) {
256  if (v.second.find(tag) != v.second.end()) {
257  int count = isHV ? v.second.at(tag).first : v.second.at(tag).second;
258  csv << count << " (" << 100. * count / num_modules << "%)";
259  }
260  csv << ",";
261  }
262  csv << std::endl;
263  }
264 
265  csv.close();
266 }
267 
T getParameter(std::string const &) const
void start(bool readOnly=true)
Definition: Session.cc:22
#define nullptr
void analyze(const edm::Event &evt, const edm::EventSetup &evtSetup) override
std::unique_ptr< T > fetchPayload(const cond::Hash &payloadHash)
Definition: Session.h:218
susybsm::HSCParticleRefVector hv
Definition: classes.h:28
std::vector< std::string > m_plotTags
Transaction & transaction()
Definition: Session.cc:66
void prepGraph(TGraph *gr, TString name, TString title, Color_t color)
void setParameters(const edm::ParameterSet &connectionPset)
edm::Service< SiStripDetInfoFileReader > detidReader
IOVProxy readIov(const std::string &tag, bool full=false)
Definition: Session.cc:81
#define DEFINE_FWK_MODULE(type)
Definition: MakerMacros.h:16
unsigned long long Time_t
Definition: Time.h:16
const std::vector< uint32_t > & getAllDetIds() const
std::string formatIOV(cond::Time_t iov, std::string format="%Y-%m-%d__%H_%M_%S")
Iterator find(cond::Time_t time)
Definition: IOVProxy.cc:320
Session createSession(const std::string &connectionString, bool writeCapable=false)
Time_t from_boost(boost::posix_time::ptime bt)
std::map< cond::Time_t, std::map< std::string, std::pair< int, int > > > iovMap
cond::persistency::ConnectionPool m_connectionPool
const std::vector< Color_t > PLOT_COLORS
SiStripDetVOffTrendPlotter(const edm::ParameterSet &iConfig)
char data[epos_bytes_allocation]
Definition: EPOS_Wrapper.h:82
boost::posix_time::ptime to_boost(Time_t iValue)
Iterator end() const
Definition: IOVProxy.cc:297
cond::UnpackedTime unpack(cond::Time_t iValue)