def extractVersion(fname): if debug: print 'extract version' ch = TChain("RunMetadataTree") ch.Add(fname) ch.SetBranchStatus("*", 1) svn_rev = TString() tag = TString() ch.SetBranchAddress("SvnRev", svn_rev) ch.SetBranchAddress("tag", tag) ch.GetEntry(0) return str(tag), str(svn_rev)
def test_gt(self): ts1 = TString(self.test_str1) ts2 = TString(self.test_str2) # Comparison between TStrings self.assertFalse(ts1 > ts2) self.assertTrue(ts2 > ts1) # Comparison with Python string self.assertFalse(ts1 > self.test_str2) self.assertTrue(ts2 > self.test_str1)
def test1TStringByValueInterpreted(self): """Test passing a TString by value through an interpreted function""" gROOT.LoadMacro('ArgumentPassingInterpreted.C') f = ROOT.InterpretedTest.StringValueArguments self.assertEqual(f('aap'), 'aap') self.assertEqual(f(TString('noot')), 'noot') self.assertEqual(f('zus', 1, 'default'), 'default') self.assertEqual(f('zus', 1), 'default') self.assertEqual(f('jet', 1, TString('teun')), 'teun')
def test5TStringByValueCompiled(self): """Test passing a TString by value through a compiled function""" gROOT.LoadMacro('ArgumentPassingCompiled.C++') f = ROOT.CompiledTest.StringValueArguments self.assertEqual(f('aap'), 'aap') self.assertEqual(f(TString('noot')), 'noot') self.assertEqual(f('zus', 1, 'default'), 'default') self.assertEqual(f('zus', 1), 'default') self.assertEqual(f('jet', 1, TString('teun')), 'teun')
def test6TStringByRefCompiled(self): """Test passing a TString by reference through a compiled function""" # script ArgumentPassingCompiled.C already loaded in by value test f = ROOT.CompiledTest.StringRefArguments self.assertEqual(f('aap'), 'aap') self.assertEqual(f(TString('noot')), 'noot') self.assertEqual(f('zus', 1, 'default'), 'default') self.assertEqual(f('zus', 1), 'default') self.assertEqual(f('jet', 1, TString('teun')), 'teun')
def test_ge(self): ts1 = TString(self.test_str1) ts2 = TString(self.test_str1) ts3 = TString(self.test_str2) # Comparison between TStrings self.assertTrue(ts1 >= ts2) self.assertFalse(ts1 >= ts3) self.assertTrue(ts3 >= ts1) # Comparison with Python string self.assertTrue(ts1 >= self.test_str1) self.assertFalse(ts1 >= self.test_str2) self.assertTrue(ts3 >= self.test_str1)
def test_ne(self): ts1 = TString(self.test_str1) ts2 = TString(self.test_str1) ts3 = TString(self.test_str2) # Comparison between TStrings self.assertFalse(ts1 != ts2) self.assertTrue(ts1 != ts3) # Comparison with Python string self.assertFalse(ts1 != self.test_str1) self.assertTrue(ts1 != self.test_str2) # Comparison with non-string self.assertTrue(ts1 != 1)
def runOptimization(self, xValues, yValues, erryValues, fixParams, doSmearing=False, printOutLevel=0): self.doSmearing = doSmearing gMinuit, istat = self.prepareAndRunOptimizer( xValues, yValues, erryValues, fixParams, self.costFunction, self.parValues, self.parNames, printOutLevel) # Extract parameters and errors ierflg = c_int(0) val, err, errLo, errHi = c_double(0.), c_double(0.), c_double( 0.), c_double(0.) self.fitErr = [0 for i in range(len(self.parValues))] self.fitErrLo = [0 for i in range(len(self.parValues))] self.fitErrHi = [0 for i in range(len(self.parValues))] for i in range(len(self.parValues)): gMinuit.mnpout(i, TString(''), val, err, errLo, errHi, ierflg) self.parValues[i] = val.value self.fitErr[i] = err.value self.fitErrLo[i] = errLo.value self.fitErrHi[i] = errHi.value for i, value in enumerate(self.parValues): self.fitFun.SetParameter(i, value) return istat
def test_lt(self): tos1 = TObjString(self.test_str1) tos2 = TObjString(self.test_str2) # Comparison between TObjStrings self.assertTrue(tos1 < tos2) self.assertFalse(tos2 < tos1) # Comparison with TString ts1 = TString(self.test_str1) ts2 = TString(self.test_str2) self.assertTrue(tos1 < ts2) self.assertFalse(tos2 < ts1) # Comparison with Python string self.assertTrue(tos1 < self.test_str2) self.assertFalse(tos2 < self.test_str1)
def GetTStringVectorSamples(path, samples): from ROOT import vector, TString, gSystem # Add the input data files v = vector(TString)() for s in samples: t = TString(path + s) v.push_back(t) return v v = GetTStringVector(samples)
def test_list_sort(self): l1 = [TString(str(i)) for i in range(self.num_elems)] l2 = list(reversed(l1)) self.assertNotEqual(l1, l2) # Test that comparison operators enable list sorting l2.sort() self.assertEqual(l1, l2)
def PlotChains(filelist, outdir, sourcename="cluster", makelists=0): """ Plots a spectra for a comma seperated list of files Eventually should include a number of cuts including fiducial region cuts Output saved in outdir/<sourcename>_Plot.root """ indirs = filelist.split(',') if sourcename == "cluster" and len(indirs) == 1: fpath = indirs[0].split('/')[-1] sourcename = fpath.rstrip('_SpectrumData.root') mychain = TChain("DTree") for folder in indirs: #folder += "/*_SpectrumData.root" for filename in glob.glob(folder): mychain.Add(str(filename)) pname = "/global/homes/l/lkorley/myprojectdir/HighNR/lists/processlist.txt" cpname = "/global/homes/l/lkorley/myprojectdir/HighNR/lists/creatorlist.txt" if os.path.exists(pname): with open(pname) as f: proclist = f.readlines() for iproc in proclist: if iproc == "": continue iproc = re.sub(r'[^\x00-\x7f]', r'', iproc) print "Creator processes: " + iproc ROOT.WriteHists(mychain, TString(outdir), TString(sourcename), TString("process(" + iproc + ")")) if os.path.exists(cpname): with open(cpname) as f: cproclist = f.readlines() for icproc in cproclist: if icproc == "": continue icproc = re.sub(r'[^\x00-\x7f]', r'', icproc) print "Process: " + icproc ROOT.WriteHists(mychain, TString(outdir), TString(sourcename), TString(""), TString("creator(" + icproc + ")")) ROOT.WriteHists(mychain, TString(outdir), TString(sourcename)) if makelists == 1: GetProcesses(filelist, sourcename + "_")
def reduce(dirlist, outdir, listname=""): indirs = dirlist.split(',') pname_wa = 'w' cpname_wa = 'w' oprocesslist = [] ocprocesslist = [] pname = outdir + "/" + listname + "processlist.txt" cpname = outdir + "/" + listname + "creatorlist.txt" if os.path.exists(pname): pname_wa = 'a' with open(pname) as f: oprocesslist = f.readlines() if os.path.exists(cpname): cpname_wa = 'a' with open(cpname) as f: ocprocesslist = f.readlines() processlist = [] cprocesslist = [] processes = TString("") cprocesses = TString("") for folder in indirs: mychain = TChain("DataTree") print "\nAdding: " + folder outnames = folder.rsplit('/')[-1] sourcename = outnames.split('_', 1)[-1] folder += "/out/*.root" mychain.Add(str(folder)) print "Processing " + sourcename ROOT.ExtractData(mychain, TString(sourcename), TString(outdir), processes, cprocesses) for ip in processes.Data().split(','): if ip not in oprocesslist and ip not in processlist and ip != "": ip = re.sub(r'[^\x00-\x7f]', r'', ip) processlist.append(ip) for ip in cprocesses.Data().split(','): if ip not in ocprocesslist and ip not in cprocesslist and ip != "": ip = re.sub(r'[^\x00-\x7f]', r'', ip) cprocesslist.append(ip) with open(pname, pname_wa) as f: for ip in processlist: line = ip + "\n" f.write(line) with open(cpname, cpname_wa) as f: for ip in cprocesslist: line = ip + "\n" f.write(line)
def test_eq(self): tos1 = TObjString(self.test_str1) tos2 = TObjString(self.test_str1) tos3 = TObjString(self.test_str2) # Comparison between TObjStrings self.assertTrue(tos1 == tos2) self.assertFalse(tos1 == tos3) # Comparison with TString ts1 = TString(self.test_str1) ts2 = TString(self.test_str2) self.assertTrue(tos1 == ts1) self.assertFalse(tos1 == ts2) # Comparison with Python string self.assertTrue(tos1 == self.test_str1) self.assertFalse(tos1 == self.test_str2) # Comparison with non-string self.assertFalse(tos1 == 1)
def test1Strings(self): """Test string/TString/TObjString compatibility""" pyteststr = "aap noot mies" s1 = TString(pyteststr) s2 = str(s1) self.assertEqual(s1, s2) s3 = TObjString(s2) self.assertEqual(s2, s3) self.assertEqual(s2, pyteststr)
def test10OpaquePointerPassing(self): """Test passing around of opaque pointers""" import ROOT s = TString("Hello World!") co = ROOT.AsCObject(s) ad = ROOT.AddressOf(s)[0] self.assert_(s == ROOT.BindObject(co, s.__class__)) self.assert_(s == ROOT.BindObject(co, "TString")) self.assert_(s == ROOT.BindObject(ad, s.__class__)) self.assert_(s == ROOT.BindObject(ad, "TString"))
def getXsec(mttbin): inFile = open('xsecFit_tab13TeV_mtt' + str(mttbin) + '.tex', 'r') l = inFile.read().splitlines() xsec = '' total = '' for line in l: if '$\\sigma_{t\\bar{t}}^{(\\mu_' + str( mttbin) in line and '\\hline' in line: xsec = line if 'Total' in line and not 'vis' in line: total = line xsec = xsec.split('&')[3] xsec = TString(xsec) xsec.ReplaceAll('pb \\\\ \\hline \\hline', '') xsec = float(str(xsec)) total = total.split('&')[3] total = TString(total) total.ReplaceAll('}_{', ' ') total.ReplaceAll(' $\mp^{', '') total.ReplaceAll(' $\pm^{', '') total.ReplaceAll('}$ \\\\', '') total.ReplaceAll(' \hline', '') total = str(total) total = total.split() err_up = float(total[0]) err_down = float(total[1]) err_up *= xsec / 100. err_down *= xsec / 100. h = rFile.Get('h_xsec_' + str(mttbin)) err_toys = h.GetRMS() err_up = (err_up**2 + err_toys**2)**.5 err_down = (err_down**2 + err_toys**2)**.5 err_up = round(err_up, 2) err_down = round(err_down, 2) return [xsec, err_up, err_down]
def test14OpaquePointerPassing(self): """Test passing around of opaque pointers""" import ROOT s = TString("Hello World!") co = AsCObject(s) ad = addressof(s) self.assertTrue(s == BindObject(co, s.__class__)) self.assertTrue(s == BindObject(co, "TString")) self.assertTrue(s == BindObject(ad, s.__class__)) self.assertTrue(s == BindObject(ad, "TString"))
def writeCurrentFile(rootFile): ''' Save a copy of the current script, as a TText, in the current ROOT file nothing happens if a ROOT file is not currently open! ''' import sys, os.path from ROOT import TString, TText, TFile filename = sys.argv[0] if (not os.path.exists(filename)): m_log.error("Could not open file " + filename + "!") return s = TString() t = TText() # Too fresh #with open(filename) as input: input = open(filename) if input: for line in input: s += line t.SetName(os.path.basename(filename)) t.SetText(0, 0, s.Data()) f = TFile(rootFile, 'UPDATE') t.Write() f.Close()
def runGlobalOptimization(self, evolutions, xValues, yValues, erryValues, fixParams, doSmearing=False, printOutLevel=0): self.evolutions = evolutions self.doSmearing = doSmearing parNames = ['Initial population', 'Carrying capacity', 'Growth rate-0'] parNames.extend( ['Growth rate-' + str(i + 1) for i in range(len(evolutions))]) parValues = [0 for i in range(len(parNames))] parValues[0] = self.parValues[0] parValues[1] = self.parValues[1] parValues[2] = self.parValues[2] for i, ev in enumerate(self.evolutions): parValues[3 + i] = ev.parValues[2] gMinuit, istat = self.prepareAndRunOptimizer(xValues, yValues, erryValues, fixParams, self.costFunctionGlobal, parValues, parNames, printOutLevel) # Extract parameters and errors ierflg = c_int(0) val, err, errLo, errHi = c_double(0.), c_double(0.), c_double( 0.), c_double(0.) self.fitErr = [0 for i in range(len(parValues))] self.fitErrLo = [0 for i in range(len(parValues))] self.fitErrHi = [0 for i in range(len(parValues))] for i in range(len(parValues)): gMinuit.mnpout(i, TString(''), val, err, errLo, errHi, ierflg) parValues[i] = val.value self.fitErr[i] = err.value self.fitErrLo[i] = errLo.value self.fitErrHi[i] = errHi.value self.setFitFun(self.evolveGlobalWrapper, self.tStart, evolutions[-1].tStop, parNames, parValues) return istat, parValues, parNames
def test13OpaquePointerPassing(self): """Test passing around of opaque pointers""" import ROOT s = TString("Hello World!") co = self.AsCObject(s) if self.exp_pyroot: # In new Cppyy, addressof returns an integer/long ad = self.AddressOf(s) else: ad = self.AddressOf(s)[0] self.assert_(s == self.BindObject(co, s.__class__)) self.assert_(s == self.BindObject(co, "TString")) self.assert_(s == self.BindObject(ad, s.__class__)) self.assert_(s == self.BindObject(ad, "TString"))
def GetProcesses(filelist, appendagename=""): """ Generates list of processes and creator processes in the dataset for plotting if not already done """ pname = "/global/homes/l/lkorley/myprojectdir/HighNR/lists/" + appendagename + "processlist.txt" cpname = "/global/homes/l/lkorley/myprojectdir/HighNR/lists/" + appendagename + "creatorlist.txt" oprocesslist = [] ocprocesslist = [] if os.path.exists(pname): with open(pname) as f: oprocesslist = f.readlines() else: cmd = "touch " + pname os.system(cmd) if os.path.exists(cpname): with open(cpname) as f: ocprocesslist = f.readlines() else: cmd = "touch " + cpname os.system(cmd) processes = TString("") cprocesses = TString("") for filename in glob.glob(filelist): mychain = TChain("DTree") mychain.Add(str(filename)) ROOT.listprocess(mychain, processes, cprocesses) for ip in processes.Data().split(','): if ip not in oprocesslist: ip = re.sub(r'[^\x00-\x7f]', r'', ip) oprocesslist.append(ip) with open(pname, "a") as f: line = ip + "\n" f.write(line) for ip in cprocesses.Data().split(','): if ip not in ocprocesslist: ip = re.sub(r'[^\x00-\x7f]', r'', ip) ocprocesslist.append(ip) with open(cpname, "a") as f: line = ip + "\n" f.write(line)
def __init__(self, taggerName="DeepFlav", meastype="mujets", wp="Medium", year=2017): taggerName = TString(taggerName) #"DeepFlav","CSVv2";"DeepCSV"; MeasType = TString(meastype) # comb, mujets stringWP = TString(wp) self.fBTagSFnom = BTagSFUtil(MeasType.Data(), pathtolib, taggerName.Data(), stringWP, 0, year, '') self.fBTagSFbUp = BTagSFUtil(MeasType.Data(), pathtolib, taggerName.Data(), stringWP, 1, year, '') self.fBTagSFbDo = BTagSFUtil(MeasType.Data(), pathtolib, taggerName.Data(), stringWP, -1, year, '') self.fBTagSFlUp = BTagSFUtil(MeasType.Data(), pathtolib, taggerName.Data(), stringWP, 3, year, '') self.fBTagSFlDo = BTagSFUtil(MeasType.Data(), pathtolib, taggerName.Data(), stringWP, -3, year, '')
os = ROOT.TFile("output_selection.root", "RECREATE") sel = TTree('Selection', 'Selection outputs') branches = {} for branch in data.GetListOfBranches(): branchName = branch.GetName() if (branchName != 'a' and branchName != 'b'): branches[branchName] = array.array('f', [0]) reader.AddVariable(branchName, branches[branchName]) sel.Branch(branchName, branches[branchName], branchName + "/F") # Book methods reader.BookMVA( 'PyKeras', TString('dataset/weights/TMVAClassification_PyKeras.weights.xml')) # Print some example classifications print reader.EvaluateMVA('PyKeras') print('Some signal example classifications:') a = data.GetEntries() for i in range(20): data.GetEntry(i) ev = reader.EvaluateMVA('PyKeras') print(ev) print data.a00 print('') ''' #!/usr/bin/env python
def main(): usage = 'usage: %prog [options]' parser = optparse.OptionParser(usage) parser.add_option( '-s', '--suffix', dest='input_suffix', help='suffix used to identify inputs from network training', default=None, type='string') parser.add_option('-j', '--json', dest='json', help='json file with list of variables', default=None, type='string') parser.add_option('-i', '--input', dest='input_file', help='input file', default=None, type='string') (opt, args) = parser.parse_args() jsonFile = open(opt.json, 'r') if opt.json == None: print 'input variable .json not defined!' sys.exit(1) if opt.input_suffix == None: print 'Input files suffix not defined!' sys.exit(1) if opt.input_file == None: print 'Input file not defined!' sys.exit(1) new_variable_list = json.load(jsonFile, encoding="utf-8").items() n_input_vars = 0 for key, value in new_variable_list: n_input_vars = n_input_vars + 1 input_file = opt.input_file classifier_suffix = opt.input_suffix classifier_parent_dir = '/afs/cern.ch/work/j/jthomasw/private/IHEP/ttHML/github/ttH_multilepton/DNN/Evaluation/V7-DNN_%s' % ( classifier_suffix) # Setup TMVA TMVA.Tools.Instance() TMVA.PyMethodBase.PyInitialize() reader = TMVA.Reader("Color:!Silent") # Check files exist if not isfile(input_file): print 'No such input file: %s' % input_file # Open files and load ttrees data_file = TFile.Open(input_file) data_tree = data_file.Get("syncTree") branches_tree = {} integer_branches_tree = {} for key, value in new_variable_list: if 'hadTop_BDT' in key: branches_tree[key] = array('f', [-999]) keyname = 'hadTop_BDT' data_tree.SetBranchAddress(str(keyname), branches_tree[key]) elif 'Hj1_BDT' in key: branches_tree[key] = array('f', [-999]) keyname = 'Hj1_BDT' data_tree.SetBranchAddress(str(keyname), branches_tree[key]) elif ('n_fakeablesel_mu' in key) or ('n_fakeablesel_ele' in key) or ('Jet_numLoose' in key): integer_branches_tree[key] = array('I', [9999]) data_tree.SetBranchAddress(str(key), integer_branches_tree[key]) else: branches_tree[key] = array('f', [-999]) data_tree.SetBranchAddress(str(key), branches_tree[key]) branches_reader = {} # Register names of inputs with reader. Together with the name give the address of the local variable that carries the updated input variables during event loop. for key, value in new_variable_list: print 'Add variable name %s: ' % key branches_reader[key] = array('f', [-999]) reader.AddVariable(str(key), branches_reader[key]) event_number = array('f', [-999]) reader.AddSpectator('nEvent', event_number) # Book methods # First argument is user defined name. Doesn not have to be same as training name. # True type of method and full configuration are read from the weights file specified in the second argument. mva_weights_dir = '%s/weights/Factory_V7-DNN_%s_DNN.weights.xml' % ( classifier_parent_dir, classifier_suffix) print 'using weights file: ', mva_weights_dir reader.BookMVA('DNN', TString(mva_weights_dir)) if '/2L/' in input_file: analysis_region = '2L' elif '/ttWctrl/' in input_file: analysis_region = 'ttWctrl' elif '/JESDownttWctrl/' in input_file: analysis_region = 'JESDownttWctrl' elif '/JESUpttWctrl/' in input_file: analysis_region = 'JESUpttWctrl' elif '/ClosTTWctrl/' in input_file: analysis_region = 'ClosTTWctrl' elif '/ttZctrl/' in input_file: analysis_region = 'ttZctrl' elif '/Clos2LSS/' in input_file: analysis_region = 'Closure' elif '/JESDown2L/' in input_file: analysis_region = 'JESDown2L' elif '/JESUp2L/' in input_file: analysis_region = 'JESUp2L' time_suffix = str(datetime.now(pytz.utc)).split(' ') print time_suffix[0] #classifier_samples_dir = classifier_parent_dir+"/outputs" classifier_samples_dir = classifier_parent_dir + "/outputs-newbinning" #classifier_plots_dir = classifier_parent_dir+"/plots" classifier_plots_dir = classifier_parent_dir + "/plots-newbinning" if not os.path.exists(classifier_plots_dir): os.makedirs(classifier_plots_dir) if not os.path.exists(classifier_samples_dir): os.makedirs(classifier_samples_dir) analysis_region_samples_dir = '%s/%s' % (classifier_samples_dir, analysis_region) analysis_region_plots_dir = '%s/%s' % (classifier_plots_dir, analysis_region) if not os.path.exists(analysis_region_plots_dir): os.makedirs(analysis_region_plots_dir) if not os.path.exists(analysis_region_samples_dir): os.makedirs(analysis_region_samples_dir) output_suffix = input_file[input_file.rindex('/') + 1:] print 'output_suffix: ', output_suffix # Define outputs: files to store histograms/ttree with results from application of classifiers and any histos/trees themselves. output_file_name = '%s/Evaluated_%s_%s' % ( analysis_region_samples_dir, classifier_suffix, output_suffix) output_file = TFile.Open(output_file_name, 'RECREATE') output_tree = data_tree.CopyTree("") output_tree.SetName("output_tree") nEvents_check = output_tree.BuildIndex("nEvent", "run") print 'Copied %s events from original tree' % (nEvents_check) sample_nickname = '' if 'THQ_htt_2L' in input_file: sample_nickname = 'THQ_htt_2L' if 'THQ_hzz_2L' in input_file: sample_nickname = 'THQ_hzz_2L' if 'THW_hww_2L' in input_file: sample_nickname = 'THW_hww_2L' if 'TTH_hmm_2L' in input_file: sample_nickname = 'TTH_hmm_2L' if 'TTH_htt_2L' in input_file: sample_nickname = 'TTH_htt_2L' if 'TTH_hzz_2L' in input_file: sample_nickname = 'TTH_hzz_2L' if 'THQ_hww_2L' in input_file: sample_nickname = 'THQ_hww_2L' if 'THW_htt_2L' in input_file: sample_nickname = 'THW_htt_2L' if 'THW_hzz_2L' in input_file: sample_nickname = 'THW_hzz_2L' if 'TTH_hot_2L' in input_file: sample_nickname = 'TTH_hot_2L' if 'TTH_hww_2L' in input_file: sample_nickname = 'TTH_hww_2L' if 'TTWW_2L' in input_file: sample_nickname = 'TTWW_2L' if 'TTW_2L' in input_file: sample_nickname = 'TTW_2L' if 'TTZ_2L' in input_file: sample_nickname = 'TTZ_2L' if 'Conv_2L' in input_file: sample_nickname = 'Conv_2L' if 'EWK_2L' in input_file: sample_nickname = 'EWK_2L' if 'Fakes_2L' in input_file: sample_nickname = 'Fakes_2L' if 'Flips_2L' in input_file: sample_nickname = 'Flips_2L' if 'Rares_2L' in input_file: sample_nickname = 'Rares_2L' if 'TT_Clos' in input_file: sample_nickname = 'TT_Clos' if 'Data' in input_file: sample_nickname = 'Data' # Evaluate network and use max node response to categorise event. Only maximum node response will be plotted per event meaning each event will only contribute in the maximum nodes response histogram. network_evaluation(data_tree, new_variable_list, sample_nickname, branches_tree, integer_branches_tree, branches_reader, reader, True, output_tree) output_file.Write() gDirectory.Delete("syncTree;*") output_file.Close() print 'Job complete. Exiting.' sys.exit(0)
self.combined.Fill(value,-1.) def write(self): outputfile.WriteTObject(self.pos) outputfile.WriteTObject(self.neg) outputfile.WriteTObject(self.combined) del self #-------------------------------------------------# #---------------- Cut definitions ----------------# # ptcuts is a list of different cut values ptcuts = [25., 30., 50., 100.] etacut = 2.5 #-------------------------------------------------# #First use FW Lite from CMSSW #-------------------- FW Lite --------------------# cmsswbase = TString.getenv("CMSSW_BASE") print 'Loading FW Lite setup.\n' gSystem.Load("libFWCoreFWLite.so") ROOT.AutoLibraryLoader.enable() gSystem.Load("libDataFormatsFWLite.so") gSystem.Load("libDataFormatsPatCandidates.so") #-------------------------------------------------# #Create output file bevor loop outputfile = TFile(sys.argv[1],"RECREATE") #Read in the inputfiles for every loop, else it won't work inputlist = [] if mode == 0: if len(sys.argv) > 2: dirs = sys.argv[2:]
#nfiles = len(hist_name) nfiles = len(cut) xmin = 2.0 xmax = 6.0 n_bin = 80 i = 0 print "length of the cut parameter list ", len( cut), reference_frame[nframe] #print vars() while i < nfiles: print "cut parameters", cut[i] histograms = TString() # hist = hist_name + "_"+ str(i) histograms = "{}_{}".format(hist_name, i) #print i #print hist # i=i+1 canvas = TCanvas(histograms, "Canvas of Mass", 600, 300) histogram = TH1F(histograms, "Mass Plots", n_bin, xmin, xmax) #print hist bin_width = (xmax - xmin) / n_bin #ytitle = "Number of Events/"+ str(bin_width) + " GeV/C #rightarrow" ytitle = "Number of Events/{}GeV/C #rightarrow".format(bin_width)
else :suffix = suffix+"_B"; if options.onlybackgroundfit : suffix = suffix+"_B"; else: suffix = suffix+"_SB"; os.system("ls "+nameInputDirectory+" | grep root | grep _"+options.fgen+"_"+options.fres+"_ | grep "+suffix+" > list_temp.txt"); print "ls "+nameInputDirectory+" | grep root | grep _"+options.fgen+"_"+options.fres+"_ | grep "+suffix+" > list_temp.txt" vector_root_file = []; os.system("mkdir -p "+options.outputDir); with open("list_temp.txt") as input_list: for line in input_list: for name in line.split(): name.replace(" ", ""); vector_root_file.append(TFile(TString(nameInputDirectory+"/"+name).Data(),"READ")); ## make the histograms histogram_pull_vs_mass_nback = ROOT.TH1F("histogram_pull_vs_mass_nback","",len(mass),0,len(mass)); gaussian_pull_vs_mass_nback = ROOT.TH1F("gaussian_pull_vs_mass_nback","",len(mass),0,len(mass)); if not options.onlybackgroundfit: histogram_pull_vs_mass_nsig = ROOT.TH1F("histogram_pull_vs_mass_nsig","",len(mass),0,len(mass)); gaussian_pull_vs_mass_nsig = ROOT.TH1F("gaussian_pull_vs_mass_nsig","",len(mass),0,len(mass)); graph_1 = ROOT.TGraphErrors(); graph_2 = ROOT.TGraphErrors(); canvas_pull_bkg_data = []; canvas_pull_sig_data = [];
TMVA.PyMethodBase.PyInitialize() reader = TMVA.Reader("Color:!Silent") # Load data if not isfile('tmva_reg_example.root'): call([ 'curl', '-L', '-O', 'http://root.cern.ch/files/tmva_reg_example.root' ]) data = TFile.Open('tmva_reg_example.root') tree = data.Get('TreeR') branches = {} for branch in tree.GetListOfBranches(): branchName = branch.GetName() branches[branchName] = array('f', [-999]) tree.SetBranchAddress(branchName, branches[branchName]) if branchName != 'fvalue': reader.AddVariable(branchName, branches[branchName]) # Book methods reader.BookMVA('PyKeras', TString('dataset/weights/TMVARegression_PyKeras.weights.xml')) # Print some example regressions print('Some example regressions:') for i in range(20): tree.GetEntry(i) print('True/MVA value: {}/{}'.format(branches['fvalue'][0], reader.EvaluateMVA('PyKeras')))
def read_file(arr, meas_type, mapsa_fitter_inst, path): if not os.path.isfile(str(path + arr[0])): print "Root file not found at", str(path + arr[0]) #sys.exit(1) return f = TFile(str(path + arr[0]), 'READ') if (f.IsZombie()): print "Error opening file" return else: print "Reading File ", arr[0] #f.ls() tree = f.Get('tree') f_GlobalData_Map = ROOT.TMap() f_GlobalData_Map.Add(ROOT.TObjString("tree"), tree) #tree.Print() outfile = TString(arr[0]) outfile.ReplaceAll(".root", "") outfile.ReplaceAll(" ", "") # print outfile if (meas_type == 0): outfile = "pedestal" if (not g.FindKey(str(outfile))): g.mkdir(str(outfile)) g.cd(str(outfile)) else: return channels = 288 if (arr[2] == 'inv'): channels = 96 mapsa_mat = [[1, 0, 0], [1, 0, 0]] elif (arr[2] == 'norm'): channels = 288 mapsa_mat = [[1, 1, 1], [1, 0, 1]] #print "channels", channels #print "mapsa_mat", mapsa_mat c1 = TCanvas('c1', 'Pixel Monitor ', 700, 900) c2 = TCanvas('c2', 'Pixel Monitor ', 500, 500) c3 = TCanvas('c3', 'Pixel Monitor ', 1280, 720) c4 = TCanvas('c4', 'Pixel Monitor ', 500, 500) c5 = TCanvas('c5', 'Pixel Monitor ', 500, 500) f_GlobalData_Map.Add(ROOT.TObjString("c1"), c1) f_GlobalData_Map.Add(ROOT.TObjString("c2"), c2) f_GlobalData_Map.Add(ROOT.TObjString("c3"), c3) f_GlobalData_Map.Add(ROOT.TObjString("c4"), c4) f_GlobalData_Map.Add(ROOT.TObjString("c5"), c5) # c2.Divide(2,1) #c2.cd(0) c1.Divide(3, 2) for i in range(1, 7): c1.cd(i) ROOT.gPad.SetGridx() ROOT.gPad.SetGridy() # channelcounts = TH2I('HitMap','Counts; Channel; DAC Value (1.456 mV)', 288, .5,288.5,256, .5, 256.5) channelcounts = TH2I('HitMap', 'Counts; Channel; DAC Value (a.u.)', 288, .5, 288.5, 256, .5, 256.5) channelcounts_norm = TH2F('HitMap_norm', 'Occupancy ; Channel; DAC Value (a.u.)', 288, .5, 288.5, 256, .5, 256.5) f_GlobalData_Map.Add(ROOT.TObjString("HitMap"), channelcounts) f_GlobalData_Map.Add(ROOT.TObjString("HitMap"), channelcounts_norm) norm_2d = TH2F('Norm2D', 'Normalization; Column; Row', 48, .5, 48.5, 6, .5, 6.5) mean_2d = TH2F('Mean2D', 'Mean; Column; Row', 48, .5, 48.5, 6, .5, 6.5) sigma_2d = TH2F('Sigma2D', 'Sigma; Column; Row', 48, .5, 48.5, 6, .5, 6.5) chisquare = TH2F('Chisquare2D', 'Chisquare; Column; Row', 48, .5, 48.5, 6, .5, 6.5) f_GlobalData_Map.Add(ROOT.TObjString("Norm2D"), norm_2d) f_GlobalData_Map.Add(ROOT.TObjString("Mean2D"), mean_2d) f_GlobalData_Map.Add(ROOT.TObjString("Sigma2D"), sigma_2d) f_GlobalData_Map.Add(ROOT.TObjString("Chisquare2D"), chisquare) objarr2d = [] objarr2d.append(norm_2d) objarr2d.append(mean_2d) objarr2d.append(sigma_2d) objarr2d.append(chisquare) normgraph = TGraphErrors() meangraph = TGraphErrors() sigmagraph = TGraphErrors() chisquaregraph = TGraphErrors() mean_corrgraph = TGraphErrors() f_GlobalData_Map.Add(ROOT.TObjString("normgraph "), normgraph) f_GlobalData_Map.Add(ROOT.TObjString("meangraph "), meangraph) f_GlobalData_Map.Add(ROOT.TObjString("sigmagraph "), sigmagraph) f_GlobalData_Map.Add(ROOT.TObjString("chisquaregraph"), chisquaregraph) f_GlobalData_Map.Add(ROOT.TObjString("mean_corrgraph"), mean_corrgraph) meanhist = TH1F('meanhist', 'Mean DAC; DAC Value (a.u.); counts', 2560, 0, 255) sigmahist = TH1F('sigmahist', 'Sigma DAC; DAC Value (a.u.); counts', 100, 0, 10) meanhist_std = TH1F('meanhist_std', 'Mean DAC Standard; DAC Value (a.u.); counts', 2560, 0, 255) sigmahist_std = TH1F('sigmahist_std', 'Sigma DAC Standard; DAC Value (a.u.); counts', 100, 0, 10) meanhist_double = TH1F('meanhist_double', 'Mean DAC Double; DAC Value (a.u.); counts', 2560, 0, 255) sigmahist_double = TH1F('sigmahist_double', 'Sigma DAC Double; DAC Value (a.u.); counts', 100, 0, 10) meanhist_double_neighbour = TH1F( 'meanhist_double_neighbour', 'Mean DAC Double Neighbour; DAC Value (a.u.); counts', 2560, 0, 255) sigmahist_double_neighbour = TH1F( 'sigmahist_double_neighbour', 'Sigma DAC Double Neighbour; DAC Value (a.u.); counts', 100, 0, 10) objarr = [] objarr.append(normgraph) objarr.append(meangraph) objarr.append(sigmagraph) objarr.append(chisquaregraph) objarr.append(mean_corrgraph) f_GlobalData_Map.Add(ROOT.TObjString('meanhist'), meanhist) f_GlobalData_Map.Add(ROOT.TObjString('sigmahist'), sigmahist) f_GlobalData_Map.Add(ROOT.TObjString('meanhist_std'), meanhist_std) f_GlobalData_Map.Add(ROOT.TObjString('sigmahist_std'), sigmahist_std) f_GlobalData_Map.Add(ROOT.TObjString('meanhist_double'), meanhist_double) f_GlobalData_Map.Add(ROOT.TObjString('sigmahist_double'), sigmahist_double) f_GlobalData_Map.Add(ROOT.TObjString('meanhist_double_neighbour'), meanhist_double_neighbour) f_GlobalData_Map.Add(ROOT.TObjString('sigmahist_double_neighbour'), sigmahist_double_neighbour) objarr.append(meanhist) objarr.append(sigmahist) objarr.append(meanhist_std) objarr.append(sigmahist_std) objarr.append(meanhist_double) objarr.append(sigmahist_double) objarr.append(meanhist_double_neighbour) objarr.append(sigmahist_double_neighbour) for objs in objarr: objs.SetMarkerColor(2) objs.SetMarkerStyle(20) objs.SetMarkerSize(1) normgraph.SetName('normgraph') meangraph.SetName('meangraph') sigmagraph.SetName('sigmagraph') chisquaregraph.SetName('chisquare') mean_corrgraph.SetName('mean_corr') normgraph.SetTitle('Normalization; Channel; Normalization') meangraph.SetTitle('Mean; Channel; DAC Value (a.u.)') sigmagraph.SetTitle('Sigma; Channel; DAC Value (a.u.)') chisquaregraph.SetTitle('Chisquared/NDF_gr; Channel; Chisquared/NDF ') ROOT.gStyle.SetOptFit(1111) stack = THStack('a', ';DAC Value (a.u.); Occupancy') f_GlobalData_Map.Add(ROOT.TObjString("stack"), stack) fitfuncs = [] fitparams = [] gr1 = [] for pixel in range(0, channels): gr1.append( TH1D( str(pixel).zfill(3), str(pixel + 1).zfill(3) + ';DAC Value (a.u.); Occupancy ', 256, 0.5, 256.5)) f_GlobalData_Map.Add(ROOT.TObjString(str(pixel).zfill(3)), gr1[pixel]) #gr2.append(TH1F('th1f_'+str(pixel).zfill(3),str(pixel+1).zfill(3)+';DAC Value (a.u.); Occupancy',256,0.5,256.5)) color = pixel % 8 + 1 formating_th1(gr1[pixel], color) if (meas_type == 0): fitfuncs.append( TF1('gauss' + str(pixel + 1).zfill(3), 'gaus(0)', 0, 256)) fitfuncs[pixel].SetNpx(256) fitfuncs[pixel].SetLineColor(color) f_GlobalData_Map.Add( ROOT.TObjString('gauss' + str(pixel).zfill(3)), fitfuncs[pixel]) #Here we read the data and fill the histogram for event in tree: eventstr = [] for counter, vals in enumerate(tree.AR_MPA): #eventstr.append(vals) channelcounts.Fill(counter, tree.THRESHOLD, vals) if (counter < channels): gr1[counter].Fill(tree.THRESHOLD, vals) #if tree.THRESHOLD%20==0 and tree.REPETITION==0: #print eventstr #print ("Threshold %d Repetion %d" % (tree.THRESHOLD,tree.REPETITION)) #print tree.AR_MPA #now we make a small analysis of the curves fitting different functions to it: print "Finished Reading the Tree\n Normalization of Histograms\n" for pixel in range(0, channels): #gr1[pixel].ResetStats() for j in range(0, gr1[pixel].GetXaxis().GetNbins() + 1): gr1[pixel].SetBinError( gr1[pixel].GetBin(j), TMath.Sqrt(gr1[pixel].GetBinContent(gr1[pixel].GetBin(j)))) #if(pixel==0): #gr1[pixel].Print("all") #gr1[pixel].Sumw2(ROOT.kTRUE) gr1[pixel].Scale(1 / arr[1]) #if(pixel==0): #gr1[pixel].Print("all") stack.Add(gr1[pixel]) #first create a THStack with histograms: iterator = stack.GetHists() if (meas_type == 0): for idx, it in enumerate(iterator): fitparams.append([]) if (it.Integral() > 0): if (idx < channels): #fitfuncs.append(TF1('combined'+str(idx),combined, 0,256,5)) #fitfuncs.append(TF1('combined_same_mean'+str(idx),combined_mean, 0,256,4)) #fitfuncs.append(TF1('double_gauss'+str(idx),'gaus(0)+gaus(3)',0,256)) #fitfuncs.append(TF1('gauss'+str(idx),'gaus(0)',0,256)) #fitfuncs.append(TF1('double_gauss_same_mean'+str(idx),double_gauss, 0,256,5)) #print it.GetName(), idx #fitfuncs[idx].SetParameters(it.GetMaximum(),it.GetMean()+1,it.GetRMS(),it.GetMean()-1,it.GetRMS()); #fitfuncs[idx].SetParameters(it.GetMaximum(),it.GetMean(),it.GetRMS()*0.1,it.GetRMS()*0.1); #print ("Channels %f\t%f\t%f\n" % (it.GetMaximum(),it.GetMean(),it.GetRMS())) fitfuncs[idx].SetParameters(it.GetMaximum(), it.GetMean(), it.GetRMS()) #fitfuncs[idx].SetParameters(0.999*it.GetMaximum(),it.GetMean(),.7*it.GetRMS(),0.001*it.GetMaximum(),it.GetMean(),10*it.GetRMS()); #fitfuncs[idx].SetParameters(0.999*it.GetMaximum(),it.GetMean(),.7*it.GetRMS(),0.001*it.GetMaximum(),10*it.GetRMS()); #it.Fit(fitfuncs[idx],'lr0 rob=0.95','same',0,256) #it.Fit(fitfuncs[idx],'lr0q ','',0,256) it.Fit(fitfuncs[idx], 'r0q ', '', 0, 256) fitparams[idx].append(fitfuncs[idx].GetParameter(0)) fitparams[idx].append(fitfuncs[idx].GetParameter(1)) fitparams[idx].append(fitfuncs[idx].GetParameter(2)) fitparams[idx].append(fitfuncs[idx].GetParError(0)) fitparams[idx].append(fitfuncs[idx].GetParError(1)) fitparams[idx].append(fitfuncs[idx].GetParError(2)) if (fitfuncs[idx].GetNDF() > 0): fitparams[idx].append(fitfuncs[idx].GetChisquare() / fitfuncs[idx].GetNDF()) else: for kk in range(0, 7): fitparams[idx].append(0) #print "fitparamarray" fitarray = np.array(fitparams) ## print fitarray for pointno, it in enumerate(fitarray): if (fitarray[pointno][0] > 0): normgraph.SetPoint(pointno, pointno + 1, fitarray[pointno][0]) normgraph.SetPointError(pointno, 0, fitarray[pointno][3]) meangraph.SetPoint(pointno, pointno + 1, fitarray[pointno][1]) meangraph.SetPointError(pointno, 0, fitarray[pointno][4]) meanhist.Fill(fitarray[pointno][1]) sigmagraph.SetPoint(pointno, pointno + 1, fitarray[pointno][2]) sigmagraph.SetPointError(pointno, 0, fitarray[pointno][5]) sigmahist.Fill(fitarray[pointno][2]) chisquaregraph.SetPoint(pointno, pointno + 1, fitarray[pointno][6]) chisquaregraph.SetPointError(pointno, 0, 0) ## iterator.ls() # Map the data to the pixel layout: tmp_objarr = [] tmp_objarr.extend( [meanhist_std, meanhist_double, meanhist_double_neighbour]) tmp_objarr.extend( [sigmahist_std, sigmahist_double, sigmahist_double_neighbour]) for i in tmp_objarr: print str(i.GetName()) fill2d(fitarray[:, 0], mapsa_mat, objarr2d[0]) fill2d(fitarray[:, 1], mapsa_mat, objarr2d[1]) fill2d(fitarray[:, 2], mapsa_mat, objarr2d[2]) fill2d(fitarray[:, 6], mapsa_mat, objarr2d[3]) fill1d_edges(objarr2d[1], tmp_objarr[0:3]) fill1d_edges(objarr2d[2], tmp_objarr[3:]) g.cd(str(outfile)) mapsa_fitter_inst.Make_dirs() mapsa_fitter_inst.Set_run_no(outfile) if (meas_type == 1): for idx, it in enumerate(iterator): if (it.Integral() > 0): if (idx < channels): mapsa_fitter_inst.Find_signal(it, idx, 0.0025, 3) g.cd() #g.mkdir(str(outfile)+"/Channels") #g.cd(str(outfile)+"/Channels") #iterator.Write() g.cd(str(outfile)) g.mkdir(str(outfile) + "/Overview") ## iterator.First().Print("all") Maximum = TMath.Power(10, (round(TMath.Log10(stack.GetMaximum())) - 1)) #Minimum = TMath.Power(10,(round(TMath.Log10(stack.GetMinimum()))+1)) Minimum = .1 ROOT.gStyle.SetLabelSize(0.06, "xyz") ROOT.gStyle.SetTitleSize(0.06, "xyz") ROOT.gStyle.SetTitleOffset(1.2, "y") ROOT.gStyle.SetTitleOffset(.825, "x") ROOT.gStyle.SetPadGridX(1) ROOT.gStyle.SetPadGridY(1) ROOT.gStyle.SetOptStat(0) # ROOT.gStyle.SetPadLeftMargin(.2); # ROOT.gStyle.SetPadRightMargin(.1); c1.cd(1) stack.Draw("nostack hist e1 x0") stack.GetXaxis().SetRangeUser(0, 256) stack.SetMinimum(Minimum) stack.SetMaximum(Maximum) ROOT.gPad.SetLogy() c2.cd(0) stack.Draw("nostack hist e1 x0") #if(outfile.Contains("SR_90_on_top")): #stack.GetXaxis().SetRangeUser(0,256) #else: #stack.GetXaxis().SetRangeUser(0,100) stack.SetMinimum(Minimum) stack.SetMaximum(Maximum) ROOT.gPad.SetLeftMargin(.15) ROOT.gPad.SetRightMargin(.05) ROOT.gPad.SetLogy() ROOT.gPad.Update() #for idx, it in enumerate(fitfuncs): ## if idx>0 and idx<7: #c1.cd(1) #fitfuncs[idx].Draw("same") #c2.cd(0) #fitfuncs[idx].DrawCopy("psame") ## it.SetLineColor(idx%9+1) ## it.Draw("same") #g.cd(str(outfile)+"/Channels") #it.Write("HitMap_py_"+str(idx+1)+"_fit") g.cd(str(outfile) + "/Overview") c1.cd(2) chisquaregraph.Draw("ap") c1.cd(3) normgraph.Draw("ap") c1.cd(4) sigmagraph.Draw("ap") sigmagraph.GetYaxis().SetRangeUser(0, 5) sigmagraph.GetXaxis().SetRangeUser(0, channels + 1) c2.cd(2) sigmagraph.Draw("ap") ROOT.gPad.SetLeftMargin(.15) ROOT.gPad.SetRightMargin(.05) c1.cd(5) meangraph.Draw("ap") c1.cd(6) channelcounts.Draw("colz") channelcounts.GetXaxis().SetRangeUser(0, channels + 1) # c2.cd(3) c3.cd(0) ROOT.gStyle.SetOptStat(0) ROOT.gPad.SetRightMargin(.15) ROOT.gPad.SetLeftMargin(.15) ROOT.gPad.SetGrid(0) copy = channelcounts.DrawCopy("colz") #f_GlobalData_Map.Add(ROOT.TObjString("copy"),copy) #if(outfile.Contains("SR_90_on_top")): #copy.SetMaximum(100) #copy.SetMinimum(1) copy.GetYaxis().SetTitle("DAC Value (a.u.)") c4.cd(0) ROOT.gStyle.SetOptStat(0) ROOT.gPad.SetRightMargin(.15) ROOT.gPad.SetLeftMargin(.15) ROOT.gPad.SetGrid(0) copy1 = sigma_2d.DrawCopy("colz") #f_GlobalData_Map.Add(ROOT.TObjString("copy1"),copy1) copy1.GetZaxis().SetTitle("Sigma (a.u.)") copy1.GetZaxis().SetTitleOffset(1.2) ROOT.gPad.SetRightMargin(.2) if (arr[2] == 'inv'): copy1.GetXaxis().SetRangeUser(.5, 16.5) copy1.SetMaximum(5) copy1.SetMinimum(0) c5.cd(0) ROOT.gStyle.SetOptStat(0) ROOT.gPad.SetRightMargin(.15) ROOT.gPad.SetLeftMargin(.15) ROOT.gPad.SetGrid(0) #copy1 = chisquare.DrawCopy("colz") #f_GlobalData_Map.Add(ROOT.TObjString("copy2"),copy1) copy1 = sigma_2d.DrawCopy("colz") #f_GlobalData_Map.Add(ROOT.TObjString("copy2"),copy1) copy1.GetZaxis().SetTitle("sigma (a.u.)") if (arr[2] == 'inv'): copy1.GetXaxis().SetRangeUser(.5, 16.5) copy1.SetMaximum(5) copy1.SetMinimum(0) c1.Update() c1.Modified() c2.Update() c2.Modified() c3.Update() c3.Modified() c4.Update() c4.Modified() c5.Update() c5.Modified() ## c1.SaveAs("double_gauss_same_mean.pdf") ## time.sleep(2) g.cd(str(outfile) + "/Overview") #for objs in objarr: #objs.Write(objs.GetName()) #norm_2d.GetZaxis().SetRangeUser(1E5,2E6) #mean_2d.GetZaxis().SetRangeUser(54,64) ## norm_2d.GetZaxis().SetRangeUser(TMath.Power(10,(round(TMath.Log10(norm_2d.GetStdDev(3))-2)), TMath.Power(10,(round(TMath.Log10(norm_2d.GetStdDev(3)))-1))) ## mean_2d.GetZaxis().SetRangeUser(TMath.Power(10,(round(TMath.Log10(mean_2d.mean_2d.GetStdDev(3)))-1))-5,TMath.Power(10,(round(TMath.Log10(mean_2d.GetStdDev(3)))-1))+5) #sigma_2d.GetZaxis().SetRangeUser(0,5) #chisquare.GetZaxis().SetRangeUser(0,10000 ) #for objs in objarr2d: #objs.Write(objs.GetName()) #c1.Write("c1") #outfile1=outfile+TString(".pdf") #c2.SaveAs(str(outfile1)) #c2.Write("c2") #c3.SaveAs("c3"+str(outfile1)) #c3.Write("c3") #c4.SaveAs("c4"+str(outfile1)) #c4.Write("c4") ## while (TObject(iterator.Next())): ## print iterator.Next().Title() #stack.Write("stack") #g.cd(str(outfile)) #channelcounts.Write(str(outfile)) #f.Close() c1.Close() c2.Close() c3.Close() c4.Close() c5.Close() f_GlobalData_Map.DeleteAll() f.Close()
def limit_canvas(limits_, signal_, oname_): m = [mp.mass for mp in limits_] exp = [mp.exp for mp in limits_] exp68up = [mp.exp68up for mp in limits_] exp68dn = [mp.exp68dn for mp in limits_] exp95up = [mp.exp95up for mp in limits_] exp95dn = [mp.exp95dn for mp in limits_] obs = [mp.obs for mp in limits_] N = len(limits_) gExp = TGraph() g68 = TGraph(2 * N) g95 = TGraph(2 * N) gObs = TGraph() gTH = get_theory_XsecBR_graph(signal_) for a in range(0, N): gExp.SetPoint(a, m[a], exp[a]) gObs.SetPoint(a, m[a], obs[a]) g68.SetPoint(a, m[a], exp68dn[a]) g95.SetPoint(a, m[a], exp95dn[a]) g68.SetPoint(N + a, m[N - a - 1], exp68up[N - a - 1]) g95.SetPoint(N + a, m[N - a - 1], exp95up[N - a - 1]) trans = 0 up = 0 if signal_ == 'n': trans = 0.770776 up = 3 if signal_ == 'w': trans = 0.836432 up = 10 if signal_ == 'r': trans = 0.899902 up = 4 gExp.SetLineStyle(2) gExp.SetLineWidth(4) gExp.SetLineColor(TColor.GetColor('#112288')) g68.SetLineStyle(1) g68.SetLineWidth(0) g68.SetLineColor(ROOT.kBlack) g68.SetFillColor(TColor.GetColor('#4488dd')) g95.SetLineStyle(1) g95.SetLineWidth(0) g95.SetLineColor(ROOT.kBlack) g95.SetFillColor(TColor.GetColor('#99bbff')) gObs.SetLineStyle(1) gObs.SetLineWidth(4) gObs.SetLineColor(ROOT.kBlack) gObs.SetMarkerStyle(21) gObs.SetMarkerSize(0.8) gTH.SetLineStyle(7) gTH.SetLineWidth(4) gTH.SetMarkerSize(0) gTH.SetMarkerColor(ROOT.kRed + 1) gTH.SetLineColor(ROOT.kRed + 1) leg = TLegend(0.58, 0.633, 0.969, 0.908) leg.SetFillColor(0) leg.SetBorderSize(0) leg.AddEntry(gExp, 'Expected (95% CL)', 'l') leg.AddEntry(gObs, 'Observed (95% CL)', 'l') leg.AddEntry(gTH, signal_dict[signal_][1], 'l') leg.AddEntry(g68, '#pm1#sigma Expected', 'f') leg.AddEntry(g95, '#pm2#sigma Expected', 'f') text_TL = TPaveText(0.14, 0.830, 0.44, 0.900, 'NDC') text_TL.AddText(label_TL) text_TL.SetFillColor(0) text_TL.SetTextAlign(12) text_TL.SetTextSize(0.06) text_TL.SetTextFont(42) text_TR = TPaveText(0.586, 0.923, 0.999, 0.997, 'NDC') text_TR.AddText(label_TR) text_TR.SetFillColor(0) text_TR.SetTextAlign(32) text_TR.SetTextSize(0.055) text_TR.SetTextFont(42) c = TCanvas('c', 'c', 950, 750) c.SetTopMargin(0.08) c.SetRightMargin(0.02) c.SetBottomMargin(0.135) c.SetLeftMargin(0.11) #c.SetGrid() c.SetLogy() #hr = c.DrawFrame(0.401,0.001,3.999,1000) hr = c.DrawFrame(0.401, 0.001, 4.199, 1000) gExp.Sort() g95.Draw('f') g68.Draw('f') gTH.Draw('L') gExp.Draw('L') gObs.Sort() gObs.Draw('L') hr.GetXaxis().SetTitle('M_{' + signal_dict[signal_][0] + '} [TeV]') hr.GetYaxis().SetTitle('Upper limit on #sigma_{' + signal_dict[signal_][0] + '} #times B(' + signal_dict[signal_][0] + ' #rightarrow t#bar{t}) [pb]') #hr.GetYaxis().SetTitle('\\mathrm{Upper~limit~on~}\\sigma_{'+signal_dict[signal_][0]+'}\\times\\mathscr{B}('+signal_dict[signal_][0]+' \\rightarrow t\\bar{t}) [pb]') hr.GetXaxis().SetTitleSize(0.055) hr.GetYaxis().SetTitleSize(0.055) hr.GetXaxis().SetTitleFont(42) hr.GetYaxis().SetTitleFont(42) hr.GetXaxis().SetTitleOffset(1.00) hr.GetYaxis().SetTitleOffset(0.98) hr.GetXaxis().SetLabelSize(0.045) hr.GetYaxis().SetLabelSize(0.045) name = TString(oname_) if name.Contains("com"): tl = TLine(trans, 1e-3, trans, up) tl.SetLineStyle(ROOT.kDashed) tl.SetLineColor(ROOT.kGray + 1) tl.SetLineWidth(3) tl.Draw() c.Update() text_TL.Draw('same') text_TR.Draw('same') leg.Draw() c.SaveAs(oname_ + '.pdf') c.Close()