4 from CoolRunQuery.selector.AtlRunQuerySelectorBase
import Selector, RunLBBasedCondition, OOO
5 from CoolRunQuery.utils.AtlRunQueryIOV
import IOVRange
6 from CoolRunQuery.utils.AtlRunQueryUtils
import coolDbConn
7 from CoolRunQuery.utils.AtlRunQueryLookup
import DQChannel
9 from collections
import defaultdict, namedtuple
11 DQDefectPayload = namedtuple(
"DQDefectPayload",
"defect comment user ignore primary tolerable recoverable")
12 DQDefectPayload.pickled = DQDefectPayload._asdict
14 DD = namedtuple(
"DD",
"description comment since until")
18 yield OOO(obj.channel, (
str(obj.Code),obj.Comment), IOVRange(starttime=obj.since, endtime=obj.until),
True)
22 super(DQSelector,self).
__init__(name)
25 from CoolRunQuery.AtlRunQuerySelectorWorker
import SelectorWorker
26 SelectorWorker.getRetrieveSelector(
'readyforphysics',
'ReadyForPhysicsSelector')
30 cf = chanAndfolder.split()
36 return (channel,folder)
41 if folder.startswith(
'DEFECTS'):
49 dq can be e.g. ['EMBA yellow SHIFTOFL', 'FCALA green+ DQMFOFL', 'EMBA,EMBC,EMECA,EMECC yellow+ SHIFTOFL']
50 this example should be translated into two selectors, one for each of the folders 'SHIFTOFL' and 'DQMFOFL'
52 folderCriteria = defaultdict(list)
55 folderCriteria[s[-1]].
append(s[:-1])
56 for f
in folderCriteria.keys():
57 if f.startswith(
'DEFECTS'):
59 self.
selectors[f].addSelectionChannels(folderCriteria[f])
67 condition.addShowChannel(folder, channel,
'HEAD')
89 runlist = sel.select(runlist)
94 sel.runAfterQuery(runlist)
100 code = {
'unknown': 0,
'red': 1,
'yellow': 2,
'green': 3,
'black': -1}
101 color = {
'n.a.':
'n.a.',
'0':
'U',
'1':
'R',
'2':
'Y',
'3':
'G',
'-1':
'B'}
102 invert = {
'n.a.': -2,
'B': -1,
'U': 0,
'R': 1,
'Y': 2,
'G': 3 }
114 dbname =
'COOLOFL_GLOBAL'
116 dbname =
'COOLONL_GLOBAL'
125 self.
flags += [(x+[
''])[1]]
151 super(DQCondition,self).
__init__(name=name,
152 dbfolderkey=
'%s::/GLOBAL/DETSTATUS/%s' % (dbname, self.
foldername),
153 channelKeys = channelKeys)
156 for flag
in self.
flags:
161 d[
'passFncName'] =
''
164 d[
'passFnc'] =
lambda x: x==-2
165 d[
'passFncName'] =
"x=='n.a.'"
166 elif flag[-1]
in '+-':
167 cd = self.
code[flag[:-1].lower()]
171 d[
'passFnc'] =
lambda x:
int(x)>=-1
173 d[
'passFnc'] =
lambda x:
int(x)>=0
175 d[
'passFnc'] =
lambda x:
int(x)>=1
177 d[
'passFnc'] =
lambda x:
int(x)>=2
179 d[
'passFnc'] =
lambda x:
int(x)>=3
180 d[
'passFncName'] =
"x>='%i'" % d[
'refVal']
183 d[
'passFnc'] =
lambda x:
int(x)<=-1
185 d[
'passFnc'] =
lambda x:
int(x)<=0
187 d[
'passFnc'] =
lambda x:
int(x)<=1
189 d[
'passFnc'] =
lambda x:
int(x)<=2
191 d[
'passFnc'] =
lambda x:
int(x)<=3
192 d[
'passFncName'] =
"x<='%i'" % d[
'refVal']
194 cd = self.
code[flag.lower()]
197 d[
'passFnc'] =
lambda x:
int(x)==-1
199 d[
'passFnc'] =
lambda x:
int(x)==0
201 d[
'passFnc'] =
lambda x:
int(x)==1
203 d[
'passFnc'] =
lambda x:
int(x)==2
205 d[
'passFnc'] =
lambda x:
int(x)==3
206 d[
'passFncName'] =
"x=='%i'" % d[
'refVal']
214 from CoolRunQuery.AtlRunQueryRun
import RunData
218 f = coolDbConn.GetDBConn(schema = self.schema,db=Selector.condDB()).getFolder(self.folder)
222 if f.versioningMode()==0:
224 if self.
tagname not in [
"HEAD",
""]:
231 objs =
vfgen(f.browseObjects( iovmin, iovmax, channels, self.
tagname ))
233 objs = super(DQCondition,self).
_retrieve(iovmin, iovmax, f, sortedRanges)
237 dqname = dqfullname.split(
':')[-1].
split(
'#')[0]
240 return self.
vfl.get_logic_list()[dqname].record.channel
241 except AttributeError:
242 return self.
vfl.get_logic_list()[dqname].channel
246 for i
in range(len(dqlist)):
247 dqs = dqlist[i][0].
split(
',')
254 dqlist[i][0] =
','.
join(newdqs)
258 vflags = vfl.get_logic_list().
keys()
259 useprimaries = cpflag[-1]==
'+'
260 cpflag=cpflag.rstrip(
'+')
270 if vf.startswith(cpflag):
277 raise RuntimeError(
"Virtual Flag pattern %s does not match any virtual flag: %r" % (cpflag, vfl.get_logic_list().
keys()))
286 from VirtualFlags
import VirtualFlagLogicFolder, VirtualFlagFolder
288 print (
"Can't import virtual flags")
290 traceback.print_exc()
293 self.
vfl = VirtualFlagLogicFolder(coolDbConn.GetDBConn(schema=schema, db=db))
299 from CoolRunQuery.AtlRunQueryRun
import Run
300 if cpflag
in Run.Fieldinfo:
302 Run.Fieldinfo[cpflag] =
'<strong><b>%s</b></strong><br><table width="300"><tr><td>%s</td></tr></div>' % \
303 (self.
vfl.get_logic_list()[cpflag].comment,
307 return self.
vfl.resolve_primary_flags(self.
vfl.resolve_dependancies([cpflag]))
317 tmplist = [[channelname,
'']]
320 for shch
in tmplist[0][0].
split(
','):
325 ssr = self.DoSelectShowRetrieve()
342 self.setChannelKeys(channelKeys,ssr)
345 if self.applySelection:
346 s =
"SELOUT Checking in the DQ folder %s" % self.
foldername
347 flagCh = defaultdict(list)
349 flagCh[flag].
append(
'(' +
' or '.
join(ch) +
')')
351 chlist =
' and '.
join(flagCh[flag])
352 s +=
"\nSELOUT %s is %r" % (chlist, flag)
359 if isinstance(values,tuple):
376 for k
in self.ResultKey():
378 for entry
in run.data[k]:
380 dqres = v[0]
if type(v)==tuple
else v
381 dqcode = self.
invert[dqres]
382 entry.rejected =
not passfnc( dqcode )
383 return super(DQCondition,self).
rejectRun(run)
388 if type(value)==tuple:
389 return (self.
color[value[0]], value[1])
391 return self.
color[value]
394 dqs = [
'G',
'Y',
'R',
'B',
'U',
'n.a.']
396 for k
in self.ResultKey():
402 for entry
in run.data[k]:
404 if entry.value ==
'n.a.':
405 dq, dqcomment = (
'n.a.',
'')
407 dq, dqcomment = entry.value
409 dq, dqcomment = (entry.value,
None)
412 if entry.startlb == 0:
414 if len(blocks) > 0
and blocks[-1][0]==(dq,dqcomment)
and blocks[-1][2]==entry.startlb:
415 blocks[-1][2] = entry.endlb
417 blocks += [ [(dq, dqcomment), entry.startlb, entry.endlb] ]
419 maxn =
max(n.values())
426 run.stats[k] = {
"counts" : n,
"max": dqmax,
"blocks": blocks }
437 super(DQDefectCondition,self).
__init__(name=name,
438 dbfolderkey =
'COOLOFL_GLOBAL::%s' % self.
foldername,
439 channelKeys = [(
'DQDEFECT',
'DQ',(
'Code',
'Comment'))])
441 self.data_keys[0]._second_internal_key = self.tagname
444 from CoolRunQuery.AtlRunQueryRun
import RunData
445 RunData.DefectSelector = self.
_pass
446 self.
__db = coolDbConn.GetDBConn(
'DEFECTS',self.tagname)
453 if x.value.ignore
is None:
454 these_defects += [x.value.defect]
456 these_defects += [x.value.defect+
'\\'+x.value.ignore]
464 passes = kk
not in these_defects
466 passes = k
in these_defects
482 newlitem.append(
'!' + db.normalize_defect_names(k[1:]))
484 newlitem.append(db.normalize_defect_names(k))
485 newl.append(newlitem)
491 """ based on the patterns in the list channel_name_patterns create a
492 list of pairs of patterns and matching defects ( pattern, set(matching defects) )
493 and attach it to the global Run.FieldInfo dictionary under 'DQ'
495 from re
import compile
496 from CoolRunQuery.AtlRunQueryRun
import Run
497 if 'DQ' not in Run.Fieldinfo:
498 Run.Fieldinfo[
'DQ'] = {}
499 if 'DefMatch' not in Run.Fieldinfo[
'DQ']:
500 Run.Fieldinfo[
'DQ'][
'DefMatch'] = []
501 Run.Fieldinfo[
'DQ'][
'IntolerableDefects'] = db.get_intolerable_defects(old_primary_only=
False)
503 for pattern
in channel_name_patterns:
504 if pattern.upper() !=
'DET':
505 cpattern = compile(pattern)
506 channelnames =
set(
filter(cpattern.match,db.defect_names))
507 channelnames.update(
filter(cpattern.match,db.virtual_defect_names))
509 channelnames =
set([d
for d
in db.defect_names
if '_' not in d])
510 channelnames.update([d
for d
in db.virtual_defect_names
if '_' not in d])
511 matches.update(channelnames)
512 Run.Fieldinfo[
'DQ'][
'DefMatch'] += [(pattern,channelnames)]
519 since = (runmin,iovmin&0xFFFFFFFF)
520 until = (runmax,iovmax&0xFFFFFFFF)
529 channels_with_ignore = {}
531 channels.update([x.lstrip(
'!')
for x
in selChans
if '\\' not in x])
536 if ignore_str
not in channels_with_ignore:
537 channels_with_ignore[ignore_str] = []
538 channels_with_ignore[ignore_str] += [channel.lstrip(
'!')]
541 if len(channels) + len(channels_with_ignore)==0:
545 if 'ANY' in channels:
546 channels.remove(
'ANY')
548 res = []
if len(channels)==0
else [ (db.retrieve(since=since, until=until, channels=channels, ignore=self.
global_ignore, with_primary_dependencies=
True).trim_iovs,
None) ]
551 for _ignore_str, _channels
in channels_with_ignore.items():
552 ignore =
set(_ignore_str.split(
'\\'))
555 res += [ (db.retrieve(since=since, until=until, channels=_channels, ignore=ignore, with_primary_dependencies=
True).trim_iovs, _ignore_str) ]
557 return self.
defgen(db, res, channels, channels_with_ignore)
561 def defgen(self, db, defects_with_ignore, channels, channels_with_ignore):
563 defects: list of defects returned by query
564 channels: explicit list of channels that matched the pattern
566 intolerableDefects = db.get_intolerable_defects(old_primary_only=
False)
567 for defects, ignore
in defects_with_ignore:
568 chanlist = channels
if ignore
is None else channels_with_ignore[ignore]
572 isVirtual = (d.user ==
'sys:virtual')
579 if d.channel
not in chanlist:
583 user = d.user, primary =
not isVirtual,
585 tolerable = (d.channel
not in intolerableDefects),
586 recoverable = d.recoverable)
592 o =
OOO(
"DQDEFECT", defPayload, IOVRange(starttime=d.since.real, endtime=d.until.real),
True)
602 if '\\' not in requirement:
604 x = requirement.split(
'\\')
610 for channels,flag
in dq:
612 prefix =
'!' if flag ==
'green' else ''
613 for x
in channels.split(
','):
624 from CoolRunQuery.AtlRunQueryRun
import Run
625 if 'DQ' not in Run.Fieldinfo:
626 Run.Fieldinfo[
'DQ'] = {}
627 if 'DefChannels' not in Run.Fieldinfo[
'DQ']:
628 Run.Fieldinfo[
'DQ'][
'DefChannels'] = []
629 Run.Fieldinfo[
'DQ'][
'DefChannels'] += [channelname]
633 if self.applySelection:
642 return super(DQDefectCondition,self).
rejectRun(run)
645 """ two adjacent defect entries are merged into one"""
650 (openedat,openuntil) = (x.startlb,x.endlb)
652 if x.startlb == openuntil:
655 mergedByDefect += [(openedat, openuntil)]
656 openedat,openuntil = x.startlb,x.endlb
657 mergedByDefect += [(openedat, openuntil)]
658 return mergedByDefect
660 return [(x.startlb,x.endlb)
for x
in it]
666 collects, sorts, and groups defects with LBs and comments
668 from itertools
import groupby
669 from operator
import attrgetter
673 for k
in self.ResultKey():
679 if k
not in run.data.keys():
683 all_defects =
sorted(
list(
set([x.value[0]
for x
in run.data[k]])))
685 grouped_defects = groupby(
sorted(run.data[k],key=
lambda x: x.value[0]),key =
lambda x: x.value[0])
687 desired_defects = [ (defect_name, self.
mergeRanges(lblist))
for defect_name, lblist
in grouped_defects ]
689 run.stats[k] = {
"defects": desired_defects,
694 primgroups = groupby(
sorted([p
for p
in self.
primaries[run.runNr]],key=attrgetter(
'channel')),key=attrgetter(
'channel'))
695 primaries = dict([(p,
list(l))
for p,l
in primgroups])
697 for defect
in all_defects:
698 if self.
__db.defect_is_virtual(defect):
700 self.
find_primaries(DD, self.
__db.virtual_defect_logics[defect], primaries, defect, reps)
701 run.stats[k][
"primaries"][defect] = reps
702 elif defect
in primaries:
703 run.stats[k][
"primaries"][defect] = [
DD(
"->%s" % def_obj.channel, def_obj.comment, def_obj.since.lumi, def_obj.until.lumi)
for def_obj
in primaries[defect] ]
718 for pdef
in defect_logic.primary_defects:
719 if pdef
not in primaries:
721 pdefects = primaries[pdef]
722 for pdeflb
in pdefects:
723 reps += [
DD(
"%s->%s" % (curpath, pdeflb.channel), pdeflb.comment, pdeflb.since.lumi, pdeflb.until.lumi) ]
724 for dep
in defect_logic.dependencies:
725 self.
find_primaries(DD, dep, primaries, curpath+
"->"+dep.name, reps)