ATLAS Offline Software
Loading...
Searching...
No Matches
physval_make_web_display.py
Go to the documentation of this file.
1#!/usr/bin/env python
2
3# Copyright (C) 2002-2026 CERN for the benefit of the ATLAS collaboration
4
5"""
6Transate arbitrary root file into a han config file
7@author: ponyisi@utexas.edu
89 Oct 2008
9Adapted for physics validation 14 May 2014
10"""
11
12
13from DQConfMakerBase.DQElements import DQRegion, DQReference, DQAlgorithm, DQAlgorithmParameter
14from DQConfMakerBase.Helpers import make_thresholds
15from DataQualityUtils.hanwriter import writeHanConfiguration
16from DataQualityUtils import HanMetadata
17import ROOT
18
19repeatalgorithm = DQAlgorithm(id='RepeatAlgorithm',
20 libname='libdqm_algorithms.so')
21worst = DQAlgorithm(id='WorstCaseSummary',libname='libdqm_summaries.so')
22
23
27algorithmparameters = [DQAlgorithmParameter('AuxAlgName--Chi2Test_Chi2_per_NDF', 1),
28 DQAlgorithmParameter('RepeatAlgorithm--ResultsNEntries', 1)]
29
30# this will be used if no references are provided
31norefalgorithm = DQAlgorithm(id='GatherData',
32 libname='libdqm_algorithms.so')
33
34# Edit this to change thresholds
35thresh = make_thresholds('Chi2_per_NDF', 1.0, 1.50, 'Chi2Thresholds')
36
37
39 """Return whether ROOT can load the library used to create PNG files."""
40 print('====> Checking ROOT PNG support')
41 print('ROOT version: %s' % ROOT.gROOT.GetVersion())
42
43 asimage = ROOT.gSystem.DynamicPathName('libASImage', True)
44 if asimage:
45 print('ROOT image library: %s' % asimage)
46
47 load_status = ROOT.gSystem.Load('libASImage')
48 if load_status < 0:
49 print('ERROR: ROOT cannot load libASImage; PNG output is unavailable.')
50 print(' Check the loader diagnostics above for a missing runtime')
51 print(' dependency (for example, "libgif.so.7 => not found" from')
52 print(' "ldd $(root-config --libdir)/libASImage.so").')
53 return False
54
55 if not ROOT.TImage.Create():
56 print('ERROR: ROOT loaded libASImage, but could not create a TImage.')
57 print(' PNG output is unavailable in this environment.')
58 return False
59
60 print('ROOT PNG support: OK')
61 return True
62
63
64def recurse(rdir, dqregion, ignorepath, modelrefs=[], displaystring='Draw=PE', displaystring2D='Draw=COLZ', regex=None, startpath=None, hists=None, manglefunc=None):
65 if manglefunc is None:
66 manglefunc = lambda a, b: a # noqa: E731
67 for key in rdir.GetListOfKeys():
68 cl = key.GetClassName(); rcl = ROOT.TClass.GetClass(cl)
69 if ' ' in key.GetName():
70 print('WARNING: cannot have spaces in histogram names for han config; not including %s %s' % (cl, key.GetName()))
71 continue
72 if rcl.InheritsFrom('TH1') or rcl.InheritsFrom('TGraph') or rcl.InheritsFrom('TEfficiency'):
73 if '/' in key.GetName():
74 print('WARNING: cannot have slashes in histogram names, encountered in directory %s, histogram %s' % (rdir.GetPath(), key.GetName()))
75 continue
76 if key.GetName() == 'summary':
77 print('WARNING: cannot have histogram named summary, encountered in %s' % rdir.GetPath())
78 continue
79 fpath = rdir.GetPath().replace(ignorepath, '')
80 name = (fpath + '/' + key.GetName()).lstrip('/')
81 #print rdir.GetPath(), ignorepath, name
82 if hists:
83 match = False
84 for hist in hists:
85 if hist.match(name):
86 match = True
87 if not match: continue
88 elif regex:
89 if not regex.match(name): continue
90 dqpargs = { 'id' : ('' if fpath else 'top_level/') + name,
91 'inputdatasource': (startpath + '/' if startpath else '') + name,
92 }
93 if modelrefs:
94 lnewrefs = []
95 for mref in modelrefs:
96 newref = DQReference(manglefunc(mref.getReference().replace('same_name', (startpath + '/' if startpath else '') + name), mref.id))
97 newref.addAnnotation('info', mref.id)
98 lnewrefs.append(newref)
99 dqpargs.update({'algorithm': repeatalgorithm,
100 'algorithmparameters': algorithmparameters,
101 'thresholds': thresh,
102 'references': lnewrefs
103 })
104 else:
105 dqpargs['algorithm'] = norefalgorithm
106 dqpar = dqregion.newDQParameter( **dqpargs)
107 drawstrs = []
108 if not options.normalize: drawstrs.append('NoNorm')
109 if options.logy and (cl.startswith('TH1') or cl=='TProfile'): drawstrs.append('LogY')
110 if options.logy and (cl.startswith('TH2') or cl=='TProfile2D'): drawstrs.append('LogZ')
111 if cl.startswith('TH1'): drawstrs.append(displaystring)
112 if cl == 'TProfile': drawstrs.append(displaystring)
113 if cl.startswith('TH2') or cl=='TProfile2D': drawstrs.append(displaystring2D)
114 if options.scaleref != 1: drawstrs.append('ScaleRef=%f' % options.scaleref)
115 if options.ratio: drawstrs.append('RatioPad')
116 #if options.ratio: drawstrs.append('Ref2DSignif')
117 if options.ratio2D: drawstrs.append('Ref2DRatio')
118 if options.ratiorange is not None:
119 drawstrs.append('delta(%f)' % options.ratiorange)
120
121 drawstrs.append('DataName=%s' % options.title)
122 dqpar.addAnnotation('display', ','.join(drawstrs))
123
124 elif rcl.InheritsFrom('TDirectory'):
125 newregion = dqregion.newDQRegion( key.GetName(), algorithm=worst )
126 recurse(key.ReadObj(), newregion, ignorepath, modelrefs, displaystring, displaystring2D, regex, startpath, hists, manglefunc)
127
128def prune(dqregion):
129 """
130 returns True if we should kill this node
131 False if we should not
132 """
133 params = dqregion.getDQParameters()
134 if params is None:
135 params = []
136 subregions = dqregion.getSubRegions()
137 if subregions is None:
138 subregions = []
139 else:
140 subregions = subregions[:]
141 # kill subregions
142 for sr in subregions:
143 if sr is None:
144 continue
145 if prune(sr):
146 dqregion.delRelation('DQRegions', sr)
147 subregions = dqregion.getSubRegions()
148 if subregions is None:
149 subregions = []
150 if len(subregions) + len(params) == 0:
151 return True
152 else:
153 return False
154
155def paramcount(dqregion):
156 params = dqregion.getDQParameters()
157 if params is None:
158 params = []
159 subregions = dqregion.getSubRegions()
160 if subregions is None:
161 subregions = []
162
163 return len(params) + sum([paramcount(region) for region in subregions])
164
165def process(infname, confname, options, refs=None):
166 import re
167 f = ROOT.TFile.Open(infname, 'READ')
168 if not f.IsOpen():
169 print('ERROR: cannot open %s' % infname)
170 return
171
172 top_level = DQRegion(id='topRegion',algorithm=worst)
173 print('Building tree...')
174 refpairs = refs.split(',') if refs else []
175 try:
176 refdict = dict(_.split(':', 1) for _ in refpairs)
177 except Exception as e:
178 print(e)
179 # "Model" references
180 dqrs = [DQReference(reference='%s:same_name' % v, id=k)
181 for k, v in list(refdict.items())]
182 displaystring = options.drawopt
183 if options.refdrawopt:
184 displaystring += ',' + (','.join('DrawRef=%s' % _ for _ in options.refdrawopt.split(',')))
185 displaystring2D = options.drawopt2D
186 if options.drawrefopt2D:
187 displaystring2D += ',' + (','.join('DrawRef2D=%s' % _ for _ in options.drawrefopt2D.split(',')))
188
189 if options.startpath:
190 topindir = f.Get(options.startpath)
191 if not topindir:
192 raise ValueError("Path %s doesn't exist in input file" % options.startpath)
193 topindirname = f.GetPath() + options.startpath.strip('/')
194 startpath = options.startpath.strip('/')
195 else:
196 topindir = f
197 topindirname = f.GetPath()
198 startpath = None
199
200 # make a map for the reference path names
201 refstartpaths = options.refstartpath.split(',') if options.refstartpath else []
202 try:
203 refstartpathdict = dict(_.split(':') for _ in refstartpaths)
204 for k, v in refstartpathdict.items():
205 refstartpathdict[k] = v.strip('/')
206 except Exception as e:
207 print(e)
208 def refpath_manglefunc(path, id):
209 try:
210 pfx = refstartpathdict[id]
211 # consider also the case where pfx is ''
212 return path.replace(':' + (startpath + '/' if startpath else ''), ':' + (pfx +'/' if pfx else ''), 1)
213 except KeyError:
214 return path
215
216 hists = []
217 if options.histlistfile:
218 hists = [re.compile(line.rstrip('\n')) for line in open(options.histlistfile)]
219 if options.pathregex: print("histlistfile given, pathregex is ignored")
220 if options.refmangle:
221 import sys
222 sys.path.append(os.getcwd())
223 import importlib
224 manglefunc = importlib.import_module(options.refmangle).mangle
225 else:
226 manglefunc = refpath_manglefunc
227 recurse(topindir, top_level, topindirname, dqrs, displaystring, displaystring2D,
228 re.compile(options.pathregex), startpath, hists, manglefunc=manglefunc)
229 print('Pruning dead branches...')
230 prune(top_level)
231 pc = paramcount(top_level)
232
233 sublevel = top_level.getSubRegions()[:]
234 for x in sublevel:
235 top_level.delRelation('DQRegions', x)
236
237 print('Writing output')
238 writeHanConfiguration( filename = confname , roots = sublevel)
239 return pc
240
241def super_process(fname, options):
242 import shutil, os, sys, contextlib
243 import ROOT
244 if not options.hanonly and not check_png_support():
245 return False
246 han_is_found = (ROOT.gSystem.Load('libDataQualityInterfaces') != 1)
247 if not han_is_found:
248 print('ERROR: unable to load offline DQMF; unable to proceed')
249 sys.exit(1)
250 bname = os.path.basename(fname)
251
252 hanconfig = None
253 hanhcfg = None
254 hanoutput = None
255
256 failed = False
257 prebuilt_hcfg = False
258
259 @contextlib.contextmanager
260 def tmpdir():
261 import tempfile
262 td = tempfile.mkdtemp()
263 yield td
264 shutil.rmtree(td)
265
266 with tmpdir() as hantmpdir:
267 try:
268 print('====> Processing file %s' % (fname))
269 print('====> Generating han configuration file')
270 hantmpinput = os.path.join(hantmpdir, bname)
271 shutil.copyfile(fname, hantmpinput)
272 haninput = hantmpinput
273 hanconfig = os.path.join(hantmpdir, 'han.config')
274 rv = process(hantmpinput, hanconfig, options, options.reffile)
275 #shutil.copy(hanconfig, os.getcwd())
276
277 # bad hack. rv = number of histogram nodes
278 if rv == 0:
279 print('No histograms to display; exiting with code 0')
280 sys.exit(0)
281
282 print('====> Compiling han configuration')
283 hanhcfg = os.path.join(hantmpdir, 'han.hcfg')
284 ROOT.dqi.HanConfig().AssembleAndSave( hanconfig, hanhcfg )
285 print('====> Executing han')
286 import resource
287 memlimit = resource.getrlimit(resource.RLIMIT_AS)
288 resource.setrlimit(resource.RLIMIT_AS, (memlimit[1], memlimit[1]))
289 hanoutput = haninput.rpartition('.')[0] + '_han.root'
290
291 rv = ROOT.dqi.HanApp().Analyze( hanhcfg, haninput, hanoutput )
292 if rv != 0:
293 raise Exception('failure in han')
294 if options.amitag:
295 rf = ROOT.TFile.Open(hanoutput, 'UPDATE')
296 HanMetadata.addMetadata(rf, 'AMI', {'AMI Tag': options.amitag})
297 rf.Close()
298 if not options.hanonly:
299 print('====> Dumping web display output')
300 from DataQualityUtils import handimod
301 handimod.handiWithComparisons( options.title,
302 hanoutput,
303 options.outdir,
304 '', False, False,
305 'https://atlasdqm.web.cern.ch/atlasdqm/js/',
306 3 if options.jsRoot else 1)
307 if options.hanoutput:
308 from pathlib import Path
309 print('====> Copying han output to', options.hanoutput)
310 target = Path(options.hanoutput)
311 try:
312 target.parent.mkdir(parents=True, exist_ok=True)
313 except Exception as e:
314 print('Unable to create %s for some reason: %s' % (target.parent, e))
315 raise Exception('Error during execute') from e
316 shutil.copy2(hanoutput, options.hanoutput)
317 print('====> Cleaning up')
318 os.unlink(hanoutput)
319 except Exception as e:
320 print(e)
321 import traceback
322 traceback.print_exc()
323 if 'canonical format' not in str(e):
324 failed = True
325 finally:
326 try:
327 if not prebuilt_hcfg:
328 os.unlink(hantmpinput)
329 os.unlink(hanconfig)
330 os.unlink(hanhcfg)
331 os.unlink(hanoutput)
332 except Exception:
333 pass
334
335 return not failed
336
337
338if __name__=="__main__":
339 import sys, optparse, os
340 os.environ['TDAQ_ERS_NO_SIGNAL_HANDLERS']='1'
341 parser = optparse.OptionParser(usage='usage: %prog [options] inputfile')
342 parser.add_option('--reffile', default=None,
343 help='Reference files to use. Must have same structure as inputfile. Format: tag1:reffile1.root,tag2:reffile2.root,...')
344 parser.add_option('--outdir', default='./handi',
345 help='Directory for web ouptut')
346 parser.add_option('--hanoutput', default=None,
347 help='Filename to save han output to (will not save if not set)')
348 parser.add_option('--hanonly', action='store_true',
349 help='Only save han output file, do not write HTML/PNG')
350 parser.add_option('--check-png-support', action='store_true',
351 help='Check whether ROOT can create PNG output and exit; no input file is required')
352 parser.add_option('--normalize', default=False, action='store_true',
353 help='Normalize reference histograms for display')
354 parser.add_option('--title', default='Summary',
355 help='Title for histograms being tested')
356 parser.add_option('--drawopt', default='Draw=PE',
357 help='Draw options for tested histograms (only use if you know what you are doing)')
358 parser.add_option('--refdrawopt',
359 help='ROOT Draw option for reference histograms (e.g. HIST)')
360 parser.add_option('--drawopt2D', default='Draw=COLZ',
361 help='Draw options for tested TH2 histograms (only use if you know what you are doing)')
362 parser.add_option('--drawrefopt2D', default=None,
363 help='Draw options for reference TH2 histograms. If nothing is specified, no 2D reference histograms are drawn. If you want to draw both test and reference histo, recommended settings are --drawopt2D="Draw=BOX" --drawrefopt2D="COLZ"')
364 parser.add_option('--logy', action='store_true',
365 help='Display on log Y scale')
366 parser.add_option('--pathregex', default='.*',
367 help='Specify regex to match histograms, e.g. "(Btag|Jets)"')
368 parser.add_option('--startpath', default=None,
369 help='Start from this subdirectory of the file')
370 parser.add_option('--refstartpath', default=None,
371 help='Start from this subdirectory of reference files. By default is the same as startpath. Format: tag1:dir1,tag2:dir2,...')
372 parser.add_option('--histlistfile',
373 help='text file with a list of regexes/histogram names')
374 parser.add_option('--scaleref', type="float", default=1,
375 help='Scale references by this value')
376 parser.add_option('--Kolmogorov', default=False, action='store_true',
377 help='Run Kolmogorov test instead of Chi2 test')
378 parser.add_option('--ratio', default=False, action='store_true',
379 help='Draw histograms with ratio plots')
380 parser.add_option('--ratio2D', default=False, action='store_true',
381 help='Draw 2D histograms with ratio plots')
382 parser.add_option('--jsRoot',action='store_true', default=False,
383 help="make interactive jsRoot displays")
384 parser.add_option('--ratiorange', default=None, type="float",
385 help='set range for ratio plots (as delta to 1.0)')
386 parser.add_option('--refmangle', default=None, type="string",
387 help='provide a Python module to translate histogram names between test and reference files. Module should provide\na function mangle(testhistoname, reflabel)')
388 parser.add_option('--amitag', default=None,
389 help='AMI tag to add as metadata')
390
391 options, args = parser.parse_args()
392
393 if options.check_png_support:
394 sys.exit(0 if check_png_support() else 1)
395
396 if not 1 == len(args):
397 parser.print_help()
398 sys.exit(1)
399 fname = args[0]
400 if options.Kolmogorov:
401 algorithmparameters = [DQAlgorithmParameter('AuxAlgName--KolmogorovTest_Prob', 1),
402 DQAlgorithmParameter('RepeatAlgorithm--ResultsNEntries', 1)]
403 thresh = make_thresholds('P', 0.05, 0.01, 'pThresholds')
404
405 rv = super_process(fname, options)
406 if rv:
407 sys.exit(0)
408 else:
409 sys.exit(1)
void print(char *figname, TCanvas *c1)
const std::string process
std::string replace(std::string s, const std::string &s2, const std::string &s3)
Definition hcg.cxx:312
recurse(rdir, dqregion, ignorepath, modelrefs=[], displaystring='Draw=PE', displaystring2D='Draw=COLZ', regex=None, startpath=None, hists=None, manglefunc=None)