def init_canvas( ratiopad = False): if not ratiopad: canvas = rp.Canvas(width = 1024, height = 768) canvas.SetTopMargin(0.07) canvas.SetBottomMargin(0.15) canvas.SetRightMargin(0.05) canvas.SetLeftMargin(0.15) canvas.SetTicks(1,1) else: canvas = rp.Canvas(width = 1024, height = 1024) canvas.Divide(1,2) canvas.cd(1).SetPad(0.,0.3,1.0,1.0) canvas.cd(1).SetTopMargin(0.07) canvas.cd(1).SetBottomMargin(0.0) canvas.cd(2).SetPad(0.,0.0,1.0,0.3) canvas.cd(2).SetTopMargin(0.0) canvas.cd(2).SetBottomMargin(0.4) canvas.cd(1).SetRightMargin(0.05) canvas.cd(1).SetLeftMargin(0.15) canvas.cd(1).SetTicks(1,1) canvas.cd(2).SetRightMargin(0.05) canvas.cd(2).SetLeftMargin(0.15) canvas.cd(2).SetTicks(1,1) return canvas
def __init__(self, outputdir='./', defaults={}, styles={}): ''' Initialize the BasePlotter outputdir is where histograms will be saved. defaults provides basic configuration of the plotter. Most of the options can be anyway overridden by the specific command in case one exception to the general rule is needed. Available defaults: - clone : (bool, default True) chooses the clone policy. If true histograms will be cloned before being styled and drawn - show_title : (bool, default False) shows the histogram title in the canvas - name_canvas: (bool, default False) name the canvas after the histogram.name it is drawn inside - save: (dict, default {'png' : True, 'pdf' : True, 'dotc' : False, 'dotroot' : False, 'json' : False} set the formats to which save the canvas styles provides the plotter a look-up table of styles to be applied to the histograms in the form key : style. Key is a POSIX regular expression that is matched to the histogram title. ''' self.outputdir = outputdir self.base_out_dir = outputdir self.canvas = plotting.Canvas(800, 800, name='adsf', title='asdf') self.set_canvas_style(self.canvas) self.canvas.cd() self.pad = plotting.Pad(0., 0., 1., 1.) #ful-size pad self.pad.Draw() self.set_canvas_style(self.pad) self.pad.cd() self.lower_pad = None self.keep = [] self.defaults = defaults self.styles = styles self.label_factor = None BasePlotter.set_canvas_style(self.canvas) self.set_style()
def __init__(self, files, lumifiles, outputdir, blinder=None): ''' Initialize the Plotter object Files should be a list of SAMPLE_NAME.root files. Lumifiles should contain floats giving the effective luminosity of each of the files. If [blinder] is not None, it will be applied to the data view. ''' self.outputdir = outputdir self.views = data_views(files, lumifiles) self.canvas = plotting.Canvas(name='adsf', title='asdf') self.canvas.cd() if blinder: # Keep the unblinded data around if desired. self.views['data']['unblinded_view'] = self.views['data']['view'] # Apply a blinding function self.views['data']['view'] = blinder(self.views['data']['view']) self.data = self.views['data']['view'] self.keep = [] # List of MC sample names to use. Can be overridden. self.mc_samples = [ 'Zjets_M50', 'WplusJets_madgraph', 'TTplusJets_madgraph', 'WZ*', 'ZZ*', 'WW*', ]
def make_hist(key, rfit_vals, out, prefix=''): canvas = plotting.Canvas() vals = [i.getVal() for i in rfit_vals] hist = fill_hist(vals) hist.Draw() log.debug('%s has %i entries, %.0f integral' % (key, hist.GetEntries(), hist.Integral())) canvas.SaveAs('%s/%s%s.png' % (out, prefix, key.replace('/','_')))
def create_and_save_canvas(histo, xname): canvas = plotting.Canvas() histo.SetStats(True) histo.GetXaxis().SetName(xname) histo.Draw() canvas.Update() canvas.SaveAs('%s.png' % histo.GetName()) canvas.SaveAs('%s.pdf' % histo.GetName())
def reset(self): '''hard graphic reset''' del self.canvas del self.pad del self.lower_pad self.keep = [] self.canvas = plotting.Canvas(name='adsf', title='asdf') self.canvas.cd() self.pad = plotting.Pad('up', 'up', 0., 0., 1., 1.) #ful-size pad self.pad.Draw() self.pad.cd() self.lower_pad = None
def reset(self): '''hard graphic reset''' del self.canvas del self.pad del self.lower_pad self.keep = [] self.canvas = plotting.Canvas(800, 800, name='adsf', title='asdf') BasePlotter.set_canvas_style(self.canvas) self.canvas.cd() self.pad = plotting.Pad(0., 0., 1., 1.) #ful-size pad self.pad.Draw() BasePlotter.set_canvas_style(self.pad) self.pad.cd() self.lower_pad = None self.label_factor = None
def __init__(self, files, lumifiles, outputdir, blinder=None, forceLumi=-1): ''' Initialize the Plotter object Files should be a list of SAMPLE_NAME.root files. Lumifiles should contain floats giving the effective luminosity of each of the files. If [blinder] is not None, it will be applied to the data view. ''' self.outputdir = outputdir self.views = data_views(files, lumifiles, forceLumi) self.canvas = plotting.Canvas(name='adsf', title='asdf') self.canvas.cd() self.pad = plotting.Pad('up', 'up', 0., 0., 1., 1.) #ful-size pad self.pad.Draw() self.pad.cd() self.lower_pad = None if blinder: # Keep the unblinded data around if desired. self.views['data']['unblinded_view'] = self.views['data']['view'] # Apply a blinding function self.views['data']['view'] = blinder(self.views['data']['view']) self.data = self.views['data']['view'] self.keep = [] # List of MC sample names to use. Can be overridden. self.mc_samples = [ 'Zjets_M50', 'WplusJets_madgraph', 'TTplusJets_madgraph', 'WZ*', 'ZZ*', 'WW*', ] file_to_map = filter(lambda x: x.startswith('data_'), self.views.keys())[0] if not file_to_map: #no data here! file_to_map = self.views.keys()[0] #from pdb import set_trace; set_trace() self.file_dir_structure = Plotter.map_dir_structure( self.views[file_to_map]['file'])
def overlay(reference, target): canvas = plotting.Canvas(name='adsf', title='asdf') reference.linecolor = 'red' reference.Draw('hist') target.markerstyle = 20 target.Draw('E1P same') maxreference = reference.GetBinContent(reference.GetMaximumBin()) maxtarget = target.GetBinContent(target.GetMaximumBin()) minreference = reference.GetBinContent(reference.GetMinimumBin()) mintarget = target.GetBinContent(target.GetMinimumBin()) maxy = max(maxreference, maxtarget)*1.2 miny = min(minreference, mintarget) miny = 0 if miny>0 else miny*1.2 reference.GetYaxis().SetRangeUser(miny, maxy) return canvas
def save(self, filename, dotc=False, dotroot=False): ''' Save the current canvas contents to [filename] ''' self.canvas.Update() if not os.path.exists(self.outputdir): os.makedirs(self.outputdir) self.canvas.SaveAs(os.path.join(self.outputdir, filename) + '.png') self.canvas.SaveAs(os.path.join(self.outputdir, filename) + '.pdf') if dotc: self.canvas.SaveAs(os.path.join(self.outputdir, filename) + '.C') if dotroot: outfile = ROOT.TFile.Open( os.path.join(self.outputdir, filename) + '.root', 'recreate') outfile.cd() self.canvas.Write() for obj in self.keep: obj.Write() self.keep = [] outfile.Close() self.canvas = plotting.Canvas(name='adsf', title='asdf') # Reset keeps self.keep = [] # Reset logx/y self.canvas.SetLogx(False) self.canvas.SetLogy(False)
set(i.y.low for i in migration_matrix) ) ybins = list(ybins) ybins.sort() full_matrix = plotting.Hist2D(xbins, ybins) full_matrix.xaxis.title = migration_matrix.xaxis.title full_matrix.yaxis.title = migration_matrix.yaxis.title for bin in migration_matrix: ibin = full_matrix.FindFixBin( bin.x.center, bin.y.center ) full_matrix[ibin].value = bin.value full_matrix[ibin].error = bin.error canvas = plotting.Canvas(1000, 800) BasePlotter.set_canvas_style(canvas) full_matrix.SetStats(False) full_matrix.Draw('colz TEXT') canvas.Update() canvas.SetLogz(True) canvas.SaveAs('%s/migration_matrix.png' % opts.dir) #make relative uncertainty for bin in full_matrix: if not bin.value: continue bin.value = bin.error / bin.value full_matrix.Draw('colz txt') canvas.Update() canvas.SaveAs('%s/migration_matrix_unc.png' % opts.dir)
def run_module(**kwargs): args = Struct(**kwargs) if not args.name: args.name = args.var results = [prettyjson.loads(open(i).read())[-1] for i in args.results] #set_trace() results.sort(key=lambda x: x['median']) nevts_graph = plotting.Graph(len(results)) upbound_graph = plotting.Graph(len(results)) max_unc = 0. bound_range = args.vrange #results[-1]['up_edge'] - results[0]['up_edge'] step = results[1]['up_edge'] - results[0]['up_edge'] #bound_range += step bound_min = results[0]['up_edge'] - step for idx, info in enumerate(results): nevts_graph.SetPoint(idx, info['median'], info["one_sigma"]["relative"]) upbound_graph.SetPoint(idx, info['up_edge'], info["one_sigma"]["relative"]) if info["one_sigma"]["relative"] > max_unc: max_unc = info["one_sigma"]["relative"] canvas = plotting.Canvas() nevts_graph.Draw('APL') nevts_graph.GetXaxis().SetTitle('average number of events') nevts_graph.GetYaxis().SetTitle('relative fit uncertainty') canvas.SaveAs(os.path.join(args.outdir, 'nevts_%s.png' % args.name)) tf1 = Plotter.parse_formula( 'scale / (x - shift) + offset', 'scale[1,0,10000],shift[%.2f,%.2f,%.2f],offset[0, 0, 1]' % (bound_min, bound_min - 2 * step, bound_min + step)) # ROOT.TF1('ret', '[0]/(x - [1])', -3, 1000) tf1.SetRange(0, 1000) tf1.SetLineColor(ROOT.EColor.kAzure) tf1.SetLineWidth(3) result = upbound_graph.Fit(tf1, 'MES') #WL scale = tf1.GetParameter('scale') shift = tf1.GetParameter('shift') offset = tf1.GetParameter('offset') upbound_graph.Draw('APL') upbound_graph.GetXaxis().SetTitle('upper bin edge') upbound_graph.GetYaxis().SetTitle('relative fit uncertainty') if args.fullrange: upbound_graph.GetYaxis().SetRangeUser(offset, max_unc * 1.2) upbound_graph.GetXaxis().SetRangeUser(shift, (shift + bound_range) * 1.2) delta = lambda x, y: ((x - shift) / bound_range)**2 + ((y - offset) / (max_unc - offset)) points = ((bound_min + step) + i * (bound_range / 100.) for i in xrange(100)) math_best_x = min(points, key=lambda x: delta(x, tf1.Eval(x))) math_best_y = tf1.Eval(math_best_x) ## math_best_x = math.sqrt(scale*bound_range*(max_unc-offset))+shift ## math_best_y = tf1.Eval(math_best_x) #max_unc*math.sqrt(scale)+offset best = min(results, key=lambda x: abs(x['up_edge'] - math_best_x)) upbound_best = plotting.Graph(1) upbound_best.SetPoint(0, best['up_edge'], best["one_sigma"]["relative"]) upbound_best.markerstyle = 29 upbound_best.markersize = 3 upbound_best.markercolor = 2 upbound_best.Draw('P same') print math_best_x, math_best_y print best['up_edge'], best["one_sigma"]["relative"] math_best = plotting.Graph(1) math_best.SetPoint(0, math_best_x, math_best_y) math_best.markerstyle = 29 math_best.markersize = 3 math_best.markercolor = ROOT.EColor.kAzure math_best.Draw('P same') canvas.SaveAs(os.path.join(args.outdir, 'upbound_%s.png' % args.name)) json = {'best': best['up_edge'], 'unc': best["one_sigma"]["relative"]} with open(os.path.join(args.outdir, '%s.json' % args.name), 'w') as jfile: jfile.write(prettyjson.dumps(json))
def make_post_distributions(key, vals, out, mean_summary, sigma_summary, dist='pull', fitfunc='gaus', prefix='', prefit=None, tdir=None, skipFit=False): canvas = plotting.Canvas() values = [] nvals = len(vals) prefit_val = 1. if 'YieldSF' in key else 0. if prefit: parname = vals[0].GetName() prefit_val = prefit[parname].getVal() if parname in prefit else 1. #FIXME 1. assumption quite arbitrary if dist == 'pull': for val in vals: isValid = (val.getError() and val.hasError()) or \ (val.getErrorLo() and val.getErrorHi() and val.hasAsymError()) if not isValid: continue pull = val.getVal()-prefit_val err = val.getError() if val.hasAsymError(): err = val.getErrorHi() if pull <= 0 else -val.getErrorLo() values.append(pull/err) ninf = len(vals) - len(values) if ninf: log.error('%s: found %i with no paramenter error' % (key, ninf)) elif dist == 'delta': prefix += dist values = [(i.getVal()-1) for i in vals] else: log.error('Distribution named "%s" is not supported!' % dist) raise ValueError('Distribution named "%s" is not supported!' % dist) #print key if filter(str.isdigit, key) != '': index = int(filter(str.isdigit, key))+1 else: index = 1 #print index singlekey=get_key(key) hist = fill_hist(values) function = None if skipFit: return if nvals > 1: hist.Fit(fitfunc, 'QIMES') function = hist.GetFunction("gaus") hist.Draw() canvas.SaveAs('%s/%s%s.png' % (out, prefix, key.replace('/','_'))) tdir.WriteObject(hist, '%s%s' % (prefix, key.replace('/','_'))) if (not hist.GetFunction("gaus") and nvals > 1): log.warning("Function not found for histogram %s" % name) else: mean = function.GetParameter(1) if nvals > 1 else vals[0].getVal() meanerror = function.GetParError(1) if nvals > 1 else vals[0].getError() sigma = function.GetParameter(2) if nvals > 1 else 0 sigmaerror = function.GetParError(2) if nvals > 1 else 0 mean_summary[singlekey].SetBinContent(index,mean) mean_summary[singlekey].SetBinError(index,meanerror) sigma_summary[singlekey].SetBinContent(index,sigma) sigma_summary[singlekey].SetBinError(index,sigmaerror) index = min( i for i in range(1, mean_summary['all'].GetNbinsX()+1) if mean_summary['all'].GetBinContent(i) == 0 ) mean_summary['all'].SetBinContent(index,mean) mean_summary['all'].SetBinError(index,meanerror) mean_summary['all'].GetXaxis().SetBinLabel(index,key) sigma_summary['all'].SetBinContent(index,sigma) sigma_summary['all'].SetBinError(index,sigmaerror) sigma_summary['all'].GetXaxis().SetBinLabel(index,key)
def run_module(**kwargs): args = Struct(**kwargs) mkdir(args.out) canvas = plotting.Canvas() pars_regex = None if args.pars_regex: pars_regex = re.compile(args.pars_regex) sample_regex = None if args.sample_regex: sample_regex = re.compile(args.sample_regex) pars_out_regex = None if args.pars_out_regex: pars_out_regex = re.compile(args.pars_out_regex) sample_out_regex = None if args.sample_out_regex: sample_out_regex = re.compile(args.sample_out_regex) output_file = io.root_open('%s/output.root' % args.out, 'recreate') fpars_tdir = output_file.mkdir('floating_pars') pulls_tdir = output_file.mkdir('postfit_pulls') failed_fits = set() fit_statuses = plotting.Hist(10, -1.5, 8.5) with io.root_open(args.mlfit) as mlfit: failed_results = [] passes_results = [] pars = {} yields = {} first = True toys = [i.GetName() for i in mlfit.keys() if i.GetName().startswith('toy_')] if not args.oneshot else [None] log.info('examining %i toys' % len(toys)) prefit_nuis = None if args.useprefit: prefit_nuis = ArgSet(mlfit.nuisances_prefit) nfailed = 0 for toy in toys: toy_dir = mlfit.Get(toy) if not args.oneshot else mlfit keys = set([i.GetName() for i in toy_dir.GetListOfKeys()]) if 'norm_fit_s' not in keys or 'fit_s' not in keys: log.error('Fit %s failed to produce output!' % toy) failed_fits.add(toy) continue norms = ArgSet( toy_dir.Get( 'norm_fit_s' ) ) norms = [i for i in norms] fit_result = toy_dir.Get( 'fit_s' ) fit_pars = ArgList(fit_result.floatParsFinal()) if first: first = False for i in fit_pars: if pars_regex and not pars_regex.match(i.GetName()): continue if pars_out_regex and pars_out_regex.match(i.GetName()): continue pars[i.GetName()] = [] for i in norms: if sample_regex and not sample_regex.match(i.GetName()): continue if sample_out_regex and sample_out_regex.match(i.GetName()): continue yields[i.GetName()] = [] fit_statuses.Fill(fit_result.status()) fit_failed = any(i.getError() == 0 for i in fit_pars) or fit_result.status() != 0 if fit_failed: log.error('Fit %s failed to converge properly. It has status %i!' % (toy, fit_result.status())) nfailed+=1 failed_fits.add(toy) failed_results.append(fit_result) continue passes_results.append(fit_result) for i in norms: if i.GetName() in yields: yields[i.GetName()].append(i) for i in fit_pars: if i.GetName() in pars: pars[i.GetName()].append(i) if nfailed: log.error('There were %i fit failed!' % nfailed) with open('%s/info.txt' % args.out, 'w') as info: info.write('There were %i fit failed!\n' % nfailed) fit_statuses.Draw() canvas.SaveAs('%s/fit_status.png' % args.out) if not args.nopars: #Plots the post-fit distribution of the POI and nuisances out = os.path.join(args.out, 'floating_parameters') mkdir(out) for i, j in yields.iteritems(): make_hist(i, j, out, prefix='yield_') for i, j in pars.iteritems(): make_hist(i, j, out, prefix='par_') if not args.postpulls: #Plots the post-fit pulls (nuisance(post) - nuisance(pre))/unc(post) pulls_dir = os.path.join(args.out, 'postfit_pulls') mkdir(pulls_dir) ROOT.gStyle.SetOptFit(11111) singlenames=set() for name,value in pars.iteritems(): if pars_regex and not pars_regex.match(name): continue if pars_out_regex and pars_out_regex.match(i): continue singlenames.add(get_key(name)) pulls_mean_summary={} pulls_sigma_summary={} deltas_mean_summary={} deltas_sigma_summary={} for name in singlenames: nbins = 0 for fullname in pars: if name in fullname: nbins = nbins + 1 #print name, nbins try: hist = plotting.Hist(nbins, 0.5,nbins+0.5, name = "%s_pull_mean_summary" %name) pulls_mean_summary[name] = hist hist = plotting.Hist(nbins, 0.5,nbins+0.5, name = "%s_pull_sigma_summary" %name) pulls_sigma_summary[name] = hist hist = plotting.Hist(nbins, 0.5,nbins+0.5, name = "%s_delta_mean_summary" %name) deltas_mean_summary[name] = hist hist = plotting.Hist(nbins, 0.5,nbins+0.5, name = "%s_delta_sigma_summary" %name) deltas_sigma_summary[name] = hist except: set_trace() pulls_mean_summary[ 'all'] = plotting.Hist(len(pars), 0.5, len(pars)+0.5, name = "all_pull_mean_summary" ) pulls_sigma_summary[ 'all'] = plotting.Hist(len(pars), 0.5, len(pars)+0.5, name = "all_pull_sigma_summary" ) deltas_mean_summary[ 'all'] = plotting.Hist(len(pars), 0.5, len(pars)+0.5, name = "all_delta_mean_summary" ) deltas_sigma_summary['all'] = plotting.Hist(len(pars), 0.5, len(pars)+0.5, name = "all_delta_sigma_summary") for i, j in pars.iteritems(): make_post_distributions(i, j, pulls_dir, pulls_mean_summary, pulls_sigma_summary, prefix='pull_', dist='pull', prefit=prefit_nuis, tdir=pulls_tdir, skipFit=args.skipFit) make_post_distributions(i, j, pulls_dir, deltas_mean_summary, deltas_sigma_summary, prefix='delta_', dist='delta', prefit=prefit_nuis, tdir=pulls_tdir, skipFit=args.skipFit) for name,histo in pulls_mean_summary.iteritems(): canvas = plotting.Canvas() histo.Draw() canvas.Update() line = ROOT.TLine(histo.GetBinLowEdge(1),0,histo.GetBinLowEdge(histo.GetNbinsX()+1),0) line.SetLineColor(2) line.Draw("same") canvas.Update() canvas.SaveAs('%s/%s.png' % (pulls_dir,histo.GetName())) canvas.SaveAs('%s/%s.pdf' % (pulls_dir,histo.GetName())) pulls_tdir.WriteObject(histo, histo.GetName()) for name,histo in pulls_sigma_summary.iteritems(): canvas = plotting.Canvas() histo.Draw() canvas.Update() line = ROOT.TLine(histo.GetBinLowEdge(1),1,histo.GetBinLowEdge(histo.GetNbinsX()+1),1) line.SetLineColor(2) line.Draw("same") canvas.Update() canvas.SaveAs('%s/%s.png' % (pulls_dir,histo.GetName())) canvas.SaveAs('%s/%s.pdf' % (pulls_dir,histo.GetName())) pulls_tdir.WriteObject(histo, histo.GetName()) for name,histo in deltas_mean_summary.iteritems(): canvas = plotting.Canvas() histo.Draw() canvas.Update() line = ROOT.TLine(histo.GetBinLowEdge(1),0,histo.GetBinLowEdge(histo.GetNbinsX()+1),0) line.SetLineColor(2) line.Draw("same") canvas.Update() canvas.SaveAs('%s/%s.png' % (pulls_dir,histo.GetName())) canvas.SaveAs('%s/%s.pdf' % (pulls_dir,histo.GetName())) pulls_tdir.WriteObject(histo, histo.GetName()) for name,histo in deltas_sigma_summary.iteritems(): histo.Draw() canvas.Update() #line = ROOT.TLine(histo.GetBinLowEdge(1),1,histo.GetBinLowEdge(histo.GetNbinsX()+1),1) #line.Draw("same") canvas.Update() canvas.SaveAs('%s/%s.png' % (pulls_dir,histo.GetName())) canvas.SaveAs('%s/%s.pdf' % (pulls_dir,histo.GetName())) pulls_tdir.WriteObject(histo, histo.GetName()) if not args.noshapes: #Overlays the prefit values of the different shapes with the envelope of #what is fitted by the toys out = os.path.join(args.out, 'shapes') mkdir(out) biased_shapes={} if args.biasFile: with io.root_open(args.biasFile) as biased: biased_dir= biased.prefit \ if hasattr(biased, 'prefit') else \ None ROOT.TH1.AddDirectory(False) for key in biased_dir.keys(): biased_shapes[key.name] = asrootpy(key.ReadObj().Clone()) with io.root_open(args.harvested) as harvest: has_prefit = hasattr(harvest, 'prefit') prefit = harvest.prefit if has_prefit else None toys = EnvelopeView( *[harvest.get(i.GetName()).get(args.variable) for i in harvest.keys() if i.GetName().startswith('toy_') and (i.GetName() not in failed_fits) ] ) #shapes = [i.GetName() for i in prefit.keys()] #FIXME! should not depend on prefit! first_toy = [i.GetName() for i in harvest.keys() if i.GetName().startswith('toy_')][0] not_shapes = set('correlation_matrix') shapes = [i.GetName() for i in harvest.get(first_toy).get(args.variable).keys() if i.GetName() not in not_shapes] for shape in shapes: canvas = plotting.Canvas() canvas.SetCanvasSize( canvas.GetWw(), int(canvas.GetWh()*1.3) ) upper_pad = plotting.Pad(0, 0.33, 1., 1.) lower_pad = plotting.Pad(0, 0., 1., 0.33) upper_pad.set_bottom_margin(0.001) lower_pad.set_top_margin(0.005) lower_pad.set_bottom_margin(lower_pad.get_bottom_margin()*3) upper_pad.Draw() lower_pad.Draw() upper_pad.cd() biased_shape = biased_shapes.get(shape, None) toy_shape = toys.Get(shape) pre_shape = None legend = plotting.Legend( 3+int(has_prefit)+int(bool(biased_shape)), rightmargin=0.07, topmargin=0.05, leftmargin=0.45) legend.SetBorderSize(0) if biased_shape: biased_shape.title = 'true shape' biased_shape.legendstyle = 'p' biased_shape.inlegend = True biased_shape.drawstyle = 'p' if has_prefit: pre_shape = prefit.Get(shape) pre_shape.title = 'input shape' pre_shape.legendstyle = 'p' pre_shape.drawstyle = 'p' if biased_shape: pre_shape.legendstyle = 'l' pre_shape.drawstyle = 'hist' pre_shape.linecolor = 'blue' pre_shape.fillstyle = 0 toy_shape.Draw() if has_prefit: pre_shape.Draw('same') if biased_shape: biased_shape.Draw('same') legend.AddEntry(toy_shape.two_sigma) legend.AddEntry(toy_shape.one_sigma) legend.AddEntry(toy_shape.median) if has_prefit: legend.AddEntry(pre_shape) if biased_shape: legend.AddEntry(biased_shape) legend.Draw() #compute pulls pulls = None labelSizeFactor2 = (upper_pad.GetHNDC()+lower_pad.GetHNDC()) / lower_pad.GetHNDC() labelSizeFactor1 = (upper_pad.GetHNDC()+lower_pad.GetHNDC()) / upper_pad.GetHNDC() label_factor = labelSizeFactor2/labelSizeFactor1 if has_prefit or biased_shape: lower_pad.cd() ref_histo = biased_shape if biased_shape else pre_shape pulls = toy_shape.median.Clone() pulls.Reset() for ref, toy, pull in zip(ref_histo, toy_shape, pulls): if toy.error == (0.0, 0.0): continue abs_pull = toy.median-ref.value #pick correct side of the errors err = toy.error[1] if abs_pull < 0 else toy.error[0] pull.value = abs_pull/err pulls.xaxis.title = args.variable pulls.yaxis.title = 'pulls' pulls.set_label_size(ROOT.gStyle.GetLabelSize()*label_factor, "XYZ") pulls.set_title_size(ROOT.gStyle.GetTitleSize()*label_factor, "XYZ") pulls.yaxis.set_title_offset(pulls.GetYaxis().GetTitleOffset()/label_factor) pulls.Draw() canvas.Update() canvas.SaveAs('%s/%s.png' % (out, shape)) canvas.SaveAs('%s/%s.pdf' % (out, shape)) with open(os.path.join(out, '%s.json' % shape), 'w') as jfile: jfile.write(toy_shape.json()) output_file.Close()
import os import re from URAnalysis.Utilities.struct import Struct asrootpy = rootpy.asrootpy rootpy.log["/"].setLevel(rootpy.log.INFO) rootpy.log["/rootpy"].setLevel(rootpy.log.INFO) ROOT.gStyle.SetOptTitle(0) ROOT.gStyle.SetOptStat(0) ROOT.gROOT.SetBatch() log = rootpy.log["/toy_diagnostics"] rootpy.log["/toy_diagnostics"].setLevel(rootpy.log.INFO) import URAnalysis.Utilities.prettyjson as prettyjson from argparse import ArgumentParser canvas = plotting.Canvas() def mkdir(path): if not os.path.isdir(path): os.makedirs(path) def fill_hist(vals): low = min(vals) low = low*0.8 if low > 0 else low*1.2 hi = max(vals) hi *= 1.2 if hi > 0 else 0.8 if low == hi: #0 == 0 low, hi = -0.1, 0.1 hist = plotting.Hist(50, low, hi, title='') for v in vals:
if entry.num_muonsLoose_noPrompt == 1 and entry.num_promptMuons > 0 and entry.d3D_SecReco > 0: deltaZ = entry.vz_SecReco - entry.vz_PVReco deltaX = entry.vx_SecReco - entry.vx_PVReco deltaY = entry.vz_SecReco - entry.vz_PVReco L_z_reco = abs(deltaZ) L_xy_reco = sqrt(deltaX * deltaX + deltaY * deltaY) L_yxz_reco = sqrt(deltaX * deltaX + deltaY * deltaY + deltaZ * deltaZ) if inputF == inputfile_4GeV: h_3D_4GeV.fill(entry.d3D_SecReco) if inputF == inputfile_7GeV: h_3D_7GeV.fill(entry.d3D_SecReco) if inputF == inputfile_10GeV: h_3D_10GeV.fill(entry.d3D_SecReco) canvas_3Ddist = plt.Canvas(800, 600) h_3D_4GeV.markercolor = 'crimson' h_3D_7GeV.markercolor = 'darkblue' h_3D_10GeV.markercolor = 'green' h_3D_4GeV.Scale(1 / h_3D_4GeV.Integral()) h_3D_7GeV.Scale(1 / h_3D_7GeV.Integral()) h_3D_10GeV.Scale(1 / h_3D_10GeV.Integral()) h_3D_4GeV.xaxis.title = 'd_xyz' h_3D_4GeV.yaxis.title = 'A.U.' h_3D_4GeV.Draw() h_3D_7GeV.Draw('SAME') h_3D_10GeV.Draw('SAME') legend = plt.Legend([h_3D_4GeV, h_3D_7GeV, h_3D_10GeV], leftmargin=0.45, margin=0.3, textsize=20)
histograms = [ apply_style(input_view.Get(i), i) for i in keys ] histograms = sorted(histograms, key=lambda x: x.Integral()) observed = apply_style(input_view.Get(data), data) logging.debug("debugging histos:") for histo in histograms: logging.debug(" %s: style: %s, integral: %.2f" % ( histo.GetTitle(), histo.drawstyle, histo.Integral() ) ) stack = plotting.HistStack() for obj in histograms: stack.Add(obj) maximum = max(list(observed)+[stack.GetMaximum()]) canvas = plotting.Canvas(name='adsf', title='asdf') canvas.cd() stack.SetMaximum(maximum*1.8) stack.Draw() stack.GetXaxis().SetTitle(options.xtitle) stack.GetYaxis().SetTitle(options.ytitle) observed.Draw('same') #tries to figure which side the legend goes obslist = list(observed) sx_mean = obslist[:len(obslist) / 2] dx_mean = obslist[len(obslist) / 2:] sx_mean = sum(sx_mean) / float(len(sx_mean)) dx_mean = sum(dx_mean) / float(len(dx_mean)) legend = plotting.Legend(len(histograms)+1, rightmargin=0.03, topmargin=0.02, leftmargin=0.45) \
file_names = [tuple(i) for i in jconf['file_names']] output = jconf['output'] graph_path = jconf['graph_path'] #dump configuration in json for bookkeeping jconf = { 'file_names': file_names, 'output': output, 'graph_path': graph_path, } jout = output.split('.')[0] with open('%s.json' % jout, 'w') as out: out.write(prettyjson.dumps(jconf)) canvas = plt.Canvas(800, 800) canvas.SetLogy() canvas.SetGridx() canvas.SetGridy() max_txt_len = max(len(i) for _, i in file_names) legend = plt.Legend(len(file_names), leftmargin=0.18 + (30 - max_txt_len) * 0.016, rightmargin=0.005, topmargin=0.60 - 0.057 * (len(file_names) - 3), entrysep=0, margin=0.1 + 0.006 * (30 - max_txt_len)) legend.SetTextSize(legend.GetTextSize() * 0.8) legend.SetFillColor(0) legend.SetFillStyle(1001)