CMS 3D CMS Logo

LHCInfoPerFillPopConAnalyzer.cc
Go to the documentation of this file.
9 #include "CoralBase/Attribute.h"
10 #include "CoralBase/AttributeList.h"
11 #include "CoralBase/AttributeSpecification.h"
12 #include "CoralBase/TimeStamp.h"
17 #include "RelationalAccess/ICursor.h"
18 #include "RelationalAccess/IQuery.h"
19 #include "RelationalAccess/ISchema.h"
20 #include "RelationalAccess/ISessionProxy.h"
21 
23 
25 //define this as a plug-in
27 
28 namespace cond {
29  namespace theLHCInfoPerFillPopConImpl {
30 
31  static const std::pair<const char*, LHCInfoPerFill::FillType> s_fillTypeMap[] = {
32  std::make_pair("PROTONS", LHCInfoPerFill::PROTONS),
33  std::make_pair("IONS", LHCInfoPerFill::IONS),
34  std::make_pair("COSMICS", LHCInfoPerFill::COSMICS),
35  std::make_pair("GAP", LHCInfoPerFill::GAP)};
36 
37  static const std::pair<const char*, LHCInfoPerFill::ParticleType> s_particleTypeMap[] = {
38  std::make_pair("PROTON", LHCInfoPerFill::PROTON),
39  std::make_pair("PB82", LHCInfoPerFill::PB82),
40  std::make_pair("AR18", LHCInfoPerFill::AR18),
41  std::make_pair("D", LHCInfoPerFill::D),
42  std::make_pair("XE54", LHCInfoPerFill::XE54)};
43 
45  for (auto const& i : s_fillTypeMap)
46  if (s_fill_type == i.first)
47  return i.second;
49  }
50 
52  for (auto const& i : s_particleTypeMap)
53  if (s_particle_type == i.first)
54  return i.second;
55  return LHCInfoPerFill::NONE;
56  }
57  } // namespace theLHCInfoPerFillPopConImpl
58 
59  namespace impl {
60 
61  template <>
63  return from_string_impl<LHCInfoPerFill::FillType, &theLHCInfoPerFillPopConImpl::fillTypeFromString>(
64  attributeValue, LHCInfoPerFill::UNKNOWN);
65  }
66 
67  template <>
69  return from_string_impl<LHCInfoPerFill::ParticleType, &theLHCInfoPerFillPopConImpl::particleTypeFromString>(
70  attributeValue, LHCInfoPerFill::NONE);
71  }
72 
73  } // namespace impl
74 } // namespace cond
75 
77 
78  bool makeFillPayload(std::unique_ptr<LHCInfoPerFill>& targetPayload, const cond::OMSServiceResult& queryResult) {
79  bool ret = false;
80  if (!queryResult.empty()) {
81  auto row = *queryResult.begin();
82  auto currentFill = row.get<unsigned short>("fill_number");
83  auto bunches1 = row.get<unsigned short>("bunches_beam1");
84  auto bunches2 = row.get<unsigned short>("bunches_beam2");
85  auto collidingBunches = row.get<unsigned short>("bunches_colliding");
86  auto targetBunches = row.get<unsigned short>("bunches_target");
87  auto fillType = row.get<LHCInfoPerFill::FillType>("fill_type_runtime");
88  auto particleType1 = row.get<LHCInfoPerFill::ParticleType>("fill_type_party1");
89  auto particleType2 = row.get<LHCInfoPerFill::ParticleType>("fill_type_party2");
90  auto intensityBeam1 = row.get<float>("intensity_beam1");
91  auto intensityBeam2 = row.get<float>("intensity_beam2");
92  auto energy = row.get<float>("energy");
93  auto creationTime = row.get<boost::posix_time::ptime>("start_time");
94  auto stableBeamStartTime = row.get<boost::posix_time::ptime>("start_stable_beam");
95  std::string endTimeStr = row.get<std::string>("end_time");
96  auto beamDumpTime =
97  (endTimeStr == "null") ? 0 : cond::time::from_boost(row.get<boost::posix_time::ptime>("end_time"));
98  auto injectionScheme = row.get<std::string>("injection_scheme");
99  targetPayload = std::make_unique<LHCInfoPerFill>();
100  targetPayload->setFillNumber(currentFill);
101  targetPayload->setBunchesInBeam1(bunches1);
102  targetPayload->setBunchesInBeam2(bunches2);
103  targetPayload->setCollidingBunches(collidingBunches);
104  targetPayload->setTargetBunches(targetBunches);
105  targetPayload->setFillType(fillType);
106  targetPayload->setParticleTypeForBeam1(particleType1);
107  targetPayload->setParticleTypeForBeam2(particleType2);
108  targetPayload->setIntensityForBeam1(intensityBeam1);
109  targetPayload->setIntensityForBeam2(intensityBeam2);
110  targetPayload->setEnergy(energy);
111  targetPayload->setCreationTime(cond::time::from_boost(creationTime));
112  targetPayload->setBeginTime(cond::time::from_boost(stableBeamStartTime));
113  targetPayload->setEndTime(beamDumpTime);
114  targetPayload->setInjectionScheme(injectionScheme);
115  ret = true;
116  }
117  return ret;
118  }
119 } // namespace theLHCInfoPerFillImpl
120 
121 namespace theLHCInfoPerFillImpl {
122  static const std::map<std::string, int> vecMap = {
123  {"Beam1/beamPhaseMean", 1}, {"Beam2/beamPhaseMean", 2}, {"Beam1/cavPhaseMean", 3}, {"Beam2/cavPhaseMean", 4}};
125  const std::string& dipVal,
126  unsigned int elementNr,
127  float value,
129  std::set<cond::Time_t>& initList) {
130  if (initList.find(since) == initList.end()) {
131  payload.beam1VC().resize(LHCInfoPerFill::bunchSlots, 0.);
132  payload.beam2VC().resize(LHCInfoPerFill::bunchSlots, 0.);
133  payload.beam1RF().resize(LHCInfoPerFill::bunchSlots, 0.);
134  payload.beam2RF().resize(LHCInfoPerFill::bunchSlots, 0.);
135  initList.insert(since);
136  }
137  // set the current values to all of the payloads of the lumi section samples after the current since
138  if (elementNr < LHCInfoPerFill::bunchSlots) {
139  switch (vecMap.at(dipVal)) {
140  case 1:
141  payload.beam1VC()[elementNr] = value;
142  break;
143  case 2:
144  payload.beam2VC()[elementNr] = value;
145  break;
146  case 3:
147  payload.beam1RF()[elementNr] = value;
148  break;
149  case 4:
150  payload.beam2RF()[elementNr] = value;
151  break;
152  default:
153  break;
154  }
155  }
156  }
157 } // namespace theLHCInfoPerFillImpl
158 
159 namespace theLHCInfoPerFillImpl {
160  bool comparePayloads(const LHCInfoPerFill& rhs, const LHCInfoPerFill& lhs) {
161  if (rhs.fillNumber() != lhs.fillNumber() || rhs.delivLumi() != lhs.delivLumi() || rhs.recLumi() != lhs.recLumi() ||
162  rhs.instLumi() != lhs.instLumi() || rhs.instLumiError() != lhs.instLumiError() ||
163  rhs.lhcState() != lhs.lhcState() || rhs.lhcComment() != lhs.lhcComment() ||
164  rhs.ctppsStatus() != lhs.ctppsStatus()) {
165  return false;
166  }
167  return true;
168  }
169 
170  size_t transferPayloads(const std::vector<std::pair<cond::Time_t, std::shared_ptr<LHCInfoPerFill>>>& buffer,
171  std::map<cond::Time_t, std::shared_ptr<LHCInfoPerFill>>& iovsToTransfer,
172  std::shared_ptr<LHCInfoPerFill>& prevPayload) {
173  size_t niovs = 0;
174  std::stringstream condIovs;
175  std::stringstream formattedIovs;
176  for (auto& iov : buffer) {
177  bool add = false;
178  auto payload = iov.second;
179  cond::Time_t since = iov.first;
180  if (iovsToTransfer.empty()) {
181  add = true;
182  } else {
183  LHCInfoPerFill& lastAdded = *iovsToTransfer.rbegin()->second;
184  if (!comparePayloads(lastAdded, *payload)) {
185  add = true;
186  }
187  }
188  if (add) {
189  niovs++;
190  condIovs << since << " ";
191  formattedIovs << boost::posix_time::to_iso_extended_string(cond::time::to_boost(since)) << " ";
192  iovsToTransfer.insert(std::make_pair(since, payload));
193  prevPayload = iov.second;
194  }
195  }
196  edm::LogInfo("transferPayloads") << "TRANSFERED IOVS: " << condIovs.str();
197  edm::LogInfo("transferPayloads") << "FORMATTED TRANSFERED IOVS: " << formattedIovs.str();
198  return niovs;
199  }
200 
201 } // namespace theLHCInfoPerFillImpl
203 public:
205  : m_debug(pset.getUntrackedParameter<bool>("debug", false)),
206  m_startTime(),
207  m_endTime(),
208  m_endFillMode(pset.getUntrackedParameter<bool>("endFill", true)),
209  m_name(pset.getUntrackedParameter<std::string>("name", "LHCInfoPerFillPopConSourceHandler")),
210  m_connectionString(pset.getUntrackedParameter<std::string>("connectionString", "")),
211  m_ecalConnectionString(pset.getUntrackedParameter<std::string>("ecalConnectionString", "")),
212  m_authpath(pset.getUntrackedParameter<std::string>("authenticationPath", "")),
213  m_omsBaseUrl(pset.getUntrackedParameter<std::string>("omsBaseUrl", "")),
214  m_fillPayload(),
215  m_prevPayload(),
216  m_tmpBuffer() {
217  if (!pset.getUntrackedParameter<std::string>("startTime").empty()) {
218  m_startTime = boost::posix_time::time_from_string(pset.getUntrackedParameter<std::string>("startTime"));
219  }
220  boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
221  m_endTime = now;
222  if (!pset.getUntrackedParameter<std::string>("endTime").empty()) {
223  m_endTime = boost::posix_time::time_from_string(pset.getUntrackedParameter<std::string>("endTime"));
224  if (m_endTime > now)
225  m_endTime = now;
226  }
227  }
228 
229  ~LHCInfoPerFillPopConSourceHandler() override = default;
230 
231  void getNewObjects() override {
232  //if a new tag is created, transfer fake fill from 1 to the first fill for the first time
233  if (tagInfo().size == 0) {
234  edm::LogInfo(m_name) << "New tag " << tagInfo().name << "; from " << m_name << "::getNewObjects";
235  } else {
236  //check what is already inside the database
237  edm::LogInfo(m_name) << "got info for tag " << tagInfo().name << ": size " << tagInfo().size
238  << ", last object valid since " << tagInfo().lastInterval.since << " ( "
239  << boost::posix_time::to_iso_extended_string(
240  cond::time::to_boost(tagInfo().lastInterval.since))
241  << " ); from " << m_name << "::getNewObjects";
242  }
243 
244  cond::Time_t lastSince = tagInfo().lastInterval.since;
245  if (tagInfo().isEmpty()) {
246  // for a new or empty tag, an empty payload should be added on top with since=1
247  if (m_endFillMode) {
248  addEmptyPayload(1);
249  lastSince = 1;
250  } else {
252  lastSince = cond::time::lumiTime(1, 1);
253  }
254  } else {
255  edm::LogInfo(m_name) << "The last Iov in tag " << tagInfo().name << " valid since " << lastSince << "from "
256  << m_name << "::getNewObjects";
257  }
258 
259  //retrieve the data from the relational database source
261  //configure the connection
262  if (m_debug) {
263  connection.setMessageVerbosity(coral::Debug);
264  } else {
265  connection.setMessageVerbosity(coral::Error);
266  }
267  connection.setAuthenticationPath(m_authpath);
268  connection.configure();
269  //create the sessions
270  cond::persistency::Session session = connection.createSession(m_connectionString, false);
272  // fetch last payload when available
273  if (!tagInfo().lastInterval.payloadId.empty()) {
275  session3.transaction().start(true);
277  session3.transaction().commit();
278  }
279 
280  boost::posix_time::ptime executionTime = boost::posix_time::second_clock::local_time();
281  cond::Time_t executionTimeIov = cond::time::from_boost(executionTime);
282 
283  cond::Time_t startTimestamp = m_startTime.is_not_a_date_time() ? 0 : cond::time::from_boost(m_startTime);
284  cond::Time_t nextFillSearchTimestamp =
285  std::max(startTimestamp, m_endFillMode ? lastSince : m_prevPayload->createTime());
286 
287  edm::LogInfo(m_name) << "Starting sampling at "
288  << boost::posix_time::to_simple_string(cond::time::to_boost(nextFillSearchTimestamp));
289 
290  while (true) {
291  if (nextFillSearchTimestamp >= executionTimeIov) {
292  edm::LogInfo(m_name) << "Sampling ended at the time "
293  << boost::posix_time::to_simple_string(cond::time::to_boost(executionTimeIov));
294  break;
295  }
296  boost::posix_time::ptime nextFillSearchTime = cond::time::to_boost(nextFillSearchTimestamp);
297  boost::posix_time::ptime startSampleTime;
298  boost::posix_time::ptime endSampleTime;
299 
300  cond::OMSService oms;
301  oms.connect(m_omsBaseUrl);
302  auto query = oms.query("fills");
303 
304  edm::LogInfo(m_name) << "Searching new fill after " << boost::posix_time::to_simple_string(nextFillSearchTime);
305  query->filterNotNull("start_stable_beam").filterNotNull("fill_number");
306  if (nextFillSearchTime > cond::time::to_boost(m_prevPayload->createTime())) {
307  query->filterGE("start_time", nextFillSearchTime);
308  } else {
309  query->filterGT("start_time", nextFillSearchTime);
310  }
311 
312  query->filterLT("start_time", m_endTime);
313  if (m_endFillMode)
314  query->filterNotNull("end_time");
315  bool foundFill = query->execute();
316  if (foundFill)
318  if (!foundFill) {
319  edm::LogInfo(m_name) << "No fill found - END of job.";
320  break;
321  }
322 
323  startSampleTime = cond::time::to_boost(m_fillPayload->createTime());
324  cond::Time_t startFillTime = m_fillPayload->createTime();
325  cond::Time_t endFillTime = m_fillPayload->endTime();
326  unsigned short lhcFill = m_fillPayload->fillNumber();
327  bool ongoingFill = endFillTime == 0ULL;
328  if (ongoingFill) {
329  edm::LogInfo(m_name) << "Found ongoing fill " << lhcFill << " created at "
330  << cond::time::to_boost(startFillTime);
331  endSampleTime = executionTime;
332  nextFillSearchTimestamp = executionTimeIov;
333  } else {
334  edm::LogInfo(m_name) << "Found fill " << lhcFill << " created at " << cond::time::to_boost(startFillTime)
335  << " ending at " << cond::time::to_boost(endFillTime);
336  endSampleTime = cond::time::to_boost(endFillTime);
337  nextFillSearchTimestamp = endFillTime;
338  }
339  if (m_endFillMode || ongoingFill) {
340  getDipData(oms, startSampleTime, endSampleTime);
341  getLumiData(oms, lhcFill, startSampleTime, endSampleTime);
342  if (!m_tmpBuffer.empty()) {
343  boost::posix_time::ptime flumiStart = cond::time::to_boost(m_tmpBuffer.front().first);
344  boost::posix_time::ptime flumiStop = cond::time::to_boost(m_tmpBuffer.back().first);
345  edm::LogInfo(m_name) << "First lumi starts at " << flumiStart << " last lumi starts at " << flumiStop;
346  session.transaction().start(true);
347  getCTPPSData(session, startSampleTime, endSampleTime);
348  session.transaction().commit();
349  session2.transaction().start(true);
350  getEcalData(session2, startSampleTime, endSampleTime);
351  session2.transaction().commit();
352  }
353  }
354 
355  // In duringFill mode, convert the timestamp-type IOVs to lumiid-type IOVs
356  // before transferring the payloads from the buffer to the final collection
357  if (!m_endFillMode) {
359  }
360 
362  edm::LogInfo(m_name) << "Added " << niovs << " iovs within the Fill time";
363  m_tmpBuffer.clear();
364  m_timestampToLumiid.clear();
365  if (m_prevPayload->fillNumber() and !ongoingFill) {
366  if (m_endFillMode) {
367  addEmptyPayload(endFillTime);
368  } else {
370  }
371  }
372  }
373  }
374 
375  std::string id() const override { return m_name; }
376 
377  static constexpr unsigned int kLumisectionsQueryLimit = 4000;
378 
379 private:
381  bool add = false;
382  if (m_iovs.empty()) {
383  if (!m_lastPayloadEmpty)
384  add = true;
385  } else {
386  auto lastAdded = m_iovs.rbegin()->second;
387  if (lastAdded->fillNumber() != 0) {
388  add = true;
389  }
390  }
391  if (add) {
392  auto newPayload = std::make_shared<LHCInfoPerFill>();
393  m_iovs.insert(std::make_pair(iov, newPayload));
394  m_prevPayload = newPayload;
395  edm::LogInfo(m_name) << "Added empty payload with IOV " << iov << " ( "
396  << boost::posix_time::to_iso_extended_string(cond::time::to_boost(iov)) << " )";
397  }
398  }
399 
400  // Add payload to buffer and store corresponding lumiid IOV in m_timestampToLumiid map
402  auto startTime = row.get<boost::posix_time::ptime>("start_time");
403  auto delivLumi = row.get<float>("delivered_lumi");
404  auto recLumi = row.get<float>("recorded_lumi");
405  auto runNumber = std::stoul(row.get<std::string>("run_number"));
406  auto lsNumber = std::stoul(row.get<std::string>("lumisection_number"));
407  auto lumiid = cond::time::lumiTime(runNumber, lsNumber);
408 
409  LHCInfoPerFill* thisLumiSectionInfo = m_fillPayload->cloneFill();
410  m_tmpBuffer.emplace_back(std::make_pair(cond::time::from_boost(startTime), thisLumiSectionInfo));
411  if (!m_endFillMode) {
413  }
414  LHCInfoPerFill& payload = *thisLumiSectionInfo;
415  payload.setDelivLumi(delivLumi);
416  payload.setRecLumi(recLumi);
417  }
418 
419  void convertBufferedIovsToLumiid(std::map<cond::Time_t, cond::Time_t> timestampToLumiid) {
420  for (auto& item : m_tmpBuffer) {
421  // Check if the lumiid IOV corresponding to the timestamp is present in the map
422  if (timestampToLumiid.find(item.first) == timestampToLumiid.end()) {
423  throw cms::Exception("LHCInfoPerFillPopConSourceHandler")
424  << "Can't find corresponding lumiid IOV for timestamp " << item.first << "\n";
425  }
426  // Update the buffer with the lumiid-type IOV
427  item.first = timestampToLumiid.at(item.first);
428  }
429  }
430 
431  size_t getLumiData(const cond::OMSService& oms,
432  unsigned short fillId,
433  const boost::posix_time::ptime& beginFillTime,
434  const boost::posix_time::ptime& endFillTime) {
435  auto query = oms.query("lumisections");
436  query->addOutputVars(
437  {"start_time", "delivered_lumi", "recorded_lumi", "beams_stable", "run_number", "lumisection_number"});
438  query->filterEQ("fill_number", fillId);
439  query->filterGT("start_time", beginFillTime).filterLT("start_time", endFillTime);
440  query->filterEQ("beams_stable", "true");
442  if (query->execute()) {
443  auto queryResult = query->result();
444  edm::LogInfo(m_name) << "Found " << queryResult.size() << " lumisections with STABLE BEAM during the fill "
445  << fillId;
446 
447  if (!queryResult.empty()) {
448  if (m_endFillMode) {
449  auto firstRow = queryResult.front();
450  addPayloadToBuffer(firstRow);
451  }
452 
453  auto lastRow = queryResult.back();
454  addPayloadToBuffer(lastRow);
455  }
456  }
457  return 0;
458  }
459 
460  void getDipData(const cond::OMSService& oms,
461  const boost::posix_time::ptime& beginFillTime,
462  const boost::posix_time::ptime& endFillTime) {
463  // unsure how to handle this.
464  // the old implementation is not helping: apparently it is checking only the bunchconfiguration for the first diptime set of values...
465  auto query1 = oms.query("diplogger/dip/acc/LHC/RunControl/CirculatingBunchConfig/Beam1");
466  query1->filterGT("dip_time", beginFillTime).filterLT("dip_time", endFillTime);
467  //This query is limited to 100 rows, but currently only one is used
468  //If all this data is needed and saved properly the limit has to be set: query1->limit(...)
469  if (query1->execute()) {
470  auto res = query1->result();
471  if (!res.empty()) {
472  std::bitset<LHCInfoPerFill::bunchSlots + 1> bunchConfiguration1(0ULL);
473  auto row = *res.begin();
474  auto vbunchConf1 = row.getArray<unsigned short>("value");
475  for (auto vb : vbunchConf1) {
476  if (vb != 0) {
477  unsigned short slot = (vb - 1) / 10 + 1;
478  bunchConfiguration1[slot] = true;
479  }
480  }
481  m_fillPayload->setBunchBitsetForBeam1(bunchConfiguration1);
482  }
483  }
484  auto query2 = oms.query("diplogger/dip/acc/LHC/RunControl/CirculatingBunchConfig/Beam2");
485  query2->filterGT("dip_time", beginFillTime).filterLT("dip_time", endFillTime);
486  //This query is limited to 100 rows, but currently only one is used
487  if (query2->execute()) {
488  auto res = query2->result();
489  if (!res.empty()) {
490  std::bitset<LHCInfoPerFill::bunchSlots + 1> bunchConfiguration2(0ULL);
491  auto row = *res.begin();
492  auto vbunchConf2 = row.getArray<unsigned short>("value");
493  for (auto vb : vbunchConf2) {
494  if (vb != 0) {
495  unsigned short slot = (vb - 1) / 10 + 1;
496  bunchConfiguration2[slot] = true;
497  }
498  }
499  m_fillPayload->setBunchBitsetForBeam2(bunchConfiguration2);
500  }
501  }
502 
503  auto query3 = oms.query("diplogger/dip/CMS/LHC/LumiPerBunch");
504  query3->filterGT("dip_time", beginFillTime).filterLT("dip_time", endFillTime);
505  //This query is limited to 100 rows, but currently only one is used
506  if (query3->execute()) {
507  auto res = query3->result();
508  if (!res.empty()) {
509  std::vector<float> lumiPerBX;
510  auto row = *res.begin();
511  auto lumiBunchInst = row.getArray<float>("lumi_bunch_inst");
512  for (auto lb : lumiBunchInst) {
513  if (lb != 0.) {
514  lumiPerBX.push_back(lb);
515  }
516  }
517  m_fillPayload->setLumiPerBX(lumiPerBX);
518  }
519  }
520  }
521 
523  const boost::posix_time::ptime& beginFillTime,
524  const boost::posix_time::ptime& endFillTime) {
525  //run the fifth query against the CTPPS schema
526  //Initializing the CMS_CTP_CTPPS_COND schema.
527  coral::ISchema& CTPPS = session.coralSession().schema("CMS_PPS_SPECT_COND");
528  //execute query for CTPPS Data
529  std::unique_ptr<coral::IQuery> CTPPSDataQuery(CTPPS.newQuery());
530  //FROM clause
531  CTPPSDataQuery->addToTableList(std::string("PPS_LHC_MACHINE_PARAMS"));
532  //SELECT clause
533  CTPPSDataQuery->addToOutputList(std::string("DIP_UPDATE_TIME"));
534  CTPPSDataQuery->addToOutputList(std::string("LHC_STATE"));
535  CTPPSDataQuery->addToOutputList(std::string("LHC_COMMENT"));
536  if (m_debug) {
537  CTPPSDataQuery->addToOutputList(std::string("RUN_NUMBER"));
538  CTPPSDataQuery->addToOutputList(std::string("LUMI_SECTION"));
539  }
540  //WHERE CLAUSE
541  coral::AttributeList CTPPSDataBindVariables;
542  CTPPSDataBindVariables.extend<coral::TimeStamp>(std::string("beginFillTime"));
543  CTPPSDataBindVariables.extend<coral::TimeStamp>(std::string("endFillTime"));
544  CTPPSDataBindVariables[std::string("beginFillTime")].data<coral::TimeStamp>() = coral::TimeStamp(beginFillTime);
545  CTPPSDataBindVariables[std::string("endFillTime")].data<coral::TimeStamp>() = coral::TimeStamp(endFillTime);
546  std::string conditionStr = std::string("DIP_UPDATE_TIME>= :beginFillTime and DIP_UPDATE_TIME< :endFillTime");
547  CTPPSDataQuery->setCondition(conditionStr, CTPPSDataBindVariables);
548  //ORDER BY clause
549  CTPPSDataQuery->addToOrderList(std::string("DIP_UPDATE_TIME"));
550  //define query output
551  coral::AttributeList CTPPSDataOutput;
552  CTPPSDataOutput.extend<coral::TimeStamp>(std::string("DIP_UPDATE_TIME"));
553  CTPPSDataOutput.extend<std::string>(std::string("LHC_STATE"));
554  CTPPSDataOutput.extend<std::string>(std::string("LHC_COMMENT"));
555  if (m_debug) {
556  CTPPSDataOutput.extend<int>(std::string("RUN_NUMBER"));
557  CTPPSDataOutput.extend<int>(std::string("LUMI_SECTION"));
558  }
559  CTPPSDataQuery->defineOutput(CTPPSDataOutput);
560  //execute the query
561  coral::ICursor& CTPPSDataCursor = CTPPSDataQuery->execute();
562  cond::Time_t dipTime = 0;
563  std::string lhcState = "", lhcComment = "", ctppsStatus = "";
564 
565  //debug informations
566  unsigned int lumiSection = 0;
568  cond::Time_t savedDipTime = 0;
569  unsigned int savedLumiSection = 0;
570  cond::Time_t savedRunNumber = 0;
571 
572  bool ret = false;
574  while (CTPPSDataCursor.next()) {
575  if (m_debug) {
576  std::ostringstream CTPPS;
577  CTPPSDataCursor.currentRow().toOutputStream(CTPPS);
578  }
579  coral::Attribute const& dipTimeAttribute = CTPPSDataCursor.currentRow()[std::string("DIP_UPDATE_TIME")];
580  if (!dipTimeAttribute.isNull()) {
581  dipTime = cond::time::from_boost(dipTimeAttribute.data<coral::TimeStamp>().time());
582  if (filter.process(dipTime)) {
583  ret = true;
584  coral::Attribute const& lhcStateAttribute = CTPPSDataCursor.currentRow()[std::string("LHC_STATE")];
585  if (!lhcStateAttribute.isNull()) {
586  lhcState = lhcStateAttribute.data<std::string>();
587  }
588  coral::Attribute const& lhcCommentAttribute = CTPPSDataCursor.currentRow()[std::string("LHC_COMMENT")];
589  if (!lhcCommentAttribute.isNull()) {
590  lhcComment = lhcCommentAttribute.data<std::string>();
591  }
592 
593  if (m_debug) {
594  coral::Attribute const& runNumberAttribute = CTPPSDataCursor.currentRow()[std::string("RUN_NUMBER")];
595  if (!runNumberAttribute.isNull()) {
596  runNumber = runNumberAttribute.data<int>();
597  }
598  coral::Attribute const& lumiSectionAttribute = CTPPSDataCursor.currentRow()[std::string("LUMI_SECTION")];
599  if (!lumiSectionAttribute.isNull()) {
600  lumiSection = lumiSectionAttribute.data<int>();
601  }
602  }
603 
604  for (auto it = filter.current(); it != m_tmpBuffer.end(); it++) {
605  // set the current values to all of the payloads of the lumi section samples after the current since
606  LHCInfoPerFill& payload = *(it->second);
607  payload.setLhcState(lhcState);
608  payload.setLhcComment(lhcComment);
609  payload.setCtppsStatus(ctppsStatus);
610 
611  if (m_debug) {
612  savedDipTime = dipTime;
613  savedLumiSection = lumiSection;
614  savedRunNumber = runNumber;
615  }
616  }
617  }
618  }
619  }
620  if (m_debug) {
621  edm::LogInfo(m_name) << "Last assigned: "
622  << "DipTime: " << savedDipTime << " "
623  << "LumiSection: " << savedLumiSection << " "
624  << "RunNumber: " << savedRunNumber;
625  }
626  return ret;
627  }
628 
630  const boost::posix_time::ptime& lowerTime,
631  const boost::posix_time::ptime& upperTime) {
632  //run the sixth query against the CMS_DCS_ENV_PVSS_COND schema
633  //Initializing the CMS_DCS_ENV_PVSS_COND schema.
634  coral::ISchema& ECAL = session.nominalSchema();
635  //start the transaction against the fill logging schema
636  //execute query for ECAL Data
637  std::unique_ptr<coral::IQuery> ECALDataQuery(ECAL.newQuery());
638  //FROM clause
639  ECALDataQuery->addToTableList(std::string("BEAM_PHASE"));
640  //SELECT clause
641  ECALDataQuery->addToOutputList(std::string("CHANGE_DATE"));
642  ECALDataQuery->addToOutputList(std::string("DIP_value"));
643  ECALDataQuery->addToOutputList(std::string("element_nr"));
644  ECALDataQuery->addToOutputList(std::string("VALUE_NUMBER"));
645  //WHERE CLAUSE
646  coral::AttributeList ECALDataBindVariables;
647  ECALDataBindVariables.extend<coral::TimeStamp>(std::string("lowerTime"));
648  ECALDataBindVariables.extend<coral::TimeStamp>(std::string("upperTime"));
649  ECALDataBindVariables[std::string("lowerTime")].data<coral::TimeStamp>() = coral::TimeStamp(lowerTime);
650  ECALDataBindVariables[std::string("upperTime")].data<coral::TimeStamp>() = coral::TimeStamp(upperTime);
651  std::string conditionStr = std::string(
652  "(DIP_value LIKE '%beamPhaseMean%' OR DIP_value LIKE '%cavPhaseMean%') AND CHANGE_DATE >= :lowerTime AND "
653  "CHANGE_DATE < :upperTime");
654 
655  ECALDataQuery->setCondition(conditionStr, ECALDataBindVariables);
656  //ORDER BY clause
657  ECALDataQuery->addToOrderList(std::string("CHANGE_DATE"));
658  ECALDataQuery->addToOrderList(std::string("DIP_value"));
659  ECALDataQuery->addToOrderList(std::string("element_nr"));
660  //define query output
661  coral::AttributeList ECALDataOutput;
662  ECALDataOutput.extend<coral::TimeStamp>(std::string("CHANGE_DATE"));
663  ECALDataOutput.extend<std::string>(std::string("DIP_value"));
664  ECALDataOutput.extend<unsigned int>(std::string("element_nr"));
665  ECALDataOutput.extend<float>(std::string("VALUE_NUMBER"));
666  //ECALDataQuery->limitReturnedRows( 14256 ); //3564 entries per vector.
667  ECALDataQuery->defineOutput(ECALDataOutput);
668  //execute the query
669  coral::ICursor& ECALDataCursor = ECALDataQuery->execute();
670  cond::Time_t changeTime = 0;
671  cond::Time_t firstTime = 0;
672  std::string dipVal = "";
673  unsigned int elementNr = 0;
674  float value = 0.;
675  std::set<cond::Time_t> initializedVectors;
677  bool ret = false;
678  if (m_prevPayload.get()) {
679  for (auto& lumiSlot : m_tmpBuffer) {
680  lumiSlot.second->setBeam1VC(m_prevPayload->beam1VC());
681  lumiSlot.second->setBeam2VC(m_prevPayload->beam2VC());
682  lumiSlot.second->setBeam1RF(m_prevPayload->beam1RF());
683  lumiSlot.second->setBeam2RF(m_prevPayload->beam2RF());
684  }
685  }
686  std::map<cond::Time_t, cond::Time_t> iovMap;
687  if (m_tmpBuffer.empty()) {
688  return ret;
689  }
690  cond::Time_t lowerLumi = m_tmpBuffer.front().first;
691  while (ECALDataCursor.next()) {
692  if (m_debug) {
693  std::ostringstream ECAL;
694  ECALDataCursor.currentRow().toOutputStream(ECAL);
695  }
696  coral::Attribute const& changeDateAttribute = ECALDataCursor.currentRow()[std::string("CHANGE_DATE")];
697  if (!changeDateAttribute.isNull()) {
698  ret = true;
699  boost::posix_time::ptime chTime = changeDateAttribute.data<coral::TimeStamp>().time();
700  // move the first IOV found to the start of the fill interval selected
701  if (changeTime == 0) {
702  firstTime = cond::time::from_boost(chTime);
703  }
704  changeTime = cond::time::from_boost(chTime);
705  cond::Time_t iovTime = changeTime;
706  if (changeTime == firstTime)
707  iovTime = lowerLumi;
708  coral::Attribute const& dipValAttribute = ECALDataCursor.currentRow()[std::string("DIP_value")];
709  coral::Attribute const& valueNumberAttribute = ECALDataCursor.currentRow()[std::string("VALUE_NUMBER")];
710  coral::Attribute const& elementNrAttribute = ECALDataCursor.currentRow()[std::string("element_nr")];
711  if (!dipValAttribute.isNull() and !valueNumberAttribute.isNull()) {
712  dipVal = dipValAttribute.data<std::string>();
713  elementNr = elementNrAttribute.data<unsigned int>();
714  value = valueNumberAttribute.data<float>();
715  if (std::isnan(value))
716  value = 0.;
717  if (filter.process(iovTime)) {
718  iovMap.insert(std::make_pair(changeTime, filter.current()->first));
719  for (auto it = filter.current(); it != m_tmpBuffer.end(); it++) {
720  LHCInfoPerFill& payload = *(it->second);
721  theLHCInfoPerFillImpl::setElementData(it->first, dipVal, elementNr, value, payload, initializedVectors);
722  }
723  }
724  }
725  }
726  }
727  if (m_debug) {
728  for (auto& im : iovMap) {
729  edm::LogInfo(m_name) << "Found iov=" << im.first << " (" << cond::time::to_boost(im.first) << " ) moved to "
730  << im.second << " ( " << cond::time::to_boost(im.second) << " )";
731  }
732  }
733  return ret;
734  }
735 
736 private:
737  bool m_debug;
738  // starting date for sampling
739  boost::posix_time::ptime m_startTime;
740  boost::posix_time::ptime m_endTime;
741  bool m_endFillMode = true;
743  //for reading from relational database source
747  std::unique_ptr<LHCInfoPerFill> m_fillPayload;
748  std::shared_ptr<LHCInfoPerFill> m_prevPayload;
749  std::vector<std::pair<cond::Time_t, std::shared_ptr<LHCInfoPerFill>>> m_tmpBuffer;
750  bool m_lastPayloadEmpty = false;
751  // to hold correspondance between timestamp-type IOVs and lumiid-type IOVs
752  std::map<cond::Time_t, cond::Time_t> m_timestampToLumiid;
753 };
size
Write out results.
edm::ErrorSummaryEntry Error
def isnan(num)
static constexpr unsigned int kLumisectionsQueryLimit
Iov_t lastInterval
Definition: Types.h:73
std::unique_ptr< OMSServiceQuery > query(const std::string &function) const
Definition: OMSAccess.cc:129
T get(const std::string &attributeName)
Definition: OMSAccess.h:114
static const std::pair< const char *, LHCInfoPerFill::FillType > s_fillTypeMap[]
ret
prodAgent to be discontinued
void start(bool readOnly=true)
Definition: Session.cc:18
std::shared_ptr< LHCInfoPerFill > m_prevPayload
T from_string(const std::string &attributeValue)
Definition: OMSAccess.h:28
bool empty() const
Definition: OMSAccess.cc:69
Time_t since
Definition: Types.h:53
size_t size
Definition: Types.h:74
std::unique_ptr< T > fetchPayload(const cond::Hash &payloadHash)
Definition: Session.h:213
float const delivLumi() const
float const recLumi() const
Transaction & transaction()
Definition: Session.cc:52
popcon::PopConAnalyzer< LHCInfoPerFillPopConSourceHandler > LHCInfoPerFillPopConAnalyzer
void getDipData(const cond::OMSService &oms, const boost::posix_time::ptime &beginFillTime, const boost::posix_time::ptime &endFillTime)
LHCInfoPerFill::ParticleType particleTypeFromString(const std::string &s_particle_type)
std::string const & lhcState() const
Definition: Electron.h:6
std::string name
Definition: Types.h:72
LHCInfoPerFill::FillType fillTypeFromString(const std::string &s_fill_type)
Definition: query.py:1
void setElementData(cond::Time_t since, const std::string &dipVal, unsigned int elementNr, float value, LHCInfoPerFill &payload, std::set< cond::Time_t > &initList)
static size_t const bunchSlots
unsigned long long Time_t
Definition: Time.h:14
Time_t lumiTime(unsigned int run, unsigned int lumiId)
Definition: Time.cc:66
std::string const & ctppsStatus() const
static const std::pair< const char *, LHCInfoPerFill::ParticleType > s_particleTypeMap[]
bool comparePayloads(const LHCInfoPerFill &rhs, const LHCInfoPerFill &lhs)
bool getCTPPSData(cond::persistency::Session &session, const boost::posix_time::ptime &beginFillTime, const boost::posix_time::ptime &endFillTime)
bool makeFillPayload(std::unique_ptr< LHCInfoPerFill > &targetPayload, const cond::OMSServiceResult &queryResult)
coral::ISchema & nominalSchema()
Definition: Session.cc:224
std::unique_ptr< LHCInfoPerFill > m_fillPayload
Hash payloadId
Definition: Types.h:55
Session createSession(const std::string &connectionString, bool writeCapable=false)
#define DEFINE_FWK_MODULE(type)
Definition: MakerMacros.h:16
bool getEcalData(cond::persistency::Session &session, const boost::posix_time::ptime &lowerTime, const boost::posix_time::ptime &upperTime)
Definition: value.py:1
void setMessageVerbosity(coral::MsgLevel level)
~LHCInfoPerFillPopConSourceHandler() override=default
void addPayloadToBuffer(cond::OMSServiceResultRef &row)
Time_t from_boost(boost::posix_time::ptime bt)
static const std::map< std::string, int > vecMap
Log< level::Info, false > LogInfo
void convertBufferedIovsToLumiid(std::map< cond::Time_t, cond::Time_t > timestampToLumiid)
std::string const & lhcComment() const
unsigned short const fillNumber() const
float const instLumi() const
cond::persistency::Session & dbSession() const
coral::ISessionProxy & coralSession()
Definition: Session.cc:218
void add(std::map< std::string, TH1 *> &h, TH1 *hist)
LHCInfoPerFillPopConSourceHandler(edm::ParameterSet const &pset)
std::map< cond::Time_t, cond::Time_t > m_timestampToLumiid
void connect(const std::string &baseUrl)
Definition: OMSAccess.cc:128
OMSServiceResultIterator begin() const
Definition: OMSAccess.cc:32
size_t getLumiData(const cond::OMSService &oms, unsigned short fillId, const boost::posix_time::ptime &beginFillTime, const boost::posix_time::ptime &endFillTime)
void setAuthenticationPath(const std::string &p)
float const instLumiError() const
const bool Debug
cond::Time_t getFillLastLumiIOV(const cond::OMSService &oms, unsigned short fillId)
Definition: LHCInfoHelper.cc:8
boost::posix_time::ptime to_boost(Time_t iValue)
std::vector< std::pair< cond::Time_t, std::shared_ptr< LHCInfoPerFill > > > m_tmpBuffer
size_t transferPayloads(const std::vector< std::pair< cond::Time_t, std::shared_ptr< LHCInfoPerFill >>> &buffer, std::map< cond::Time_t, std::shared_ptr< LHCInfoPerFill >> &iovsToTransfer, std::shared_ptr< LHCInfoPerFill > &prevPayload)