ATLAS Offline Software
AtlRunQueryLib.py
Go to the documentation of this file.
1 #!/bin/env python
2 
3 # Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
4 #
5 # ----------------------------------------------------------------
6 # Script : AtlRunQueryLib.py
7 # Project: AtlRunQuery
8 # Purpose: Library with the actual query classes
9 # Authors: Andreas Hoecker (CERN), Joerg Stelzer (DESY)
10 # Created: Nov 13, 2008
11 # ----------------------------------------------------------------
12 #
13 
14 from __future__ import with_statement, print_function
15 
16 from CoolRunQuery.utils.AtlRunQueryTimer import timer
17 
18 import re
19 import os
20 from time import time
21 
22 from CoolRunQuery.utils.AtlRunQueryUtils import coolDbConn, runsOnServer
23 
24 from CoolRunQuery.selector.AtlRunQuerySelectorRuntime import RunTimeSelector
25 from CoolRunQuery.selector.AtlRunQuerySelectorBase import Selector, DataKey
26 
27 from CoolRunQuery.AtlRunQueryRun import Run
28 from CoolRunQuery.AtlRunQueryQueryConfig import QC
29 
30 
31 # -----------------------------------------------------------------------------------------
32 # class: AtlRunQuery
33 # -----------------------------------------------------------------------------------------
34 
36 
37  def __init__(self, options, readoracle=False, loglevel=1, html="AUTO", origQuery="", datapath='data', parsedstring=""):
38 
39  with timer('total'):
40 
41  with timer('config'):
42  self.config(options, readoracle, loglevel, html, origQuery, datapath, parsedstring)
43 
44  with timer('run all'):
45  runlist = self.run()
46 
47  with timer('evaluate all'):
48  (dic, dicsum, xmlhtmlstr, roothtmlstr) = self.evaluate(runlist)
49 
50  with timer('output all'):
51  self.output(runlist, dic, dicsum, xmlhtmlstr, roothtmlstr)
52 
53  with timer('finalize'):
54  self.finalize()
55 
56  from CoolRunQuery.utils.AtlRunQueryTimer import TimerStats as TS
57  TS.printTimeSummary()
58  TS.printTimeFlat()
59 
60 
61 
62  def config(self, options, readoracle, loglevel, html, origQuery, datapath, parsedstring):
63 
64  self.cmdlineOptions = options
65  self.origQuery = origQuery
66  QC.datapath = datapath
67  self.parsedstring = parsedstring
68  self.maxNumOfRuns = -1 # in case a maximum number of to be selected runs is given
69  self.makeSummary = 'summary' in options.show # in case a summary shall be printed
70  self.makeDQSummary = 'dqsummary' in options.show # in case a DQ efficiency summary shall be printed
71  self.makeDQPlots = 'dqplots' in options.show # in case only DQ plots shall be printed
72  self.makeDQeff = 'dqeff' in options.show # in case a DQ efficiency summary shall be printed
73  self.xmlFileName = 'MyLBCollection.xml'
74  self.xmlFileLabel = 'MyLBCollection'
75  self.querystart = time()
76  self.selectionOutput = []
77 
78  # ensure the output directory exists
79  if QC.datapath=='':
80  QC.datapath='.'
81  else:
82  try:
83  os.makedirs(QC.datapath, exist_ok = True)
84  print("Using output directory: %s" % QC.datapath)
85  except (PermissionError, FileExistsError) as err:
86  print("Could not create data output directory: %s" % QC.datapath)
87  print("Reason: %s" % err)
88  print("Will write to local directory")
89  QC.datapath = "."
90 
91  # if no show argument is specified, we use the minimal version
92  if not self.cmdlineOptions.show:
93  self.cmdlineOptions.show = ['run','time']
94 
95  if self.cmdlineOptions.xmlfile is not None:
96  # format 'file.xml:runlist' or 'runlist:file.xml'
97  str1,str2 = self.cmdlineOptions.xmlfile.strip().split(':',1)
98  if '.xml' in str1:
99  self.xmlFileName = str1
100  if str2 != '':
101  self.xmlFileLabel = str2
102  elif '.xml' in str2:
103  self.xmlFileName = str2
104  if str1 != '':
105  self.xmlFileLabel = str1
106 
107  if self.cmdlineOptions.html:
108  self.html = self.cmdlineOptions.html
109  else:
110  if html=="AUTO":
111  self.html = runsOnServer()
112  elif html=="YES":
113  self.html = True
114  elif html=="NO":
115  self.html = False
116  else:
117  raise RuntimeError ("Unknown argument for option 'html': %s" % html)
118  Run.writehtml = self.html
119 
120  if self.cmdlineOptions.prodgrl is not None : # happens only if --nogrl is specified
121  self.prodgrl = self.cmdlineOptions.prodgrl
122  elif self.cmdlineOptions.xmlfile is not None :
123  self.prodgrl = True # if an xml file is specified it will be produced
124  else:
125  self.prodgrl = not runsOnServer()
126 
127  if self.cmdlineOptions.dictroot is not None : # happens if --root or --noroot is specified
128  self.dictroot = self.cmdlineOptions.dictroot
129  else:
130  self.dictroot = not runsOnServer()
131 
132 
133  if self.cmdlineOptions.database and self.cmdlineOptions.database.upper()=='MC':
134  Selector.setCondDBMC()
135 
136  if self.cmdlineOptions.condtag:
137  Selector.condtag = self.cmdlineOptions.condtag
138 
139  QC.localtime = (self.cmdlineOptions.utc is None)
140  QC.settimezone()
141 
142  # check which runs currently participate in prompt calibration
143  # we need this for the web display only
144  if self.html:
145  nemo_dir = '/afs/cern.ch/user/a/atlcond/scratch0/nemo/prod/web/'
146  try:
147  f = open( nemo_dir + 'calibruns.txt' )
148  for line in f:
149  try:
150  if line:
151  Run.PromptCalibRuns.append( int(line.strip()) )
152  except ValueError:
153  pass
154  # read list of NEMO tasks
155  # do we need this for each query, or just for the web??
156  fname = os.listdir( nemo_dir + 'tasks' )
157  i = 0
158  for taskname in fname:
159  m = re.match(r'.*(task_(\d+)_\d+.txt)',taskname)
160  if m:
161  i+=1
162  fname, runnr = m.groups()
163  Run.NemoTasks[int(runnr)] = fname
164  except IOError as err:
165  print (err)
166  print ("Because of this I can't mark runs that are currently in the calibration loop")
167 
168  #DQ summary relative to GRL
169  if 'cosmics' in options.show:
170  self.dqsumgrl = "PHYS_Cosmics_AllGood"
171  elif 'heavyions' in options.show:
172  self.dqsumgrl = "PHYS_HeavyIonP_All_Good"
173  elif self.cmdlineOptions.dqsumgrl:
174  self.dqsumgrl = self.cmdlineOptions.dqsumgrl
175  else:
176  self.dqsumgrl = 'PHYS_StandardGRL_All_Good_25ns'
177 
178  #defect and logic tag of defect database
179  if self.cmdlineOptions.defecttag and self.cmdlineOptions.logictag:
180  self.dbbtag = (self.cmdlineOptions.defecttag, self.cmdlineOptions.logictag)
181  else:
182  self.dbbtag = ("HEAD", "HEAD")
183 
184 
185  def run(self):
186  # is last run still open ?
187  from CoolRunQuery.AtlRunQuerySFO import GetSFO_lastNruns
188  sfoconnection = coolDbConn.GetSFODBConnection()
189  sfocursor = sfoconnection.cursor()
190  retlist = GetSFO_lastNruns( sfocursor, 1 )
191  if 'OPENED' in retlist[0][1]:
192  Run.runnropen = retlist[0][0]
193 
194  if self.cmdlineOptions.runlist is not None:
195  runlist = self.cmdlineOptions.runlist
196  if any('last' in x for x in self.cmdlineOptions.runlist):
197  for idx in range(len(runlist)):
198  rrange = runlist[idx]
199  if 'last' not in rrange:
200  continue
201  rrange = rrange.replace('last','')
202  self.maxNumOfRuns = int(rrange)
203  # list of last n runs run numbers, where at least one stream is not calibration
204  retlist = GetSFO_lastNruns( sfocursor, 1.1*self.maxNumOfRuns )
205  runlist[idx] = '%i+' % (retlist[-1][0])
206 
207  elif self.cmdlineOptions.timelist is not None:
208  # translate time into run-range
209  if 'last' in self.cmdlineOptions.timelist[0]:
210  # contains 'last'
211  from CoolRunQuery.utils.AtlRunQueryUtils import get_runs_last_dt
212  rlist = get_runs_last_dt(self.cmdlineOptions.timelist[0])
213 
214  runlist = ['%i+' % rlist[-1]] if (len(rlist)>0) else ['99999999+']
215 
216  else:
217  # translate time into run-range
218  from CoolRunQuery.utils.AtlRunQueryUtils import timeStringToSecondsUTC,secondsToTimeStringUTC,get_run_range2,GetTimeRanges
219  timelist = ','.join(self.cmdlineOptions.timelist)
220  timeranges,timerangesHR = GetTimeRanges(timelist, intRepFnc=timeStringToSecondsUTC, maxval=time())
221  timerangesAsString = [ list(map(secondsToTimeStringUTC, tr)) for tr in timeranges ]
222  runranges = [ ( "%s-%s" % get_run_range2(tr[0],tr[1]) ) for tr in timerangesAsString]
223  runlist = [','.join(runranges)]
224 
225 
226  # the run selector
227  rtSel = RunTimeSelector(name = 'runtime', runlist = runlist)
228 
229  # find the begin and end of each interesting run
230  runlist = rtSel.select()
231 
232  # if Selector.condDB()=="CONDBR2":
233  # self.cmdlineOptions.show = [x for x in self.cmdlineOptions.show if x not in ["lhc","olclumi","olcfillparams","olclbdata"]]
234  # self.cmdlineOptions.partition=None
235  # self.cmdlineOptions.projecttag=None
236  # print ("Pre-run2 selection removed partition and projecttag from querying")
237  # print ("Pre-run2 selection removed lhc, olc from showing. Modified show list: %r" % self.cmdlineOptions.show)
238 
239  self.selectionOutput += ["%s" % rtSel]
240 
241 
242  from CoolRunQuery.AtlRunQuerySelectorWorker import SelectorWorker
243 
244  # create all selectors that are actively select
245  SelectorWorker.parseSelectorOptions(self.cmdlineOptions)
246 
247  # parse show option:
248  SelectorWorker.parseShowOption(self.cmdlineOptions)
249 
250  # call setApply for all selectors that actively select
251  SelectorWorker.setApplySelection()
252 
253  # call setShowOutput for all selectors that show
254  SelectorWorker.setShowOutput()
255 
256  SelectorWorker.getRetrieveSelector('trigkey','TrigKeySelector')
257 
258  # Selectors can implement an initialize function which runs after any constructor and setShow
259  for s in SelectorWorker.getOrderedSelectorList():
260  s = s.selector
261  if hasattr(s, 'initialize'):
262  with timer("initializing selector '%s'" % s.name):
263  s.verbose = True
264  s.initialize()
265 
266  # apply the selectors to initial run list
267  for s in SelectorWorker.selectors():
268  with timer("run selector '%s'" % s.name):
269  s.verbose = True
270  runlist = s.select(runlist)
271  self.selectionOutput += ["%s" % s.__str__()]
272  with timer("run AfterQuery for selector '%s'" % s.name):
273  s.runAfterQuery(runlist)
274 
275  # reverse list for presentation: newest run on top
276  runlist.reverse()
277 
278  # if "last" option used, the runlist has to be truncated
279  if self.maxNumOfRuns > 0:
280  print ('SELOUT Selecting the %i most recent runs' % self.maxNumOfRuns)
281  runlist = runlist[0:self.maxNumOfRuns]
282  self.selectionOutput += ['SELOUT Selecting the %i most recent runs' % self.maxNumOfRuns]
283 
284  return runlist
285 
286 
287  def evaluate(self, runlist):
288 
289  # provide pickled dictionary of query result
290  with timer('CreateResultDict'):
291  from CoolRunQuery.output.AtlRunQuerySave import CreateResultDict
292  dic, dicsum = CreateResultDict( runlist )
293 
294 
295  # create XML file (and return pretty html output for print)
296  if self.prodgrl:
297  with timer('CreateXMLFile'):
298  print ("Producing XML file")
299  from CoolRunQuery.output.AtlRunQueryXML import CreateXMLFile
300  from CoolRunQuery.AtlRunQueryVersion import SvnVersion
301  xmlhtmlstr = CreateXMLFile( runlist, self.cmdlineOptions, self.origQuery, QC.datapath,
302  self.xmlFileName, self.xmlFileLabel, SvnVersion )
303  else:
304  xmlhtmlstr = None
305  print ("Creation of GRL disabled")
306 
307  if self.dictroot and len(runlist) > 0:
308  with timer('CreateRootFile'):
309  # create root file from dictionary - and make plots
310  from CoolRunQuery.output.AtlRunQueryRoot import CreateRootFile
311  rootfilename, roothtmlstr = CreateRootFile( dic )
312  else:
313  roothtmlstr = None
314  print ("Creation of root file disabled")
315 
316  return (dic, dicsum, xmlhtmlstr, roothtmlstr)
317 
318 
319  def output(self, runlist, dic, dicsum, xmlhtmlstr, roothtmlstr):
320 
321  if self.html:
322 
323  with timer('GetOKS link info'):
324  from CoolRunQuery.AtlRunQuerySFO import SetOKSLinks
325  SetOKSLinks(runlist)
326 
327  # create web page
328  from CoolRunQuery.html.AtlRunQueryHTML import ResultPageMaker
329  #try:
330  pageinfo = { 'datapath' : QC.datapath,
331  'origQuery' : self.origQuery,
332  'fullQuery' : self.parsedstring,
333  'runlist' : runlist,
334  'dic' : dic,
335  'dicsum' : dicsum,
336  'makeSummary' : self.makeSummary,
337  'makeDQeff' : self.makeDQeff,
338  'makeDQSummary' : self.makeDQSummary,
339  'makeDQPlots' : self.makeDQPlots,
340  'dqsumgrl' : self.dqsumgrl,
341  'dbbtag' : self.dbbtag,
342  'roothtmlstr' : roothtmlstr,
343  'xmlfilename' : self.xmlFileName,
344  'xmlhtmlstr' : xmlhtmlstr,
345  'querytime' : time() - self.querystart,
346  'selout' : self.selectionOutput,
347  }
348  with timer("run ResultPageMaker makePage"):
349  ResultPageMaker.makePage(pageinfo)
350  #except ImportError, ie:
351  # print ("Can't import pagemaker, no web page made",ie)
352 
353  else:
354  print ('---------------------------------------------------------------------')
355  print (Run.header())
356  runlist.reverse()
357  for r in runlist:
358  print (r)
359 
360  from CoolRunQuery.utils.AtlRunQueryUtils import addKommaToNumber, filesize
361  print ('Summary:')
362  for data_key, summary in dicsum.items():
363  if data_key.Type==DataKey.STREAM:
364  key = data_key.ResultKey.replace('STR:','')
365  val = '%s (%s)' % ( addKommaToNumber(summary[0]), filesize(summary[1]) )
366  else:
367  key = data_key.ResultKey
368  val = addKommaToNumber(summary)
369  print ('%20s : %s' % (key,val))
370  duration = time() - self.querystart
371  print ("%20s : %g sec" % ('Total execution time',duration))
372  print ('---------------------------------------------------------------------')
373 
374  def finalize(self):
375  coolDbConn.CloseAll()
376 
377 if __name__ == '__main__':
378  from CoolRunQuery.AtlRunQueryOptions import AtlRunQueryOptions
379  (options, args) = AtlRunQueryOptions().parse()
380  rsq = AtlRunQuery(options)
381 
python.utils.AtlRunQueryUtils.get_runs_last_dt
def get_runs_last_dt(last)
Definition: AtlRunQueryUtils.py:590
python.utils.AtlRunQueryUtils.filesize
def filesize(no)
Definition: AtlRunQueryUtils.py:198
python.AtlRunQueryLib.AtlRunQuery.xmlFileName
xmlFileName
Definition: AtlRunQueryLib.py:73
CaloCellPos2Ntuple.int
int
Definition: CaloCellPos2Ntuple.py:24
python.utils.AtlRunQueryUtils.addKommaToNumber
def addKommaToNumber(no)
Definition: AtlRunQueryUtils.py:190
parse
std::map< std::string, std::string > parse(const std::string &list)
Definition: egammaLayerRecalibTool.cxx:1054
python.output.AtlRunQuerySave.CreateResultDict
def CreateResultDict(runlist)
Definition: AtlRunQuerySave.py:23
python.utils.AtlRunQueryUtils.GetTimeRanges
def GetTimeRanges(timeranges, intRepFnc=timeStringToSecondsUTC, maxval=1<< 30)
Definition: AtlRunQueryUtils.py:369
python.AtlRunQueryLib.AtlRunQuery.__init__
def __init__(self, options, readoracle=False, loglevel=1, html="AUTO", origQuery="", datapath='data', parsedstring="")
Definition: AtlRunQueryLib.py:37
python.AtlRunQueryLib.AtlRunQuery.origQuery
origQuery
Definition: AtlRunQueryLib.py:65
python.AtlRunQueryLib.AtlRunQuery.prodgrl
prodgrl
Definition: AtlRunQueryLib.py:121
python.AtlRunQueryLib.AtlRunQuery.finalize
def finalize(self)
Definition: AtlRunQueryLib.py:374
python.AtlRunQueryLib.AtlRunQuery.dqsumgrl
dqsumgrl
Definition: AtlRunQueryLib.py:170
python.utils.AtlRunQueryUtils.runsOnServer
def runsOnServer()
Definition: AtlRunQueryUtils.py:48
python.AtlRunQueryLib.AtlRunQuery.makeDQeff
makeDQeff
Definition: AtlRunQueryLib.py:72
python.utils.AtlRunQueryTimer.timer
def timer(name, disabled=False)
Definition: AtlRunQueryTimer.py:86
python.utils.AtlRunQueryUtils.get_run_range2
def get_run_range2(start, end=None)
Definition: AtlRunQueryUtils.py:623
python.AtlRunQueryLib.AtlRunQuery.querystart
querystart
Definition: AtlRunQueryLib.py:75
python.AtlRunQueryLib.AtlRunQuery.config
def config(self, options, readoracle, loglevel, html, origQuery, datapath, parsedstring)
Definition: AtlRunQueryLib.py:62
python.AtlRunQueryLib.AtlRunQuery.maxNumOfRuns
maxNumOfRuns
Definition: AtlRunQueryLib.py:68
plotBeamSpotVxVal.range
range
Definition: plotBeamSpotVxVal.py:195
python.AtlRunQuerySFO.SetOKSLinks
def SetOKSLinks(runlist)
The following function is used to get OKS info.
Definition: AtlRunQuerySFO.py:280
python.output.AtlRunQueryXML.CreateXMLFile
def CreateXMLFile(runlist, options, origQuery, datapath, xmlfname, xmllabel, svnversion='Unknown')
Definition: AtlRunQueryXML.py:74
histSizes.list
def list(name, path='/')
Definition: histSizes.py:38
python.AtlRunQueryLib.AtlRunQuery.makeDQPlots
makeDQPlots
Definition: AtlRunQueryLib.py:71
python.AtlRunQueryLib.AtlRunQuery.cmdlineOptions
cmdlineOptions
Definition: AtlRunQueryLib.py:64
python.AtlRunQueryLib.AtlRunQuery
Definition: AtlRunQueryLib.py:35
TCS::join
std::string join(const std::vector< std::string > &v, const char c=',')
Definition: Trigger/TrigT1/L1Topo/L1TopoCommon/Root/StringUtils.cxx:10
python.AtlRunQueryLib.AtlRunQuery.makeDQSummary
makeDQSummary
Definition: AtlRunQueryLib.py:70
python.AtlRunQuerySFO.GetSFO_lastNruns
def GetSFO_lastNruns(cursor, nruns)
Definition: AtlRunQuerySFO.py:267
python.AtlRunQueryLib.AtlRunQuery.evaluate
def evaluate(self, runlist)
Definition: AtlRunQueryLib.py:287
python.AtlRunQueryLib.AtlRunQuery.run
def run(self)
Definition: AtlRunQueryLib.py:185
Trk::open
@ open
Definition: BinningType.h:40
python.AtlRunQueryLib.AtlRunQuery.dbbtag
dbbtag
Definition: AtlRunQueryLib.py:180
python.AtlRunQueryLib.AtlRunQuery.html
html
Definition: AtlRunQueryLib.py:108
python.AtlRunQueryLib.AtlRunQuery.output
def output(self, runlist, dic, dicsum, xmlhtmlstr, roothtmlstr)
Definition: AtlRunQueryLib.py:319
python.AtlRunQueryLib.AtlRunQuery.parsedstring
parsedstring
Definition: AtlRunQueryLib.py:67
python.AtlRunQueryLib.AtlRunQuery.selectionOutput
selectionOutput
Definition: AtlRunQueryLib.py:76
dbg::print
void print(std::FILE *stream, std::format_string< Args... > fmt, Args &&... args)
Definition: SGImplSvc.cxx:70
python.AtlRunQueryLib.AtlRunQuery.xmlFileLabel
xmlFileLabel
Definition: AtlRunQueryLib.py:74
python.AtlRunQueryLib.AtlRunQuery.dictroot
dictroot
Definition: AtlRunQueryLib.py:128
python.output.AtlRunQueryRoot.CreateRootFile
def CreateRootFile(dic)
Definition: AtlRunQueryRoot.py:784
python.AtlRunQueryLib.AtlRunQuery.makeSummary
makeSummary
Definition: AtlRunQueryLib.py:69
Trk::split
@ split
Definition: LayerMaterialProperties.h:38