ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/UserCode/RootMacros/overlayHists.py
Revision: 1.7
Committed: Mon Nov 23 21:44:18 2009 UTC (15 years, 5 months ago) by klukas
Content type: text/x-python
Branch: MAIN
Changes since 1.6: +19 -7 lines
Log Message:
Tweaked colors, improved handling of no arguments and lack of rootlogon, added option for markers

File Contents

# User Rev Content
1 klukas 1.1 #!/usr/bin/env python
2    
3     ## Created by Jeff Klukas (klukas@wisc.edu), November 2009
4    
5     ## For more information, use the -h option:
6     ## ./overlayHists.py -h
7    
8     ## Define usage string for help option
9     usage="""usage: %prog [options] file1.root file2.root file3.root ...
10    
11 klukas 1.3 function: overlays corresponding histograms from several files, dumping the
12     images into an identical directory structure in the local directory
13     and also merging all images into a single file (if output is pdf)
14 klukas 1.1
15     naming: histograms whose names contain certain key terms will be handled
16     specially. Use this to your advantage!
17     'Eff' : y-axis will be scaled from 0 to 1
18     'Norm': plot will be area normalized
19     'Logx': x-axis will be on log scale
20     'Logy': y-axis will be on log scale"""
21    
22 klukas 1.7 ## Define colors and styles
23 klukas 1.4 rgbvals = [[82, 124, 219],
24 klukas 1.7 [212,58,143],
25     [231, 139, 77],
26 klukas 1.4 [145, 83, 207],
27     [114, 173, 117],
28     [67, 77, 83]]
29 klukas 1.7 marker_styles = [3, 4, 5, 25, 26, 27, 28, 30]
30 klukas 1.1
31     ## Import python libraries
32     import sys
33     import optparse
34     import os
35     import re
36    
37     ## Import ROOT in batch mode
38 klukas 1.7 if '-h' not in sys.argv and len(sys.argv) > 1:
39 klukas 1.1 sys.argv.append('-b')
40     import ROOT
41 klukas 1.7 if os.path.exists('rootlogon.C'):
42     ROOT.gROOT.Macro('rootlogon.C')
43     else:
44     os.system('echo -e "{\n}\n" >> rootlogon.C')
45     ROOT.gROOT.Macro('rootlogon.C')
46     os.remove('rootlogon.C')
47 klukas 1.1 sys.argv.remove('-b')
48     ROOT.gErrorIgnoreLevel = ROOT.kWarning
49 klukas 1.4 colors = [ROOT.TColor.GetColor(rgb[0], rgb[1], rgb[2]) for rgb in rgbvals]
50 klukas 1.1 c1 = ROOT.TCanvas()
51    
52     ## Parse options
53     parser = optparse.OptionParser(usage=usage)
54     parser.add_option('-n', '--normalize', action="store_true", default=False,
55     help="area normalize all histograms")
56 klukas 1.7 parser.add_option('-m', '--markers', action="store_true", default=False,
57     help="add markers to histograms")
58 klukas 1.1 parser.add_option('-e', '--ext', default="pdf",
59 klukas 1.3 help="choose an output extension; default is pdf")
60 klukas 1.1 parser.add_option('-o', '--output', default="overlaidHists", metavar="NAME",
61 klukas 1.3 help="name of output directory; default is 'overlaidHists'")
62 klukas 1.7 parser.add_option('--match', default="", metavar="REGEX",
63 klukas 1.3 help="only make plots for paths containing the specified "
64     "regular expression (use '.*' for wildcard)")
65 klukas 1.1 options, arguments = parser.parse_args()
66     plot_dir = "%s/%s" % (os.path.abspath('.'), options.output)
67     regex = re.compile(options.match)
68    
69    
70 klukas 1.4
71 klukas 1.1 class RootFile:
72     def __init__(self, file_name):
73     self.name = file_name[0:file_name.find(".root")]
74     self.file = ROOT.TFile(file_name, "read")
75     if self.file.IsZombie():
76     print "Error opening %s, exiting..." % file_name
77     sys.exit(1)
78     def Get(self, object_name):
79     return self.file.Get(object_name)
80    
81    
82    
83     def main():
84 klukas 1.4 files = [RootFile(filename) for filename in arguments]
85 klukas 1.2 if len(files) == 0:
86     parser.print_help()
87     sys.exit(0)
88 klukas 1.1 process_directory("", files)
89 klukas 1.6 print
90 klukas 1.1 if options.ext == "pdf":
91 klukas 1.6 print "Writing merged pdf..."
92 klukas 1.1 os.system("gs -q -dBATCH -dNOPAUSE -sDEVICE=pdfwrite "
93     "-dAutoRotatePages=/All "
94     "-sOutputFile=%s.pdf " % options.output +
95     "[0-9][0-9][0-9].pdf")
96     os.system("rm [0-9]*.pdf")
97    
98    
99    
100     def process_directory(path, files):
101     dir_to_make = "%s/%s" % (plot_dir, path)
102     if not os.path.exists(dir_to_make):
103     os.mkdir(dir_to_make)
104     keys = files[0].file.GetDirectory(path).GetListOfKeys()
105     key = keys[0]
106     while key:
107     obj = key.ReadObj()
108     key = keys.After(key)
109     new_path = "%s/%s" % (path, obj.GetName())
110     if obj.IsA().InheritsFrom("TDirectory"):
111     process_directory(new_path, files)
112     if (regex.search(new_path) and
113     obj.IsA().InheritsFrom("TH1") and
114     not obj.IsA().InheritsFrom("TH2") and
115     not obj.IsA().InheritsFrom("TH3")):
116     counter = next_counter()
117     name = obj.GetName()
118     hist = files[0].file.GetDirectory(path).Get(name)
119     title = hist.GetTitle()
120     x_title = hist.GetXaxis().GetTitle()
121     y_title = hist.GetYaxis().GetTitle()
122     if "Norm" in name or options.normalize:
123     y_title = "Fraction of Events in Bin"
124     hist.Draw()
125     stack = ROOT.THStack("st%.3i" % int(counter), title)
126 klukas 1.5 legend_height = 0.04 * len(files) + 0.02
127     legend = ROOT.TLegend(0.65, 0.89 - legend_height, 0.87, 0.89)
128 klukas 1.1 c1.SetLogx("Logx" in name)
129     c1.SetLogy("Logy" in name)
130     for i, file in enumerate(files):
131     hist = file.file.GetDirectory(path).Get(name)
132     if not hist: continue
133     hist.Draw()
134     hist.SetTitle(file.name)
135     color = colors[i % len(colors)]
136     hist.SetLineColor(color)
137 klukas 1.7 if options.markers:
138     hist.SetMarkerColor(color)
139     hist.SetMarkerStyle(marker_styles[i])
140     else:
141     hist.SetMarkerSize(0)
142 klukas 1.1 if "Norm" in name or options.normalize:
143     integral = hist.Integral()
144 klukas 1.4 hist.Scale(1. / integral)
145 klukas 1.1 stack.Add(hist)
146     legend.AddEntry(hist)
147     stack.Draw("nostack p H")
148     stack.SetTitle("%s;%s;%s" % (title, x_title, y_title))
149     if "Eff" in name:
150     stack.Draw("nostack e p")
151     stack.SetMaximum(1.)
152     stack.SetMinimum(0.)
153     legend.Draw()
154     if options.ext == "pdf":
155     c1.SaveAs("%.3i.pdf" % counter)
156     c1.SaveAs("%s/%s/%s.%s" % (plot_dir, path, name, options.ext))
157 klukas 1.6 print "\r%i plots written to %s" % (counter, options.output),
158     sys.stdout.flush()
159 klukas 1.1
160    
161    
162     def counter_generator():
163     k = 0
164     while True:
165     k += 1
166     yield k
167     next_counter = counter_generator().next
168    
169    
170    
171     if __name__ == "__main__":
172     sys.exit(main())
173