ATLAS Offline Software
AtlRunQuerySelectorDQ.py
Go to the documentation of this file.
1 # Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
2 
3 
4 from __future__ import print_function
5 from CoolRunQuery.selector.AtlRunQuerySelectorBase import Selector, RunLBBasedCondition, OOO
6 from CoolRunQuery.utils.AtlRunQueryIOV import IOVRange
7 from CoolRunQuery.utils.AtlRunQueryUtils import coolDbConn
8 from CoolRunQuery.utils.AtlRunQueryLookup import DQChannel
9 
10 from collections import defaultdict, namedtuple
11 
12 DQDefectPayload = namedtuple("DQDefectPayload", "defect comment user ignore primary tolerable recoverable")
13 DQDefectPayload.pickled = DQDefectPayload._asdict
14 
15 DD = namedtuple("DD","description comment since until")
16 
17 def vfgen(vfobjs):
18  for obj in vfobjs:
19  yield OOO(obj.channel, (str(obj.Code),obj.Comment), IOVRange(starttime=obj.since, endtime=obj.until), True)
20 
21 class DQSelector(Selector):
22  def __init__(self, name='dataquality'):
23  super(DQSelector,self).__init__(name)
24  self.selectors = {}
25 
26  from CoolRunQuery.AtlRunQuerySelectorWorker import SelectorWorker
27  SelectorWorker.getRetrieveSelector('readyforphysics','ReadyForPhysicsSelector')
28 
29 
30  def __getChannelAndFolder(self, chanAndfolder):
31  cf = chanAndfolder.split()
32  if len(cf)==1:
33  channel=''
34  folder=cf[0]
35  else:
36  channel, folder = cf
37  return (channel,folder)
38 
39  def __getCondition(self, folder):
40  if folder in self.selectors:
41  return self.selectors[folder]
42  if folder.startswith('DEFECTS'):
43  self.selectors[folder] = DQDefectCondition(self.name+"DEFECTS", folder)
44  else:
45  self.selectors[folder] = DQCondition(self.name+folder, folder, [])
46  return self.selectors[folder]
47 
48  def addSelectionChannel(self, dq=[]):
49  """
50  dq can be e.g. ['EMBA yellow SHIFTOFL', 'FCALA green+ DQMFOFL', 'EMBA,EMBC,EMECA,EMECC yellow+ SHIFTOFL']
51  this example should be translated into two selectors, one for each of the folders 'SHIFTOFL' and 'DQMFOFL'
52  """
53  folderCriteria = defaultdict(list)
54  for x in dq:
55  s = x.split()
56  folderCriteria[s[-1]].append(s[:-1])
57  for f in folderCriteria.keys():
58  if f.startswith('DEFECTS'):
59  self.selectors[f] = DQDefectCondition(self.name+"DEFECTS", f )
60  self.selectors[f].addSelectionChannels(folderCriteria[f])
61  else:
62  self.selectors[f] = DQCondition(self.name+f, f, folderCriteria[f])
63 
64 
65  def addShowChannel(self, chanAndfolder):
66  (channel,folder) = self.__getChannelAndFolder(chanAndfolder)
67  condition = self.__getCondition(folder)
68  condition.addShowChannel(folder, channel, 'HEAD')
69 
70  def setShowOutput(self):
71  for sel in self.selectors.values():
72  sel.setShowOutput()
73 
74 
75  def __str__(self):
76  s = ""
77  for sel in self.selectors.values():
78  s += "\n%s" % sel
79  return s
80 
81 
82  def select(self, runlist):
83  # garbage collector
84  # import gc
85  # gcod = gc.get_objects()
86  # print ("GC objects",len(gcod))
87  # print ("GC object count",gc.get_count())
88 
89  for sel in self.selectors.values():
90  runlist = sel.select(runlist)
91  return runlist
92 
93  def runAfterQuery(self,runlist):
94  for sel in self.selectors.values():
95  sel.runAfterQuery(runlist)
96 
97 
98 
99 class DQCondition(RunLBBasedCondition):
100 
101  code = {'unknown': 0, 'red': 1, 'yellow': 2, 'green': 3, 'black': -1}
102  color = {'n.a.': 'n.a.', '0': 'U', '1': 'R', '2': 'Y', '3': 'G', '-1': 'B'}
103  invert = {'n.a.': -2, 'B': -1, 'U': 0, 'R': 1, 'Y': 2, 'G': 3 }
104 
105  def __init__(self, name, foldername, dq):
106 
107  self.foldername = foldername
108  self.channelNames = []
110  self.channels = []
111  self.channelsflat = []
112  self.flags = []
113  self.useVirtualFlags = False
114 
115  dbname = 'COOLOFL_GLOBAL'
116  if 'ONL' in self.foldername:
117  dbname = 'COOLONL_GLOBAL'
118 
119  # set up virtual flag logic folder and expand wild cards for VF in dq
120  self.GetVirtualFlagsExpanded(dq, Selector.compDB(), dbname)
121 
122  for x in dq:
123  ch = x[0].split(',')
124  self.channelNames += [["%s:%s" % (self.foldername,chn) for chn in ch]]
125  self.channels += [[self.DQChannel(chn) for chn in ch]]
126  self.flags += [(x+[''])[1]]
127 
128  for chN in self.channelNames:
129  self.channelNamesFlat += chN
130  for ch in self.channels:
131  self.channelsflat += ch
132 
133  self.channelCommentsFlat = [n+"_m" for n in self.channelNamesFlat]
134 
135  # choose DB based on foldername
136 
137  # out of 'SHIFTOFL', 'DQCALCOFL', 'DQMFOFL', 'DQMFOFLH', 'DCSOFL', 'TISUMM', 'LBSUMM', 'MUONCALIB', 'DQMFONL', 'SHIFTONL'
138  # these ones have a comment field
139 
140  self.folderHasComment = ( (self.foldername == "SHIFTOFL") or (self.foldername.startswith("SHIFTOFL#")) or
141  (self.foldername == "LBSUMM") or (self.foldername.startswith("LBSUMM#")) or
142  (self.foldername == "DQCALCOFL") or (self.foldername.startswith("DQCALCOFL#")) or
143  (self.foldername.startswith("MUONCALIB#")) )
144 
145  # channel keys:
146  # [Code (Int32) : 1], [deadFrac (Float) : 0], [Thrust (Float) : 0], [Comment (String255) : "warm start"]
147  if self.folderHasComment:
148  channelKeys = zip(self.channelsflat, self.channelNamesFlat, len(self.channelsflat)*[('Code','Comment')])
149  else:
150  channelKeys = zip(self.channelsflat, self.channelNamesFlat, len(self.channelsflat)*['Code'])
151 
152  super(DQCondition,self).__init__(name=name,
153  dbfolderkey='%s::/GLOBAL/DETSTATUS/%s' % (dbname, self.foldername),
154  channelKeys = channelKeys)
155 
156  self.flagInterpreter = {}
157  for flag in self.flags:
158  self.flagInterpreter[flag] = {}
159  d = self.flagInterpreter[flag]
160  d['refVal'] = None
161  d['passFnc'] = None
162  d['passFncName'] = ''
163 
164  if flag=='n.a.':
165  d['passFnc'] = lambda x: x==-2
166  d['passFncName'] = "x=='n.a.'"
167  elif flag[-1] in '+-':
168  cd = self.code[flag[:-1].lower()]
169  d['refVal'] = cd
170  if flag[-1]=='+':
171  if cd == -1:
172  d['passFnc'] = lambda x: int(x)>=-1
173  elif cd == 0:
174  d['passFnc'] = lambda x: int(x)>=0
175  elif cd == 1:
176  d['passFnc'] = lambda x: int(x)>=1
177  elif cd == 2:
178  d['passFnc'] = lambda x: int(x)>=2
179  elif cd == 3:
180  d['passFnc'] = lambda x: int(x)>=3
181  d['passFncName'] = "x>='%i'" % d['refVal']
182  else:
183  if cd == -1:
184  d['passFnc'] = lambda x: int(x)<=-1
185  elif cd == 0:
186  d['passFnc'] = lambda x: int(x)<=0
187  elif cd == 1:
188  d['passFnc'] = lambda x: int(x)<=1
189  elif cd == 2:
190  d['passFnc'] = lambda x: int(x)<=2
191  elif cd == 3:
192  d['passFnc'] = lambda x: int(x)<=3
193  d['passFncName'] = "x<='%i'" % d['refVal']
194  else:
195  cd = self.code[flag.lower()]
196  d['refVal'] = cd
197  if cd == -1:
198  d['passFnc'] = lambda x: int(x)==-1
199  elif cd == 0:
200  d['passFnc'] = lambda x: int(x)==0
201  elif cd == 1:
202  d['passFnc'] = lambda x: int(x)==1
203  elif cd == 2:
204  d['passFnc'] = lambda x: int(x)==2
205  elif cd == 3:
206  d['passFnc'] = lambda x: int(x)==3
207  d['passFncName'] = "x=='%i'" % d['refVal']
208 
209  self.passSpecs = {}
210  for chgrp, flag in zip(self.channelNames,self.flags):
211  for ch in chgrp:
212  self.passSpecs[ch] = self.flagInterpreter[flag]
213 
214  def _getFolder(self):
215  from CoolRunQuery.AtlRunQueryRun import RunData
216  RunData.DQLogic = self.channelNames
217  RunData.DQKeys = self.channelNamesFlat
218 
219  f = coolDbConn.GetDBConn(schema = self.schema,db=Selector.condDB()).getFolder(self.folder)
220  if self.useVirtualFlags:
221  f = self.VirtualFlagFolder(f)
222  else:
223  if f.versioningMode()==0:
224  self.tagname=""
225  if self.tagname not in ["HEAD", ""]:
226  self.tagname = f.resolveTag(self.tagname)
227  return f
228 
229  def _retrieve(self, iovmin, iovmax, f, sortedRanges):
230  if self.useVirtualFlags:
231  channels = [x.lower().split(':')[-1] for x in self.channelNamesFlat]
232  objs = vfgen(f.browseObjects( iovmin, iovmax, channels, self.tagname ))
233  else:
234  objs = super(DQCondition,self)._retrieve(iovmin, iovmax, f, sortedRanges)
235  return objs
236 
237  def DQChannel(self,dqfullname):
238  dqname = dqfullname.split(':')[-1].split('#')[0]
239  if self.useVirtualFlags and dqname in self.vfl.get_logic_list().keys():
240  try:
241  return self.vfl.get_logic_list()[dqname].record.channel
242  except AttributeError:
243  return self.vfl.get_logic_list()[dqname].channel
244  return DQChannel(dqname)
245 
246  def GetVirtualFlagsExpanded(self, dqlist, db, schema):
247  for i in range(len(dqlist)):
248  dqs = dqlist[i][0].split(',')
249  newdqs = []
250  for c in dqs:
251  if '_' in c:
252  newdqs += self.ExpandVFlag(c,db,schema)
253  else:
254  newdqs.append(c)
255  dqlist[i][0] = ','.join(newdqs)
256 
257  def ExpandVFlag(self, cpflag, db, schema):
258  vfl = self.GetVirtualFlagLogic(db, schema)
259  vflags = vfl.get_logic_list().keys()
260  useprimaries = cpflag[-1]=='+'
261  cpflag=cpflag.rstrip('+')
262  expflags = []
263 
264  if cpflag in vflags:
265  self.AddVFHeaderData(cpflag)
266  expflags += [cpflag]
267  if useprimaries:
268  expflags += self.getVFDef(cpflag)
269  else:
270  for vf in vflags:
271  if vf.startswith(cpflag):
272  self.AddVFHeaderData(vf)
273  expflags += [vf]
274  if useprimaries:
275  expflags += self.getVFDef(vf)
276 
277  if len(expflags)==0:
278  raise RuntimeError("Virtual Flag pattern %s does not match any virtual flag: %r" % (cpflag, vfl.get_logic_list().keys()))
279 
280  return expflags
281 
282 
283  def GetVirtualFlagLogic(self, db, schema):
284  if self.useVirtualFlags:
285  return self.vfl
286  try: # import
287  from VirtualFlags import VirtualFlagLogicFolder, VirtualFlagFolder
288  except ImportError:
289  print ("Can't import virtual flags")
290  import traceback
291  traceback.print_exc()
292 
293  self.VirtualFlagFolder = VirtualFlagFolder
294  self.vfl = VirtualFlagLogicFolder(coolDbConn.GetDBConn(schema=schema, db=db))
295  self.logics = self.vfl.get_logic_list()
296  self.useVirtualFlags = True
297  return self.vfl
298 
299  def AddVFHeaderData(self,cpflag):
300  from CoolRunQuery.AtlRunQueryRun import Run
301  if cpflag in Run.Fieldinfo:
302  return
303  Run.Fieldinfo[cpflag] = '<strong><b>%s</b></strong><br><table width="300"><tr><td>%s</td></tr></div>' % \
304  (self.vfl.get_logic_list()[cpflag].comment,
305  ", ".join(self.getVFDef(cpflag)) )
306 
307  def getVFDef(self,cpflag):
308  return self.vfl.resolve_primary_flags(self.vfl.resolve_dependancies([cpflag]))
309 
310 
311 
312  def ApplySelection(self,key):
313  if key in self.passSpecs:
314  return True
315  return False
316 
317  def addShowChannel(self, folder, channelname, tag):
318  tmplist = [[channelname,'']]
319  self.GetVirtualFlagsExpanded(tmplist, Selector.compDB(), self.schema)
320 
321  for shch in tmplist[0][0].split(','):
322  self.addSingleShowChannel(folder+':'+shch)
323 
324  def addSingleShowChannel(self, channelname):
325  ch = self.DQChannel(channelname)
326  ssr = self.DoSelectShowRetrieve()
327  if ch in self.channelsflat: # channel exists already, just need to set showoutput to true
328  idx = self.channelsflat.index(ch) # location of the channel in the flat list
329  self.channelNamesFlat[idx] = channelname
330  ssr[idx] += 2
331  else:
332  self.channelNamesFlat += [channelname]
333  self.channelsflat += [self.DQChannel(channelname)]
334  ssr += [2]
335  # re-assign
336  self.channels = self.channelsflat
337 
338  if self.folderHasComment:
339  channelKeys = zip(self.channelsflat, self.channelNamesFlat, len(self.channelsflat)*[('Code','Comment')])
340  else:
341  channelKeys = zip(self.channelsflat, self.channelNamesFlat, len(self.channelsflat)*['Code'])
342 
343  self.setChannelKeys(channelKeys,ssr)
344 
345  def __str__(self):
346  if self.applySelection:
347  s = "SELOUT Checking in the DQ folder %s" % self.foldername
348  flagCh = defaultdict(list)
349  for flag,ch in zip(self.flags,self.channelNames):
350  flagCh[flag].append('(' + ' or '.join(ch) + ')')
351  for flag in flagCh:
352  chlist = ' and '.join(flagCh[flag])
353  s += "\nSELOUT %s is %r" % (chlist, flag)
354  return s
355  else:
356  return "Retrieving DQ for channels %r from folder %s" % (self.channelNamesFlat, self.foldername)
357 
358  def passes(self,values, key):
359  passfnc = self.passSpecs[key]['passFnc']
360  if isinstance(values,tuple):
361  v = values[0]
362  else:
363  v = values
364  if v=='n.a.':
365  v=-2
366  try:
367  if passfnc(v): # passed this DQ flag in the OR group?
368  return True
369  except ValueError:
370  # happens when comparing 'n.a.' with 0,1,2,3 (for 'U','R','Y','G') ... and the black flag? (AH)
371  # should never set pass=True
372  pass
373 
374  return False
375 
376  def rejectRun(self,run):
377  for k in self.ResultKey():
378  passfnc = self.passSpecs[k]['passFnc']
379  for entry in run.data[k]:
380  v = entry.value
381  dqres = v[0] if type(v)==tuple else v
382  dqcode = self.invert[dqres]
383  entry.rejected = not passfnc( dqcode )
384  return super(DQCondition,self).rejectRun(run)
385 
386 
387 
388  def prettyValue(self, value, key):
389  if type(value)==tuple:
390  return (self.color[value[0]], value[1])
391  else:
392  return self.color[value]
393 
394  def runAfterQuery(self,runlist):
395  dqs = ['G','Y','R','B','U','n.a.']
396  for run in runlist:
397  for k in self.ResultKey():
398  n={}
399  run.stats[k] = {}
400  for dq in dqs:
401  n[dq] = 0
402  blocks = []
403  for entry in run.data[k]:
404  if self.folderHasComment:
405  if entry.value == 'n.a.':
406  dq, dqcomment = ('n.a.','')
407  else:
408  dq, dqcomment = entry.value
409  else:
410  dq, dqcomment = (entry.value,None)
411 
412  n[dq] += len(entry)
413  if entry.startlb == 0:
414  n[dq] -= 1 # CAUTION: problem with LB-1 = 0 ==> needs to be corrected
415  if len(blocks) > 0 and blocks[-1][0]==(dq,dqcomment) and blocks[-1][2]==entry.startlb:
416  blocks[-1][2] = entry.endlb
417  else:
418  blocks += [ [(dq, dqcomment), entry.startlb, entry.endlb] ]
419 
420  maxn = max(n.values())
421  # find maximum DQ flag
422  dqmax = dqs[0]
423  for dq in dqs:
424  if n[dq]==maxn:
425  dqmax=dq
426  run.result[k]=dqmax
427  run.stats[k] = { "counts" : n, "max": dqmax, "blocks": blocks }
428 
429 
430 class DQDefectCondition(RunLBBasedCondition):
431 
432  def __init__(self, name, folder):
433  self.foldername = folder # DEFECTS#<TAG>
434  self.primaries = {} # self.primaries[runnr] is the list of primary defects that are set in each run
435  self.channelNames = []
437  self.global_ignore = set() # set of all primary defects that should be ignored in all defects
438  super(DQDefectCondition,self).__init__(name=name,
439  dbfolderkey = 'COOLOFL_GLOBAL::%s' % self.foldername, # folder name handled internally by DQDefects
440  channelKeys = [('DQDEFECT', 'DQ',('Code','Comment'))])
441 
442  self.data_keys[0]._second_internal_key = self.tagname
443 
444  def _getFolder(self):
445  from CoolRunQuery.AtlRunQueryRun import RunData
446  RunData.DefectSelector = self._pass
447  self.__db = coolDbConn.GetDBConn('DEFECTS',self.tagname)
448  return self.__db # return the DB, not the folder
449 
450  def _pass(self,data):
451  these_defects = []
452  if data is not None:
453  for x in data:
454  if x.value.ignore is None: # no ignore
455  these_defects += [x.value.defect]
456  else:
457  these_defects += [x.value.defect+'\\'+x.value.ignore]
458  for orGroup in self.selectionChannelNames:
459  any_passes = False
460  for k in orGroup:
461  if k[0]=='\\':
462  continue # "\Defect" are modifiers not requirements so we ignore it in the check
463  if k[0]=='!': # !DEFECT
464  kk = k[1:]
465  passes = kk not in these_defects
466  else:
467  passes = k in these_defects
468  if passes:
469  any_passes = True
470  break
471  if not any_passes: # none pass in the OR-group
472  return False
473  return True
474 
475  def _fix_channel_names(self, db):
476  newl = []
477  for litem in self.selectionChannelNames:
478  newlitem = []
479  for k in litem:
480  if k[0]=='\\':
481  newlitem.append(k)
482  elif k[0] == '!':
483  newlitem.append('!' + db.normalize_defect_names(k[1:]))
484  else:
485  newlitem.append(db.normalize_defect_names(k))
486  newl.append(newlitem)
487  self.selectionChannelNames = newl
488  self.global_ignore = set(db.normalize_defect_names(self.global_ignore))
489 
490 
491  def __getChannels(self, db, channel_name_patterns):
492  """ based on the patterns in the list channel_name_patterns create a
493  list of pairs of patterns and matching defects ( pattern, set(matching defects) )
494  and attach it to the global Run.FieldInfo dictionary under 'DQ'
495  """
496  from re import compile
497  from CoolRunQuery.AtlRunQueryRun import Run
498  if 'DQ' not in Run.Fieldinfo:
499  Run.Fieldinfo['DQ'] = {}
500  if 'DefMatch' not in Run.Fieldinfo['DQ']:
501  Run.Fieldinfo['DQ']['DefMatch'] = []
502  Run.Fieldinfo['DQ']['IntolerableDefects'] = db.get_intolerable_defects(old_primary_only=False)
503  matches = set()
504  for pattern in channel_name_patterns:
505  if pattern.upper() != 'DET':
506  cpattern = compile(pattern)
507  channelnames = set(filter(cpattern.match,db.defect_names))
508  channelnames.update(filter(cpattern.match,db.virtual_defect_names))
509  else:
510  channelnames = set([d for d in db.defect_names if '_' not in d])
511  channelnames.update([d for d in db.virtual_defect_names if '_' not in d])
512  matches.update(channelnames)
513  Run.Fieldinfo['DQ']['DefMatch'] += [(pattern,channelnames)]
514  return matches
515 
516 
517  def _retrieve(self, iovmin, iovmax, db, sortedRanges):
518  runmin = iovmin>>32
519  runmax = iovmax>>32
520  since = (runmin,iovmin&0xFFFFFFFF)
521  until = (runmax,iovmax&0xFFFFFFFF)
522 
523  # add the channels for showing (those can be wildcarded, so call __getChannels to get exact matches)
524  channels = self.__getChannels(db,self.channelNames)
525 
526  # Rewrite defect names to get cases to be correct
527  self._fix_channel_names(db)
528 
529  # add the channels for selection (those have to match exactly, they are simply added)
530  channels_with_ignore = {} # unique
531  for selChans in self.selectionChannelNames:
532  channels.update([x.lstrip('!') for x in selChans if '\\' not in x])
533  for x in selChans: # for the defects with ignore condition
534  if '\\' not in x:
535  continue
536  channel, ignore_str = self.sort_uniq_ignores(x).split('\\',1)
537  if ignore_str not in channels_with_ignore:
538  channels_with_ignore[ignore_str] = []
539  channels_with_ignore[ignore_str] += [channel.lstrip('!')]
540 
541  #print ("CHANNELS",channels)
542  if len(channels) + len(channels_with_ignore)==0:
543  return []
544 
545  # we need to remove the special case ANY from the set
546  if 'ANY' in channels:
547  channels.remove('ANY')
548 
549  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) ]
550 
551  # and also treat the defects with 'ignore' condition
552  for _ignore_str, _channels in channels_with_ignore.items():
553  ignore = set(_ignore_str.split('\\'))
554  ignore.update(self.global_ignore)
555 
556  res += [ (db.retrieve(since=since, until=until, channels=_channels, ignore=ignore, with_primary_dependencies=True).trim_iovs, _ignore_str) ]
557 
558  return self.defgen(db, res, channels, channels_with_ignore)
559 
560 
561 
562  def defgen(self, db, defects_with_ignore, channels, channels_with_ignore):
563  """
564  defects: list of defects returned by query
565  channels: explicit list of channels that matched the pattern
566  """
567  intolerableDefects = db.get_intolerable_defects(old_primary_only=False)
568  for defects, ignore in defects_with_ignore:
569  chanlist = channels if ignore is None else channels_with_ignore[ignore]
570  for d in defects:
571  if not d.present:
572  continue
573  isVirtual = (d.user == 'sys:virtual') # db.defect_is_virtual(d.channel)
574  if not isVirtual:
575  run = d.since.run
576  # fill list of primaries defects for this run (this is needed for the comments, but not for the selection)
577  if run not in self.primaries:
578  self.primaries[run] = []
579  self.primaries[run] += [d]
580  if d.channel not in chanlist:
581  continue
582 
583  defPayload = DQDefectPayload(defect = d.channel, comment = d.comment,
584  user = d.user, primary = not isVirtual,
585  ignore = ignore,
586  tolerable = (d.channel not in intolerableDefects),
587  recoverable = d.recoverable)
588  # note that the comment is either the user's comment,
589  # a comment that the defect is auto-generated, or the
590  # list of source defects in case of virtual defects
591 
592  #o = O("DQDEFECT", (d.channel, d.comment, ignore), IOVRange(starttime=d.since.real, endtime=d.until.real), True)
593  o = OOO("DQDEFECT", defPayload, IOVRange(starttime=d.since.real, endtime=d.until.real), True)
594  yield o
595 
596 
597 
598  def ApplySelection(self,key):
599  return key=='DQ' and len(self.selectionChannelNames)!=0
600 
601 
602  def sort_uniq_ignores(self,requirement):
603  if '\\' not in requirement:
604  return requirement
605  x = requirement.split('\\')
606  new_req = x[0] + '\\' + '\\'.join(sorted(list(set(x[1:]))))
607  return new_req
608 
609 
610  def addSelectionChannels(self, dq):
611  for channels,flag in dq:
612  a = []
613  prefix = '!' if flag == 'green' else ''
614  for x in channels.split(','):
615  if x[0]=='\\':
616  self.global_ignore.update( x.lstrip('\\').split('\\') ) # "\Defect" are modifiers not a selection requirement
617  else:
618  a += [ prefix+self.sort_uniq_ignores(x) ]
619  if len(a)>0:
620  self.selectionChannelNames += [ a ]
621 
622 
623  def addShowChannel(self, folder, channelname, tag):
624  self.channelNames += [channelname]
625  from CoolRunQuery.AtlRunQueryRun import Run
626  if 'DQ' not in Run.Fieldinfo:
627  Run.Fieldinfo['DQ'] = {}
628  if 'DefChannels' not in Run.Fieldinfo['DQ']:
629  Run.Fieldinfo['DQ']['DefChannels'] = []
630  Run.Fieldinfo['DQ']['DefChannels'] += [channelname]
631 
632 
633  def __str__(self):
634  if self.applySelection:
635  return "SELOUT Checking the DQ defects %s" % ', '.join([', '.join(cn) for cn in self.selectionChannelNames])
636  else:
637  return "Retrieving DQ defects %s" % ', '.join([', '.join(cn) for cn in self.selectionChannelNames])
638 
639  def passes(self,values, key):
640  return True
641 
642  def rejectRun(self,run):
643  return super(DQDefectCondition,self).rejectRun(run)
644 
645  def mergeRanges(self,it):
646  """ two adjacent defect entries are merged into one"""
647  doMerge = False
648  if doMerge:
649  mergedByDefect = []
650  x = it.next()
651  (openedat,openuntil) = (x.startlb,x.endlb)
652  for x in it:
653  if x.startlb == openuntil:
654  openuntil = x.endlb
655  else:
656  mergedByDefect += [(openedat, openuntil)]
657  openedat,openuntil = x.startlb,x.endlb
658  mergedByDefect += [(openedat, openuntil)]
659  return mergedByDefect
660  else:
661  return [(x.startlb,x.endlb) for x in it]
662 
663 
664 
665  def runAfterQuery(self,runlist):
666  """
667  collects, sorts, and groups defects with LBs and comments
668  """
669  from itertools import groupby
670  from operator import attrgetter
671 
672  for run in runlist:
673 
674  for k in self.ResultKey():
675  # format of run.data[k] is
676  # [ <DataEntry with value = (defect_name, defect_comment or defect_composition)>, ...]
677 
678  #for x in run.data[k]:
679  # print (" %r" % (x,))
680  if k not in run.data.keys():
681  run.result[k] = {}
682  run.stats[k] = {}
683 
684  all_defects = sorted(list(set([x.value[0] for x in run.data[k]])))
685 
686  grouped_defects = groupby(sorted(run.data[k],key=lambda x: x.value[0]),key = lambda x: x.value[0]) # first sort by defect name, then group by defect name
687 
688  desired_defects = [ (defect_name, self.mergeRanges(lblist)) for defect_name, lblist in grouped_defects ]
689 
690  run.stats[k] = { "defects": desired_defects,
691  "primaries": {} }
692 
693  primaries = {} # defect : list of primaries with lb-range
694  if run.runNr in self.primaries:
695  primgroups = groupby(sorted([p for p in self.primaries[run.runNr]],key=attrgetter('channel')),key=attrgetter('channel'))
696  primaries = dict([(p,list(l)) for p,l in primgroups])
697 
698  for defect in all_defects:
699  if self.__db.defect_is_virtual(defect):
700  reps = []
701  self.find_primaries(DD, self.__db.virtual_defect_logics[defect], primaries, defect, reps)
702  run.stats[k]["primaries"][defect] = reps
703  elif defect in primaries:
704  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] ]
705 
706 
707  #import pickle
708  #f = open("dev.pickle","w")
709  #pickle.dump(run.stats[k]["primaries"],f)
710  #f.close()
711 
712  #for x,l in run.stats[k]["primaries"].items():
713  # print (x)
714  # for y in sorted(l):
715  # print (" ",y)
716 
717 
718  def find_primaries(self, DD, defect_logic, primaries, curpath, reps):
719  for pdef in defect_logic.primary_defects:
720  if pdef not in primaries:
721  continue
722  pdefects = primaries[pdef]
723  for pdeflb in pdefects:
724  reps += [ DD("%s->%s" % (curpath, pdeflb.channel), pdeflb.comment, pdeflb.since.lumi, pdeflb.until.lumi) ]
725  for dep in defect_logic.dependencies:
726  self.find_primaries(DD, dep, primaries, curpath+"->"+dep.name, reps)
727 
python.selector.AtlRunQuerySelectorDQ.DQCondition
Definition: AtlRunQuerySelectorDQ.py:99
python.selector.AtlRunQuerySelectorDQ.DQSelector.select
def select(self, runlist)
Definition: AtlRunQuerySelectorDQ.py:82
python.selector.AtlRunQuerySelectorDQ.DQCondition.GetVirtualFlagsExpanded
def GetVirtualFlagsExpanded(self, dqlist, db, schema)
Definition: AtlRunQuerySelectorDQ.py:246
python.selector.AtlRunQuerySelectorDQ.DQDefectCondition.foldername
foldername
Definition: AtlRunQuerySelectorDQ.py:433
python.selector.AtlRunQuerySelectorDQ.DQDefectCondition._getFolder
def _getFolder(self)
Definition: AtlRunQuerySelectorDQ.py:444
python.selector.AtlRunQuerySelectorDQ.DQCondition._retrieve
def _retrieve(self, iovmin, iovmax, f, sortedRanges)
Definition: AtlRunQuerySelectorDQ.py:229
python.selector.AtlRunQuerySelectorDQ.DQDefectCondition.mergeRanges
def mergeRanges(self, it)
Definition: AtlRunQuerySelectorDQ.py:645
python.selector.AtlRunQuerySelectorDQ.DQCondition._getFolder
def _getFolder(self)
Definition: AtlRunQuerySelectorDQ.py:214
python.selector.AtlRunQuerySelectorDQ.DQCondition.channelNamesFlat
channelNamesFlat
Definition: AtlRunQuerySelectorDQ.py:109
max
#define max(a, b)
Definition: cfImp.cxx:41
python.selector.AtlRunQuerySelectorDQ.DQDefectCondition.__getChannels
def __getChannels(self, db, channel_name_patterns)
Definition: AtlRunQuerySelectorDQ.py:491
python.selector.AtlRunQuerySelectorDQ.DQCondition.__init__
def __init__(self, name, foldername, dq)
Definition: AtlRunQuerySelectorDQ.py:105
CaloCellPos2Ntuple.int
int
Definition: CaloCellPos2Ntuple.py:24
python.selector.AtlRunQuerySelectorDQ.DQCondition.color
dictionary color
Definition: AtlRunQuerySelectorDQ.py:102
index
Definition: index.py:1
python.selector.AtlRunQuerySelectorDQ.DQCondition.flags
flags
Definition: AtlRunQuerySelectorDQ.py:112
python.selector.AtlRunQuerySelectorDQ.DQCondition.folderHasComment
folderHasComment
Definition: AtlRunQuerySelectorDQ.py:140
python.selector.AtlRunQuerySelectorDQ.DQSelector.runAfterQuery
def runAfterQuery(self, runlist)
Definition: AtlRunQuerySelectorDQ.py:93
python.selector.AtlRunQuerySelectorDQ.DQCondition.GetVirtualFlagLogic
def GetVirtualFlagLogic(self, db, schema)
Definition: AtlRunQuerySelectorDQ.py:283
python.selector.AtlRunQuerySelectorDQ.DQDefectCondition.addSelectionChannels
def addSelectionChannels(self, dq)
Definition: AtlRunQuerySelectorDQ.py:610
python.selector.AtlRunQuerySelectorDQ.DQCondition.tagname
tagname
Definition: AtlRunQuerySelectorDQ.py:224
python.selector.AtlRunQuerySelectorDQ.DQCondition.channelsflat
channelsflat
Definition: AtlRunQuerySelectorDQ.py:111
python.selector.AtlRunQuerySelectorDQ.DQCondition.runAfterQuery
def runAfterQuery(self, runlist)
Definition: AtlRunQuerySelectorDQ.py:394
python.selector.AtlRunQuerySelectorDQ.DQSelector.__init__
def __init__(self, name='dataquality')
Definition: AtlRunQuerySelectorDQ.py:22
dumpHVPathFromNtuple.append
bool append
Definition: dumpHVPathFromNtuple.py:91
python.selector.AtlRunQuerySelectorDQ.DQCondition.getVFDef
def getVFDef(self, cpflag)
Definition: AtlRunQuerySelectorDQ.py:307
python.selector.AtlRunQuerySelectorBase.OOO
OOO
Definition: AtlRunQuerySelectorBase.py:19
python.selector.AtlRunQuerySelectorDQ.DQCondition.channelNames
channelNames
Definition: AtlRunQuerySelectorDQ.py:108
python.selector.AtlRunQuerySelectorDQ.DQCondition.rejectRun
def rejectRun(self, run)
Definition: AtlRunQuerySelectorDQ.py:376
python.selector.AtlRunQuerySelectorDQ.DQSelector.addShowChannel
def addShowChannel(self, chanAndfolder)
Definition: AtlRunQuerySelectorDQ.py:65
python.selector.AtlRunQuerySelectorDQ.DQDefectCondition.selectionChannelNames
selectionChannelNames
Definition: AtlRunQuerySelectorDQ.py:436
python.Bindings.values
values
Definition: Control/AthenaPython/python/Bindings.py:797
python.selector.AtlRunQuerySelectorDQ.DQDefectCondition.__str__
def __str__(self)
Definition: AtlRunQuerySelectorDQ.py:633
covarianceTool.filter
filter
Definition: covarianceTool.py:514
python.selector.AtlRunQuerySelectorDQ.DQSelector.selectors
selectors
Definition: AtlRunQuerySelectorDQ.py:24
python.selector.AtlRunQuerySelectorDQ.DQDefectCondition.global_ignore
global_ignore
Definition: AtlRunQuerySelectorDQ.py:437
python.selector.AtlRunQuerySelectorDQ.DQCondition.__str__
def __str__(self)
Definition: AtlRunQuerySelectorDQ.py:345
python.selector.AtlRunQuerySelectorDQ.DQCondition.useVirtualFlags
useVirtualFlags
Definition: AtlRunQuerySelectorDQ.py:113
python.selector.AtlRunQuerySelectorDQ.DQDefectCondition.channelNames
channelNames
Definition: AtlRunQuerySelectorDQ.py:435
python.selector.AtlRunQuerySelectorDQ.DQSelector.__str__
def __str__(self)
Definition: AtlRunQuerySelectorDQ.py:75
python.selector.AtlRunQuerySelectorDQ.DQDefectCondition.addShowChannel
def addShowChannel(self, folder, channelname, tag)
Definition: AtlRunQuerySelectorDQ.py:623
python.selector.AtlRunQuerySelectorDQ.DQDefectCondition.runAfterQuery
def runAfterQuery(self, runlist)
Definition: AtlRunQuerySelectorDQ.py:665
python.selector.AtlRunQuerySelectorDQ.DQDefectCondition.passes
def passes(self, values, key)
Definition: AtlRunQuerySelectorDQ.py:639
python.selector.AtlRunQuerySelectorDQ.DQCondition.ExpandVFlag
def ExpandVFlag(self, cpflag, db, schema)
Definition: AtlRunQuerySelectorDQ.py:257
python.selector.AtlRunQuerySelectorDQ.DD
DD
Definition: AtlRunQuerySelectorDQ.py:15
python.selector.AtlRunQuerySelectorDQ.DQCondition.channelCommentsFlat
channelCommentsFlat
Definition: AtlRunQuerySelectorDQ.py:133
python.selector.AtlRunQuerySelectorDQ.DQDefectCondition.sort_uniq_ignores
def sort_uniq_ignores(self, requirement)
Definition: AtlRunQuerySelectorDQ.py:602
python.selector.AtlRunQuerySelectorDQ.DQCondition.flagInterpreter
flagInterpreter
Definition: AtlRunQuerySelectorDQ.py:156
python.selector.AtlRunQuerySelectorDQ.DQDefectPayload
DQDefectPayload
Definition: AtlRunQuerySelectorDQ.py:12
python.selector.AtlRunQuerySelectorDQ.DQDefectCondition.find_primaries
def find_primaries(self, DD, defect_logic, primaries, curpath, reps)
Definition: AtlRunQuerySelectorDQ.py:718
plotBeamSpotVxVal.range
range
Definition: plotBeamSpotVxVal.py:195
python.selector.AtlRunQuerySelectorDQ.DQCondition.VirtualFlagFolder
VirtualFlagFolder
Definition: AtlRunQuerySelectorDQ.py:293
python.selector.AtlRunQuerySelectorDQ.DQDefectCondition._retrieve
def _retrieve(self, iovmin, iovmax, db, sortedRanges)
Definition: AtlRunQuerySelectorDQ.py:517
python.selector.AtlRunQuerySelectorDQ.DQCondition.DQChannel
def DQChannel(self, dqfullname)
Definition: AtlRunQuerySelectorDQ.py:237
histSizes.list
def list(name, path='/')
Definition: histSizes.py:38
python.selector.AtlRunQuerySelectorDQ.DQCondition.vfl
vfl
Definition: AtlRunQuerySelectorDQ.py:294
python.selector.AtlRunQuerySelectorDQ.DQSelector.addSelectionChannel
def addSelectionChannel(self, dq=[])
Definition: AtlRunQuerySelectorDQ.py:48
python.selector.AtlRunQuerySelectorDQ.DQCondition.foldername
foldername
Definition: AtlRunQuerySelectorDQ.py:107
DerivationFramework::TriggerMatchingUtils::sorted
std::vector< typename T::value_type > sorted(T begin, T end)
Helper function to create a sorted vector from an unsorted one.
CxxUtils::set
constexpr std::enable_if_t< is_bitmask_v< E >, E & > set(E &lhs, E rhs)
Convenience function to set bits in a class enum bitmask.
Definition: bitmask.h:224
python.selector.AtlRunQuerySelectorDQ.DQCondition.passes
def passes(self, values, key)
Definition: AtlRunQuerySelectorDQ.py:358
python.selector.AtlRunQuerySelectorDQ.DQDefectCondition.ApplySelection
def ApplySelection(self, key)
Definition: AtlRunQuerySelectorDQ.py:598
TCS::join
std::string join(const std::vector< std::string > &v, const char c=',')
Definition: Trigger/TrigT1/L1Topo/L1TopoCommon/Root/StringUtils.cxx:10
python.selector.AtlRunQuerySelectorDQ.DQCondition.addShowChannel
def addShowChannel(self, folder, channelname, tag)
Definition: AtlRunQuerySelectorDQ.py:317
python.selector.AtlRunQuerySelectorDQ.DQSelector
Definition: AtlRunQuerySelectorDQ.py:21
python.selector.AtlRunQuerySelectorDQ.DQCondition.channels
channels
Definition: AtlRunQuerySelectorDQ.py:110
python.selector.AtlRunQuerySelectorDQ.DQCondition.prettyValue
def prettyValue(self, value, key)
Definition: AtlRunQuerySelectorDQ.py:388
python.selector.AtlRunQuerySelectorDQ.DQDefectCondition
Definition: AtlRunQuerySelectorDQ.py:430
python.selector.AtlRunQuerySelectorDQ.DQCondition.code
dictionary code
Definition: AtlRunQuerySelectorDQ.py:101
python.selector.AtlRunQuerySelectorDQ.DQCondition.ApplySelection
def ApplySelection(self, key)
Definition: AtlRunQuerySelectorDQ.py:312
python.selector.AtlRunQuerySelectorDQ.DQDefectCondition._fix_channel_names
def _fix_channel_names(self, db)
Definition: AtlRunQuerySelectorDQ.py:475
python.selector.AtlRunQuerySelectorDQ.DQCondition.logics
logics
Definition: AtlRunQuerySelectorDQ.py:295
dqt_zlumi_pandas.update
update
Definition: dqt_zlumi_pandas.py:42
python.selector.AtlRunQuerySelectorDQ.DQCondition.AddVFHeaderData
def AddVFHeaderData(self, cpflag)
Definition: AtlRunQuerySelectorDQ.py:299
python.selector.AtlRunQuerySelectorDQ.DQCondition.invert
dictionary invert
Definition: AtlRunQuerySelectorDQ.py:103
python.selector.AtlRunQuerySelectorDQ.vfgen
def vfgen(vfobjs)
Definition: AtlRunQuerySelectorDQ.py:17
python.selector.AtlRunQuerySelectorDQ.DQSelector.__getChannelAndFolder
def __getChannelAndFolder(self, chanAndfolder)
Definition: AtlRunQuerySelectorDQ.py:30
python.CaloScaleNoiseConfig.type
type
Definition: CaloScaleNoiseConfig.py:78
python.selector.AtlRunQuerySelectorDQ.DQCondition.passSpecs
passSpecs
Definition: AtlRunQuerySelectorDQ.py:209
python.selector.AtlRunQuerySelectorDQ.DQDefectCondition.__db
__db
Definition: AtlRunQuerySelectorDQ.py:447
python.selector.AtlRunQuerySelectorDQ.DQDefectCondition.defgen
def defgen(self, db, defects_with_ignore, channels, channels_with_ignore)
Definition: AtlRunQuerySelectorDQ.py:562
python.selector.AtlRunQuerySelectorDQ.DQSelector.__getCondition
def __getCondition(self, folder)
Definition: AtlRunQuerySelectorDQ.py:39
python.selector.AtlRunQuerySelectorDQ.DQDefectCondition.rejectRun
def rejectRun(self, run)
Definition: AtlRunQuerySelectorDQ.py:642
python.selector.AtlRunQuerySelectorDQ.DQSelector.setShowOutput
def setShowOutput(self)
Definition: AtlRunQuerySelectorDQ.py:70
str
Definition: BTagTrackIpAccessor.cxx:11
python.Bindings.keys
keys
Definition: Control/AthenaPython/python/Bindings.py:790
python.selector.AtlRunQuerySelectorDQ.DQDefectCondition._pass
def _pass(self, data)
Definition: AtlRunQuerySelectorDQ.py:450
Trk::split
@ split
Definition: LayerMaterialProperties.h:38
python.selector.AtlRunQuerySelectorDQ.DQDefectCondition.__init__
def __init__(self, name, folder)
Definition: AtlRunQuerySelectorDQ.py:432
python.selector.AtlRunQuerySelectorDQ.DQDefectCondition.primaries
primaries
Definition: AtlRunQuerySelectorDQ.py:434
python.selector.AtlRunQuerySelectorDQ.DQCondition.addSingleShowChannel
def addSingleShowChannel(self, channelname)
Definition: AtlRunQuerySelectorDQ.py:324