def test_draw(): with root_open(FILE_PATHS[0]) as f: tree = f.tree tree.draw('a_x') tree.draw('a_x:a_y') tree.draw('a_x:TMath::Exp(a_y)') tree.draw('a_x:a_y:a_z') tree.draw('a_x:a_y:a_z:b_x') tree.draw('a_x:a_y:a_z:b_x:b_y', options='para') h1 = Hist(10, -1, 2, name='h1') h2 = Hist2D(10, -1, 2, 10, -1, 2) h3 = Hist3D(10, -1, 2, 10, -1, 2, 10, -1, 2) # dimensionality does not match assert_raises(TypeError, tree.draw, 'a_x:a_y', hist=h1) # name does not match assert_raises(ValueError, tree.draw, 'a_x>>+something', hist=h1) # hist is not a TH1 assert_raises(TypeError, tree.draw, 'a_x:a_y', hist=ROOT.TGraph()) # name does match and is fine (just redundant) tree.draw('a_x>>h1', hist=h1) assert_equal(h1.Integral() > 0, True) h1.Reset() tree.draw('a_x>>+h1', hist=h1) assert_equal(h1.Integral() > 0, True) h1.Reset() # both binning and hist are specified assert_raises(ValueError, tree.draw, 'a_x>>+h1(10, 0, 1)', hist=h1) tree.draw('a_x', hist=h1) assert_equal(h1.Integral() > 0, True) tree.draw('a_x:a_y', hist=h2) assert_equal(h2.Integral() > 0, True) tree.draw('a_x:a_y:a_z', hist=h3) assert_equal(h3.Integral() > 0, True) h3.Reset() tree.draw('a_x>0:a_y/2:a_z*2', hist=h3) assert_equal(h3.Integral() > 0, True) # create a histogram hist = tree.draw('a_x:a_y:a_z', create_hist=True) assert_equal(hist.Integral() > 0, True) hist = tree.draw('a_x:a_y:a_z>>new_hist_1') assert_equal(hist.Integral() > 0, True) assert_equal(hist.name, 'new_hist_1') # create_hist=True is redundant here hist = tree.draw('a_x:a_y:a_z>>new_hist_2', create_hist=True) assert_equal(hist.Integral() > 0, True) assert_equal(hist.name, 'new_hist_2')
def test_chain_draw(): chain = TreeChain('tree', FILE_PATHS) hist = Hist(100, 0, 1) chain.draw('a_x', hist=hist) assert_equal(hist.Integral() > 0, True) # check that Draw can be repeated hist2 = Hist(100, 0, 1) chain.draw('a_x', hist=hist2) assert_equal(hist.Integral(), hist2.Integral())
def test_chain_draw(self): chain = TreeChain('tree', self.file_paths) hist = Hist(100, 0, 1) chain.draw('a_x', hist=hist) assert_equals(hist.Integral() > 0, True) # check that Draw can be repeated hist2 = Hist(100, 0, 1) chain.draw('a_x', hist=hist2) assert_equals(hist.Integral(), hist2.Integral())
def test_chain_draw(): if sys.version_info[0] >= 3: raise SkipTest("Python 3 support not implemented") chain = TreeChain('tree', FILE_PATHS) hist = Hist(100, 0, 1) chain.draw('a_x', hist=hist) assert_equal(hist.Integral() > 0, True) # check that Draw can be repeated hist2 = Hist(100, 0, 1) chain.draw('a_x', hist=hist2) assert_equal(hist.Integral(), hist2.Integral())
def test_chain_draw_hist_init_first(): if sys.version_info[0] >= 3: raise SkipTest("Python 3 support not implemented") hist = Hist(100, 0, 1) chain = TreeChain('tree', FILE_PATHS) chain.draw('a_x', hist=hist) assert_equal(hist.Integral() > 0, True)
def test_chain_draw(): if sys.version_info[0] >= 3: raise SkipTest("Python 3 support not implemented") chain = TreeChain('tree', FILE_PATHS) hist = Hist(100, 0, 1) chain.draw('a_x', hist=hist) assert_equal(hist.Integral() > 0, True) assert_equal(hist.GetEntries(), 300) # check that Draw can be repeated hist2 = Hist(100, 0, 1) chain.draw('a_x', hist=hist2) assert_equal(hist.Integral(), hist2.Integral()) # draw into a graph graph = chain.draw("a_x:a_y") assert_true(isinstance(graph, _GraphBase)) assert_equal(len(graph), chain.GetEntries()) assert_equal(len(graph), 300)
def score_plot(sig_arr, bkg_arr, sig_weight, bkg_weight): ''' make a plot of the score for bkg and signal ''' hsig = Hist(100, -0.5, 0.5) hbkg = Hist(100, -0.5, 0.5) fill_hist(hsig, sig_arr, sig_weight) fill_hist(hbkg, bkg_arr, bkg_weight) hsig /= hsig.Integral() hbkg /= hbkg.Integral() hsig.color = 'red' hbkg.color = 'blue' hsig.title = 'signal' hbkg.title = 'background' fig = plt.figure() rmpl.hist([hsig, hbkg], stacked=False) plt.ylabel('Arbitrary Unit') plt.xlabel('BDT Score') plt.legend(loc='upper right') return fig
def makeDiscr(discr_dict, outfile, xtitle="discriminator", nbins=30, x_min=0, x_max=1): c = ROOT.TCanvas("c", "c", 800, 500) ROOT.gStyle.SetOptStat(0) ROOT.gPad.SetMargin(0.15, 0.1, 0.2, 0.1) #ROOT.gPad.SetLogy(1) #ROOT.gPad.SetGrid(1,1) ROOT.gStyle.SetGridColor(17) l = TLegend(0.17, 0.75, 0.88, 0.88) l.SetTextSize(0.055) l.SetBorderSize(0) l.SetFillStyle(0) l.SetNColumns(2) colors = [2, 4, 8, ROOT.kCyan + 2] counter = 0 for leg, discr in discr_dict.iteritems(): a = Hist(nbins, x_min, x_max) #fill_hist_with_ndarray(a, discr) a.fill_array(discr) a.SetLineColor(colors[counter]) a.SetLineWidth(2) a.GetXaxis().SetTitle(xtitle) a.GetXaxis().SetLabelSize(0.05) a.GetXaxis().SetTitleSize(0.05) a.GetXaxis().SetTitleOffset(1.45) a.GetYaxis().SetTitle("a.u.") a.GetYaxis().SetTickSize(0) a.GetYaxis().SetLabelSize(0) a.GetYaxis().SetTitleSize(0.06) a.GetYaxis().SetTitleOffset(0.9) a.Scale(1. / a.Integral()) #a.GetYaxis().SetRangeUser(0.00001,100) a.GetYaxis().SetRangeUser(0, 0.2) if counter == 0: a.draw("hist") else: a.draw("same hist") l.AddEntry(a, leg, "l") counter += 1 l.Draw("same") c.SaveAs(outfile)
def test_cuts(self): with root_open(self.file_paths[0]) as f: tree = f.tree h1 = Hist(10, -1, 2) h2 = Hist2D(10, -1, 2, 10, -1, 2) h3 = Hist3D(10, -1, 2, 10, -1, 2, 10, -1, 2) tree.draw('a_x', hist=h1) assert_equals(h1.Integral() > 0, True) tree.draw('a_x:a_y', hist=h2) assert_equals(h2.Integral() > 0, True) tree.draw('a_x:a_y:a_z', hist=h3) assert_equals(h3.Integral() > 0, True) h3.Reset() tree.draw('a_x>0:a_y/2:a_z*2', hist=h3) assert_equals(h3.Integral() > 0, True)
def test_draw(): for sample in analysis.backgrounds: print sample.name hist = Hist(30, 0, 250) hist_array = hist.Clone() field_hist = {'mmc1_mass': hist_array} sample.draw_into(hist, 'mmc1_mass', Category_VBF, 'OS_TRK') sample.draw_array(field_hist, Category_VBF, 'OS_TRK') assert_almost_equal(hist.Integral(), hist_array.Integral(), places=3) assert_equal(sorted(hist.systematics.keys()), sorted(hist_array.systematics.keys())) for term, sys_hist in hist.systematics.items(): print term sys_hist_array = hist_array.systematics[term] assert_almost_equal(sys_hist.Integral(), sys_hist_array.Integral())
else: expr = expr.format( var_info['name'], h.name, (var_info['bins'], var_info['range'][0], var_info['range'][1])) print expr tree.Draw(expr, cut, var_info['style']) h = asrootpy(ROOT.gPad.GetPrimitive(h.name)) h.xaxis.title = get_label(var_info) h.yaxis.title = 'Number of Events' if h.integral() != 0: h /= h.integral() h.SetLineWidth(2) h.yaxis.SetRangeUser(0, 0.5) if 'binlabels' in var_info.keys(): for ib, lab in enumerate(var_info['binlabels']): h.xaxis.SetBinLabel(ib + 1, lab) c = Canvas() # c.SetLogy() c.SetTopMargin(0.08) h.Draw('HIST') label = ROOT.TLatex( c.GetLeftMargin() + 0.05, 1 - c.GetTopMargin() + 0.02, '{0}H #rightarrow #tau#tau (m_{{H}} = {1} GeV) - Hist Integral = {2}'.format( get_dir_mode(d), get_dir_mass(d), h.Integral())) label.SetNDC() label.SetTextSize(20) label.Draw('same') c.SaveAs('./plots/{0}_mass{1}_mode{2}.png'.format( key, get_dir_mass(d), get_dir_mode(d)))
tree = Tree("test") branches = {'x': 'F', 'y': 'F', 'z': 'F', 'i': 'I'} tree.create_branches(branches) for i in range(10000): tree.x = gauss(.5, 1.) tree.y = gauss(.3, 2.) tree.z = gauss(13., 42.) tree.i = i tree.fill() # Make a histogram of x when y > 1 hist1 = Hist(100, -10, 10, name='hist1') tree.Draw('x', 'y > 1', hist=hist1) hist1.SetDirectory(0) # memory resident print("The first tree has {0:f} entries where y > 1".format(hist1.Integral())) tree.write() f.close() print("Creating test tree in chaintest2.root") f = root_open("chaintest2.root", "recreate") tree = Tree("test") tree.create_branches(branches) for i in range(10000): tree.x = gauss(.5, 1.) tree.y = gauss(.3, 2.) tree.z = gauss(13., 42.) tree.i = i
# create normal distributions mu1, mu2, sigma = 100, 140, 15 x1 = mu1 + sigma * np.random.randn(10000) x2 = mu2 + sigma * np.random.randn(10000) # create histograms h1 = Hist(100, 40, 160) h2 = Hist(100, 40, 160) # fill the histograms with our distributions map(h1.Fill, x1) map(h2.Fill, x2) # normalize the histograms h1 /= h1.Integral() h2 /= h2.Integral() # set visual attributes h1.SetFillStyle("solid") h1.SetFillColor("green") h1.SetLineColor("green") h2.SetFillStyle("solid") h2.SetFillColor("red") h2.SetLineColor("red") # plot with ROOT h1.GetXaxis().SetTitle('Smarts') h1.GetYaxis().SetTitle('Probability') h1.SetTitle("Histogram of IQ: #mu=100, #sigma=15")
def test_chain_draw_hist_init_first(): hist = Hist(100, 0, 1) chain = TreeChain('tree', FILE_PATHS) chain.draw('a_x', hist=hist) assert_equal(hist.Integral() > 0, True)
if os.path.exists(sPathToFile): a_acceptance_fraction = pickle.load(open(sPathToFile, 'r')) print 'Successfully loaded acceptance fraction array!' #a_acor = pickle.load(open(sPathToFile_autocorrelation, 'r')) else: print sPathToFile print 'Could not find file!' sys.exit() #print a_acor c_acceptance = Canvas() h_acceptance = Hist(100, 0, 1, name='h_acceptance', title='Acceptance Fraction of Most Recent Sampler') h_acceptance.fill_array(a_acceptance_fraction) h_acceptance.Scale(1. / h_acceptance.Integral()) #h_acceptance.SetStats(0) h_acceptance.Draw() c_acceptance.Update() raw_input('Press enter to continue...') plot_name = '%s_acceptance_fraction' % (dir_specifier_name) plot_name = 'yields_fit_%s' % (plot_name) neriX_analysis.save_plot(l_plots, c_acceptance, plot_name)
from config import CMS CMS.axis_label_major['labelsize'] = 40 CMS.title['fontsize'] = 40 # create a normal distribution mu, sigma = 100, 15 x = mu + sigma * np.random.randn(10000) # create a histogram with 100 bins from 40 to 160 h = Hist(100, 40, 160) # fill the histogram with our distribution map(h.Fill, x) # normalize the histogram h /= h.Integral() # set visual attributes h.SetFillStyle('solid') h.SetFillColor('green') h.SetLineColor('green') # the histogram of the data plt.figure(figsize=(16, 12), dpi=200) axes = plt.axes() axes.minorticks_on() rplt.hist(h, label=r'$\epsilon$(Something complicated)', alpha=0.7) plt.xlabel('Discovery', CMS.x_axis_title) plt.ylabel('Probability of a discovery', CMS.y_axis_title) #plt.title(r'combined, CMS Preliminary, $\mathcal{L}$ = 5.1 fb$^{-1}$ at $\sqrt{s}$ = 7 TeV', # fontsize=30,
def do_analysis(chain, analyze_this, outfile, eventtype): # get trees from files #t = f.Get("Delphes") # get number of entries nentries = chain.GetEntries() # initialize everything here before filling histograms if (analyze_this['Jet.PT']): print "\nInitializing Jet.PT...\n" # create the histograms numJets = Hist(NBINS, NLO, NHI, title='numJets ' + eventtype, legendstyle='L') # interesting values to plot max_jetpt_per_event = Hist(PT_NBINS, PT_NLO, PT_NHI, title='Max JetPT/Event ' + eventtype, legendstyle='L') min_jetpt_per_event = Hist(PT_NBINS, PT_NLO, PT_NHI, title='Min JetPT/Event ' + eventtype, legendstyle='L') else: print "Skipped Jet.PT" if (analyze_this['Jet.BTag']): print "Initializing Jet.BTag...\n" # create the histograms loose = Hist(NBINS, NLO, NHI, title='loose ' + eventtype, legendstyle='L') medium = Hist(NBINS, NLO, NHI, title='medium ' + eventtype, legendstyle='L') tight = Hist(NBINS, NLO, NHI, title='tight ' + eventtype, legendstyle='L') else: print "Skipped Jet.BTag" if (analyze_this['Electron.PT']): print "Initializing Electron.PT...\n" # create the histograms numElectrons = Hist(NBINS, NLO, NHI, title='numElectrons ' + eventtype, legendstyle='L') # interesting values to plot max_ept_per_event = Hist(PT_NBINS, PT_NLO, PT_NHI, title='Max ElectronPT/Event ' + eventtype, legendstyle='L') min_ept_per_event = Hist(PT_NBINS, PT_NLO, PT_NHI, title='Min ElectronPT/Event ' + eventtype, legendstyle='L') # initialize any variable-specific constants here: # counter for no electrons noeleaf = 0 else: print "Skipped Electron.PT" if (analyze_this['MuonTight.PT']): print "Initializing MuonTight.PT...\n" # create the histograms numMuons = Hist(NBINS, NLO, NHI, title='numMuons ' + eventtype, legendstyle='L') # interesting values to plot max_upt_per_event = Hist(PT_NBINS, PT_NLO, PT_NHI, title='Max MuonPT/Event ' + eventtype, legendstyle='L') min_upt_per_event = Hist(PT_NBINS, PT_NLO, PT_NHI, title='Min MuonPT/Event ' + eventtype, legendstyle='L') # initialize any variable-specific constants here: # counter for no electrons nouleaf = 0 else: print "Skipped MuonTight.PT" if (analyze_this['MissingET.MET']): print "Initializing MissingET.MET...\n" # create the histograms MET = Hist(MET_NBINS, MET_NLO, MET_NHI, title='MET ' + eventtype, legendstyle='L') else: print "Skipped MissingET.MET" if (analyze_this['MT (NON-LEAF)']): print "Initializing MT...\n" # create the histograms MT = Hist(MT_NBINS, MT_NLO, MT_NHI, title='MT ' + eventtype, legendstyle='L') else: print "Skipped HT" if (analyze_this['HT (NON-LEAF)']): print "Initializing HT...\n" # create the histograms HT = Hist(HT_NBINS, HT_NLO, HT_NHI, title='HT ' + eventtype, legendstyle='L') else: print "Skipped HT" if (analyze_this['DELTA PHI (NON-LEAF)']): print "Initializing Delta Phi...\n" # create the histograms DPHI_metlep = Hist(30, -1 * np.pi, np.pi, title='Delta Phi (MET-lep) ' + eventtype, legendstyle='L') DPHI_metjet = Hist(30, -1 * np.pi, np.pi, title='Delta Phi (MET-jet)' + eventtype, legendstyle='L') else: print "Skipped DELTA PHI" if (analyze_this['DELTA R (NON-LEAF)']): print "Initializing Delta R...\n" #create histograms DR = Hist(50, 0, 2 * np.pi, title='DELTA R ' + eventtype, legendstyle='L') else: print "Skipped DELTA R" # Now fill histograms print "\nFilling histograms...\n" # get float version of num entries to normalize below; subtract 1 to get # actual integral value of hist norm = float(nentries - 1) for e in range(nentries): entry = chain.GetEntry(e) # to check whether each entry is electron or muon is_electron = False is_muon = False e_maxpt = 0 e_maxpt_phi = 0 u_maxpt = 0 u_maxpt_phi = 0 jet_maxpt = 0 jet_maxpt_phi = 0 jet_maxpt_eta = 0 met = 0 met_phi = 0 met_eta = 0 lepton_vec = [] if (analyze_this['Electron.PT']): # define leaves var = "Electron.PT" leaf = chain.GetLeaf(var) phileaf = chain.GetLeaf('Electron.Phi') etaleaf = chain.GetLeaf('Electron.Eta') # returns phi of max pt for entry (e_maxpt, e_maxpt_phi, e_maxpt_eta) = fill_Electron_hist( chain, leaf, entry, numElectrons, min_ept_per_event, max_ept_per_event, phileaf, etaleaf, lepton_vec) #print lepton_vec if (leaf.GetLen() == 0): noeleaf += 1 e_maxpt = INVALID e_maxpt_phi = INVALID e_maxpt_eta = INVALID else: is_electron = True if (analyze_this['MuonTight.PT']): # define leaves var = "MuonTight.PT" leaf = chain.GetLeaf(var) phileaf = chain.GetLeaf('MuonTight.Phi') etaleaf = chain.GetLeaf('MuonTight.Eta') (u_maxpt, u_maxpt_phi, u_maxpt_eta) = fill_Muon_hist( chain, leaf, entry, numMuons, min_upt_per_event, max_upt_per_event, phileaf, etaleaf, lepton_vec) if leaf.GetLen() == 0: nouleaf += 1 u_maxpt = INVALID u_maxpt_phi = INVALID u_maxpt_eta = INVALID else: is_muon = True # Get preferred lepton for future calcs if e_maxpt >= u_maxpt: lpt = e_maxpt lphi = e_maxpt_phi leta = e_maxpt_eta else: lpt = u_maxpt lphi = u_maxpt_phi leta = u_maxpt_eta if (analyze_this['Jet.PT']): # define leaves var = 'Jet.PT' leaf = chain.GetLeaf(var) phileaf = chain.GetLeaf('Jet.Phi') etaleaf = chain.GetLeaf('Jet.Eta') # analyze with Jet.PT because HT is sum of Jet.PTs if (analyze_this['HT (NON-LEAF)']): HTfill = True else: HTfill = False # returns phi of max pt for entry (jet_maxpt, jet_maxpt_phi, jet_maxpt_eta) = fill_JetPT_hist( chain, leaf, entry, numJets, min_jetpt_per_event, max_jetpt_per_event, HTfill, HT, phileaf, etaleaf, lepton_vec) if (leaf.GetLen() == 0): jet_maxpt = INVALID jet_maxpt_phi = INVALID jet_maxpt_eta = INVALID if (analyze_this['Jet.BTag']): # define leaves var = "Jet.BTag" leaf = chain.GetLeaf(var) fill_JetBTag_hist(chain, leaf, entry, loose, medium, tight) if (analyze_this['MissingET.MET']): # define leaves var = "MissingET.MET" leaf = chain.GetLeaf(var) phileaf = chain.GetLeaf('MissingET.Phi') etaleaf = chain.GetLeaf('MissingET.Eta') (met, metphi, meteta) = fill_MET_hist(chain, leaf, entry, MET, phileaf, etaleaf) if (analyze_this['MT (NON-LEAF)']): #print "ok got here" #print "here ",e_maxpt, e_maxpt_phi, u_maxpt, u_maxpt_phi, met, metphi if (not (is_muon or is_electron)): mt_val = 0 else: #print e_maxpt, e_maxpt_phi, u_maxpt, u_maxpt_phi, met, metphi #print is_electron, is_muon mt_val = get_mt(lpt, lphi, met, metphi) if mt_val == 0: MT.Fill(INVALID) else: MT.Fill(mt_val) if (analyze_this['DELTA PHI (NON-LEAF)']): dphi_metlep_val = delta_phi(metphi, lphi) dphi_metjet_val = delta_phi(metphi, jet_maxpt_phi) DPHI_metlep.Fill(dphi_metlep_val) DPHI_metjet.Fill(dphi_metjet_val) if (analyze_this['DELTA R (NON-LEAF)']): dr_val = delta_R(jet_maxpt_phi, lphi, jet_maxpt_eta, leta) if dr_val == 0: dr_val = INVALID #elif dr_val > 3.0 and dr_val < 3.3: #print jet_maxpt_phi, lphi, jet_maxpt_eta, leta DR.Fill(dr_val) if (analyze_this['Jet.PT']): # normalize numJets.Scale(1 / (numJets.Integral())) max_jetpt_per_event.Scale(1 / (max_jetpt_per_event.Integral())) min_jetpt_per_event.Scale(1 / (min_jetpt_per_event.Integral())) if (analyze_this['Jet.BTag']): # normalize tight.Scale(1 / (tight.Integral())) medium.Scale(1 / (medium.Integral())) loose.Scale(1 / (loose.Integral())) if (analyze_this['Electron.PT']): # normalize numElectrons.Scale(1 / (numElectrons.Integral())) max_ept_per_event.Scale(1 / (max_ept_per_event.Integral())) min_ept_per_event.Scale(1 / (min_ept_per_event.Integral())) print "\nentries: " + str(nentries) + " noeleaf number: " + str( noeleaf) if (analyze_this['MuonTight.PT']): # normalize numMuons.Scale(1 / (numMuons.Integral())) max_upt_per_event.Scale(1 / (max_upt_per_event.Integral())) min_upt_per_event.Scale(1 / (min_upt_per_event.Integral())) print "\nentries: " + str(nentries) + " nouleaf number: " + str( nouleaf) if (analyze_this['MissingET.MET']): # normalize MET.Scale(1 / (MET.Integral())) if (analyze_this['MT (NON-LEAF)']): #normalize MT.Scale(1 / (MT.Integral())) if (analyze_this['HT (NON-LEAF)']): #normalize HT.Scale(1 / (HT.Integral())) if (analyze_this['DELTA PHI (NON-LEAF)']): #normalize DPHI_metlep.Scale(1 / (DPHI_metlep.Integral())) DPHI_metjet.Scale(1 / (DPHI_metjet.Integral())) if (analyze_this['DELTA R (NON-LEAF)']): #normalize DR.Scale(1 / (DR.Integral())) print "" print "\nDone!\n" numJets.Write(eventtype + "numJets") max_jetpt_per_event.Write(eventtype + "max_jetpt_per_event") min_jetpt_per_event.Write(eventtype + "min_jetpt_per_event") loose.Write(eventtype + "loose") medium.Write(eventtype + "medium") tight.Write(eventtype + "tight") numElectrons.Write(eventtype + "numElectrons") max_ept_per_event.Write(eventtype + "max_ept_per_event") min_ept_per_event.Write(eventtype + "min_ept_per_event") numMuons.Write(eventtype + "numMuons") max_upt_per_event.Write(eventtype + "max_upt_per_event") min_upt_per_event.Write(eventtype + "min_upt_per_event") MET.Write(eventtype + "MET") MT.Write(eventtype + "MT") HT.Write(eventtype + "HT") DPHI_metlep.Write(eventtype + "dphi_metlep") DPHI_metjet.Write(eventtype + "dphi_metjet") DR.Write(eventtype + "deltaR")
minuit_fitter.fit() results = minuit_fitter.readResults() c.cd(2) ymax = h_data.GetBinContent(h_data.GetMaximumBin()) * 1.1 h_data.GetYaxis().SetRangeUser(0, ymax) h_data.Draw('PE') leg = Legend(nTemplates + 2) leg.AddEntry(h_data, style='LEP') h_tSumAfter = 0 print '----> Target \t Fit Result' if useT1: h_t1After = h_t1.Clone() h_t1After.Scale(results['t1'][0] / h_t1.Integral()) h_t1After.Draw('SAME HIST') h_tSumAfter += h_t1After leg.AddEntry(h_t1After, style='L') t1AfterCont = h_t1.Integral() * t1Scale * h_data.Integral() / ( h_t1.Integral() * t1Scale + h_t2.Integral() * t2Scale + h_t3.Integral() * t3Scale) print '%s : \t %.3g \t %.3g +/- %.3g' % ( t1Name, t1AfterCont, results['t1'][0], results['t1'][1]) scan1 = results['t1'][2] pass if useT2: h_t2After = h_t2.Clone() h_t2After.Scale(results['t2'][0] / h_t2.Integral()) h_t2After.Draw('SAME HIST') h_tSumAfter += h_t2After
def test_chain_draw_hist_init_first(self): hist = Hist(100, 0, 1) chain = TreeChain('tree', self.file_paths) chain.draw('a_x', hist=hist) assert_equals(hist.Integral() > 0, True)
def makeDiscr(train_discr_dict, discr_dict, outfile, xtitle="discriminator"): c = ROOT.TCanvas("c", "c", 800, 500) ROOT.gStyle.SetOptStat(0) ROOT.gPad.SetMargin(0.15, 0.1, 0.2, 0.1) #ROOT.gPad.SetLogy(1) #ROOT.gPad.SetGrid(1,1) ROOT.gStyle.SetGridColor(17) l = TLegend(0.17, 0.75, 0.88, 0.88) l.SetTextSize(0.055) l.SetBorderSize(0) l.SetFillStyle(0) l.SetNColumns(2) colors = [2, 1, 4, ROOT.kCyan + 2] counter = 0 for leg, discr in train_discr_dict.iteritems(): a = Hist(30, 0, 1) #fill_hist_with_ndarray(a, discr) a.fill_array(discr) a.SetLineColor(colors[counter]) a.SetLineWidth(2) a.GetXaxis().SetTitle(xtitle) a.GetXaxis().SetLabelSize(0.05) a.GetXaxis().SetTitleSize(0.06) a.GetXaxis().SetTitleOffset(1.45) a.GetYaxis().SetTitle("a.u.") a.GetYaxis().SetTickSize(0) a.GetYaxis().SetLabelSize(0) a.GetYaxis().SetTitleSize(0.06) a.GetYaxis().SetTitleOffset(0.9) a.Scale(1. / a.Integral()) #a.GetYaxis().SetRangeUser(0.00001,100) a.GetYaxis().SetRangeUser(0, 0.9) if counter == 0: a.draw("hist") else: a.draw("same hist") l.AddEntry(a, leg, "l") counter += 1 counter = 0 for leg, discr in discr_dict.iteritems(): a = Hist(30, 0, 1) #fill_hist_with_ndarray(a, discr) a.fill_array(discr) a.SetLineColor(colors[counter]) a.SetMarkerColor(colors[counter]) a.SetMarkerStyle(34) a.SetMarkerSize(1.8) a.SetLineWidth(2) a.GetXaxis().SetTitle(xtitle) a.GetXaxis().SetLabelSize(0.05) a.GetXaxis().SetTitleSize(0.06) a.GetXaxis().SetTitleOffset(1.45) a.GetYaxis().SetTitle("a.u.") a.GetYaxis().SetTickSize(0) a.GetYaxis().SetLabelSize(0) a.GetYaxis().SetTitleSize(0.06) a.GetYaxis().SetTitleOffset(0.9) a.Scale(1. / a.Integral()) #a.GetYaxis().SetRangeUser(0.00001,100) a.GetYaxis().SetRangeUser(0, 0.4) a.draw("same p X0") l.AddEntry(a, leg, "p") counter += 1 # counter = 0 # for leg,discr in train_discr_dict.iteritems(): # d = Hist(30, 0, 1) # d.fill_array(discr) # d.SetLineColor(colors[counter]) # d.SetLineWidth(2) # l.AddEntry(d,leg,"l") # # b = Hist(30, 0, 1) # d.fill_array(discr_dict[leg.split(" ")[0] + " test"]) # b.SetLineColor(colors[counter]) # b.SetMarkerColor(colors[counter]) # b.SetMarkerStyle(34) # b.SetMarkerSize(1.8) # b.SetLineWidth(2) # l.AddEntry(b,leg,"p") # counter += 1 l.Draw("same") c.SaveAs(outfile)
def ln_likelihood_full_matching(self, w_value, alpha, zeta, beta, gamma, delta, kappa, eta, lamb, g1_value, extraction_efficiency, gas_gain_value, gas_gain_width, spe_res, s1_acc_par0, s1_acc_par1, s2_acc_par0, s2_acc_par1, scale_par, d_gpu_local_info, draw_fit=False): # ----------------------------------------------- # ----------------------------------------------- # determine prior likelihood and variables # ----------------------------------------------- # ----------------------------------------------- prior_ln_likelihood = 0 matching_ln_likelihood = 0 # get w-value prior lieklihood prior_ln_likelihood += self.get_ln_prior_w_value(w_value) # priors of detector variables prior_ln_likelihood += self.get_ln_prior_g1(g1_value) prior_ln_likelihood += self.get_ln_prior_extraction_efficiency( extraction_efficiency) prior_ln_likelihood += self.get_ln_prior_gas_gain_value(gas_gain_value) prior_ln_likelihood += self.get_ln_prior_gas_gain_width(gas_gain_width) prior_ln_likelihood += self.get_ln_prior_spe_res(spe_res) prior_ln_likelihood += self.get_ln_prior_s1_acc_pars( s1_acc_par0, s1_acc_par1) prior_ln_likelihood += self.get_ln_prior_s2_acc_pars( s2_acc_par0, s2_acc_par1) # get priors from lindhard parameters prior_ln_likelihood += self.get_ln_prior_par_greater_than_zero(alpha) prior_ln_likelihood += self.get_ln_prior_par_greater_than_zero(beta) prior_ln_likelihood += self.get_ln_prior_par_greater_than_zero(gamma) prior_ln_likelihood += self.get_ln_prior_par_greater_than_zero(kappa) prior_ln_likelihood += self.get_ln_prior_par_greater_than_zero(eta) prior_ln_likelihood += self.get_ln_prior_par_greater_than_zero(lamb) prior_ln_likelihood += self.get_ln_prior_zeta(zeta) prior_ln_likelihood += self.get_ln_prior_delta(delta) # if prior is -inf then don't bother with MC #print 'removed prior infinity catch temporarily' if not np.isfinite(prior_ln_likelihood) and not draw_fit: return -np.inf # ----------------------------------------------- # ----------------------------------------------- # run MC # ----------------------------------------------- # ----------------------------------------------- num_trials = np.asarray(self.num_mc_events, dtype=np.int32) num_repetitions = np.asarray(d_gpu_local_info['num_repetitions'], dtype=np.int32) mean_field = np.asarray(self.d_data_parameters['mean_field'], dtype=np.float32) w_value = np.asarray(w_value, dtype=np.float32) alpha = np.asarray(alpha, dtype=np.float32) zeta = np.asarray(zeta, dtype=np.float32) beta = np.asarray(beta, dtype=np.float32) gamma = np.asarray(gamma, dtype=np.float32) delta = np.asarray(delta, dtype=np.float32) kappa = np.asarray(kappa, dtype=np.float32) eta = np.asarray(eta, dtype=np.float32) lamb = np.asarray(lamb, dtype=np.float32) g1_value = np.asarray(g1_value, dtype=np.float32) extraction_efficiency = np.asarray(extraction_efficiency, dtype=np.float32) gas_gain_value = np.asarray(gas_gain_value, dtype=np.float32) gas_gain_width = np.asarray(gas_gain_width, dtype=np.float32) spe_res = np.asarray(spe_res, dtype=np.float32) s1_acc_par0 = np.asarray(s1_acc_par0, dtype=np.float32) s1_acc_par1 = np.asarray(s1_acc_par1, dtype=np.float32) s2_acc_par0 = np.asarray(s2_acc_par0, dtype=np.float32) s2_acc_par1 = np.asarray(s2_acc_par1, dtype=np.float32) # for histogram binning num_bins_s1 = np.asarray(self.s1_settings[0], dtype=np.int32) num_bins_s2 = np.asarray(self.s2_settings[0], dtype=np.int32) a_hist_2d = np.zeros(self.s1_settings[0] * self.s2_settings[0], dtype=np.int32) #print d_gpu_local_info['d_gpu_energy'][degree_setting] l_gpu_args = (d_gpu_local_info['rng_states'], drv.In(num_trials), drv.In(num_repetitions), drv.In(mean_field), d_gpu_local_info['gpu_energies'], drv.In(w_value), drv.In(alpha), drv.In(zeta), drv.In(beta), drv.In(gamma), drv.In(delta), drv.In(kappa), drv.In(eta), drv.In(lamb), drv.In(g1_value), drv.In(extraction_efficiency), drv.In(gas_gain_value), drv.In(gas_gain_width), drv.In(spe_res), drv.In(s1_acc_par0), drv.In(s1_acc_par1), drv.In(s2_acc_par0), drv.In(s2_acc_par1), drv.In(num_bins_s1), d_gpu_local_info['gpu_bin_edges_s1'], drv.In(num_bins_s2), d_gpu_local_info['gpu_bin_edges_s2'], drv.InOut(a_hist_2d)) #print '\n\n\nBefore call...' #print d_gpu_local_info d_gpu_local_info['function_to_call'](*l_gpu_args, **self.d_gpu_scale) #print 'After call...\n\n\n' a_s1_s2_mc = np.reshape(a_hist_2d, (self.s2_settings[0], self.s1_settings[0])).T #print list(a_s1_s2_mc) sum_mc = np.sum(a_s1_s2_mc, dtype=np.float32) if sum_mc == 0: #print 'sum mc == 0' return -np.inf # this forces our scale to be close to 1 (difference comes from acceptance) a_s1_s2_mc = np.multiply( a_s1_s2_mc, float(scale_par) * len(self.a_data_s1) / float(self.num_mc_events * self.num_repetitions)) #'ml' if draw_fit: f, (ax1, ax2) = plt.subplots(2, sharex=True, sharey=True) ax1.set_xlabel('S1 [PE]') ax1.set_ylabel('log(S2/S1)') ax2.set_xlabel('S1 [PE]') ax2.set_ylabel('log(S2/S1)') s1_s2_data_plot = np.rot90(self.d_coincidence_data_information[ self.l_cathode_settings_in_use[0]][degree_setting] ['a_log_s2_s1']) s1_s2_data_plot = np.flipud(s1_s2_data_plot) ax1.pcolormesh(self.a_s1_bin_edges, self.a_log_bin_edges, s1_s2_data_plot) s1_s2_mc_plot = np.rot90(a_s1_s2_mc) s1_s2_mc_plot = np.flipud(s1_s2_mc_plot) #print self.l_s1_settings #print self.l_log_settings #print self.d_coincidence_data_information[self.l_cathode_settings_in_use[0]][self.l_degree_settings_in_use[0]]['a_log_s2_s1'].shape #print a_s1_s2_mc.shape #print s1_s2_data_plot.shape #print s1_s2_mc_plot.shape ax2.pcolormesh(self.a_s1_bin_edges, self.a_log_bin_edges, s1_s2_mc_plot) #plt.colorbar() c1 = Canvas(1400, 400) c1.Divide(2) h_s1_data = Hist(*self.l_s1_settings, name='hS1_draw_data') root_numpy.array2hist( self.d_coincidence_data_information[ self.l_cathode_settings_in_use[0]][degree_setting] ['a_log_s2_s1'].sum(axis=1), h_s1_data) hS1MC = Hist(*self.l_s1_settings, name='hS1_draw_mc') root_numpy.array2hist(a_s1_s2_mc.sum(axis=1), hS1MC) s1_scale_factor = h_s1_data.Integral() / float(hS1MC.Integral()) g_s1_data = neriX_analysis.convert_hist_to_graph_with_poisson_errors( h_s1_data) g_s1_mc = neriX_analysis.convert_hist_to_graph_with_poisson_errors( hS1MC, scale=s1_scale_factor) g_s1_mc.SetFillColor(root.kBlue) g_s1_mc.SetMarkerColor(root.kBlue) g_s1_mc.SetLineColor(root.kBlue) g_s1_mc.SetFillStyle(3005) g_s1_data.SetTitle('S1 Comparison') g_s1_data.GetXaxis().SetTitle('S1 [PE]') g_s1_data.GetYaxis().SetTitle('Counts') g_s1_data.SetLineColor(root.kRed) g_s1_data.SetMarkerSize(0) g_s1_data.GetXaxis().SetRangeUser(self.l_s1_settings[1], self.l_s1_settings[2]) g_s1_data.GetYaxis().SetRangeUser( 0, 1.2 * max(h_s1_data.GetMaximum(), hS1MC.GetMaximum())) c1.cd(1) g_s1_data.Draw('ap') g_s1_mc.Draw('same') g_s1_mc_band = g_s1_mc.Clone() g_s1_mc_band.Draw('3 same') h_s2_data = Hist(*self.l_log_settings, name='h_s2_draw_data') root_numpy.array2hist( self.d_coincidence_data_information[ self.l_cathode_settings_in_use[0]][degree_setting] ['a_log_s2_s1'].sum(axis=0), h_s2_data) h_s2_mc = Hist(*self.l_log_settings, name='h_s2_draw_mc') root_numpy.array2hist(a_s1_s2_mc.sum(axis=0), h_s2_mc) s2_scale_factor = h_s2_data.Integral() / float(h_s2_mc.Integral()) g_s2_data = neriX_analysis.convert_hist_to_graph_with_poisson_errors( h_s2_data) g_s2_mc = neriX_analysis.convert_hist_to_graph_with_poisson_errors( h_s2_mc, scale=s2_scale_factor) g_s2_mc.SetFillColor(root.kBlue) g_s2_mc.SetMarkerColor(root.kBlue) g_s2_mc.SetLineColor(root.kBlue) g_s2_mc.SetFillStyle(3005) g_s2_data.SetTitle('Log(S2/S1) Comparison') g_s2_data.GetXaxis().SetTitle('Log(S2/S1)') g_s2_data.GetYaxis().SetTitle('Counts') g_s2_data.SetLineColor(root.kRed) g_s2_data.SetMarkerSize(0) g_s2_data.GetXaxis().SetRangeUser(self.l_log_settings[1], self.l_log_settings[2]) g_s2_data.GetYaxis().SetRangeUser( 0, 1.2 * max(h_s2_data.GetMaximum(), h_s2_mc.GetMaximum())) c1.cd(2) g_s2_data.Draw('ap') g_s2_mc.Draw('same') g_s2_mc_band = g_s2_mc.Clone() g_s2_mc_band.Draw('3 same') c1.Update() neriX_analysis.save_plot(['temp_results'], c1, '%d_deg_1d_hists' % (degree_setting), batch_mode=True) f.savefig('./temp_results/%d_deg_2d_hist.png' % (degree_setting)) flat_s1_s2_data = np.asarray(self.a_data_hist_s1_s2.flatten(), dtype=np.float32) flat_s1_s2_mc = np.asarray(a_s1_s2_mc.flatten(), dtype=np.float32) logLikelihoodMatching = c_log_likelihood( flat_s1_s2_data, flat_s1_s2_mc, len(flat_s1_s2_data), int(self.num_mc_events * self.num_repetitions), 0.95) #print prior_ln_likelihood #print logLikelihoodMatching #print max(flat_s1_s2_data) #print max(flat_s1_s2_mc) #print '\n\n' if np.isnan(logLikelihoodMatching): return -np.inf else: matching_ln_likelihood += logLikelihoodMatching if self.b_suppress_likelihood: matching_ln_likelihood /= self.ll_suppression_factor total_ln_likelihood = prior_ln_likelihood + matching_ln_likelihood #print total_ln_likelihood if np.isnan(total_ln_likelihood): return -np.inf else: return total_ln_likelihood
tree = Tree("test") branches = {'x': 'F', 'y': 'F', 'z': 'F', 'i': 'I'} tree.create_branches(branches) for i in xrange(10000): tree.x = gauss(.5, 1.) tree.y = gauss(.3, 2.) tree.z = gauss(13., 42.) tree.i = i tree.fill() # Make a histogram of x when y > 1 hist1 = Hist(100, -10, 10, name='hist1') tree.Draw('x', 'y > 1', hist=hist1) hist1.SetDirectory(0) # memory resident print "The first tree has %f entries where y > 1" % hist1.Integral() tree.write() f.close() print "Creating test tree in chaintest2.root" f = root_open("chaintest2.root", "recreate") tree = Tree("test") tree.create_branches(branches) for i in xrange(10000): tree.x = gauss(.5, 1.) tree.y = gauss(.3, 2.) tree.z = gauss(13., 42.) tree.i = i
def make_plot(raw_data, binning, title_text, outfn): h = Hist(*binning, drawstyle='hist e1', color=sigCOLORS[0], linewidth=2, title=';Percent difference[%];Events') for sample, value in raw_data.items(): h.Fill(value['variation'], value['count']) hc = asrootpy(h.GetCumulative()) hc.linecolor = 'gold' hc.fillcolor = 'lightyellow' hc.fillstyle = 'solid' hc.scale(h.max(include_error=True) / hc.max()) xmin_, xmax_, ymin_, ymax_ = get_limits([h, hc]) draw([hc, h], ylimits=(0, ymax_)) x95, x99 = None, None cumsum = 0 for i in range(1, h.GetNbinsX() + 1): cumsum += h.GetBinContent(i) if x95 is None and cumsum / h.Integral() > 0.95: x95 = h.GetXaxis().GetBinUpEdge(i) if x99 is None and cumsum / h.Integral() > 0.99: x99 = h.GetXaxis().GetBinUpEdge(i) title = TitleAsLatex(title_text) title.Draw() # print(title_text, ROOT.gPad.GetUymax(), hc.max()) # draw a second axis on the right. ROOT.gPad.SetTicks( 1, 0 ) # Draw top ticks but not right ticks (https://root.cern.ch/root/roottalk/roottalk99/2908.html) low, high = 0, ROOT.gPad.GetUymax() / hc.max() raxis = ROOT.TGaxis(ROOT.gPad.GetUxmax(), ROOT.gPad.GetUymin(), ROOT.gPad.GetUxmax(), ROOT.gPad.GetUymax(), low, high, 510, "+L") raxis.SetLabelSize(0.03) raxis.SetLabelFont(42) raxis.SetLabelColor(convert_color('gold', 'root')) raxis.Draw() frame = canvas.FindObject('TFrame') lo, hi = frame.GetY1(), frame.GetY2() l95 = ROOT.TLine(x95, lo, x95, hi) l95.SetLineStyle(2) l95.SetLineColor(convert_color(sigCOLORS[1], 'root')) l95.SetLineWidth(2) l95.Draw() l99 = ROOT.TLine(x99, lo, x99, hi) l99.SetLineStyle(3) l99.SetLineColor(convert_color(sigCOLORS[2], 'root')) l99.Draw() leg = Legend(3, margin=0.25, leftmargin=0.45, topmargin=0.02, entrysep=0.01, entryheight=0.02, textsize=10) leg.AddEntry(hc, label='cumulative (norm.)', style='LF') leg.AddEntry(l95, label='95% @ {}'.format(x95), style='L') leg.AddEntry(l99, label='99% @ {}'.format(x99), style='L') leg.Draw() canvas.SaveAs(outfn) canvas.clear()
def run_landaus(title, folder_path, d_mip_variables, data_charge_inputs): ''' Plot any landaus ''' print "- - - - - - - - - - - - - - - - - - -" print "Plotting Data Simulation Comparisons" print "- - - - - - - - - - - - - - - - - - -" ######################################################################################################################## ### Fill ROOTPY Hists ######################################################################################################################## charge_deposited_hist = Hist(data_charge_inputs['edges']) for v in d_mip_variables['q_Deposited_e']: charge_deposited_hist.Fill(v) charge_deposited_hist.Scale(1 / charge_deposited_hist.Integral()) unweighted_charge_deposited_hist = Hist(data_charge_inputs['edges']) for v in d_mip_variables['q_ClusterDeposited_e']: unweighted_charge_deposited_hist.Fill(v) unweighted_charge_deposited_hist.Scale( 1 / unweighted_charge_deposited_hist.Integral()) charge_read_hist = Hist(data_charge_inputs['edges']) for v in d_mip_variables['q_Read_e']: charge_read_hist.Fill(v) charge_read_hist.Scale(1 / charge_read_hist.Integral()) charge_weight_hist = Hist(data_charge_inputs['edges_stripClusterFraction']) for v in d_mip_variables['q_Weight_e']: charge_weight_hist.Fill(v) charge_weight_hist.Scale(1 / charge_weight_hist.Integral()) ######################################################################################################################## ### Charge Weighting ######################################################################################################################## fig = plt.figure() ax = fig.add_subplot(1, 1, 1) rplt.hist( data_charge_inputs['hist_stripClusterFraction_normed'], histtype='step', facecolor='red', edgecolor='red', fill=True, alpha=0.5, label='Strip-Cluster Distribution', ) rplt.hist( charge_weight_hist, histtype='step', facecolor='blue', edgecolor='blue', fill=True, alpha=0.5, label='Scaling Distribution applied to Simulated Charge Deposition ', ) ax.set_ylim([0, 0.1]) ax.set_xlabel('Charge [e]') ax.set_ylabel('N') fig.suptitle('Strip-Cluster Charge Distribution', fontsize=14, fontweight='bold') plt.title(title, loc='right') leg = plt.legend(loc='best') leg.draw_frame(False) fig.savefig(folder_path + 'MC_Data_ChargeWeighting_Norm.pdf', bbox_inches='tight') fig.clf() plt.close() gc.collect() # ######################################################################################################################## # ### Data STRIP vs Cluster Charge # ######################################################################################################################## # fig = plt.figure() # ax = fig.add_subplot(1, 1, 1) # rplt.hist( # data_charge_inputs['hist_clusterCharge'], # histtype='step', # facecolor='orange', # edgecolor='orange', # fill = True, # alpha=0.5, # label='Cluster Charge Distribution in Data', # ) # rplt.hist( # data_charge_inputs['hist_stripCharge'], # histtype='step', # facecolor='red', # edgecolor='red', # fill = True, # alpha=0.5, # label='Strip Charge Distribution in Data', # ) # # ax.set_ylim([0,0.15]) # ax.set_xlabel('Charge [e]') # ax.set_ylabel('N') # fig.suptitle('Strip v Cluster Charge Deposition in Data', fontsize=14, fontweight='bold') # plt.title(title, loc='right') # leg = plt.legend(loc='best') # leg.draw_frame(False) # fig.savefig(folder_path+'Data_StripCluster.pdf', bbox_inches='tight') # fig.clf() # plt.close() # gc.collect() ######################################################################################################################## ### Data STRIP vs Cluster Charge ######################################################################################################################## fig = plt.figure() ax = fig.add_subplot(1, 1, 1) rplt.hist( data_charge_inputs['hist_clusterCharge_normed'], histtype='step', facecolor='orange', edgecolor='orange', fill=True, alpha=0.5, label='Cluster Charge Distribution in Data', ) rplt.hist( data_charge_inputs['hist_stripCharge_normed'], histtype='step', facecolor='red', edgecolor='red', fill=True, alpha=0.5, label='Strip Charge Distribution in Data', ) ax.set_ylim([0, 0.15]) ax.set_xlabel('Charge [e]') ax.set_ylabel('N') fig.suptitle('Strip v Cluster Charge in Data', fontsize=14, fontweight='bold') plt.title(title, loc='right') leg = plt.legend(loc='best') leg.draw_frame(False) fig.savefig(folder_path + 'Data_StripCluster_Norm.pdf', bbox_inches='tight') fig.clf() plt.close() gc.collect() ######################################################################################################################## ### Simulation STRIP vs Cluster Charge ######################################################################################################################## fig = plt.figure() ax = fig.add_subplot(1, 1, 1) rplt.hist( unweighted_charge_deposited_hist, histtype='step', facecolor='green', edgecolor='green', fill=True, alpha=0.5, label='Cluster Charge Distribution in Simulation', ) rplt.hist( charge_deposited_hist, histtype='step', facecolor='blue', edgecolor='blue', fill=True, alpha=0.5, label='Strip Charge Distribution in Simulation', ) ax.set_ylim([0, 0.1]) ax.set_xlabel('Charge [e]') ax.set_ylabel('N') fig.suptitle('Strip v Cluster Charge Deposition in Simulation', fontsize=14, fontweight='bold') plt.title(title, loc='right') leg = plt.legend(loc='best') leg.draw_frame(False) fig.savefig(folder_path + 'MC_ChargeDeposition_Norm.pdf', bbox_inches='tight') fig.clf() plt.close() gc.collect() ######################################################################################################################## ### Simulation STRIP vs Cluster Charge. Input vs Output Distirbutions ######################################################################################################################## fig = plt.figure() ax = fig.add_subplot(1, 1, 1) rplt.hist( charge_deposited_hist, histtype='step', facecolor='blue', edgecolor='blue', fill=True, alpha=0.5, label='Strip Charge Distribution in Simulation', ) rplt.hist( charge_read_hist, histtype='step', facecolor='purple', edgecolor='purple', fill=True, alpha=0.5, label='Strip Charge Distribution in Simulation from APV Gain', ) ax.set_ylim([0, 0.1]) ax.set_xlabel('Charge [e]') ax.set_ylabel('N') fig.suptitle( 'Simulated Charge Deposition Comparison with Readout from Gain', fontsize=14, fontweight='bold') plt.title(title, loc='right') leg = plt.legend(loc='best') leg.draw_frame(False) fig.savefig(folder_path + 'MC_ChargeDepositionFromGain_Norm.pdf', bbox_inches='tight') fig.clf() plt.close() gc.collect() ######################################################################################################################## ### Strip Charge Deposition From Data vs MC ######################################################################################################################## fig = plt.figure() ax = fig.add_subplot(1, 1, 1) rplt.hist( charge_read_hist, histtype='step', facecolor='blue', edgecolor='blue', fill=True, alpha=0.5, label='Strip Charge Distribution in Simulation', ) rplt.hist( data_charge_inputs['hist_stripCharge_normed'], histtype='step', facecolor='red', edgecolor='red', fill=True, alpha=0.5, label='Strip Charge Distribution in Data', ) # plt.axvline(x=7500, linewidth=1, color='r', label = 'Min Threshold') # plt.axvline(x=1500, linewidth=1, color='g', label = 'Min Threshold') # plt.axvline(x=3000, linewidth=1, color='b', label = 'Min Threshold') # plt.axvline(x=2000, linewidth=1, color='orange', label = 'Min Threshold') ax.set_ylim([0, 0.1]) ax.set_xlabel('Charge [e]') ax.set_ylabel('N') fig.suptitle('Strip Charge Deposition Data vs Simulation', fontsize=14, fontweight='bold') plt.title(title, loc='right') leg = plt.legend(loc='best') leg.draw_frame(False) fig.savefig(folder_path + 'MC_Data_StripChargeDeposition_Norm.pdf', bbox_inches='tight') fig.clf() plt.close() gc.collect() ######################################################################################################################## ### Cluster Charge Deposition From Data vs MC ######################################################################################################################## fig = plt.figure() ax = fig.add_subplot(1, 1, 1) rplt.hist( data_charge_inputs['hist_clusterCharge_normed'], histtype='step', facecolor='orange', edgecolor='orange', fill=True, alpha=0.5, label='Cluster Charge Distribution in Data', ) rplt.hist( unweighted_charge_deposited_hist, histtype='step', facecolor='green', edgecolor='green', fill=True, alpha=0.5, label='Cluster Charge Distribution in Simulation', ) ax.set_ylim([0, 0.1]) ax.set_xlabel('Charge [e]') ax.set_ylabel('N') fig.suptitle('Cluster Charge Deposition Data vs Simulation', fontsize=14, fontweight='bold') plt.title(title, loc='right') leg = plt.legend(loc='best') leg.draw_frame(False) fig.savefig(folder_path + 'MC_Data_ClusterChargeDeposition_Norm.pdf', bbox_inches='tight') fig.clf() plt.close() gc.collect() # ######################################################################################################################## # ### Cluster Charge Vs Charge Splitting # ######################################################################################################################## # fig = plt.figure() # ax = fig.add_subplot(1, 1, 1) # plt.scatter( # d_mip_variables['q_ClusterDeposited_e'], # d_mip_variables['q_Weight_e'], # ) # ax.set_xlim([0,8000000]) # ax.set_ylim([0,1]) # ax.set_xlabel('Cluster Charge [e]') # ax.set_ylabel('Strip Charge [e]') # # ax.set_ylabel('N') # fig.suptitle('Cluster Charge vs Strip Charge [Simulation]', fontsize=14, fontweight='bold') # plt.title(title, loc='right') # # leg = plt.legend(loc='best') # # leg.draw_frame(False) # fig.savefig(folder_path+'TEST.pdf', bbox_inches='tight') # fig.clf() # plt.close() # gc.collect() ######################################################################################################################## ### All Charge Distributions ######################################################################################################################## fig = plt.figure() ax = fig.add_subplot(1, 1, 1) rplt.hist( data_charge_inputs['hist_clusterCharge_normed'], histtype='step', facecolor='orange', edgecolor='orange', fill=True, alpha=0.5, label='Cluster Charge Distribution in Data', ) rplt.hist( data_charge_inputs['hist_stripCharge_normed'], histtype='step', facecolor='red', edgecolor='red', fill=True, alpha=0.5, label='Strip Charge Distribution in Data', ) rplt.hist( unweighted_charge_deposited_hist, histtype='step', facecolor='blue', edgecolor='blue', fill=True, alpha=0.5, label='Cluster Charge Distribution in Simulation', ) rplt.hist( charge_read_hist, histtype='step', facecolor='purple', edgecolor='purple', fill=True, alpha=0.5, label='Strip Charge Distribution in Simulation from APV Gain', ) ax.set_ylim([0, 0.05]) ax.set_xlabel('Charge [e]') ax.set_ylabel('N') fig.suptitle('Strip and Cluster Distributions in Simulation and Data', fontsize=14, fontweight='bold') plt.title(title, loc='right') leg = plt.legend(loc='best') leg.draw_frame(False) fig.savefig(folder_path + 'MC_Data_ChargeComparison_Norm.pdf', bbox_inches='tight') fig.clf() plt.close() gc.collect() return