Page MenuHomeHEPForge

aida2root
No OneTemporary

aida2root

#! /usr/bin/env python
#Verify in the ROOT user manual what needs to be setup
# for use of ROOT with python
#
#E.g. do the following additional setup steps:
# setup setenv PYTHONDIR /usr
# setenv PATH $ROOTSYS/bin:$PYTHONDIR/bin:$PATH
# setenv LD_LIBRARY_PATH $ROOTSYS/lib:$PYTHONDIR/lib/python2.3:$LD_LIBRARY_PATH
# setenv PYTHONPATH $ROOTSYS/lib:$PYTHONDIR/lib/python2.3
import sys, os
from ROOT import TGraphAsymmErrors, TFile
from array import array
try:
sorted([])
except:
def sorted(coll):
coll.sort()
return coll
class Histo:
def __init__(self):
self._bins = []
self.path = None
self.name = None
self.title = None
def __cmp__(self, other):
"""Sort by $path/$name string"""
return self.fullPath() > other.fullPath()
def __str__(self):
out = "Histogram '%s' with %d bins\n" % (self.fullPath(), self.numBins())
out += "Title: %s\n" % self.title
out += "\n".join([str(b) for b in self.getBins()])
return out
def fullPath(self):
return os.path.join(self.path, self.name)
def asFlat(self):
out = "### %s\n" % self.fullPath()
out += "## Title: %s\n" % self.title
out += "## Area: %s\n" % self.area()
out += "## Num bins: %d\n" % self.numBins()
out += "## xlow xhigh yval yerrminus yerrplus\n"
out += "\n".join([b.asFlat() for b in self.getBins()])
return out
def asRoot(self):
xerrminus = array('f',self.numBins()*[0.])
xerrplus = array('f',self.numBins()*[0.])
xval = array('f',self.numBins()*[0.])
yval = array('f',self.numBins()*[0.])
yerrminus = array('f',self.numBins()*[0.])
yerrplus= array('f',self.numBins()*[0.])
ibin = 0
for b in self.getBins():
xval[ibin] = b.getXval()
yval[ibin] = b.getYval()
xerrminus[ibin], xerrplus[ibin] = b.getXErrors()
yerrminus[ibin], yerrplus[ibin] = b.getYErrors()
#print 'xerrminus=',xerrminus[ibin],' xerrplus=',xerrplus[ibin],' xval=',xval[ibin],' yval=',yval[ibin],' yerrplus=',yerrplus[ibin],' yerrminus=',yerrminus[ibin]
ibin = ibin +1
tg = TGraphAsymmErrors(self.numBins(), xval, yval, xerrminus, xerrplus, yerrminus, yerrplus);
tg.SetTitle(self.title);
tg.SetName(self.name.replace("-", "_"));
return tg
def numBins(self):
return len(self._bins)
def getBins(self):
return sorted(self._bins)
def setBins(self, bins):
self._bins = bins
return self
def addBin(self, bin):
self._bins.append(bin)
return self
def getBin(self, index):
self._bins.sort()
return self.getBins()[index]
bins = property(getBins, setBins)
def area(self):
return sum([bin.area() for bin in self.bins])
def __iter__(self):
return iter(self.getBins())
def __len__(self):
return len(self._bins)
def __getitem__(self, index):
return self.getBin(index)
class Bin:
"""A simple container for a binned value with an error."""
def __init__(self, xval=0, xerrminus=None, xerrplus=None, yval=0, yerrminus=0, yerrplus=0, focus=None):
self.xval = xval
self.xerrplus = xerrplus
self.xerrminus= xerrminus
self.yval = yval
self.yerrplus = yerrplus
self.yerrminus = yerrminus
self.focus= focus
def __str__(self):
out = "%f to %f: %f +- %f" % (self.xval-self.xerrminus, self.xval+self.xerrplus, self._yval, self._yerr)
return out
def asFlat(self):
out = "%f %f %f %f %f" % (self.xval-self.xerrminus, self.xval+self.xerrplus, self.yval, self.yerrminus, self.yerrplus)
return out
def __cmp__(self, other):
"""Sort by mean x value (yeah, I know...)"""
return (self.xval) > (other.xval)
def getXRange(self):
return (self.xval-self.xerrminus, self.xval+self.xerrplus)
def getXErrors(self):
return (self.xerrminus, self.xerrplus)
def setXRange(self, xlow, xhigh):
self.xlow = xlow
self.xhigh = xhigh
return self
def getYErrors(self):
return (self.yerrminus, self.yerrplus)
def getBinCenter(self):
"""Geometric middle of the bin range."""
return self.xlow + .5*(self.xhigh - self.xlow)
def getFocus(self):
"""Mean x-value of the bin."""
if self.focus is not None:
return (self.xlow + self.xhigh)/2.0
else:
return self.focus
def getXval(self):
return self.xval
def getYval(self):
return self.yval
def area(self):
return self.yval * (self.xerrplus - self.xerrminus)
def getYErr(self):
"""Get mean of +ve and -ve y-errors."""
return (self.yerrplus + self.yerrminus)/2.0
def setYErr(self, yerr):
"""Set both +ve and -ve y-errors simultaneously."""
self.yerrplus = yerr
self.yerrminus = yerr
return self
## Try to load faster but non-standard cElementTree module
try:
import xml.etree.cElementTree as ET
except ImportError:
try:
import cElementTree as ET
except ImportError:
import xml.etree.ElementTree as ET
def mkHistoFromDPS(dps):
"""Make a mini histo representation from an AIDA dataPointSet tag."""
myhist = Histo()
myhist.name = dps.get("name")
myhist.title = dps.get("title")
myhist.path = dps.get("path")
points = dps.findall("dataPoint")
numbins = len(points)
for binnum, point in enumerate(points):
bin = Bin()
for d, m in enumerate(point.findall("measurement")):
val = float(m.get("value"))
down = float(m.get("errorMinus"))
up = float(m.get("errorPlus"))
if d == 0:
low = val - down
high = val + up
bin.setXRange(low, high)
bin.xval = val
bin.xerrplus = up
bin.xerrminus = down
elif d == 1:
bin.yval = val
bin.yerrplus = up
bin.yerrminus = down
myhist.addBin(bin)
return myhist
from optparse import OptionParser
parser = OptionParser(usage="%prog aidafile [aidafile2 ...]")
parser.add_option("-s", "--smart-output", action="store_true", default=True,
help="Write to output files with names based on the corresponding input filename",
dest="SMARTOUTPUT")
parser.add_option("-m", "--match", action="append",
help="Only write out histograms whose $path/$name string matches these regexes",
dest="PATHPATTERNS")
opts, args = parser.parse_args()
if opts.PATHPATTERNS is None:
opts.PATHPATTERNS = []
if len(args) < 1:
sys.stderr.write("Must specify at least one AIDA histogram file\n")
sys.exit(1)
import re
for aidafile in args:
out = sys.stdout
tree = ET.parse(aidafile)
histos = []
for dps in tree.findall("dataPointSet"):
useThisDps = True
if len(opts.PATHPATTERNS) > 0:
useThisDps = False
dpspath = os.path.join(dps.get("path"), dps.get("name"))
for regex in opts.PATHPATTERNS:
if re.compile(regex).search(dpspath):
useThisDps = True
break
if useThisDps:
histos.append(mkHistoFromDPS(dps))
if len(histos) > 0:
if opts.SMARTOUTPUT:
outfile = os.path.basename(aidafile).replace(".aida", ".root")
out = TFile(outfile,"RECREATE")
for h in sorted(histos):
h.asRoot().Write()
out.Close()
else:
sys.stderr.write("ROOT objects must be written to a file")

File Metadata

Mime Type
text/x-python
Expires
Sat, Dec 21, 3:20 PM (1 d, 35 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
4023269
Default Alt Text
aida2root (7 KB)

Event Timeline