CMS 3D CMS Logo

LumiCorrectionSource.cc
Go to the documentation of this file.
1 // -*- C++ -*-
2 //
3 // Package: LumiProducer
4 // Class: LumiCorrectionSource
5 //
11 //#include <memory>
16 
24 #include "CoralBase/Exception.h"
25 #include "CoralBase/AttributeList.h"
26 #include "CoralBase/Attribute.h"
27 #include "CoralBase/AttributeSpecification.h"
28 #include "CoralBase/Exception.h"
29 #include "CoralKernel/Context.h"
30 #include "RelationalAccess/IAuthenticationService.h"
31 #include "RelationalAccess/ConnectionService.h"
32 #include "CoralBase/Exception.h"
33 #include "RelationalAccess/ISessionProxy.h"
34 #include "RelationalAccess/ITransaction.h"
35 #include "RelationalAccess/AccessMode.h"
36 #include "RelationalAccess/ITypeConverter.h"
37 #include "RelationalAccess/IQuery.h"
38 #include "RelationalAccess/ICursor.h"
39 #include "RelationalAccess/ISchema.h"
40 #include "RelationalAccess/ITable.h"
41 #include "CoralKernel/IPropertyManager.h"
42 #include "RelationalAccess/AuthenticationServiceException.h"
50 #include "LumiCorrectionSource.h"
51 #include <iostream>
52 #include <sstream>
53 #include <string>
54 #include <memory>
55 #include <algorithm>
56 #include <vector>
57 #include <cstring>
58 #include <iterator>
59 #include <boost/tokenizer.hpp>
60 #include <xercesc/dom/DOM.hpp>
61 #include <xercesc/parsers/XercesDOMParser.hpp>
63 #include <xercesc/util/XMLString.hpp>
64 #include <boost/filesystem.hpp>
65 #include "boost/filesystem/path.hpp"
66 #include "boost/filesystem/operations.hpp"
68 LumiCorrectionSource::x2s(const XMLCh *toTranscode)const{
69  std::string tmp(xercesc::XMLString::transcode(toTranscode));
70  return tmp;
71 }
72 
73 XMLCh*
75  XMLCh* buff = xercesc::XMLString::transcode(temp.c_str());
76  return buff;
77 }
78 
80 LumiCorrectionSource::toParentString(const xercesc::DOMNode &nodeToConvert)const{
81  std::ostringstream oss;
82  xercesc::DOMNodeList *childList = nodeToConvert.getChildNodes();
83 
84  unsigned int numNodes = childList->getLength ();
85  for (unsigned int i = 0; i < numNodes; ++i){
86  xercesc::DOMNode *childNode = childList->item(i);
87  if (childNode->getNodeType() != xercesc::DOMNode::ELEMENT_NODE)
88  continue;
89  xercesc::DOMElement *child = static_cast < xercesc::DOMElement *> (childNode);
90  xercesc::DOMNamedNodeMap *attributes = child->getAttributes();
91  unsigned int numAttributes = attributes->getLength ();
92  for (unsigned int j = 0; j < numAttributes; ++j){
93  xercesc::DOMNode *attributeNode = attributes->item(j);
94  if (attributeNode->getNodeType() != xercesc::DOMNode::ATTRIBUTE_NODE)
95  continue;
96  xercesc::DOMAttr *attribute = static_cast <xercesc::DOMAttr *> (attributeNode);
97 
98  oss << "(" << x2s(child->getTagName()) <<
99  x2s(attribute->getName()) << "=" <<
100  x2s(attribute->getValue()) << ")";
101  }
102  }
103  return oss.str();
104 }
105 
106 const std::string
108  std::string frontierConnect;
109  std::string realconnect;
111  std::unique_ptr< xercesc::XercesDOMParser > parser(new xercesc::XercesDOMParser);
112  try{
113  parser->setValidationScheme(xercesc::XercesDOMParser::Val_Auto);
114  parser->setDoNamespaces(false);
115  parser->parse(m_siteconfpath.c_str());
116  xercesc::DOMDocument* doc=parser->getDocument();
117  if(!doc){
118  return "";
119  }
120 
121  xercesc::DOMNodeList *frontierConnectList=doc->getElementsByTagName(s2x("frontier-connect"));
122  if (frontierConnectList->getLength()>0){
123  xercesc::DOMElement *frontierConnectElement=static_cast < xercesc::DOMElement *> (frontierConnectList->item (0));
124  frontierConnect = toParentString(*frontierConnectElement);
125  }
126  // Replace the last component of every "serverurl=" piece (up to the
127  // next close-paren) with the servlet
128  std::string::size_type nextparen = 0;
129  std::string::size_type serverurl, lastslash;
130  std::string complexstr = "";
131  while ((serverurl=frontierConnect.find("(serverurl=", nextparen)) != std::string::npos){
132  realconnect.append(frontierConnect, nextparen, serverurl - nextparen);
133  nextparen=frontierConnect.find(')', serverurl);
134  lastslash=frontierConnect.rfind('/', nextparen);
135  realconnect.append(frontierConnect,serverurl,lastslash-serverurl+1);
136  realconnect.append(servlet);
137  }
138  realconnect.append(frontierConnect, nextparen,frontierConnect.length()-nextparen);
139  }catch(xercesc::DOMException &e){
140  }
141  return realconnect;
142 }
143 
147  const std::string fproto("frontier://");
148  std::string::size_type startservlet=fproto.length();
149  std::string::size_type endservlet=connectStr.find("(",startservlet);
150  if(endservlet==std::string::npos){
151  endservlet=connectStr.rfind('/',connectStr.length());
152  }
153  std::string servlet=connectStr.substr(startservlet,endservlet-startservlet);
154  if( (!servlet.empty())&& (servlet.find_first_of(":/)[]")==std::string::npos)){
155  if(servlet=="cms_conditions_data") servlet="";
156  if(m_siteconfpath.length()==0){
157  std::string url=(boost::filesystem::path("SITECONF")/boost::filesystem::path("local")/boost::filesystem::path("JobConfig")/boost::filesystem::path("site-local-config.xml")).string();
158  char * tmp = getenv ("CMS_PATH");
159  if(tmp){
161  }
162  }else{
163  if(!boost::filesystem::exists(boost::filesystem::path(m_siteconfpath))){
164  throw cms::Exception("Non existing path ")<<m_siteconfpath;
165  }
166  m_siteconfpath = (boost::filesystem::path(m_siteconfpath)/boost::filesystem::path("site-local-config.xml")).string();
167  }
168  result=fproto+servletTranslation(servlet)+connectStr.substr(endservlet);
169  }
170  return result;
171 }
172 
175  findingRecord<LumiCorrectionParamRcd>();
176  std::string connectStr=iConfig.getParameter<std::string>("connect");
178  if(iConfig.exists("globaltag")){
179  m_globaltag=iConfig.getUntrackedParameter<std::string>("globaltag","");
180  }else{
181  m_normtag=iConfig.getUntrackedParameter<std::string>("normtag","");
182  }
183  m_datatag=iConfig.getUntrackedParameter<std::string>("datatag","");
184  m_cachesize=iConfig.getUntrackedParameter<unsigned int>("ncacheEntries",3);
185  m_siteconfpath=iConfig.getUntrackedParameter<std::string>("siteconfpath","");
186  const std::string fproto("frontier://");
187  if(connectStr.substr(0,fproto.length())==fproto){
189  }else if(connectStr.substr(0,11)=="sqlite_file"){
190  m_connectStr=connectStr;
191  }else{
192  m_connectStr=connectStr;
193  std::string authpath=iConfig.getUntrackedParameter<std::string>("authpath","");
194  boost::filesystem::path boostAuthPath( authpath );
195  if(boost::filesystem::is_directory(boostAuthPath)){
196  boostAuthPath /= boost::filesystem::path("authentication.xml");
197  }
198  m_authfilename = boostAuthPath.string();
199  }
200 }
201 
204 {
205  unsigned int currentrun=m_pcurrentTime->eventID().run();
206  if(currentrun==0||currentrun==4294967295){
207  return std::make_shared<const LumiCorrectionParam>();
208  }
209  if(m_paramcachedrun!=currentrun){//i'm in a new run
210  fillparamcache(currentrun);//fill cache
211  }else{ //i'm in an old run
212  if(m_paramcache.find(currentrun)==m_paramcache.end()){//i'm not cached
213  fillparamcache(currentrun);//
214  }
215  }
216  if(m_paramcache.empty()){
217  return std::make_shared<const LumiCorrectionParam>();
218  }
219  m_paramresult=m_paramcache[currentrun];
220  if(m_paramresult.get()==nullptr){
221  return std::make_shared<const LumiCorrectionParam>();
222  }
223  return m_paramresult;
224 }
225 
226 void
229  const edm::IOVSyncValue& iTime,
230  edm::ValidityInterval& oValidity ) {
231  m_pcurrentTime=&iTime;
232  oValidity.setFirst(iTime);
233  oValidity.setLast(iTime);
234 }
235 
236 void
238  //std::cout<<"old authfile "<<coral::Context::instance().PropertyManager().property("AuthenticationFile")->get()<<std::endl;
239  coral::Context::instance().PropertyManager().property("AuthenticationFile")->set(m_authfilename);
240  coral::Context::instance().loadComponent("CORAL/Services/XMLAuthenticationService");
241 }
242 
243 void
245  m_paramcache.clear();
247  if(!m_authfilename.empty()){
248  coral::IHandle<coral::IAuthenticationService> authSvc=coral::Context::instance().query<coral::IAuthenticationService>();
249  if( authSvc.isValid() ){
250  try{
251  authSvc->credentials( m_connectStr );
252  }catch(const coral::UnknownConnectionException& er){
253  reloadAuth();
254  }
255  }else{
256  reloadAuth();
257  }
258  }
259  coral::ConnectionService* mydbservice=new coral::ConnectionService;
260  if(!m_globaltag.empty()){
261  coral::ISessionProxy* gsession=mydbservice->connect(m_connectStr,coral::ReadOnly);
262  gsession->transaction().start(true);
263  parseGlobaltagForLumi(gsession->nominalSchema(),m_globaltag);
264  gsession->transaction().commit();
265  delete gsession;
266  }
267  coral::ISessionProxy* session=mydbservice->connect(m_connectStr,coral::ReadOnly);
268  coral::ITypeConverter& tconverter=session->typeConverter();
269  tconverter.setCppTypeForSqlType(std::string("float"),std::string("FLOAT(63)"));
270  tconverter.setCppTypeForSqlType(std::string("unsigned int"),std::string("NUMBER(10)"));
271  tconverter.setCppTypeForSqlType(std::string("unsigned short"),std::string("NUMBER(1)"));
272  auto result = std::make_unique<LumiCorrectionParam>(LumiCorrectionParam::HF);
273  try{
274  session->transaction().start(true);
275  coral::ISchema& schema=session->nominalSchema();
276  lumi::RevisionDML dml;
277  unsigned long long tagid=0;
278  if(m_datatag.empty()){
279  tagid=dml.currentHFDataTagId(schema);//get datatag id
280  }else{
281  tagid=dml.HFDataTagIdByName(schema,m_datatag);
282  }
283  lumi::RevisionDML::DataID dataid=dml.dataIDForRun(schema,runnumber,tagid);//get data id
284  unsigned int lumiid=dataid.lumi_id;
285  if(lumiid==0){
286  result->setNBX(0);
287  std::shared_ptr<const LumiCorrectionParam> const_result = std::move(result);
288  m_paramcache.insert(std::make_pair(runnumber,const_result));
289  session->transaction().commit();
290  delete session;
291  delete mydbservice;
292  return;
293  }
294 
295  coral::AttributeList lumidataBindVariables;
296  lumidataBindVariables.extend("dataid",typeid(unsigned long long));
297  lumidataBindVariables["dataid"].data<unsigned long long>()=lumiid;
298  std::string conditionStr("DATA_ID=:dataid");
299  coral::AttributeList lumiparamOutput;
300  lumiparamOutput.extend("NCOLLIDINGBUNCHES",typeid(unsigned int));
301  coral::IQuery* lumiparamQuery=schema.newQuery();
302  lumiparamQuery->addToTableList(std::string("LUMIDATA"));
303  lumiparamQuery->setCondition(conditionStr,lumidataBindVariables);
304  lumiparamQuery->addToOutputList("NCOLLIDINGBUNCHES");
305  lumiparamQuery->defineOutput(lumiparamOutput);
306  coral::ICursor& lumiparamcursor=lumiparamQuery->execute();
307  unsigned int ncollidingbx=0;
308  while( lumiparamcursor.next() ){
309  const coral::AttributeList& row=lumiparamcursor.currentRow();
310  if(!row["NCOLLIDINGBUNCHES"].isNull()){
311  ncollidingbx=row["NCOLLIDINGBUNCHES"].data<unsigned int>();
312  }
313  result->setNBX(ncollidingbx);
314  }
315  delete lumiparamQuery;
316  lumi::NormDML normdml;
317  unsigned long long normid=0;
318  std::map<std::string,unsigned long long> normidmap;
319  if (m_normtag.empty()){
320  normdml.normIdByType(schema,normidmap,lumi::NormDML::HF,true);
321  m_normtag=normidmap.begin()->first;
322  normid=normidmap.begin()->second;
323  }else{
324  normid=normdml.normIdByName(schema,m_normtag);
325  }
326 
327  std::map< unsigned int,lumi::NormDML::normData > normDataMap;
328  normdml.normById(schema,normid,normDataMap);
329 
330  std::map< unsigned int,lumi::NormDML::normData >::iterator normIt=--normDataMap.end();
331  if(runnumber<normIt->first){
332  normIt=normDataMap.upper_bound(runnumber);
333  --normIt;
334  }
335  result->setNormtag(m_normtag);
336  result->setcorrFunc(normIt->second.corrfunc);
337  result->setnonlinearCoeff(normIt->second.coefficientmap);
338  result->setafterglows(normIt->second.afterglows);
339  result->setdescription(normIt->second.amodetag,normIt->second.beamegev);
340  if(normIt->second.coefficientmap["DRIFT"]!=0.){
341  float intglumi=fetchIntglumi(schema,runnumber);
342  result->setintglumi(intglumi);
343  }
344  m_paramcache.insert(std::make_pair(runnumber,std::shared_ptr<LumiCorrectionParam>(std::move(result))));
345  session->transaction().commit();
346  }catch(const coral::Exception& er){
347  session->transaction().rollback();
348  delete session;
349  delete mydbservice;
350  throw cms::Exception("DatabaseError ")<<er.what();
351  }
352  delete session;
353  delete mydbservice;
354 }
355 void
358  std::string tagtreetabname("TAGTREE_TABLE_");
359  tagtreetabname+=std::string(globaltag);
360  coral::IQuery* qHandle=schema.newQuery();
361  qHandle->addToTableList("TAGINVENTORY_TABLE","i");
362  qHandle->addToTableList(tagtreetabname,"v");
363  coral::AttributeList qResult;
364  qResult.extend("pfn",typeid(std::string));
365  qResult.extend("tagname",typeid(std::string));
366  std::string conditionStr("v.tagid=i.tagid and i.recordname=:recordname");
367  coral::AttributeList qCondition;
368  qCondition.extend("recordname",typeid(std::string));
369  qCondition["recordname"].data<std::string>()=std::string("LumiCorrectionParamRcd");
370  qHandle->setCondition(conditionStr,qCondition);
371  qHandle->addToOutputList("i.pfn");
372  qHandle->addToOutputList("i.tagname");
373  qHandle->defineOutput(qResult);
374  coral::ICursor& iCursor=qHandle->execute();
375  while( iCursor.next() ){
376  const coral::AttributeList& row=iCursor.currentRow();
377  std::string connectStr=row["pfn"].data<std::string>();
378  const std::string fproto("frontier://");
379  if(connectStr.substr(0,fproto.length())==fproto){
381  }else{
382  m_connectStr=connectStr;
383  }
384  m_normtag=row["tagname"].data<std::string>();
385  }
386  delete qHandle;
387 }
388 float
390  float result=0.;
391  coral::IQuery* qHandle=schema.newQuery();
392  qHandle->addToTableList(lumi::LumiNames::intglumiv2TableName());
393  coral::AttributeList qResult;
394  qResult.extend("INTGLUMI",typeid(float));
395  std::string conditionStr("RUNNUM=:runnumber");
396  coral::AttributeList qCondition;
397  qCondition.extend("runnumber",typeid(unsigned int));
398  qCondition["runnumber"].data<unsigned int>()=runnumber;
399  qHandle->setCondition(conditionStr,qCondition);
400  qHandle->addToOutputList("INTGLUMI");
401  qHandle->defineOutput(qResult);
402  coral::ICursor& intglumiCursor=qHandle->execute();
403  while( intglumiCursor.next() ){
404  const coral::AttributeList& row=intglumiCursor.currentRow();
405  if(!row["INTGLUMI"].isNull()){
406  result=row["INTGLUMI"].data<float>();
407  }
408  }
409  delete qHandle;
410  return result;
411 }
412 
414 //define this as a plug-in
RunNumber_t run() const
Definition: EventID.h:39
std::string translateFrontierConnect(const std::string &connectStr)
void setFirst(const IOVSyncValue &iTime)
T getParameter(std::string const &) const
auto setWhatProduced(T *iThis, const es::Label &iLabel={})
Definition: ESProducer.h:124
T getUntrackedParameter(std::string const &, T const &) const
const std::string servletTranslation(const std::string &servlet) const
const EventID & eventID() const
Definition: IOVSyncValue.h:40
void setIntervalFor(const edm::eventsetup::EventSetupRecordKey &, const edm::IOVSyncValue &, edm::ValidityInterval &) override
static PFTauRenderPlugin instance
std::shared_ptr< const LumiCorrectionParam > ReturnParamType
bool exists(std::string const &parameterName) const
checks if a parameter exists
std::map< unsigned int, std::shared_ptr< const LumiCorrectionParam > > m_paramcache
DataID dataIDForRun(coral::ISchema &schema, unsigned int runnum, unsigned long long tagid)
Definition: RevisionDML.cc:272
static const std::string intglumiv2TableName()
Definition: LumiNames.cc:59
void parseGlobaltagForLumi(coral::ISchema &schema, const std::string &globaltag)
void xercesInitialize()
Definition: Xerces.cc:18
uint16_t size_type
float fetchIntglumi(coral::ISchema &schema, unsigned int runnumber)
const edm::IOVSyncValue * m_pcurrentTime
std::shared_ptr< const LumiCorrectionParam > m_paramresult
std::string toParentString(const xercesc::DOMNode &nodeToConvert) const
unsigned long long HFDataTagIdByName(coral::ISchema &schema, const std::string &datatagname)
Definition: RevisionDML.cc:214
void setLast(const IOVSyncValue &iTime)
void normById(const coral::ISchema &schema, unsigned long long normid, std::map< unsigned int, normData > &result)
Definition: NormDML.cc:98
void fillparamcache(unsigned int runnumber)
LumiCorrectionSource(const edm::ParameterSet &)
std::vector< std::vector< double > > tmp
Definition: MVATrainer.cc:100
XMLCh * s2x(const std::string &input) const
ReturnParamType produceLumiCorrectionParam(const LumiCorrectionParamRcd &)
#define DEFINE_FWK_EVENTSETUP_SOURCE(type)
Definition: SourceFactory.h:91
unsigned long long currentHFDataTagId(coral::ISchema &schema)
Definition: RevisionDML.cc:190
void normIdByType(const coral::ISchema &schema, std::map< std::string, unsigned long long > &resultMap, LumiType=HF, bool defaultonly=true)
Definition: NormDML.cc:50
std::string x2s(const XMLCh *input) const
unsigned long long lumi_id
Definition: RevisionDML.h:21
def move(src, dest)
Definition: eostools.py:511
unsigned long long normIdByName(const coral::ISchema &schema, const std::string &normtagname)
Definition: NormDML.cc:18