def rebin(histogram, binning): ''' Rebin a histogram [binning] can be either an integer, or a list/tuple for variable bin sizes. ''' # Just merging bins if isinstance(binning, int): if binning == 1 or isinstance(histogram, ROOT.TH2): return histogram histogram.Rebin(binning) return histogram # Fancy variable size bins if isinstance(histogram, ROOT.TH2): if not isinstance(binning[0], (list, tuple)): return histogram #print binning[0], ' ' , binning[1] bin_arrayx = binning[0] #array.array('d',binning[0]) bin_arrayy = binning[1] #array.array('d',binning[1]) if len(binning[0]) ==1 and len(binning[1])==1 : return asrootpy(histogram.Rebin2D(int(binning[0][0]),int(binning[1][0]), histogram.GetName() + 'rebin')) else: return RebinView.newRebin2D(histogram, bin_arrayx, bin_arrayy) elif isinstance(histogram, ROOT.TH1): if isinstance(binning[0], (list, tuple)): raise ValueError( "You are providing a binning scheme (%s) " "not compatible with 1D hists!" % (binning.__repr__())) bin_array = array.array('d', binning) ret = asrootpy( histogram.Rebin(len(binning)-1, histogram.GetName() + 'rebin', bin_array) ) if hasattr(histogram, 'decorators'): ret.decorate( **histogram.decorators ) return ret else: raise ValueError('ERROR in RebinView: not a TH1 or TH2 histo. Rebin not done') return histogram
def Get(self, path): hist = self.input.Get(path) if not isinstance(hist, (ROOT.TH2, ROOT.TH3)): return hist #nothin to do projection_axis = 'X' if self.axis.upper() == 'Y' else 'Y' axis = getattr(hist, 'Get%saxis' % projection_axis)() min_bin = axis.FindFixBin(self.range[0]) max_bin = axis.FindFixBin(self.range[1]) if axis.GetBinLowEdge(max_bin) == self.range[1]: max_bin -= 1 output = getattr(hist, 'Projection%s' % self.axis.upper())(hist.GetName() + '_projection', min_bin, max_bin) output = asrootpy( output ) #print "ProjectionView: path %s, minimum:%.2f --> %i, maximum:%.2f --> %i, integral: %.3f entries: %i" % (path, self.range[0], min_bin, self.range[1], max_bin, output.Integral(), output.GetEntries()) output.decorate( **hist.decorators ) output.SetTitle( hist.GetTitle() ) #print hist.GetTitle(), output.GetTitle() return output
def Get(self, path): hist = self.input.Get(path) if not isinstance(hist, (ROOT.TH2, ROOT.TH3)): return hist #nothin to do projection_axis = 'X' if self.axis.upper() == 'Y' else 'Y' axis = getattr(hist, 'Get%saxis' % projection_axis)() min_bin = axis.FindFixBin(self.range[0]) max_bin = axis.FindFixBin(self.range[1]) if axis.GetBinLowEdge(max_bin) == self.range[1]: max_bin -= 1 output = getattr(hist, 'Projection%s' % self.axis.upper())( hist.GetName() + '_projection', min_bin, max_bin) output = asrootpy(output) #print "ProjectionView: path %s, minimum:%.2f --> %i, maximum:%.2f --> %i, integral: %.3f entries: %i" % (path, self.range[0], min_bin, self.range[1], max_bin, output.Integral(), output.GetEntries()) output.decorate(**hist.decorators) output.SetTitle(hist.GetTitle()) #print hist.GetTitle(), output.GetTitle() return output
def rebin(self, histogram, binning): ''' Rebin a histogram [binning] can be either an integer, or a list/tuple for variable bin sizes. ''' # Just merging bins if isinstance(binning, int): if binning == 1 or isinstance(histogram, ROOT.TH2): return histogram histogram.Rebin(binning) return histogram # Fancy variable size bins if isinstance(histogram, ROOT.TH2): if not isinstance(binning[0], (list, tuple)): return histogram #print binning[0], ' ' , binning[1] bin_arrayx = binning[0] #array.array('d',binning[0]) bin_arrayy = binning[1] #array.array('d',binning[1]) if len(binning[0]) == 1 and len(binning[1]) == 1: return histogram.Rebin2D(int(binning[0][0]), int(binning[1][0]), histogram.GetName() + 'rebin') else: return self.newRebin2D(histogram, bin_arrayx, bin_arrayy) elif isinstance(histogram, ROOT.TH1): if isinstance(binning[0], (list, tuple)): return histogram bin_array = array.array('d', binning) ret = asrootpy( histogram.Rebin( len(binning) - 1, histogram.GetName() + 'rebin', bin_array)) if hasattr(histogram, 'decorators'): ret.decorate(**histogram.decorators) return ret else: print 'ERROR in RebinView: not a TH1 or TH2 histo. Rebin not done' return histogram
def rebin(self, histogram, binning): ''' Rebin a histogram [binning] can be either an integer, or a list/tuple for variable bin sizes. ''' # Just merging bins if isinstance(binning, int): if binning == 1 or isinstance(histogram, ROOT.TH2): return histogram histogram.Rebin(binning) return histogram # Fancy variable size bins if isinstance(histogram, ROOT.TH2): if not isinstance(binning[0], (list, tuple)): return histogram #print binning[0], ' ' , binning[1] bin_arrayx = binning[0] #array.array('d',binning[0]) bin_arrayy = binning[1] #array.array('d',binning[1]) if len(binning[0]) ==1 and len(binning[1])==1 : return histogram.Rebin2D(int(binning[0][0]),int(binning[1][0]), histogram.GetName() + 'rebin') else: return self.newRebin2D(histogram, bin_arrayx, bin_arrayy) elif isinstance(histogram, ROOT.TH1): if isinstance(binning[0], (list, tuple)): return histogram bin_array = array.array('d', binning) ret = asrootpy( histogram.Rebin(len(binning)-1, histogram.GetName() + 'rebin', bin_array) ) if hasattr(histogram, 'decorators'): ret.decorate( **histogram.decorators ) return ret else: print 'ERROR in RebinView: not a TH1 or TH2 histo. Rebin not done' return histogram
from rootpy.plotting import Canvas, Legend, HistStack from FinalStateAnalysis.Utilities.AnalysisPlotter import styling,samplestyles import rootpy.io as io import FinalStateAnalysis.StatTools.poisson as poisson # This stuff is just so we can get matching styles as analysis.py import FinalStateAnalysis.PatTools.data as data_tool int_lumi = 5000 skips = ['DoubleEl', 'EM'] samples, plotter = data_tool.build_data( 'VH', '2012-04-14-v1-WHAnalyze', 'scratch_results', int_lumi, skips, count='emt/skimCounter') # Get stupid templates to build the styles automatically signal = asrootpy(plotter.get_histogram( 'VH120', 'emt/skimCounter', ).th1) wz = asrootpy(plotter.get_histogram( 'WZ', 'emt/skimCounter', ).th1) zz = asrootpy(plotter.get_histogram( 'ZZ', 'emt/skimCounter', ).th1) fakes_myhist = asrootpy(plotter.get_histogram( 'Zjets', 'emt/skimCounter',
if args.plot: canvas = ROOT.TCanvas("asdf", "asdf", 800, 600) canvas.SetLogz(True) myeff.Draw("LEGO") efficiency.Draw("SURFSAME") # import pdb; pdb.set_trace() canvas.SaveAs(args.output) plot_name = args.output.replace('.root', '.png') # log.info("Saving fit plot in %s", plot_name) canvas.SaveAs(plot_name) canvas.SaveAs(plot_name.replace('.png', '.pdf')) canvas.SetLogz(False) canvas.SetLogy(True) graph_proj_x = asrootpy( myeff.Projection(ROOT.TEfficiencyBugFixed.xaxis) ) graph_proj_x.SetMarkerStyle(20) graph_proj_x.title = 'data' fcn_proj_x = asrootpy( myeff.ProjectFunction(ROOT.TEfficiencyBugFixed.xaxis, all_histo_finebin) ) \ if all_histo_finebin else \ asrootpy( myeff.ProjectFunction(ROOT.TEfficiencyBugFixed.xaxis) ) print graph_proj_x, fcn_proj_x fcn_proj_x.SetName('fcn_proj_x') fcn_proj_x.SetFillStyle(0) fcn_proj_x.Draw('AL') graph_proj_x.Draw('P SAME') plot_name = plot_name.replace('.png', '_projX.png') canvas.SaveAs(plot_name) canvas.SaveAs(plot_name.replace('.png', '.pdf')) graph_proj_y = asrootpy( myeff.Projection(ROOT.TEfficiencyBugFixed.yaxis) )
def apply_view(self, histo): graph = poisson.convert(histo, self.x_err, self.set_zero_bins, self.is_scaled) graph.SetMarkerSize(self.marker_size) return asrootpy(graph)
value = var_d[var] hist_maps[var]['estimate'].Fill(value, mva*weight) hist_maps[var]['all'].Fill(value, weight) hist_maps[var]['estimate_all'].Fill(value, weight) if cut: hist_maps[var]['pass'].Fill(value, weight) canvas = plotting.Canvas(name='adsf', title='asdf') canvas.SetLogy(True) for var in args.variables: for key in hist_maps[var].iterkeys(): hist_maps[var][key] = round_to_ints(hist_maps[var][key]) eff = asrootpy( ROOT.TGraphAsymmErrors( hist_maps[var]['pass'], hist_maps[var]['all']) ) eff.markerstyle = 20 estimate = hist_maps[var]['estimate'].Clone() #avoid getting divided estimate.Divide(hist_maps[var]['estimate_all']) estimate.linecolor = ROOT.kBlue estimate.linewidth = 2 estimate.fillstyle = 0 estimate.drawstyle = 'hist' estimate.Draw() eff.Draw('P same') canvas.Update() canvas.SetLogy(True) canvas.SaveAs( output_file.replace('.root', '.%s.png' % var ) ) for key, obj in hist_maps[var].iteritems():
# write some histograms h1 = Hist(100, 0, 100, name='h1', type='I') # variable bin widths h2 = Hist2D((0, 3, 5, 20, 50), (10, 20, 30, 40, 1000), name='h2') h1.Write() h2.Write() # file is automatically closed after with statement # retrieve the histograms previously saved with open('data.root') as f: h1 = f.h1 # or h1 = f.Get('h1') h2 = f.h2 # or h2 = f.Get('h2') # ROOT classes are automatically converted into # rootpy form when retrieved from a ROOT file as # long as their module was previously imported print h1.__class__.__name__ print h2.__class__.__name__ # you may also do this to convert an object into # rootpy form (again, assuming the relevant module # was previously imported) h1 = asrootpy(h1) # if it is already in rootpy form or if no rootpy form # exists then asrootpy does nothing print h1.__class__.__name__
binning = int(args.rebin) input_view = RebinView(input_view, binning) log.info("Getting histograms") pass_histo = input_view.Get(args.num) all_histo = input_view.Get(args.denom) #canvas = ROOT.TCanvas("asdf", "asdf", 800, 600) #pass_histo.Draw() #canvas.SaveAs( args.output.replace(".root", "numerator.root")) #all_histo.Draw() #canvas.SaveAs(args.output.replace(".root", "denominator.root")) ##make slice if necessary if args.slice: #maybe a check if is 2d would be a good thing log.info("Slicing! Slice #%s" % args.slice) #project pass_histo_px = asrootpy( pass_histo.ProjectionX('pass_histo_px', args.slice, args.slice, "e") ) all_histo_px = asrootpy( all_histo.ProjectionX('all_histo_px', args.slice, args.slice, "e") ) #get rootpy plotting stuff pass_histo_px.decorate( **pass_histo.decorators ) all_histo_px.decorate( **all_histo.decorators ) #reassign variables pass_histo = pass_histo_px all_histo = all_histo_px if not all_histo.Integral(): log.info("no entries in denominator!") else: log.info("pass/all = %0.0f/%0.0f = %0.2f%%",
if weight > 0: #fill only data-like events hist_maps[var]['estimate'].Fill(value, weight*mva) hist_maps[var]['estimate_all'].Fill(value, weight) hist_maps[var]['all'].Fill(value, weight) if cut: hist_maps[var]['pass'].Fill(value, weight) canvas = plotting.Canvas(name='adsf', title='asdf') canvas.SetLogy(True) for var in args.variables: for key in ['pass', 'all']: #hist_maps[var].iterkeys(): hist_maps[var][key] = round_to_ints(hist_maps[var][key]) eff = asrootpy( ROOT.TGraphAsymmErrors( hist_maps[var]['pass'], hist_maps[var]['all']) ) eff.markerstyle = 20 eff.SetName('efficiency_%s' % var) estimate = hist_maps[var]['estimate'].Clone() #avoid getting divided estimate.Divide(hist_maps[var]['estimate_all']) estimate.SetName('estimate_%s' % var) estimate.linecolor = ROOT.kBlue estimate.linewidth = 2 estimate.fillstyle = 0 estimate.drawstyle = 'hist' estimate.Draw() eff.Draw('P same') canvas.Update() canvas.SetLogy(True) canvas.SaveAs( output_file.replace('.root', '.%s.png' % var ) )
import FinalStateAnalysis.StatTools.limitplot as limitplot import FinalStateAnalysis.Utilities.styling as styling print args.plot1, args.plot4 plots_to_comp = [] key = (args.method, args.label) xmin = 1e9 xmax = -1e9 for plot in [args.plot1, args.plot2, args.plot3, args.plot4]: if plot: the_glob, title, type, color = tuple(plot) limit_data = limitplot.get_limit_info(glob.glob(the_glob)) tgraph = asrootpy(limitplot.build_line(limit_data, key, type)) print tgraph tgraph.SetLineColor(color) plots_to_comp.append((tgraph, title)) xmin = min(min(limit_data[key].keys()), xmin) xmax = max(max(limit_data[key].keys()), xmax) canvas = ROOT.TCanvas("c", "c", args.cx, args.cy) if args.maxx > 0: xmax = args.maxx frame = ROOT.TH1F("frame", "frame", 1, xmin, xmax) frame.Draw() #frame.SetTitle("WH(#tau#tau) limits [4.6 fb^{-1}]")
if args.plot: canvas = ROOT.TCanvas("asdf", "asdf", 800, 600) canvas.SetLogz(True) myeff.Draw("LEGO") efficiency.Draw("SURFSAME") # import pdb; pdb.set_trace() canvas.SaveAs(args.output) plot_name = args.output.replace('.root', '.png') # log.info("Saving fit plot in %s", plot_name) canvas.SaveAs(plot_name) canvas.SaveAs(plot_name.replace('.png', '.pdf')) canvas.SetLogz(False) canvas.SetLogy(True) graph_proj_x = asrootpy( myeff.Projection(ROOT.TEfficiencyBugFixed.xaxis)) graph_proj_x.SetMarkerStyle(20) graph_proj_x.title = 'data' fcn_proj_x = asrootpy( myeff.ProjectFunction(ROOT.TEfficiencyBugFixed.xaxis, all_histo_finebin) ) \ if all_histo_finebin else \ asrootpy( myeff.ProjectFunction(ROOT.TEfficiencyBugFixed.xaxis) ) print graph_proj_x, fcn_proj_x fcn_proj_x.SetName('fcn_proj_x') fcn_proj_x.SetFillStyle(0) fcn_proj_x.Draw('AL') graph_proj_x.Draw('P SAME') plot_name = plot_name.replace('.png', '_projX.png') canvas.SaveAs(plot_name) canvas.SaveAs(plot_name.replace('.png', '.pdf')) graph_proj_y = asrootpy(
# write some histograms h1 = Hist(100, 0, 100, name='h1', type='I') # variable bin widths h2 = Hist2D((0,3,5,20,50), (10,20,30,40,1000), name='h2') h1.Write() h2.Write() # file is automatically closed after with statement # retrieve the histograms previously saved with open('data.root') as f: h1 = f.h1 # or h1 = f.Get('h1') h2 = f.h2 # or h2 = f.Get('h2') # ROOT classes are automatically converted into # rootpy form when retrieved from a ROOT file as # long as their module was previously imported print h1.__class__.__name__ print h2.__class__.__name__ # you may also do this to convert an object into # rootpy form (again, assuming the relevant module # was previously imported) h1 = asrootpy(h1) # if it is already in rootpy form or if no rootpy form # exists then asrootpy does nothing print h1.__class__.__name__
if ',' in args.rebin: binning = tuple(int(x) for x in args.rebin.split(',')) else: binning = int(args.rebin) input_view = RebinView(input_view, binning) log.info("Getting histograms") pass_histo = input_view.Get(args.num) all_histo = input_view.Get(args.denom) #make slice if necessary if args.slice: #maybe a check if is 2d would be a good thing log.info("Slicing! Slice #%s" % args.slice) #project pass_histo_px = asrootpy( pass_histo.ProjectionX('pass_histo_px', args.slice, args.slice, "e")) all_histo_px = asrootpy( all_histo.ProjectionX('all_histo_px', args.slice, args.slice, "e")) #get rootpy plotting stuff pass_histo_px.decorate(**pass_histo.decorators) all_histo_px.decorate(**all_histo.decorators) #reassign variables pass_histo = pass_histo_px all_histo = all_histo_px if not all_histo.Integral(): log.info("no entries in denominator!") else: