ATLAS Offline Software
Functions | Variables
covarianceTool Namespace Reference

Functions

def isFloat (x)
 
def convertHistToScatter (ao)
 
def renameAOs (fin_name, aoMap)
 
def makeBeamer (plotDictionary, outdir)
 
def makeSummaryTable (plotDictionary, outfile, hdataName=None)
 
def matchAOs (aoList1, aoList2, strategy=0, recursive=True)
 
def markupYODAwithCorrelationsFromYODAs (reference, correlationsDir)
 
def markupYODAwithCorrelationsFromYAML (reference, correlationsDir)
 
def markupYODAwithCorrelations (ref, corrDir, ignoreCorrelations)
 
def returnFileContents (filename, inputType='data')
 
def getCorrelationInfoFromWeb (name=None, dlformat="yoda")
 

Variables

 parser = optparse.OptionParser(usage="%prog [options]")
 
 help
 
 dest
 
 default
 
 False
 
 action
 
 opts
 
 args
 
dictionary histograms
 
 ntoys
 
 verbosity
 
 filter
 
 ignore_corrs_data
 
 ignore_corrs_mc
 
dictionary mcNames = {}
 
dictionary plotDictionary = {'error-analysis': {}, 'covariance-matrix': {}, 'correlation-matrix': {}, 'data-vs-mc': {}, 'chi2-contribs': {}, 'chi2-value': {}, 'covDetails': {}, 'summary-plot': {}, 'summary-table': {}}
 
 data
 
string outdir = "outputs/%s/data/plots" % (opts.data.replace(".yoda", ""))
 
 plotparser = rivet.mkStdPlotParser([], [])
 
 headers = plotparser.getHeaders(hdata.path())
 
 XLabel
 
 Title
 
 xLabel
 
 title
 
 mcName = mc.split(":")[1]
 
 mc = mc.split(":")[0]
 
def mcnew = markupYODAwithCorrelations(mc, opts.corr_mc, opts.ignore_corrs_mc)
 
def aoMap = matchAOs(histograms['data'], histograms['models'][mcnew])
 
def newmc = renameAOs(mcnew, aoMap)
 
 dataSuperAO = ct.makeSuperAO(histograms['data'])
 
 mcSuperAO = ct.makeSuperAO(histograms['models'][mc])
 
dictionary mcResults = {}
 
bool passFilter = False
 
def hmc = aoMap[hdata]
 
string covDetailsData = "Size of uncertainties across range, and Data Correlation Matrix"
 
 covData = ct.makeCovarianceMatrixFromToys(hdata, opts.ntoys, opts.ignore_corrs_data)
 
string covDetailsMC = "MC Covariance Matrix"
 
 covMC = ct.makeCovarianceMatrixFromToys(hmc, opts.ntoys, opts.ignore_corrs_mc)
 
 covTotal = covData + covMC
 
 chi2
 
 ndf
 
 prob
 
 chi2contribs
 
 chi2ContribsByRow = ct.chi2ContribsByRow(chi2contribs)
 
 chi2ContribsByRowYAML = yaml.dump(chi2ContribsByRow, default_flow_style=True, default_style='', width=1e6)
 
dictionary res = {'%s' % opts.data: '[Data]', '%s' % model: '[%s (# chi^2=%.2f/%d)]' % (mcName, chi2, ndf)}
 
string outdirplots = outdir + "/data-vs-%s/plots/" % mcName
 
 plots = st.makeSystematicsPlotsWithROOT(res, outdirplots, nominalName='Data', ratioZoom=None, regexFilter=".*%s.*" % hmc.name(), regexVeto=None)
 
 pathName = hdata.path().replace("/REF", "")
 
dictionary mcR = mcResults[model]
 
def beamerPath = makeBeamer(plotDictionary, outdir)
 

Function Documentation

◆ convertHistToScatter()

def covarianceTool.convertHistToScatter (   ao)

Definition at line 69 of file covarianceTool.py.

69 def convertHistToScatter(ao):
70  print("convertHistToScatter: This is a placeholder, need to implement")
71  exit(1)
72 
73 

◆ getCorrelationInfoFromWeb()

def covarianceTool.getCorrelationInfoFromWeb (   name = None,
  dlformat = "yoda" 
)

Definition at line 479 of file covarianceTool.py.

479 def getCorrelationInfoFromWeb(name=None, dlformat="yoda"):
480  # try to get the YAML files for the corresponding HEPData record
481  # download and untar them...
482  if (name is None): name = opts.data
483  inspireID = [t for t in name.split("_") if "I" in t]
484  inspireID = inspireID[0].replace("I", "")
485  hdurl = "http://www.hepdata.net/record/ins%s?format=%s" % (inspireID, dlformat)
486  print("[INFO] Trying to download information from %s", hdurl)
487  if hdurl:
488  response = urllib2.urlopen(hdurl)
489  download = response.read()
490  if not download or "<html" in download:
491  print(("Problem encountered when getting data from HepData (%s). No reference data file written." % hdurl))
492  else:
493  tar = tarfile.open(mode="r:gz", fileobj=StringIO.StringIO(download))
494  fnames = tar.getnames()
495  if len(fnames) > 0 and dlformat == 'yaml':
496  tar.extractall()
497  os.system("mkdir -p corrInfo/ins%s" % (inspireID))
498  os.system("mv %s/* corrInfo/ins%s/." % (fnames[0], inspireID))
499  os.system("rm -r %s" % (fnames[0]))
500  print("[INFO] successfully downloaded YAML files from HEPMC, will see if they can be used for correlations")
501  if len(fnames) == 1 and dlformat == 'yoda':
502  tar.extractall()
503  os.system("mkdir -p corrInfo/ins%s" % (inspireID))
504  os.system("mv %s corrInfo/ins%s/." % (fnames[0], inspireID))
505  print("[INFO] successfully downloaded YODA files from HEPMC, will see if they can be used for correlations")
506  opts.corr_data = "corrInfo/ins%s" % inspireID
507  response.close()
508 
509 

◆ isFloat()

def covarianceTool.isFloat (   x)

Definition at line 60 of file covarianceTool.py.

60 def isFloat(x):
61  # check if the object can be cast as a float
62  try:
63  float(x)
64  return True
65  except ValueError:
66  return False
67 
68 

◆ makeBeamer()

def covarianceTool.makeBeamer (   plotDictionary,
  outdir 
)

Definition at line 93 of file covarianceTool.py.

93 def makeBeamer(plotDictionary, outdir):
94  # produce summary slides using beamer
95  frames = []
96  dataDir = os.environ["SYSTTOOLSPATH"] + "/data/"
97  os.system("mkdir -p %s " % outdir)
98  samples = plotDictionary['chi2-value'].keys()
99  histos = plotDictionary['chi2-value'][samples[0]].keys()
100  os.system('cp %s/title.tex %s/title.tex' % (dataDir, outdir))
101  os.system('cp %s/title.tex %s/title.tex' % (dataDir, outdir))
102  os.system("sed -i -e 's|!TITLE!|%s|g' %s/title.tex" % (opts.data.replace('.yoda', '').replace('_', ' '), outdir))
103  frames.append("%s/title.tex" % outdir)
104  for histo in histos:
105  if 'superAO' in histo: continue
106  os.system('cp %s/section.tex %s/%s_section.tex' % (dataDir, outdir, histo))
107  os.system("sed -i -e 's|!AOREF!|%s|g' %s/%s_section.tex" % (histo, outdir, histo))
108  frames.append('%s/%s_section.tex' % (outdir, histo))
109  os.system('cp %s/errorAnalysis.tex %s/%s_%s_errorAnalysis.tex' % (dataDir, outdir, 'data', histo))
110  os.system("sed -i -e 's|!AOREF!|%s|g' %s/%s_%s_errorAnalysis.tex" % (histo, outdir, 'data', histo))
111  os.system("sed -i -e 's|!SAMPLE!|%s|g' %s/%s_%s_errorAnalysis.tex" % ('data', outdir, 'data', histo))
112  os.system("sed -i -e 's|!ERRORBREAKDOWN!|%s|g' %s/%s_%s_errorAnalysis.tex" % (plotDictionary['error-analysis']['data'][histo], outdir, 'data', histo))
113  os.system("sed -i -e 's|!COVMATRIX!|%s|g' %s/%s_%s_errorAnalysis.tex" % (plotDictionary['correlation-matrix']['data'][histo], outdir, 'data', histo))
114  os.system("sed -i -e 's|!COVDETAILS!|%s|g' %s/%s_%s_errorAnalysis.tex" % (plotDictionary['covDetails']['data'][histo], outdir, 'data', histo))
115  frames.append("%s/%s_%s_errorAnalysis.tex" % (outdir, 'data', histo))
116  for sample in samples:
117  sampleNameClean = sample.replace("_", " ").replace("-", " ")
118  os.system('cp %s/dataMCComparison.tex %s/%s_%s_dataMCComparison.tex' % (dataDir, outdir, sample, histo))
119  os.system("sed -i -e 's|!AOREF!|%s|g' %s/%s_%s_dataMCComparison.tex" % (histo, outdir, sample, histo))
120  os.system("sed -i -e 's|!SAMPLE!|%s|g' %s/%s_%s_dataMCComparison.tex" % (sampleNameClean, outdir, sample, histo))
121  os.system("sed -i -e 's|!DATAVSMC!|%s|g' %s/%s_%s_dataMCComparison.tex" % (plotDictionary['data-vs-mc'][sample][histo], outdir, sample, histo))
122  os.system("sed -i -e 's|!CHI2CONTRIBS!|%s|g' %s/%s_%s_dataMCComparison.tex" % (plotDictionary['chi2-contribs'][sample][histo], outdir, sample, histo))
123  frames.append("%s/%s_%s_dataMCComparison.tex" % (outdir, sample, histo))
124  # summary
125  os.system('cp %s/sectionSummary.tex %s/%s_sectionSummary.tex' % (dataDir, outdir, histo))
126  os.system("sed -i -e 's|!AOREF!|%s|g' %s/%s_sectionSummary.tex" % (histo, outdir, histo))
127  os.system("sed -i -e 's|!SUMMARYPLOT!|%s|g' %s/%s_sectionSummary.tex" % (plotDictionary['summary-plot'][histo], outdir, histo))
128  os.system("sed -i -e 's|!SUMMARYTABLE!|%s|g' %s/%s_sectionSummary.tex" % (plotDictionary['summary-table'][histo], outdir, histo))
129  frames.append("%s/%s_sectionSummary.tex" % (outdir, histo))
130  os.system('cp %s/section.tex %s/%s_section.tex' % (dataDir, outdir, 'overall'))
131  os.system("sed -i -e 's|!AOREF!|%s|g' %s/%s_section.tex" % ('overall summary', outdir, 'overall'))
132  frames.append('%s/%s_section.tex' % (outdir, 'overall'))
133  os.system('cp %s/overallSummary.tex %s/%s_overallSummary.tex' % (dataDir, outdir, 'overall'))
134  os.system("sed -i -e 's|!AOREF!|%s|g' %s/%s_overallSummary.tex" % ('overall summary', outdir, 'overall'))
135  os.system("sed -i -e 's|!SUMMARYTABLE!|%s|g' %s/%s_overallSummary.tex" % (plotDictionary['summary-table']['all'], outdir, 'overall'))
136  frames.append("%s/%s_overallSummary.tex" % (outdir, 'overall'))
137  frames.append("%s/end.tex" % dataDir)
138  catLine = " ".join(frames)
139  os.system(" cat %s > %s/slides_%s.tex" % (catLine, outdir, opts.data.replace('.yoda', '')))
140  return " %s/slides_%s.tex" % (outdir, opts.data.replace('.yoda', ''))
141 
142 

◆ makeSummaryTable()

def covarianceTool.makeSummaryTable (   plotDictionary,
  outfile,
  hdataName = None 
)

Definition at line 143 of file covarianceTool.py.

143 def makeSummaryTable(plotDictionary, outfile, hdataName=None):
144  # make a summary latex table of the chi2 values for each AO
145  outf = open(outfile, 'w')
146  samples = plotDictionary['chi2-value'].keys()
147  if (hdataName):
148  histos = [hdataName]
149  else:
150  histos = sorted(plotDictionary['chi2-value'][samples[0]].keys())
151 
152  line = "\\begin{tabular}{|l|"
153  for hist in histos:
154  line += "c|"
155  line += "}"
156  outf.write(line + '\n')
157  outf.write("\\hline " + '\n')
158  line = " $\\chi^2$ / ndof "
159  for hist in histos:
160  if 'superAO' in hist: hist = 'global agreement'
161  line += " & %s " % hist
162  line += "\\\\"
163  outf.write(line + '\n')
164  outf.write("\\hline" + '\n')
165  for sample in samples:
166  line = " %s " % sample.replace("-", " ").replace("_", " ")
167  for hist in histos:
168  line += " & %s" % plotDictionary['chi2-value'][sample][hist]
169  line += "\\\\"
170  outf.write(line + '\n')
171  outf.write("\\hline" + '\n')
172  outf.write("\\end{tabular}" + '\n')
173  outf.close()
174 
175 

◆ markupYODAwithCorrelations()

def covarianceTool.markupYODAwithCorrelations (   ref,
  corrDir,
  ignoreCorrelations 
)

Definition at line 419 of file covarianceTool.py.

419 def markupYODAwithCorrelations(ref, corrDir, ignoreCorrelations):
420  # produce a new YODA file where the AOs have been marked up with
421  # covariance info from an uncertainty breakdown provided as
422  # either YAML or YODA files
423  isYoda = False
424  if ignoreCorrelations:
425  return markupYODAwithCorrelationsFromYODAs(ref, 'self')
426  else:
427  if (corrDir is None): return ref
428  for f in os.listdir(corrDir):
429  if '.yoda' in f: isYoda = True
430  if isYoda:
431  return markupYODAwithCorrelationsFromYODAs(ref, corrDir)
432  else:
433  return markupYODAwithCorrelationsFromYAML(ref, corrDir)
434 
435 

◆ markupYODAwithCorrelationsFromYAML()

def covarianceTool.markupYODAwithCorrelationsFromYAML (   reference,
  correlationsDir 
)

Definition at line 292 of file covarianceTool.py.

292 def markupYODAwithCorrelationsFromYAML(reference, correlationsDir):
293  # produce a new YODA file where the AOs have been marked up with
294  # covariance info from an uncertainty breakdown provided as
295  # one or more YAML files from HEPData
296  reference_out = reference.replace(".yoda", "_corrs.yoda")
297  reference_outf = open(reference_out, 'w')
298  infiles = {}
299  for f in os.listdir(correlationsDir):
300  if 'submission' in f: continue
301  if 'comb' in f: continue
302  if "syst" in f:
303  infiles.setdefault(correlationsDir + "/" + f.replace('syst', 'xsect'), [])
304  else:
305  infiles.setdefault(correlationsDir + "/" + f, [])
306 
307  for f in infiles.keys():
308  stream = open(f, "r")
309  doc = yaml.load(stream)
310  binLabels = {}
311  binValues = {}
312  binErrors = {}
313  for itemtype, itemarray in doc.items():
314  if itemtype == "independent_variables": # bin labels
315  for line in itemarray:
316  binLabels['name'] = itemarray[0]['header']['name']
317  counter = 0
318  for entry in itemarray[0]['values']:
319  if ('low' in entry.keys() and 'high' in entry.keys()):
320  binLabels[counter] = "%f - %f" % (entry['low'], entry['high'])
321  else:
322  binLabels[counter] = "%f" % (entry['value'])
323  counter += 1
324 
325  if itemtype == "dependent_variables": # values
326  for line in itemarray:
327  binValues['name'] = "%s [%s]" % (line['header']['name'], '')
328  binErrors['name'] = "uncertainties"
329  counter = 0
330  for entry in line['values']:
331  binValues[counter] = entry['value']
332  binErrors[counter] = {}
333  if 'errors' in entry.keys():
334  for error in entry['errors']:
335  binErrors[counter][error['label']] = {}
336  if 'symerror' in error.keys():
337  if not isFloat(error['symerror']) and '%' in (error['symerror']):
338  binErrors[counter][error['label']]['up'] = binValues[counter] * 0.01 * float(error['symerror'].replace('%', ''))
339  binErrors[counter][error['label']]['dn'] = binValues[counter] * -0.01 * float(error['symerror'].replace('%', ''))
340  else:
341  binErrors[counter][error['label']]['up'] = float(error['symerror'])
342  binErrors[counter][error['label']]['dn'] = -1 * float(error['symerror'])
343  elif 'asymerror' in error.keys():
344  if not isFloat(error['asymerror']['plus']) and '%' in error['asymerror']['plus']:
345  binErrors[counter][error['label']]['up'] = binValues[counter] * 0.01 * float(error['asymerror']['plus'].replace('%', ''))
346  binErrors[counter][error['label']]['dn'] = binValues[counter] * 0.01 * float(error['asymerror']['minus'].replace('%', ''))
347  else:
348  binErrors[counter][error['label']]['up'] = float(error['asymerror']['plus'])
349  binErrors[counter][error['label']]['dn'] = 1 * float(error['asymerror']['minus'])
350  else:
351  print('[ERROR] errors are neither symmetric or asymmetric... exit!')
352  exit(1)
353  counter += 1
354 
355  if 'xsect' in f:
356  systNames = binErrors[0].keys()
357  binErrorsGranular = {}
358  systFile = f.replace("xsect", "syst")
359  streamsyst = open(systFile, "r")
360  docsyst = yaml.load(streamsyst)
361  binErrorsGranular['name'] = "uncertainties"
362  for itemtype, itemarray in docsyst.items():
363  if "variables" not in itemtype: continue
364  if (itemtype == "independent_variables"):
365  systNames = [v['value'] for v in itemarray[0]['values']]
366  else:
367  binCounter = -1
368  for line in itemarray:
369  binCounter += 1
370  binErrorsGranular[binCounter] = {}
371  if 'values' not in line.keys(): continue
372  systCounter = -1
373  for error in line['values']:
374  systCounter += 1
375  binErrorsGranular[binCounter][systNames[systCounter]] = {}
376  binErrorsGranular[binCounter][systNames[systCounter]]['up'] = float(error['value']) * binValues[binCounter] * 0.01
377  binErrorsGranular[binCounter][systNames[systCounter]]['dn'] = -1 * float(error['value']) * binValues[binCounter] * 0.01
378  for i in range(len(binErrorsGranular.keys()) - 1):
379  binErrorsGranular[i]['stat'] = {}
380  binErrorsGranular[i]['stat']['up'] = binErrors[i]['stat']['up']
381  binErrorsGranular[i]['stat']['dn'] = binErrors[i]['stat']['dn']
382  binErrors = binErrorsGranular
383  nBins = len(binLabels) - 1
384  infiles[f] = [binValues, binErrors]
385 
386  hists = yoda.read(reference, unpatterns=".*RAW.*")
387  for name in hists:
388  nearestMatch = ""
389  smallestDiff = 999.
390  nearestMatchErrors = ""
391  nominal = [(hists[name].points()[i].y) for i in range(hists[name].numPoints())]
392  for f, corrs in infiles.items():
393  binValues = corrs[0]
394  binErrors = corrs[1]
395  nBins = len(binValues) - 1
396  if (len(nominal) != nBins): continue
397  totalDiff = 0
398  for i in range(nBins):
399  totalDiff += abs(binValues[i] - nominal[i])
400  if (totalDiff < smallestDiff):
401  nearestMatch = f
402  smallestDiff = totalDiff
403  nearestMatchErrors = binErrors
404  if (opts.verbosity > 1): print("[DEBUG] candidate", nominal, " nearest match is ", nearestMatch)
405  if smallestDiff < 1.0:
406  if (opts.verbosity > 1): print("[INFO] mapping", name, " ---> ", nearestMatch, (smallestDiff))
407  corrs = yaml.dump(nearestMatchErrors, default_flow_style=True, default_style='', width=1e6)
408  hists[name].setAnnotation("ErrorBreakdown", corrs)
409  yoda.writeYODA(hists[name], reference_outf)
410  else:
411  print("[WARNING] Warning, no match found for", name)
412  print("[INFO] %s has been marked up with correlation info from %s in this file:" % (reference, correlationsDir))
413  print("[INFO] ---> %s " % (reference_out))
414  print("[INFO] next time, you can use this file as an input instead of ", reference)
415  reference_outf.close()
416  return reference_out
417 
418 

◆ markupYODAwithCorrelationsFromYODAs()

def covarianceTool.markupYODAwithCorrelationsFromYODAs (   reference,
  correlationsDir 
)

Definition at line 228 of file covarianceTool.py.

228 def markupYODAwithCorrelationsFromYODAs(reference, correlationsDir):
229  # produce a new YODA file where the AOs have been marked up with
230  # covariance info from an uncertainty breakdown provided as
231  # a separate YODA file for each systematic variation
232  reference_out = reference.replace(".yoda", "_corrs.yoda")
233  reference_outf = open(reference_out, 'w')
234  infiles = {}
235  if correlationsDir == 'self':
236  infiles.setdefault(reference, [])
237  else:
238  for f in os.listdir(correlationsDir):
239  if "all" in f: continue
240  infiles.setdefault(correlationsDir + "/" + f, [])
241  nBins = -1
242  binLabels = {}
243  binValues = {}
244  binErrors = {}
245 
246  histos = [name for name in yoda.read(reference, unpatterns=".*RAW.*")]
247  for histname in histos:
248  hAll = yoda.read(reference, unpatterns=".*RAW.*")[histname]
249  if type(hAll) is yoda.core.Histo1D: hAll = hAll.mkScatter()
250  for f in infiles.keys():
251  systname = f.split("/")[-1].replace(".yoda", "")
252  h = yoda.read(f, unpatterns=".*RAW.*")[histname]
253  if type(h) is yoda.core.Scatter2D:
254  nBins = h.numPoints()
255  for ipt in range(nBins):
256  binValues[ipt] = h.points()[ipt].y()
257  binLabels[ipt] = "%f - %f" % (h.points()[ipt].xMin(), h.points()[ipt].xMax())
258  errs = h.points()[ipt].yErrs()
259  errAv = (abs(errs[1]) + abs(errs[0])) * 0.5
260  binErrors.setdefault(ipt, {}).setdefault(systname, {})['up'] = errs[1]
261  binErrors.setdefault(ipt, {}).setdefault(systname, {})['dn'] = -1 * errs[0]
262  elif type(h) is yoda.core.Histo1D:
263  nBins = h.numBins
264  for ipt in range(nBins):
265  binValues[ipt] = h.bins()[ipt].sumW()
266  binLabels[ipt] = "%f - %f" % (h.bins()[ipt].xMin(), h.bins()[ipt].xMax())
267  errAv = h.bins()[ipt].sumW2()
268  binErrors.setdefault(ipt, {}).setdefault(systname, {})['up'] = errAv
269  binErrors.setdefault(ipt, {}).setdefault(systname, {})['dn'] = -1 * errAv
270  else: continue
271  if (reference != ""):
272  smallestDiff = 999.
273  for f in reference.split(","):
274  hists = yoda.read(f, unpatterns=".*RAW.*")
275  for name in hists:
276  if not type(hists[name]) is yoda.core.Scatter2D: continue
277  nominal = [(hists[name].points()[i].y()) for i in range(hists[name].numPoints())]
278  if (len(nominal) != nBins): continue
279  totalDiff = 0
280  for i in range(nBins):
281  totalDiff += abs(binValues[i] - nominal[i])
282  if (totalDiff < smallestDiff):
283  smallestDiff = totalDiff
284 
285  corrs = yaml.dump(binErrors, default_flow_style=True, default_style='', width=1e6)
286  hAll.setAnnotation("ErrorBreakdown", corrs)
287  yoda.writeYODA(hAll, reference_outf)
288  reference_outf.close()
289  return reference_out
290 
291 

◆ matchAOs()

def covarianceTool.matchAOs (   aoList1,
  aoList2,
  strategy = 0,
  recursive = True 
)

Definition at line 176 of file covarianceTool.py.

176 def matchAOs(aoList1, aoList2, strategy=0, recursive=True):
177  # try to establish a 1-1 mapping between AOs in two YODA files
178  # eg in case of different naming conventions
179  aoMap = {}
180  for ao1 in aoList1:
181  aoMap.setdefault(ao1, [])
182  for ao2 in aoList2:
183  nBinsMatch = False
184  namesMatch = False
185  namesPartialMatch = False
186  binWidthsMatch = False
187  if (ao2.name() in ao1.name()): namesMatch = True
188  if (ao1.name() in ao2.name()): namesMatch = True
189  ao1NameTokens = ao1.name().split("/")[-1].split("-")
190  ao2NameTokens = ao2.name().split("/")[-1].split("-")
191  if len(list(set(ao1NameTokens).intersection(ao2NameTokens))) >= 2: namesPartialMatch = True
192  if (ao1.numPoints() == ao2.numPoints()):
193  nBinsMatch = True
194  for ipt in range(ao1.numPoints()):
195  ao1BinLabels = "%.2f - %.2f" % (ao1.points()[ipt].xMin(), ao1.points()[ipt].xMax())
196  ao2BinLabels = "%.2f - %.2f" % (ao2.points()[ipt].xMin(), ao2.points()[ipt].xMax())
197  if (ao1BinLabels == ao2BinLabels): binWidthsMatch = True
198  if strategy == 0:
199  if (namesMatch and nBinsMatch and binWidthsMatch):
200  aoMap.setdefault(ao1, []).append(ao2)
201  elif strategy == 1:
202  if (nBinsMatch and binWidthsMatch):
203  aoMap.setdefault(ao1, []).append(ao2)
204  elif strategy == 2:
205  if (nBinsMatch and binWidthsMatch and namesPartialMatch):
206  aoMap.setdefault(ao1, []).append(ao2)
207 
208  if (len(aoMap.keys()) == len(aoList1)) and ([len(aoMap[ao]) for ao in aoList1]) == ([1 for ao in aoList1]):
209  if (opts.verbosity > 0): print("[INFO] found 1-1 mapping between aoLists using strategy %d:" % strategy)
210  for ao1 in aoList1:
211  aoMap[ao1] = aoMap[ao1][0]
212  if (opts.verbosity > 1): print("%s --> %s" % (ao1.name(), aoMap[ao1].name()))
213  elif (recursive and strategy < 3):
214  if (opts.verbosity > 0):
215  print("[WARNING] Could not establish 1-1 mapping between aoLists using strategy", strategy, ", try strategy ", strategy + 1)
216  for ao1 in aoList1:
217  if (opts.verbosity > 1): print("%s --> %s" % (ao1.name(), aoMap[ao1]))
218  strategy += 1
219  aoMap = matchAOs(aoList1, aoList2, strategy)
220  else:
221  print("[ERROR] could not match AOS in the Data and MC files. Please make sure the AOs have the same binning/ number of bins (and name if possible!)")
222  print("[ERROR] aos from list 1", aoList1)
223  print("[ERROR] aos from list 2", aoList2)
224  exit(1)
225  return aoMap
226 
227 

◆ renameAOs()

def covarianceTool.renameAOs (   fin_name,
  aoMap 
)

Definition at line 74 of file covarianceTool.py.

74 def renameAOs(fin_name, aoMap):
75  # make a new YODA file where the AOs are renamed as per the reference file
76  fout_name = fin_name.replace(".yoda", ".renamed.yoda")
77  fout = open(fout_name, 'w')
78  aos = yoda.read(fin_name, unpatterns=".*RAW.*")
79  for aopath, ao in aos.items():
80  foundMatch = False
81  for ao1, ao2 in aoMap.items():
82  if ao1.name() == ao.name():
83  ao.setAnnotation("Path", ao2.path().replace("REF/", ""))
84  foundMatch = True
85  if ao2.name() == ao.name():
86  ao.setAnnotation("Path", ao1.path().replace("REF/", ""))
87  foundMatch = True
88  if foundMatch: yoda.writeYODA(ao, fout)
89  fout.close()
90  return fout_name
91 
92 

◆ returnFileContents()

def covarianceTool.returnFileContents (   filename,
  inputType = 'data' 
)

Definition at line 436 of file covarianceTool.py.

436 def returnFileContents(filename, inputType='data'):
437  result = []
438  aos = yoda.read(filename, unpatterns=".*RAW.*")
439  for aopath, ao in aos.items():
440  aoType = type(ao)
441  if aoType in [yoda.Histo1D, yoda.Histo2D]: ao = ao.mkScatter()
442  if aoType in [yoda.Counter]: continue
443  if 'all' not in opts.filter and inputType == 'data':
444  for f in opts.filter:
445  if f in aopath:
446  result.append(ao)
447  else:
448  result.append(ao)
449 
450  covInfoMissing = []
451  for ao in result:
452  corr = ao.annotation("ErrorBreakdown")
453  if (corr is None):
454  covInfoMissing.append(ao)
455  if (len(covInfoMissing) and inputType == 'data' and not opts.ignore_corrs and not opts.corr_data):
456  print("[WARNING] These DATA analysis objects are missing the correlation/covariance information:", covInfoMissing)
457  print(" --> To add correlation information, you can use the eg options: --get_corr_from_web, --corr_data ")
458  print(" --> You can also proceed by adding the --ignore_corrs_data in which case the chi2 is calculated")
459  print(" --> from the total uncertainties and assumed to be bin-bin uncorrelated.")
460  inspireID = [t for t in opts.data.split("_") if "I" in t]
461  inspireID = inspireID[0].replace("I", "")
462  if os.path().isdir("corrInfo/ins%s" % inspireID):
463  print("[INFO] Attempting to use the information in corrInfo/ins%s to build correlation info " % inspireID)
464  opts.corr_data = "corrInfo/ins%s" % inspireID
465  else:
467 
468  if (len(covInfoMissing) and inputType == 'mc' and not opts.ignore_corrs and not opts.corr_mc):
469  print("[WARNING] These MC analysis objects are missing the correlation/covariance information:", covInfoMissing)
470  print(" --> To add correlation information, you can use the eg options: --corr_mc ")
471  print(" --> You can also proceed by adding the --ignore_corrs_mc in which case the chi2 is calculated")
472  print(" --> from the total uncertainties and assumed to be bin-bin uncorrelated.")
473  if os.path.isdir("corrInfoMC/%s" % filename.replace(".yoda", "")):
474  print("[INFO] Attempting to use the information in corrInfoMC/%s to build correlation info " % filename.replace(".yoda", ""))
475  opts.corr_mc = "corrInfoMC/%s" % filename.replace(".yoda", "")
476  return result
477 
478 

Variable Documentation

◆ action

covarianceTool.action

Definition at line 34 of file covarianceTool.py.

◆ aoMap

def covarianceTool.aoMap = matchAOs(histograms['data'], histograms['models'][mcnew])

Definition at line 564 of file covarianceTool.py.

◆ args

covarianceTool.args

Definition at line 49 of file covarianceTool.py.

◆ beamerPath

def covarianceTool.beamerPath = makeBeamer(plotDictionary, outdir)

Definition at line 730 of file covarianceTool.py.

◆ chi2

covarianceTool.chi2

Definition at line 678 of file covarianceTool.py.

◆ chi2contribs

covarianceTool.chi2contribs

Definition at line 678 of file covarianceTool.py.

◆ chi2ContribsByRow

covarianceTool.chi2ContribsByRow = ct.chi2ContribsByRow(chi2contribs)

Definition at line 683 of file covarianceTool.py.

◆ chi2ContribsByRowYAML

covarianceTool.chi2ContribsByRowYAML = yaml.dump(chi2ContribsByRow, default_flow_style=True, default_style='', width=1e6)

Definition at line 684 of file covarianceTool.py.

◆ covData

covarianceTool.covData = ct.makeCovarianceMatrixFromToys(hdata, opts.ntoys, opts.ignore_corrs_data)

Definition at line 621 of file covarianceTool.py.

◆ covDetailsData

string covarianceTool.covDetailsData = "Size of uncertainties across range, and Data Correlation Matrix"

Definition at line 618 of file covarianceTool.py.

◆ covDetailsMC

string covarianceTool.covDetailsMC = "MC Covariance Matrix"

Definition at line 638 of file covarianceTool.py.

◆ covMC

covarianceTool.covMC = ct.makeCovarianceMatrixFromToys(hmc, opts.ntoys, opts.ignore_corrs_mc)

Definition at line 641 of file covarianceTool.py.

◆ covTotal

covarianceTool.covTotal = covData + covMC

Definition at line 654 of file covarianceTool.py.

◆ data

covarianceTool.data

Definition at line 529 of file covarianceTool.py.

◆ dataSuperAO

covarianceTool.dataSuperAO = ct.makeSuperAO(histograms['data'])

Definition at line 585 of file covarianceTool.py.

◆ default

covarianceTool.default

Definition at line 32 of file covarianceTool.py.

◆ dest

covarianceTool.dest

Definition at line 32 of file covarianceTool.py.

◆ False

covarianceTool.False

Definition at line 34 of file covarianceTool.py.

◆ filter

covarianceTool.filter

Definition at line 514 of file covarianceTool.py.

◆ headers

covarianceTool.headers = plotparser.getHeaders(hdata.path())

Definition at line 537 of file covarianceTool.py.

◆ help

covarianceTool.help

Definition at line 32 of file covarianceTool.py.

◆ histograms

dictionary covarianceTool.histograms
Initial value:
1 = {
2  'data': None,
3  'covariance': {},
4  'models': {},
5 }

Definition at line 53 of file covarianceTool.py.

◆ hmc

def covarianceTool.hmc = aoMap[hdata]

Definition at line 610 of file covarianceTool.py.

◆ ignore_corrs_data

covarianceTool.ignore_corrs_data

Definition at line 516 of file covarianceTool.py.

◆ ignore_corrs_mc

covarianceTool.ignore_corrs_mc

Definition at line 517 of file covarianceTool.py.

◆ mc

covarianceTool.mc = mc.split(":")[0]

Definition at line 554 of file covarianceTool.py.

◆ mcName

dictionary covarianceTool.mcName = mc.split(":")[1]

Definition at line 553 of file covarianceTool.py.

◆ mcNames

dictionary covarianceTool.mcNames = {}

Definition at line 519 of file covarianceTool.py.

◆ mcnew

def covarianceTool.mcnew = markupYODAwithCorrelations(mc, opts.corr_mc, opts.ignore_corrs_mc)

Definition at line 558 of file covarianceTool.py.

◆ mcR

dictionary covarianceTool.mcR = mcResults[model]

Definition at line 709 of file covarianceTool.py.

◆ mcResults

dictionary covarianceTool.mcResults = {}

Definition at line 602 of file covarianceTool.py.

◆ mcSuperAO

covarianceTool.mcSuperAO = ct.makeSuperAO(histograms['models'][mc])

Definition at line 589 of file covarianceTool.py.

◆ ndf

covarianceTool.ndf

Definition at line 678 of file covarianceTool.py.

◆ newmc

covarianceTool.newmc = renameAOs(mcnew, aoMap)

Definition at line 565 of file covarianceTool.py.

◆ ntoys

covarianceTool.ntoys

Definition at line 512 of file covarianceTool.py.

◆ opts

covarianceTool.opts

Definition at line 49 of file covarianceTool.py.

◆ outdir

string covarianceTool.outdir = "outputs/%s/data/plots" % (opts.data.replace(".yoda", ""))

Definition at line 532 of file covarianceTool.py.

◆ outdirplots

string covarianceTool.outdirplots = outdir + "/data-vs-%s/plots/" % mcName

Definition at line 697 of file covarianceTool.py.

◆ parser

covarianceTool.parser = optparse.OptionParser(usage="%prog [options]")

Definition at line 31 of file covarianceTool.py.

◆ passFilter

covarianceTool.passFilter = False

Definition at line 604 of file covarianceTool.py.

◆ pathName

covarianceTool.pathName = hdata.path().replace("/REF", "")

Definition at line 704 of file covarianceTool.py.

◆ plotDictionary

dictionary covarianceTool.plotDictionary = {'error-analysis': {}, 'covariance-matrix': {}, 'correlation-matrix': {}, 'data-vs-mc': {}, 'chi2-contribs': {}, 'chi2-value': {}, 'covDetails': {}, 'summary-plot': {}, 'summary-table': {}}

Definition at line 520 of file covarianceTool.py.

◆ plotparser

covarianceTool.plotparser = rivet.mkStdPlotParser([], [])

Definition at line 536 of file covarianceTool.py.

◆ plots

covarianceTool.plots = st.makeSystematicsPlotsWithROOT(res, outdirplots, nominalName='Data', ratioZoom=None, regexFilter=".*%s.*" % hmc.name(), regexVeto=None)

Definition at line 698 of file covarianceTool.py.

◆ prob

covarianceTool.prob

Definition at line 678 of file covarianceTool.py.

◆ res

dictionary covarianceTool.res = {'%s' % opts.data: '[Data]', '%s' % model: '[%s (# chi^2=%.2f/%d)]' % (mcName, chi2, ndf)}

Definition at line 696 of file covarianceTool.py.

◆ Title

covarianceTool.Title

Definition at line 540 of file covarianceTool.py.

◆ title

covarianceTool.title

Definition at line 542 of file covarianceTool.py.

◆ verbosity

covarianceTool.verbosity

Definition at line 513 of file covarianceTool.py.

◆ XLabel

covarianceTool.XLabel

Definition at line 538 of file covarianceTool.py.

◆ xLabel

covarianceTool.xLabel

Definition at line 542 of file covarianceTool.py.

replace
std::string replace(std::string s, const std::string &s2, const std::string &s3)
Definition: hcg.cxx:307
covarianceTool.markupYODAwithCorrelationsFromYAML
def markupYODAwithCorrelationsFromYAML(reference, correlationsDir)
Definition: covarianceTool.py:292
covarianceTool.returnFileContents
def returnFileContents(filename, inputType='data')
Definition: covarianceTool.py:436
covarianceTool.renameAOs
def renameAOs(fin_name, aoMap)
Definition: covarianceTool.py:74
dumpHVPathFromNtuple.append
bool append
Definition: dumpHVPathFromNtuple.py:91
intersection
std::vector< std::string > intersection(std::vector< std::string > &v1, std::vector< std::string > &v2)
Definition: compareFlatTrees.cxx:25
covarianceTool.makeSummaryTable
def makeSummaryTable(plotDictionary, outfile, hdataName=None)
Definition: covarianceTool.py:143
plotBeamSpotVxVal.range
range
Definition: plotBeamSpotVxVal.py:195
calibdata.exit
exit
Definition: calibdata.py:236
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.
covarianceTool.getCorrelationInfoFromWeb
def getCorrelationInfoFromWeb(name=None, dlformat="yoda")
Definition: covarianceTool.py:479
covarianceTool.markupYODAwithCorrelationsFromYODAs
def markupYODAwithCorrelationsFromYODAs(reference, correlationsDir)
Definition: covarianceTool.py:228
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
TCS::join
std::string join(const std::vector< std::string > &v, const char c=',')
Definition: Trigger/TrigT1/L1Topo/L1TopoCommon/Root/StringUtils.cxx:10
name
std::string name
Definition: Control/AthContainers/Root/debug.cxx:192
covarianceTool.matchAOs
def matchAOs(aoList1, aoList2, strategy=0, recursive=True)
Definition: covarianceTool.py:176
covarianceTool.markupYODAwithCorrelations
def markupYODAwithCorrelations(ref, corrDir, ignoreCorrelations)
Definition: covarianceTool.py:419
Trk::open
@ open
Definition: BinningType.h:40
covarianceTool.convertHistToScatter
def convertHistToScatter(ao)
Definition: covarianceTool.py:69
python.CaloScaleNoiseConfig.type
type
Definition: CaloScaleNoiseConfig.py:78
python.KeyStore.list
def list(self, key=None)
Definition: KeyStore.py:318
Muon::print
std::string print(const MuPatSegment &)
Definition: MuonTrackSteering.cxx:28
python.Bindings.keys
keys
Definition: Control/AthenaPython/python/Bindings.py:790
readCCLHist.float
float
Definition: readCCLHist.py:83
Trk::split
@ split
Definition: LayerMaterialProperties.h:38
covarianceTool.makeBeamer
def makeBeamer(plotDictionary, outdir)
Definition: covarianceTool.py:93
covarianceTool.isFloat
def isFloat(x)
Definition: covarianceTool.py:60