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