14 from functools
import reduce
17 from CoolRunQuery.utils.AtlRunQueryLookup
import InitDetectorMaskDecoder, DecodeDetectorMask, DQChannels
19 from DQDefects
import DefectsDB
22 dqFolderList = [
'SHIFTOFL',
'DQCALCOFL',
'DQMFOFL',
'DQMFOFLH',
'DCSOFL',
'TISUMM',
'LBSUMM',
'MUONCALIB',
23 'DQMFONL',
'DQMFONLLB',
'SHIFTONL' ]
33 self.
sortedKeys = [
"run",
"time",
"duration",
"events",
"allevents",
"projectTag",
"partition",
"readyforphysics",
34 "trigkeys",
"trigger",
"release",
35 "ami",
"magnets",
"larcond",
"db",
"ctag",
"lhc",
"lumi",
"dq",
36 "streams",
"detector",
"datasets",
"all",
"summary",
"dqeff",
"cosmics",
"heavyions" ]
39 'r(uns) [format: "run 91000", "runs 91000-92000", "runs 91000-(+)" (this run and all before (after))]',
""),
41 'all [format: only available as "show" option]',
""),
43 'summary [format: only available as "show" option]',
""),
45 'dqsum(mary) [format: only available as "show" option]',
""),
47 'dqpl(ots) [format: only available as "show" option]',
""),
49 'dqeff [format: only available as "show" option]',
""),
51 'ev(ents) [format: "events 10000+", ... (same as for run number)]',
""),
53 'alle(vents) [format: only available as "show" option]',
""),
55 't(ime) [format: "time 10.9.2008-30.9.2008", "time 15.10.2008-(+)" (this date and all before (after))]',
""),
57 'dur(ation) [format: "dur 10d/h/m/s+/-", "2000s+" (run duration more than 2000 sec), "dur 3h-" (less than 3 hours)]',
""),
59 'm(agnet) [format: "magnet s(olenoid)", "magnet t(oroid)", "not magnet t(oroid)", ...]',
""),
61 'det(ector) [format: "detector Pixel B" (for Pixel Barrel), "detector Pixel" (for Pixel B & EC), "all" (for all detectors, detector mask = 72551459979255)',
""),
63 'smk [format: "smk 398", "smk 398,399 (super-master-key labelling trigger menu, format like for run ranges)]',
""),
65 'trigk(eys) [format: "tkeys" (show all trigger keys of run: SMK, L1 and HLT prescale keys)]',
""),
67 'rel(ease) [format: "release 15.1.*" ',
""),
69 'ptag [format: "ptag data08_cos,data08_cosmag,data09_cos", "ptag data08_cos*,data09_cos" (note: the projectTag in dataset name / denoted "filenamtTag" in COOL)]',
"data0*,data1*,data2*"),
71 'p(artition) [format: "partition ATLAS"]',
"ATLAS"),
73 'ready(forphysics) [format: "readyforphysics T(rue)"]',
""),
75 'db [format: "db <DB>, where <DB> is either DATA, MC, COMP200, CONDBR2, or OFLP200',
""),
77 'ctag [format: "ctag COMCOND-HLTC-001-00" ',
""),
79 'st(reams) [format: "stream RPCwBeam,TGCwBeam", "stream physics*" ',
""),
81 'dq [format: "dq <FLAG> <status>", where the data quality status is "g(reen)", "y(ellow)", "r(ed)", "u(known)", example: dq PIXB y+ (means yellow or green status)]',
""),
83 'tr(igger) [format: "trigger *Electron*" ',
""),
85 'lu(minosity) [format: "lumi FOLDER", default: LBLESTOFL]" ',
""),
87 'olc [format: "olc" (OLC = Online Luminosity Calculator)]" ',
""),
89 'bs [format: "bs"]" ',
""),
91 'bpm [format: "show bpm"]" ',
""),
93 'da(tasets) [format: show datasets *NTUP*"]" ',
""),
95 'ami [format: show ami"]" ',
""),
97 'lar(cond) [format: larcond nsamples 7 / show larcond"]" ',
""),
99 'lhc [format: lhc fill 7 / show lhc"]" ',
""),
101 'trigr(ates) [format: sh trigrates L1_EM*"]" ',
""),
103 'dqsumgrl [format: "dqsumgrl PHYS_StandardGRL_All_Good_25ns", Define tolerable/intolerable defects for DQ summary relative to GRL or other virtual defect, default is PHYS_StandardGRL_All_Good_25ns]',
"PHYS_StandardGRL_All_Good_25ns"),
105 'cos(mics) [format: only available as "show" option]',
""),
107 'heavy(ions) [format: only available as "show" option]',
""),
109 'logictag [format: "logictag "HEAD", Define logic tag for defect database used for DQ summary relative to GRL or other virtual defect, default is "HEAD"]',
"HEAD"),
111 'defecttag [format: "defecttag "HEAD", Define defect tag for defect database used for DQ summary relative to GRL or other virtual defect, default is "HEAD"]',
"HEAD") }
119 print (
'Parser usage: python %s <string_argument>' % sys.argv[0])
121 print (
'A query starts with the keyword "f(ind)", several queries can be combined with "and", "(and) not"')
122 print (
'The requested response information is given through the keyword "sh(ow)" (the query must be terminated by a "/")')
124 print (
'Query words:')
128 print (
'Parts of a keyword written in paranthesis are optional')
132 print (
' find run 90272 and runs 90275-91900 and magnet toroid and magnet solenoid / show run and events')
133 print (
' f r 90272 and r 90275-91900 and m t and m s / sh r and ev [same as above in short-hand version]')
134 print (
' find runs 90275-91900 and not run 90280 and not dq EMEC r and show run and dq EMEC' )
138 return n.replace(
'k',
'000').
replace(
'm',
'000000')
143 ptag, period = name.split(
'.')
146 letter = period[period.find(
'period')+6:][0]
147 return ptag.strip(), period.strip(), letter
152 arg: 'run data10_7TeV.periodA' or 'run periodA' (where 'data11_7TeV' is assumed)
153 # or 'data10_7TeV.periodA-periodC' or 'data10_7TeV.periodA,data10_7TeV.periodB,...'
154 # This is case sensitive !!
156 arg = arg.split(
None,1)[1]
158 from CoolRunQuery.AtlRunQueryInterpretDataPeriods
import GetRuns
162 if len(list_of_runs)==0:
163 print (
"No runs matching pattern")
166 return "--run " +
','.
join([
str(r)
for r
in list_of_runs])
174 return "--" + atlqarg.strip() +
' "' + rge.strip().
replace(
' ',
'') +
'"'
181 return "--" + atlqarg.strip() +
' "' + rge.strip().
replace(
' ',
'') +
'"'
185 arg = arg.partition(
' ')[2]
186 arg = arg.replace(
'%',
'*')
187 arg = arg.strip().
replace(
' ',
'')
189 atlqarg = atlqarg.strip()
190 if atlqarg==
'db' and (arg==
'MC' or arg==
'OFLP'):
194 if atlqarg ==
'readyforphysics' and not arg:
198 if atlqarg ==
'dqsumgrl' and not arg:
199 arg =
'PHYS_StandardGRL_All_Good_25ns'
202 if atlqarg ==
'logictag' and not arg:
204 if atlqarg ==
'defecttag' and not arg:
207 return '--%s "%s"' % (atlqarg, arg)
211 cmd,sep,arg = arg.partition(
' ')
212 arg = arg.replace(
'%',
'*')
216 if cmd.lower() ==
'olc' and 'lumi' in arg.lower():
222 print (
'ERROR in argument of command "olc lumi": no argument given' )
226 if cmd.lower() ==
'lumi':
229 print (
'ERROR in argument of command "olc lumi": no argument given' )
233 if cmd.lower() ==
'lhc':
234 if 'stablebeams' in arg.lower():
235 arg,sep,val = arg.partition(
' ')
236 val = val.strip().
upper()
237 if val ==
'1' or val ==
'T':
239 elif val ==
'0' or val ==
'F':
241 elif val !=
'TRUE' and val !=
'FALSE':
242 print (
'ERROR in argument of command "lhc": "%s". Value must be boolean (true/false or 1/0)' % val)
246 atlqarg = atlqarg.strip()
247 if atlqarg==
'db' and (arg==
'MC' or arg==
'OFLP'):
250 return '--%s "%s"' % (atlqarg, arg)
254 arg = arg.split()[1:]
255 retstr =
"--" + atlqarg.strip() +
' "' + arg[0].
replace(
'%',
'*')
263 key, sep, arg = arg.partition(
' ')
264 units = {
'sec': 1,
's': 1,
'm': 60,
'h': 3600,
'd': 86400 }
266 for u, fac
in units.items():
268 arg = arg.replace(u,
'')
273 arg =
"%i%s" % (
int(arg.replace(sign,
'').strip())*fac,sign)
276 self.
ParseError(
"Unit missing in duration tag: '%s' - should be 's', 'm', 'h', or 'd'" % arg )
281 key, s, arg = arg.partition(
' ')
284 if arg.strip() ==
'':
285 self.
ParseError(
'Keyword "mag(net)" requires argument' )
299 self.
ParseError(
"cannot interpret of magnetic field: '%s'" % arg )
305 return "--" + atlqarg.strip() +
' "' + newarg.strip().
replace(
' ',
'') +
'"'
311 arglist = sys.argv[1].
split(
" ")
314 for idx, item
in enumerate(arglist):
315 if item ==
"logictag":
316 logictag = arglist[idx+1]
317 if item ==
"defecttag":
318 defecttag = arglist[idx+1]
322 if defecttag
not in [
'HEAD'] + ddb.defects_tags:
323 print(
'WARNING (DQGetFolder): The defined defect tag "%s" is not defined in defect database. Will use "HEAD" tag instead!' %(defecttag))
326 if logictag
not in [
'HEAD'] + ddb.logics_tags:
327 print(
'WARNING (DQGetFolder): The defined logic tag "%s" is not defined in defect database. Will use "HEAD" tag instead!' %(logictag))
330 ddb = DefectsDB(tag=(defecttag, logictag))
333 if logictag !=
"HEAD" and defecttag !=
"HEAD":
334 logic_revision =
int(logictag.split(
"-")[-1])
335 defect_part =
"-".
join(defecttag.split(
"-")[1:])
336 htag =
"DetStatus-v%02i-%s" % (logic_revision, defect_part)
339 """interpret dq show command
340 * args are all arguments after dq codeword
342 possible formats for 'dq args':
354 D is a komma-separated list of defects or DQ-flags or *, each optionally proceeded by a ! or followed by a (defect,defect,defect,...)
355 F an folder name [default DEFECTS]
356 T a cool tag [default HEAD]
358 If no folder is specified the new defects folder is used
361 d = {
'flag':
'',
'folder':
'',
'tag':
''}
364 m = re.match(
r'(?P<flag>[!.*\w,\-\$\\\]*?)\s*?(?P<folder>\w*)#(?P<tag>[\w-]*)', args)
366 m = re.match(
r'(?P<flag>[!\w,\-\$\\\]*?)\s*?(?P<folder>\w*)#(?P<tag>[\w-]*)', args)
368 m = re.match(
r'(?P<flag>[!\w,\-\$\\\]*)\s*(?P<folder>[\w-]*)', args)
371 d.update(m.groupdict())
373 flag = d[
'flag'].lower()
374 folder = d[
'folder'].
upper()
378 folder = flag.upper()
391 folder = folder + tag
393 return flag, folder, tag
399 args = arg.partition(
' ')[2]
402 flags, folder, tag = self.
DQGetFolder( args, allowWildCards =
True )
406 if folder.startswith(
'DEFECTS'):
409 return '--show "dq DEFECTS%s" ' % tag
412 return ' '.
join([
'--show "dq %s DEFECTS%s"' % (fl.upper(), tag)
for fl
in flags.split(
',')])
415 flags = flags.replace(
'lar',
'emba,embc,emeca,emecc,heca,hecc,fcala,fcalc' )
418 flags = flags.replace(
'tile',
'tigb,tilba,tilbc,tieba,tiebc' )
421 flags = flags.replace(
'trig',
'l1cal,l1mub,l1mue,l1ctp,trcal,trbjt,trbph,trcos,trele,trgam,trjet,trmet,trmbi,trmuo,trtau,tridt' )
426 for key, dqchan
in dqitems:
427 newarg +=
'--show "dq %s %s" ' % (dqchan, folder)
430 argList = flags.split(
',')
432 a = a.strip().lower()
434 newarg +=
'--show "dq %s %s" ' % (a.upper(), folder)
436 for key, dqchan
in dqitems:
439 if dc[0:2]==
"tr" and dc[2]!=
't':
440 newarg +=
'--show "dq %s %s" ' % (dqchan, folder)
443 newarg +=
'--show "dq %s %s" ' % (dqchan, folder)
454 args = args.split()[1:]
456 hasColor = len(args)>0
and re.match(
'(n.a.|u|r|y|g|b)[+-]{0,1}$',args[-1].lower())
466 useAny = len(args)>0
and (args[0] ==
'any')
475 if folder.startswith(
'DEFECTS'):
477 newarg =
"--dq !ANY " + folder
480 dqchans = flags.upper().
split(
',')
484 for dqchan
in dqchans:
489 self.
ParseError(
'DQ flags need to be assigned a value ("n.a.", "u", "g", "y", "r"), eg, "dq PIXB,TIL yellow+" or "dq g"' )
492 flags = flags.replace(
'lar',
'emba,embc,emeca,emecc,heca,hecc,fcala,fcalc' )
493 flags = flags.replace(
'tile',
'tigb,tilba,tilbc,tieba,tiebc' )
494 flags = flags.replace(
'trig',
'l1cal,l1mub,l1mue,l1ctp,trcal,trbjt,trbph,trcos,trele,trgam,trjet,trmet,trmbi,trmuo,trtau,tridt' )
500 dqchans = [y
for (x,y)
in dqitems]
504 for dqchan
in dqchans:
510 for a
in flags.upper().
split(
','):
515 tmpdqchans = [dqchan
for (k,dqchan)
in dqitems
if a
in dqchan]
516 if 'LUMI' == a
and 'LUMIONL' in tmpdqchans:
517 tmpdqchans.remove(
'LUMIONL')
518 if 'IDVX' == a
and 'MMUIDVX' in tmpdqchans:
519 tmpdqchans.remove(
'MMUIDVX')
520 if len(tmpdqchans)==0:
521 self.
ParseError(
'Unknown DQ channel: "%s"' % a )
522 dqchans += tmpdqchans
527 for dqchan
in dqchans:
539 self.
ParseError(
'ERROR in DQ argument: "%s" --> need <Flag> AND <Status> (len is: %i)' % (atlqarg, len(args)) )
540 flag, col, folder = args
546 if not folder.startswith(
'DEFECTS'):
560 self.
ParseError(
'ERROR in DQ argument: "%s" --> uknown status: %s' % (args, col) )
581 self.
ParseError(
'ERROR in DQ argument: "%s" --> uknown status: %s' % (atlqarg, col) )
584 return "--" + atlqarg.strip() +
' "' + flag +
' ' + trcol +
' ' + folder +
'"'
587 arg = (arg.partition(
' ')[2]).lower().strip()
590 arg = arg.replace(
'any',
'').strip()
596 for sarg
in arg.split(
","):
597 for i
in range(0,len(self.dName)):
599 if i
in self.vetoedbits:
603 d = self.dName[i].lower() + self.NotInAll[i]
604 if not (
'unknown' in d
or 'removed' in d):
606 if (sarg ==
'all' and 'NotInAll' not in d)
or sarg
in d:
611 print (
'ERROR: could not find detector: "%s" in detector list' % arg)
613 print (
'Note: search is case INSENSITIVE')
623 return "--" + atlqarg +
' "%i%s' % (mask,anyflag) +
'"'
627 print (
'ERROR in argument: "%s"' % self.
const_arg)
628 print (
"%s" % errtext)
636 shortNoPar = short.replace(
'(',
'').
replace(
')',
'')
638 short = short[:short.find(
'(')]
639 matchesArg = shortNoPar.startswith(arg.lower())
and arg.lower().startswith(short)
646 firstword, findarg = findarg.split(
None,1)
647 if not 'find'.startswith(firstword):
648 self.
ParseError(
"Argument must begin with 'f(ind)'", 0 )
650 argList = [x.strip()
for x
in findarg.split(
" and ")]
658 arg = arg.replace(
"not",
"").strip()
663 self.
ParseError(
"Could not find predefined keyword for arg: '%s' in 'find' block" % (arg) )
665 short, atlqarg, function = self.
queryArgs[key][0:3]
666 newarg += function( atlqarg, arg, negation ) +
' '
673 arglist = self.
default_show + [a.strip()
for a
in showarg.split(
' and ')
if a.strip()!=
'']
677 idx = arglist.index(
'all')
678 arglist[idx:idx+1] = [
'ready',
'lhc',
'trigk',
'rel',
'streams',
'det']
680 if 'summary' in arglist:
681 arglist += [
'dur',
'allev',
'str',
'dq']
683 if any([arg.startswith(
'lhc')
for arg
in arglist]):
686 tmpArgList = [arg.startswith(
'dqsum')
or arg.startswith(
'dqpl')
for arg
in arglist]
688 idx = tmpArgList.index(
True)
689 arglist[idx+1:idx+1] = [
'ready',
'lumi',
'lhc stablebeams',
'dq',
'ptag',
'trigrates L1_EM30',
'trigrates L1_EM5',
'trigrates L1_EM12']
696 self.
ParseError(
"Could not find predefined keyword for arg: '%s' in 'show' block" % (arg) )
699 (short, atlqarg, dummy, function) = self.
queryArgs[key][0:4]
700 newarg += function( atlqarg, short, arg )
706 return '--show ' + atlqarg +
' '
709 if len(arg.split())==1:
711 return '--show olclumi --show olclbdata --show olcfillparams '
712 elif atlqarg ==
'luminosity':
713 return '--show "lhc min" --show "%s 0" ' % (atlqarg)
715 return '--show %s ' % atlqarg
718 return '--show "olclumi %s" --show olcfillparams --show olclbdata ' % arg.partition(
' ')[2]
719 elif atlqarg ==
'luminosity':
720 return '--show "lhc min" --show "%s %s" ' % (atlqarg, arg.partition(
' ')[2])
722 return '--show "%s %s" ' % (atlqarg, arg.partition(
' ')[2])
727 if len(showargs.split(
'lhc')) >= 3:
728 showargs = showargs.replace(
'--show "lhc min"',
'')
731 duples = [
'--show %s' % d.strip()
for d
in showargs.split(
'--show')
if d.strip()!=
'']
732 uniques =
reduce(
lambda first, second: (second
not in first
and first.append(second))
or first, duples, [])
733 showargs =
' '.
join(uniques)
743 findarg, showarg, otherarg = [x.strip()
for x
in (self.
const_arg.
split(
'/')+[
'',
''])[0:3]]
747 if showarg[0:2] !=
'sh':
748 self.
ParseError(
"Show block must begin with 'sh(ow)'", 0 )
749 showarg = showarg[showarg.index(
' ')+1:]
751 if ' sh ' in findarg
or ' sho ' in findarg
or ' show ' in findarg:
752 self.
ParseError(
"Show block must be separated by '/' from find condition'", 0 )
760 if '--olclumi' in queryarg
and 'stablebeams' not in queryarg:
761 queryarg +=
'--lhc "stablebeams TRUE" '
767 oargs = otherarg.split()
769 extraargs = {
'verbose' :
'--verbose'}
771 while idx < len(oargs):
774 extraargs[
'verbose'] =
'--verbose'
776 extraargs[
'noroot'] =
'--noroot'
778 extraargs[
'root'] =
'--root'
780 extraargs[
'nohtml'] =
'--nohtml'
782 extraargs[
'html'] =
'--html'
784 extraargs[
'utc'] =
'--utc'
786 extraargs[
'nogrl'] =
'--nogrl'
787 elif oa ==
'grl' or oa ==
'xmlfile':
788 extraargs[
'xmlfile'] =
'--xmlfile MyLBCollection.xml:MyLBCollection'
791 elif idx>0
and (oargs[idx-1]==
'grl' or oargs[idx-1]==
'xmlfile'):
792 extraargs[
'xmlfile'] =
'--xmlfile %s' % oa
794 print (
"Extra argument '%s' unknown. Exiting." % oa)
798 if 'verbose' in extraargs:
800 print (
' find argument: "%s"' % findarg.strip())
801 print (
' show argument: "%s"' % showarg.strip())
802 print (
' extra argument: "%s"' % otherarg.strip())
810 for key, argument, defaultvalue
in [ (x[0],x[1][1],x[1][5])
for x
in self.
queryArgs.
items()]:
811 if argument
not in queryarg
and defaultvalue !=
"":
812 queryarg +=
" --" + argument +
' "' + defaultvalue +
'"'
814 extraarg =
' '.
join(extraargs.values())
816 fullarg =
'%s %s %s' % (queryarg, shwarg, extraarg)
822 if __name__==
'__main__':
827 if len(sys.argv) <= 1:
828 print (
'No query argument given')
831 if sys.argv[1].lower() ==
'detmask':
832 print (
'Detector mask %s correspond to:\n%s' % (sys.argv[2],
DecodeDetectorMask(
int(sys.argv[2] ))))
835 if sys.argv[1].lower() ==
'help':
839 atlqueryarg = ap.ParseArgument(
' '.
join(sys.argv[1:]) )
840 print (
"\nAtlRunQuery.py %s\n" % atlqueryarg)