diff --git a/DPGAnalysis/HcalTools/scripts/cmt/das_client.py b/DPGAnalysis/HcalTools/scripts/cmt/das_client.py index be89be491f066..10c9292748a76 100755 --- a/DPGAnalysis/HcalTools/scripts/cmt/das_client.py +++ b/DPGAnalysis/HcalTools/scripts/cmt/das_client.py @@ -61,7 +61,7 @@ def __init__(self, key=None, cert=None, capath=None, level=0): urllib2.HTTPSHandler.__init__(self) self.key = key self.cert = cert - self.capath = capath + self.capath = capath def https_open(self, req): """Open request method""" @@ -307,8 +307,8 @@ def get_data(host, query, idx, limit, debug, threshold=300, ckey=None, data = fdesc.read() fdesc.close() except urllib2.HTTPError as error: - print(error.read()) - sys.exit(1) + print(error.read()) + sys.exit(1) pat = re.compile(r'^[a-z0-9]{32}') if data and isinstance(data, str) and pat.match(data) and len(data) == 32: diff --git a/DPGAnalysis/HcalTools/scripts/rmt/hcal_runs.py b/DPGAnalysis/HcalTools/scripts/rmt/hcal_runs.py index 119359d675cc0..4786dc68eb4e0 100644 --- a/DPGAnalysis/HcalTools/scripts/rmt/hcal_runs.py +++ b/DPGAnalysis/HcalTools/scripts/rmt/hcal_runs.py @@ -66,7 +66,7 @@ def main(rf, rt): for t in ["pedestal","LED","laser"]: if re.search(t, r[3], flags=re.IGNORECASE) != None: d = get_single(TIME, { "p.run": int(r[0])}) - print r[0], t, "\"" + d + "\"", r[2] + print(r[0], t, "\"" + d + "\"", r[2]) break diff --git a/DPGAnalysis/HcalTools/scripts/rmt/hcal_runs_valdas.py b/DPGAnalysis/HcalTools/scripts/rmt/hcal_runs_valdas.py index 017a1008bc49f..40c7da1b5f8cd 100644 --- a/DPGAnalysis/HcalTools/scripts/rmt/hcal_runs_valdas.py +++ b/DPGAnalysis/HcalTools/scripts/rmt/hcal_runs_valdas.py @@ -72,7 +72,7 @@ def main(rf, rt): d = get_single(TIME, { "p.run": int(r[0])}) if d is not None: d = "\"" + d + "\"" - print r[0], t, d, r[2] + print(r[0], t, d, r[2]) break diff --git a/DQM/SiTrackerPhase2/test/harvestingstep_phase2tk_cfg.py b/DQM/SiTrackerPhase2/test/harvestingstep_phase2tk_cfg.py index c3179f9b376af..4991122029b5d 100644 --- a/DQM/SiTrackerPhase2/test/harvestingstep_phase2tk_cfg.py +++ b/DQM/SiTrackerPhase2/test/harvestingstep_phase2tk_cfg.py @@ -75,7 +75,7 @@ process.GlobalTag = GlobalTag(process.GlobalTag, 'auto:phase2_realistic_T21', '') # Path and EndPath definitions -process.trackerphase2ValidationHarvesting_step = cms.Path(process.trackerphase2ValidationHarvesting_standalone +process.trackerphase2ValidationHarvesting_step = cms.Path(process.trackerphase2ValidationHarvesting_standalone) ##default path in production #process.trackerphase2ValidationHarvesting_step = cms.Path(process.trackerphase2ValidationHarvesting) process.dqmsave_step = cms.Path(process.DQMSaver) diff --git a/DQMOffline/CalibCalo/test/compare.py b/DQMOffline/CalibCalo/test/compare.py index dd434cda205da..30cb48cc25774 100755 --- a/DQMOffline/CalibCalo/test/compare.py +++ b/DQMOffline/CalibCalo/test/compare.py @@ -6,7 +6,7 @@ #print error/help message and exit def help_message(): - print "Usage:\n\ + print("Usage:\n\ compare [folder_name] [options] -v versions_to_compare -f files_to_compare\n\ Versions and files must be whitespace separated.\n\ If no folder is specified the pwd will be used.\n\ @@ -18,7 +18,7 @@ def help_message(): --html produce html output\n\ --canvas with --html option and without --no_exec option produces output directly in png, if not specified output is produced in eps and then converted in png format with an external program (but can be used in batch mode).\n\ Example:\n\ -./compare.py myDir -v CMSSW_X_Y_Z CMSSW_J_K_W -f file1.root file2.root --no_exec --outfile out.root" +./compare.py myDir -v CMSSW_X_Y_Z CMSSW_J_K_W -f file1.root file2.root --no_exec --outfile out.root") sys.exit() #run command in the command line with specified environment @@ -65,9 +65,9 @@ def srcpath(fldr): try: cwd=os.getcwd() os.chdir(name) - except OSError, inst: + except OSError as inst: if inst.errno==errno.ENOENT: - print "Error: the specified working folder does not exist" + print("Error: the specified working folder does not exist") help_message() else: help_message() @@ -109,7 +109,7 @@ def srcpath(fldr): try: from ROOT import gSystem, TFile, TLegend, TCanvas, gDirectory except ImportError: - print "Warning: environment variables not set, proceeding anyway running this script with the environment variables of the higher version of CMSSW specified in -v" + print("Warning: environment variables not set, proceeding anyway running this script with the environment variables of the higher version of CMSSW specified in -v") #storing cmsenv environment variables os.chdir(max(ver)) env=os.popen("scramv1 runtime -sh","r") @@ -129,7 +129,7 @@ def srcpath(fldr): runcmd2(environment,"./compare.py",tuple(sys.argv[1:-1]))#works only if compare.py is located in the pwd else: gSystem.Load("libFWCoreFWLite.so") - FWLiteEnabler::enable() + ROOT.FWLiteEnabler.enable() outfile=TFile(root_out,"recreate") histo=[] canvas=[] @@ -165,7 +165,7 @@ def srcpath(fldr): outfile.cd() canvas[nf].Write() if execute: - print "Press enter to end the program" + print("Press enter to end the program") os.system("read") if html: if cnv: @@ -173,9 +173,9 @@ def srcpath(fldr): for nf,f in enumerate(fil): try: os.mkdir(f[:len(f)-5]) - except OSError,inst: + except OSError as inst: if inst.errno==errno.EEXIST: - print "Possibly overwriting images" + print("Possibly overwriting images") os.system("cp "+cwd+"/temp.html "+f[:len(f)-5]+"/index.html") os.chdir(f[:len(f)-5]) canvas[nf].cd() @@ -193,14 +193,14 @@ def srcpath(fldr): #os.system("sleep 2") os.chdir("../") else: - print "Warning:to use --canvas option do not use --no_exec option. Rerun without --canvas option." + print("Warning:to use --canvas option do not use --no_exec option. Rerun without --canvas option.") else: for nf,f in enumerate(fil): try: os.mkdir(f[:len(f)-5]) - except OSError,inst: + except OSError as inst: if inst.errno==errno.EEXIST: - print "Possibly overwriting images" + print("Possibly overwriting images") os.system("cp "+cwd+"temp.html "+f[:len(f)-5]+"/index.html") os.chdir(f[:len(f)-5]) canvas[nf].cd() diff --git a/DQMOffline/Configuration/scripts/cmsswConfigtrace.py b/DQMOffline/Configuration/scripts/cmsswConfigtrace.py index a7e416d534eca..e44a58244daab 100755 --- a/DQMOffline/Configuration/scripts/cmsswConfigtrace.py +++ b/DQMOffline/Configuration/scripts/cmsswConfigtrace.py @@ -305,7 +305,7 @@ def trace_python(prog_argv, path): code = compile(fp.read(), progname, 'exec') globals = {} try: - exec code in globals, globals + exec (code, globals, globals) except: print(traceback.format_exc()) finally: diff --git a/DQMOffline/Configuration/scripts/cmsswFiletrace.py b/DQMOffline/Configuration/scripts/cmsswFiletrace.py index e505aefdf32f0..91889c9ad6511 100755 --- a/DQMOffline/Configuration/scripts/cmsswFiletrace.py +++ b/DQMOffline/Configuration/scripts/cmsswFiletrace.py @@ -213,7 +213,7 @@ def exec_hook(*args): # now turn on the traceing sys.settrace(tracefunc) try: - exec code in globals, globals + exec(code, globals, globals) finally: sys.settrace(None) diff --git a/HLTriggerOffline/Btag/test/testSequences.py b/HLTriggerOffline/Btag/test/testSequences.py index 48c4640fd518e..377190bd0108c 100644 --- a/HLTriggerOffline/Btag/test/testSequences.py +++ b/HLTriggerOffline/Btag/test/testSequences.py @@ -22,12 +22,12 @@ def add_rawRelVals(process, inputName): 'The parenthood is needed to add RAW secondary input files' % process.source.fileNames[0] ) for i in dataset['data']: - try: n_files = i['dataset'][0]['num_file'] - except: pass + try: n_files = i['dataset'][0]['num_file'] + except: pass raw_files = cmssw_das_client.get_data('file '+query, limit = 0) files = [] for i in raw_files['data']: - files.append( i['file'][0]['name']) + files.append( i['file'][0]['name']) raw_files = ['root://cms-xrd-global.cern.ch/'+str(i) for i in files] process.source = cms.Source("PoolSource", fileNames = cms.untracked.vstring(raw_files)) diff --git a/Validation/CaloTowers/test/client_data_cfg.py b/Validation/CaloTowers/test/client_data_cfg.py index 7ac81fc102289..97d2326f1c0a9 100644 --- a/Validation/CaloTowers/test/client_data_cfg.py +++ b/Validation/CaloTowers/test/client_data_cfg.py @@ -7,10 +7,10 @@ class config: pass config.runNumber = int(sys.argv[1]) -print config.runNumber +print(config.runNumber) for arg in sys.argv: - print arg + print(arg) readFiles = cms.untracked.vstring() @@ -20,9 +20,9 @@ class config: pass fileToRead = "file:"+argument readFiles.append(fileToRead) -print "readFiles : \n", readFiles +print("readFiles : \n", readFiles) -print config.runNumber +print(config.runNumber) ########## diff --git a/Validation/CaloTowers/test/run_onRelVal_fromGENSIM_redigi_rereco_cfg.py b/Validation/CaloTowers/test/run_onRelVal_fromGENSIM_redigi_rereco_cfg.py index 878df3f63243b..c61de2d3b295d 100644 --- a/Validation/CaloTowers/test/run_onRelVal_fromGENSIM_redigi_rereco_cfg.py +++ b/Validation/CaloTowers/test/run_onRelVal_fromGENSIM_redigi_rereco_cfg.py @@ -10,7 +10,7 @@ options.register('SLHC' , 0, VarParsing.VarParsing.multiplicity.singleton, VarParsing.VarParsing.varType.int, "Run SLHC mode (default false) doesn't do anything yet.") options.parseArguments() -print options +print(options) ### RANDOM setting (change last digit(s) to make runs different !) process.load("Configuration.StandardSequences.SimulationRandomNumberGeneratorSeeds_cff") diff --git a/Validation/HcalHits/test/ZdcSimHitStudy_cfg.py b/Validation/HcalHits/test/ZdcSimHitStudy_cfg.py index 9f6cdfceed937..c9af945269029 100644 --- a/Validation/HcalHits/test/ZdcSimHitStudy_cfg.py +++ b/Validation/HcalHits/test/ZdcSimHitStudy_cfg.py @@ -45,7 +45,7 @@ process.dqmsave_step = cms.Path(process.DQMSaver) -print process.ZDCDigiStudy.Verbose +print(process.ZDCDigiStudy.Verbose) process.p1 = cms.Path( process.ZDCDigiStudy *process.zdcSimHitStudy) diff --git a/Validation/MuonGEMHits/test/Compare.py b/Validation/MuonGEMHits/test/Compare.py index a59f76dd06634..f1c67c33a6697 100755 --- a/Validation/MuonGEMHits/test/Compare.py +++ b/Validation/MuonGEMHits/test/Compare.py @@ -93,8 +93,8 @@ def draw_plot( file1, file2, tDir,oDir ) : options, args = parser.parse_args() if len(args)==0 : - print "Input file name is None." - print "Use default name.[ DQM_v6.root and DQM_v7.root]" + print("Input file name is None.") + print("Use default name.[ DQM_v6.root and DQM_v7.root]") args.append("DQM_v6.root") args.append("DQM_v7.root") diff --git a/Validation/MuonGEMHits/test/MakePlot.py b/Validation/MuonGEMHits/test/MakePlot.py index 21eb2481d7b5f..3866e2a64044a 100755 --- a/Validation/MuonGEMHits/test/MakePlot.py +++ b/Validation/MuonGEMHits/test/MakePlot.py @@ -18,7 +18,7 @@ def getEtaRange( station ) : if ( station ==1 or station==2 ) : return etaRange[ (station-1)*2], etaRange[ (station-1)*2+1 ] else : - print "Something is wrong" + print("Something is wrong") return 1.5,2.6 def draw_occ(target_dir, h, ext =".png", opt = ""): @@ -171,7 +171,7 @@ def draw_eff(target_dir, h, ext = ".png", opt = ""): elif ( h.GetName().find("st2") != -1 ) : xmin,xmax = getEtaRange(2) else : - print "Use default setting." + print("Use default setting.") f1 = TF1("fit1","pol0", xmin, xmax ) r = h.Fit("fit1","RQS") @@ -216,7 +216,7 @@ def draw_plot( file, tDir,oDir ) : try : tlist = d1.GetListOfKeys() except : - print oDir + print(oDir) if ( oDir.find("Digi") != -1 ): tDir = "DQMData/Run 1/MuonGEMDigisV/Run summary/GEMDigiTask" d1 = dqm_file.Get(tDir) @@ -226,7 +226,7 @@ def draw_plot( file, tDir,oDir ) : d1 = dqm_file.Get(tDir) tlist = d1.GetListOfKeys() else : - print "error" + print("error") exit(-1) for x in tlist : key_list.append(x.GetName()) @@ -249,7 +249,7 @@ def draw_plot( file, tDir,oDir ) : draw_col_overflow( oDir, d1.Get(hist) ) elif ( hist.find("eff") != -1 ) : draw_eff( oDir, d1.Get(hist) ) - #print "found " + #print("found ") elif ( hist.find("geo_phi") != -1) : draw_col_userRange( oDir, d1.Get(hist)) else : @@ -273,12 +273,12 @@ def draw_plot( file, tDir,oDir ) : exit() # If no argument, default name will be used. if len(args)==0 : - print "Input file name is None." - print "Use default name." + print("Input file name is None.") + print("Use default name.") args.append("DQM_V0001_R000000001__Global__CMSSW_X_Y_Z__RECO.root") if len(args) != 1 : - print "Can not understand input argument" + print("Can not understand input argument") parser.print_help() steps= [] @@ -299,5 +299,5 @@ def draw_plot( file, tDir,oDir ) : oDir = options.directory+"_%s"%(step)+'/' os.system("mkdir -p "+oDir ) draw_plot(args[0],tDir,oDir) - #print args[0],tDir, oDir + #print (args[0],tDir, oDir) diff --git a/Validation/MuonGEMHits/test/phiView.py b/Validation/MuonGEMHits/test/phiView.py index 2a1aa5ba14f6d..41ab0db5e2b0f 100755 --- a/Validation/MuonGEMHits/test/phiView.py +++ b/Validation/MuonGEMHits/test/phiView.py @@ -44,13 +44,13 @@ def draw_plot( file, tDir,oDir,min,max ) : try : tlist = d1.GetListOfKeys() except : - print oDir + print(oDir) if ( oDir.find("Digi") != -1 ): tDir = "DQMData/Run 1/MuonGEMDigisV/Run summary/GEMDigiTask" d1 = dqm_file.Get(tDir) tlist = d1.GetListOfKeys() else : - print "error" + print("error") exit(-1) for x in tlist : key_list.append(x.GetName()) @@ -66,7 +66,7 @@ def draw_plot( file, tDir,oDir,min,max ) : parser.add_option("--max",dest='range_max',help='Maximum of phi degree',default=15.5) options, args = parser.parse_args() - print options.range_min, options.range_max + print(options.range_min, options.range_max) min = options.range_min max = options.range_max if len(sys.argv) ==1 : @@ -74,12 +74,12 @@ def draw_plot( file, tDir,oDir,min,max ) : exit() # If no argument, default name will be used. if len(args)==0 : - print "Input file name is None." - print "Use default name." + print("Input file name is None.") + print("Use default name.") args.append("DQM_V0001_R000000001__Global__CMSSW_X_Y_Z__RECO.root") if len(args) != 1 : - print "Can not understand input argument" + print("Can not understand input argument") parser.print_help() steps= [] diff --git a/Validation/RecoMuon/test/muonReleaseSummary.py b/Validation/RecoMuon/test/muonReleaseSummary.py index 0adb4139d6037..84aaedcf82531 100644 --- a/Validation/RecoMuon/test/muonReleaseSummary.py +++ b/Validation/RecoMuon/test/muonReleaseSummary.py @@ -46,7 +46,7 @@ def GetLabel(params): label += '-' + params['Version'] if (params['PileUp']!='no'): - label = 'PU' + params['PileUp']+ '_' + label + label = 'PU' + params['PileUp']+ '_' + label return label @@ -95,13 +95,13 @@ def downloadfile(url): output=stream.readlines() if output[0]=='200': print(' + OK!') - return True + return True else: print(' + ERROR! ' + str(output[0])) - print("Skipping " + url) - print("Please check the name of the file in the repository: "+GetGuiRepository(userparams.NewParams)) + print("Skipping " + url) + print("Please check the name of the file in the repository: "+GetGuiRepository(userparams.NewParams)) sys.exit('Exiting...'); - # return False + # return False def GetSamplePath(params, sample): return params['Release']+'/'+GetTag(params)+'/'+sample @@ -175,8 +175,8 @@ def getSampleFiles(params, sample): #os.system('wget --ca-directory $X509_CERT_DIR/ --certificate=$X509_USER_PROXY --private-key=$X509_USER_PROXY '+GetGuiRepository(params)+guiFileName) #os.system('/usr/bin/curl -O -L --capath $X509_CERT_DIR --key $X509_USER_PROXY --cert $X509_USER_PROXY '+ guiFullURL) if (downloadfile(guiFullURL)==True): - print(' + Moving ' + guiFileName + ' to ' + localsample) - shutil.move(guiFileName,localsample) + print(' + Moving ' + guiFileName + ' to ' + localsample) + shutil.move(guiFileName,localsample) elif (params['GetFilesFrom']=='CASTOR'): print(' + Getting new file from castor') diff --git a/Validation/RecoMuon/test/new_muonReleaseSummary.py b/Validation/RecoMuon/test/new_muonReleaseSummary.py index 4bbca2e230fe4..3f86fafd8f61d 100644 --- a/Validation/RecoMuon/test/new_muonReleaseSummary.py +++ b/Validation/RecoMuon/test/new_muonReleaseSummary.py @@ -53,7 +53,7 @@ def GetLabel(params): label += '-' + params['Version'] if (params['PileUp']!='no'): - label = 'PU' + params['PileUp']+ '_' + label + label = 'PU' + params['PileUp']+ '_' + label return label @@ -98,13 +98,13 @@ def downloadfile(url): output=stream.readlines() if output[0]=='200': print(' + OK!') - return True + return True else: print(' + ERROR! ' + str(output[0])) - print("Skipping " + url) - print("Please check the name of the file in the repository: "+GetGuiRepository(new_userparams.NewParams)) + print("Skipping " + url) + print("Please check the name of the file in the repository: "+GetGuiRepository(new_userparams.NewParams)) sys.exit('Exiting...'); - return False + return False def GetSamplePath(params, sample): return params['Release']+'/'+GetTag(params)+'/'+sample+'_'+params['Energy'] diff --git a/Validation/RecoTrack/test/fakeAnalysis/analysis.py b/Validation/RecoTrack/test/fakeAnalysis/analysis.py index 67a4a227cf7bf..eb8e180630e7d 100644 --- a/Validation/RecoTrack/test/fakeAnalysis/analysis.py +++ b/Validation/RecoTrack/test/fakeAnalysis/analysis.py @@ -17,22 +17,22 @@ # Classification of fake tracks: classes = {-1: "UNCLASSIFIED", - 0: "UNMATCHED", - 21: "MERGED DECAY TRACK MATCHES", - 22: "MULTIPLE ALL RECONSTRUCTED MATCHES", - 23: "MULTIPLE PARTIALLY RECONSTRUCTED MATCHES", - 20: "MULTIPLE UNRECONSTRUCTED MATCHES", + 0: "UNMATCHED", + 21: "MERGED DECAY TRACK MATCHES", + 22: "MULTIPLE ALL RECONSTRUCTED MATCHES", + 23: "MULTIPLE PARTIALLY RECONSTRUCTED MATCHES", + 20: "MULTIPLE UNRECONSTRUCTED MATCHES", 11: "RECONSTRUCTED AND DECAYED MATCH", 12: "RECONSTRUCTED MATCH", - 13: "DECAYED MATCH", - 10: "MATCH"} + 13: "DECAYED MATCH", + 10: "MATCH"} # Classification of different types of the end of tracking between a fake and a particle track end_class_names = {0: "Fake and particle tracks differ", 1: "Tracking ended correctly", - 2: "Fake ended before particle", - 3: "Particle ended before fake",#}#, - 4: "Particle ended within two hits in same layer"} + 2: "Fake ended before particle", + 3: "Particle ended before fake",#}#, + 4: "Particle ended within two hits in same layer"} # Detector layer names layer_names_t = ((1, "BPix1"), @@ -40,28 +40,28 @@ (3, "BPix3"), (4, "FPix1"), (5, "FPix2"), - (11, "TIB1"), - (12, "TIB2"), - (13, "TIB3"), - (14, "TIB4"), - (21, "TID1"), - (22, "TID2"), - (23, "TID3"), - (31, "TOB1"), - (32, "TOB2"), - (33, "TOB3"), - (34, "TOB4"), - (35, "TOB5"), - (36, "TOB6"), - (41, "TEC1"), - (42, "TEC2"), - (43, "TEC3"), - (44, "TEC4"), - (45, "TEC5"), - (46, "TEC6"), - (47, "TEC7"), - (48, "TEC8"), - (49, "TEC9")) + (11, "TIB1"), + (12, "TIB2"), + (13, "TIB3"), + (14, "TIB4"), + (21, "TID1"), + (22, "TID2"), + (23, "TID3"), + (31, "TOB1"), + (32, "TOB2"), + (33, "TOB3"), + (34, "TOB4"), + (35, "TOB5"), + (36, "TOB6"), + (41, "TEC1"), + (42, "TEC2"), + (43, "TEC3"), + (44, "TEC4"), + (45, "TEC5"), + (46, "TEC6"), + (47, "TEC7"), + (48, "TEC8"), + (49, "TEC9")) layer_names = OrderedDict(layer_names_t) layer_names_rev_t = (("BPix1", 1), @@ -69,45 +69,45 @@ ("BPix3", 3), ("FPix1", 4), ("FPix2", 5), - ("TIB1", 11), - ("TIB2", 12), - ("TIB3", 13), - ("TIB4", 14), - ("TID1", 21), - ("TID2", 22), - ("TID3", 23), - ("TOB1", 31), - ("TOB2", 32), - ("TOB3", 33), - ("TOB4", 34), - ("TOB5", 35), - ("TOB6", 36), - ("TEC1", 41), - ("TEC2", 42), - ("TEC3", 43), - ("TEC4", 44), - ("TEC5", 45), - ("TEC6", 46), - ("TEC7", 47), - ("TEC8", 48), - ("TEC9", 49)) + ("TIB1", 11), + ("TIB2", 12), + ("TIB3", 13), + ("TIB4", 14), + ("TID1", 21), + ("TID2", 22), + ("TID3", 23), + ("TOB1", 31), + ("TOB2", 32), + ("TOB3", 33), + ("TOB4", 34), + ("TOB5", 35), + ("TOB6", 36), + ("TEC1", 41), + ("TEC2", 42), + ("TEC3", 43), + ("TEC4", 44), + ("TEC5", 45), + ("TEC6", 46), + ("TEC7", 47), + ("TEC8", 48), + ("TEC9", 49)) layer_names_rev = OrderedDict(layer_names_rev_t) # The following is used as a template to store data with respect to detector layers layer_data_tmp_t = ((1,0),(2,0),(3,0),(4,0),(5,0), (11,0),(12,0),(13,0),(14,0), - (21,0),(22,0),(23,0), - (31,0),(32,0),(33,0),(34,0),(35,0),(36,0), - (41,0),(42,0),(43,0),(44,0),(45,0),(46,0),(47,0),(48,0),(49,0)) + (21,0),(22,0),(23,0), + (31,0),(32,0),(33,0),(34,0),(35,0),(36,0), + (41,0),(42,0),(43,0),(44,0),(45,0),(46,0),(47,0),(48,0),(49,0)) layer_data_tmp = OrderedDict(layer_data_tmp_t) # classes for different invalid hit types invalid_types_t = ((0, "valid"), (1, "missing"), (2, "inactive"), - (3, "bad"), - (4, "missing_inner"), - (5, "missing_outer")) + (3, "bad"), + (4, "missing_inner"), + (5, "missing_outer")) invalid_types = OrderedDict(invalid_types_t) # The following is used as a template to store data with respect invalid hit types @@ -121,8 +121,8 @@ def FindFakes(event): '''Returns fake tracks of an event in a list''' fakes = [] for track in event.tracks(): - if track.nMatchedTrackingParticles() == 0: - fakes.append(track) + if track.nMatchedTrackingParticles() == 0: + fakes.append(track) print("Event: " + str(event.entry()+1) + " Number of fake tracks: " + str(len(fakes))) return fakes @@ -130,8 +130,8 @@ def FindTrues(event): '''Returns true tracks of an event in a list''' trues = [] for track in event.tracks(): - if track.nMatchedTrackingParticles() >= 0: - trues.append(track) + if track.nMatchedTrackingParticles() >= 0: + trues.append(track) print("Event: " + str(event.entry()+1) + " Number of true tracks: " + str(len(trues))) return trues @@ -139,7 +139,7 @@ def Distance(x1,x2): '''Returns Euclidean distance between two iterable vectors.''' d = 0 for i in range(len(x1)): - d += abs(x1[i]-x2[i])**2 + d += abs(x1[i]-x2[i])**2 d = sqrt(d) return d @@ -148,8 +148,8 @@ def FindUntrackedParticles(event): untracked = [] #print len(event.trackingParticles()) for particle in event.trackingParticles(): - if (particle.isValid() and particle.nMatchedTracks() == 0 and MTFEfficiencySelector(particle)): - untracked.append(particle) + if (particle.isValid() and particle.nMatchedTracks() == 0 and MTFEfficiencySelector(particle)): + untracked.append(particle) print("Number of untracked particles: " + str(len(untracked))) return untracked @@ -163,7 +163,7 @@ def MTFEfficiencySelector(particle): if(particle.pt() > 0.9 and abs(particle.eta()) < 2.5 and (particle.parentVertex().x()**2 + particle.parentVertex().y()**2 < 3.5**2) and abs(particle.parentVertex().z()) < 30 and particle.q() != 0 and particle.event() == 0): - return True + return True return False def EfficiencyRate(ntuple, N): @@ -176,12 +176,12 @@ def EfficiencyRate(ntuple, N): untracked = 0 i = 0 for event in ntuple: - if (i >= N): break - for particle in event.trackingParticles(): - if (MTFEfficiencySelector(particle)): - if(particle.nMatchedTracks() == 0): untracked += 1 - else: tracked += 1 - i += 1 + if (i >= N): break + for particle in event.trackingParticles(): + if (MTFEfficiencySelector(particle)): + if(particle.nMatchedTracks() == 0): untracked += 1 + else: tracked += 1 + i += 1 print("In " + str(N) + " events there are:") print("Tracked particles: " + str(tracked)) print("Untracked particles: " + str(untracked)) @@ -197,13 +197,13 @@ def SharedHitFrac(track, particle, frac = 0): shared_hits = 0 ntrack_hits = 0 for hit in track.hits(): - if hit.isValidHit() and hit.index() in particle_hits: + if hit.isValidHit() and hit.index() in particle_hits: shared_hits += 1 - ntrack_hits += 1 + ntrack_hits += 1 if frac: - return shared_hits, ntrack_hits, len(particle_hits) + return shared_hits, ntrack_hits, len(particle_hits) else: - return 1.0*shared_hits/ntrack_hits + return 1.0*shared_hits/ntrack_hits def SharedHitsFromBeginning(track, particle, tolerance=0): ''' @@ -216,13 +216,13 @@ def SharedHitsFromBeginning(track, particle, tolerance=0): Output: [3, 3, 4, 4, 4] Means: first 3 particle hits are shared with track, then 1 unshared particle hit, - then 1 more shared particle hit, - then 2 unshared particle hits - until tolerance < 0 (or particle track ended) + then 1 more shared particle hit, + then 2 unshared particle hits + until tolerance < 0 (or particle track ended) NOTE: Often this is called with a TrackingParticle as parameter "track" and a Track as the parameter "particle", which is because it was later needed to analyse the hits which are consecutive with respect to the Track. - Sorry about inconvenience. + Sorry about inconvenience. ''' particle_hits = [hit.index() for hit in particle.hits() if hit.isValidHit()] track_hits = [hit.index() for hit in track.hits() if hit.isValidHit()] @@ -232,15 +232,15 @@ def SharedHitsFromBeginning(track, particle, tolerance=0): i = 0 result = [] while tolerance >= 0 and i < len(particle_hits) and count < len(track_hits): - if particle_hits[i] in track_hits: - count += 1 - i += 1 - else: - tolerance -= 1 - result.append(count) - i += 1 + if particle_hits[i] in track_hits: + count += 1 + i += 1 + else: + tolerance -= 1 + result.append(count) + i += 1 if tolerance >= 0: - result.append(count) + result.append(count) return result def SharedHits(track, particle): @@ -250,22 +250,22 @@ def SharedHits(track, particle): track_hits = [hit for hit in track.hits() if hit.isValidHit()] for hit in track_hits: - if hit.index() in particle_hit_indexes: - res_hits.append(hit) - - return res_hits + if hit.index() in particle_hit_indexes: + res_hits.append(hit) + + return res_hits def FindAssociatedParticles(track): '''Returns TrackingParticles in a list that have any shared hits with the given Track''' particle_inds = [] particles = [] for hit in track.hits(): - if hit.isValidHit() and hit.nSimHits() >= 0: - for simHit in hit.simHits(): - particle = simHit.trackingParticle() - if particle.index() not in particle_inds: - particle_inds.append(particle.index()) - particles.append(particle) + if hit.isValidHit() and hit.nSimHits() >= 0: + for simHit in hit.simHits(): + particle = simHit.trackingParticle() + if particle.index() not in particle_inds: + particle_inds.append(particle.index()) + particles.append(particle) return particles def MatchedParticles(fake, real_criterion = ["consecutive", 3]): @@ -285,29 +285,29 @@ def MatchedParticles(fake, real_criterion = ["consecutive", 3]): particles = FindAssociatedParticles(fake) matches = [] for particle in particles: - if CRITERION == "consecutive": - tolerance_mask = SharedHitsFromBeginning(particle, fake, particle.nValid()) - diff = [abs(tolerance_mask[i+1] - tolerance_mask[i]) for i in range(len(tolerance_mask)-1)] - if tolerance_mask[0] >= LIMIT or (diff and max(diff) >= LIMIT): - matches.append(particle) - if CRITERION == "fraction": - if SharedHitFrac(fake, particle, 0) >= LIMIT: - matches.append(particle) - if CRITERION == "NLay": - hits = SharedHits(fake, particle) - nPix = 0 - nStr = 0 - tracked_layers = [] - for hit in hits: - layer = hit.layerStr() - if layer not in tracked_layers: - tracked_layers.append(layer) - if "Pix" in layer: nPix += 1 - else: nStr += 1 - if 2*nPix + nStr >= LIMIT: # LIMIT default should be 6 - matches.append(particle) + if CRITERION == "consecutive": + tolerance_mask = SharedHitsFromBeginning(particle, fake, particle.nValid()) + diff = [abs(tolerance_mask[i+1] - tolerance_mask[i]) for i in range(len(tolerance_mask)-1)] + if tolerance_mask[0] >= LIMIT or (diff and max(diff) >= LIMIT): + matches.append(particle) + if CRITERION == "fraction": + if SharedHitFrac(fake, particle, 0) >= LIMIT: + matches.append(particle) + if CRITERION == "NLay": + hits = SharedHits(fake, particle) + nPix = 0 + nStr = 0 + tracked_layers = [] + for hit in hits: + layer = hit.layerStr() + if layer not in tracked_layers: + tracked_layers.append(layer) + if "Pix" in layer: nPix += 1 + else: nStr += 1 + if 2*nPix + nStr >= LIMIT: # LIMIT default should be 6 + matches.append(particle) return matches - + def IsUnmatched(fake, unmatch_criterion = ["nShared", 2]): ''' Returns True if the the particle is unmatched to any particle with respect @@ -318,10 +318,10 @@ def IsUnmatched(fake, unmatch_criterion = ["nShared", 2]): LIMIT = unmatch_criterion[1] for particle in FindAssociatedParticles(fake): - if CRITERION == "nShared": - shared, track_hits, particle_hits = SharedHitFrac(fake, particle, 1) - if shared > LIMIT: - return False + if CRITERION == "nShared": + shared, track_hits, particle_hits = SharedHitFrac(fake, particle, 1) + if shared > LIMIT: + return False return True def FindEndOfTracking(fake, particle, end_criterion = ["nMissing", 2], real_criterion = ["consecutive", 3], only_valid = False): @@ -330,7 +330,7 @@ def FindEndOfTracking(fake, particle, end_criterion = ["nMissing", 2], real_crit end_criterion, which is 2 consecutive missing layers in particle hits by default. Returns: last: the last shared hit between the fake and the particle, which is the first hit in particle trajectory after which tracks separate by the end criterion (or end) fake_end: the fake track hit following the last shared hit - particle_end: the particle hit following the last shared hit + particle_end: the particle hit following the last shared hit fake_end and particle_end might be the same as the last shared hit, if the fake track or the particle track (or both) end ''' CRITERION = end_criterion[0] @@ -339,80 +339,80 @@ def FindEndOfTracking(fake, particle, end_criterion = ["nMissing", 2], real_crit REAL_LIMIT = real_criterion[1] if CRITERION == "nMissing" and REAL_CRITERION == "consecutive": - if only_valid: - particle_hits = [hit for hit in particle.hits() if hit.isValidHit()] - particle_hit_indexes = [hit.index() for hit in particle.hits() if hit.isValidHit()] - track_hits = [hit for hit in fake.hits() if hit.isValidHit()] - track_hit_indexes = [hit.index() for hit in fake.hits() if hit.isValidHit()] - else: - particle_hits = [hit for hit in particle.hits()] - particle_hit_indexes = [hit.index() for hit in particle.hits()] - track_hits = [hit for hit in fake.hits()] - track_hit_indexes = [hit.index() for hit in fake.hits()] - - #print particle_hit_indexes - #print track_hit_indexes - tolerance = LIMIT - i = 0 - start_tolerance = 0 - last = particle_hits[0] - particle_end = particle_hits[0] - fake_end = particle_hits[0] - # FIND THE END OF THE MATCHED 3 POINTS - while i < len(track_hits): - #print track_hits[i].index() - if track_hit_indexes[i] in particle_hit_indexes: - start_tolerance += 1 - #print start_tolerance - if start_tolerance >= REAL_LIMIT: - #print "STARTED" - tolerance = LIMIT - i = particle_hit_indexes.index(track_hit_indexes[i]) - last = particle_hits[i] - particle_end = particle_hits[min([i+1, len(particle_hits)-1])] - fake_end = track_hits[min(track_hit_indexes.index(particle_hit_indexes[i])+1, len(track_hits)-1)] - #fake_end = [hit for hit in track_hits if hit.index() == particle_hits[i].index()][0] - break - i += 1 - else: - start_tolerance = 0 - i += 1 + if only_valid: + particle_hits = [hit for hit in particle.hits() if hit.isValidHit()] + particle_hit_indexes = [hit.index() for hit in particle.hits() if hit.isValidHit()] + track_hits = [hit for hit in fake.hits() if hit.isValidHit()] + track_hit_indexes = [hit.index() for hit in fake.hits() if hit.isValidHit()] + else: + particle_hits = [hit for hit in particle.hits()] + particle_hit_indexes = [hit.index() for hit in particle.hits()] + track_hits = [hit for hit in fake.hits()] + track_hit_indexes = [hit.index() for hit in fake.hits()] + + #print particle_hit_indexes + #print track_hit_indexes + tolerance = LIMIT + i = 0 + start_tolerance = 0 + last = particle_hits[0] + particle_end = particle_hits[0] + fake_end = particle_hits[0] + # FIND THE END OF THE MATCHED 3 POINTS + while i < len(track_hits): + #print track_hits[i].index() + if track_hit_indexes[i] in particle_hit_indexes: + start_tolerance += 1 + #print start_tolerance + if start_tolerance >= REAL_LIMIT: + #print "STARTED" + tolerance = LIMIT + i = particle_hit_indexes.index(track_hit_indexes[i]) + last = particle_hits[i] + particle_end = particle_hits[min([i+1, len(particle_hits)-1])] + fake_end = track_hits[min(track_hit_indexes.index(particle_hit_indexes[i])+1, len(track_hits)-1)] + #fake_end = [hit for hit in track_hits if hit.index() == particle_hits[i].index()][0] + break + i += 1 + else: + start_tolerance = 0 + i += 1 # FIND THE END OF TRACKING AFTER MATCHED POINTS - while tolerance >= 0 and i < len(particle_hits): - #print particle_hits[i].index() - #print i - if particle_hit_indexes[i] in track_hit_indexes: - tolerance = LIMIT - last = particle_hits[i] - particle_end = particle_hits[min([i+1, len(particle_hits)-1])] - fake_end = track_hits[min(track_hit_indexes.index(particle_hit_indexes[i])+1, len(track_hits)-1)] - #fake_end = [hit for hit in track_hits if hit.index() == particle_hits[i].index()][0] - elif not (particle_hits[i-1].layerStr() in particle_hits[i].layerStr() or particle_hits[i].layerStr() in particle_hits[i-1].layerStr()): # only missing layers are considered # double condition for invalid hits - tolerance -= 1 - i += 1 - end_class = 0 - if last.index() == fake_end.index() and last.index() == particle_end.index(): - end_class = 1 - elif last.index() == fake_end.index(): end_class = 2 - elif last.index() == particle_end.index(): end_class = 3 - elif last.layerStr() == particle_hits[-1].layerStr() and (len(particle_hits)-1 - i < 4): end_class = 3 #4 #3 # particle_end.layerStr() - ''' - if tolerance >= LIMIT: # If the end of the particle was reached, last and fail are the same - last = particle_end - fake_end = particle_end - end_class = 1 - - print [[hit.index(), hit.layerStr()] for hit in track_hits] - print [[hit.index(), hit.layerStr()] for hit in particle_hits] - print i - print last.index() - print fake_end.index() - print particle_end.index() - print end_class - print "*****" - input() - ''' - return last, fake_end, particle_end, end_class + while tolerance >= 0 and i < len(particle_hits): + #print particle_hits[i].index() + #print i + if particle_hit_indexes[i] in track_hit_indexes: + tolerance = LIMIT + last = particle_hits[i] + particle_end = particle_hits[min([i+1, len(particle_hits)-1])] + fake_end = track_hits[min(track_hit_indexes.index(particle_hit_indexes[i])+1, len(track_hits)-1)] + #fake_end = [hit for hit in track_hits if hit.index() == particle_hits[i].index()][0] + elif not (particle_hits[i-1].layerStr() in particle_hits[i].layerStr() or particle_hits[i].layerStr() in particle_hits[i-1].layerStr()): # only missing layers are considered # double condition for invalid hits + tolerance -= 1 + i += 1 + end_class = 0 + if last.index() == fake_end.index() and last.index() == particle_end.index(): + end_class = 1 + elif last.index() == fake_end.index(): end_class = 2 + elif last.index() == particle_end.index(): end_class = 3 + elif last.layerStr() == particle_hits[-1].layerStr() and (len(particle_hits)-1 - i < 4): end_class = 3 #4 #3 # particle_end.layerStr() + ''' + if tolerance >= LIMIT: # If the end of the particle was reached, last and fail are the same + last = particle_end + fake_end = particle_end + end_class = 1 + + print [[hit.index(), hit.layerStr()] for hit in track_hits] + print [[hit.index(), hit.layerStr()] for hit in particle_hits] + print i + print last.index() + print fake_end.index() + print particle_end.index() + print end_class + print "*****" + input() + ''' + return last, fake_end, particle_end, end_class def MatchPixelHits(fake, particle, real_criterion = ["consecutive", 3]): ''' @@ -423,104 +423,104 @@ def MatchPixelHits(fake, particle, real_criterion = ["consecutive", 3]): LIMIT = real_criterion[1] if CRITERION == "consecutive": - particle_hits = [hit for hit in particle.hits() if hit.isValidHit()] - track_hits = [hit for hit in fake.hits() if hit.isValidHit()] - particle_hit_indexes = [hit.index() for hit in particle.hits() if hit.isValidHit()] - #print particle_hits - #print track_hits - i = 0 - start_tolerance = 0 - hit_candidates = [] - start_flag = False - - layer_strs = [] - nPix = 0 - - while i <= len(track_hits)-1: - if track_hits[i].index() in particle_hit_indexes: - start_tolerance += 1 - hit_candidates.append(track_hits[i]) - if start_tolerance >= LIMIT: - start_flag = True - i += 1 - elif start_flag: - # End the iteration - break - else: - hit_candidates = [] - start_tolerance = 0 - i += 1 + particle_hits = [hit for hit in particle.hits() if hit.isValidHit()] + track_hits = [hit for hit in fake.hits() if hit.isValidHit()] + particle_hit_indexes = [hit.index() for hit in particle.hits() if hit.isValidHit()] + #print particle_hits + #print track_hits + i = 0 + start_tolerance = 0 + hit_candidates = [] + start_flag = False + + layer_strs = [] + nPix = 0 + + while i <= len(track_hits)-1: + if track_hits[i].index() in particle_hit_indexes: + start_tolerance += 1 + hit_candidates.append(track_hits[i]) + if start_tolerance >= LIMIT: + start_flag = True + i += 1 + elif start_flag: + # End the iteration + break + else: + hit_candidates = [] + start_tolerance = 0 + i += 1 # Analyse the results, end the iteration - for hit in hit_candidates: - if "Pix" in hit.layerStr(): - if hit.layerStr() not in layer_strs: - layer_strs.append(hit.layerStr()) - nPix += 1 - else: - break - nPixLayers = len(layer_strs) - ''' Uncomment to analyse fakes having >= 4 pixelhits - if nPixLayers >= 4: #print [hit.layerStr() for hit in hit_candidates] - if 'BPix1' in layer_strs and 'BPix2' in layer_strs: - if 'BPix3' in layer_strs and 'FPix1' in layer_strs: - print "B3-F1" - elif 'FPix1' in layer_strs and 'FPix2' in layer_strs: - print "F1-F2" - else: - print "B1-B2 Other" + for hit in hit_candidates: + if "Pix" in hit.layerStr(): + if hit.layerStr() not in layer_strs: + layer_strs.append(hit.layerStr()) + nPix += 1 + else: + break + nPixLayers = len(layer_strs) + ''' Uncomment to analyse fakes having >= 4 pixelhits + if nPixLayers >= 4: #print [hit.layerStr() for hit in hit_candidates] + if 'BPix1' in layer_strs and 'BPix2' in layer_strs: + if 'BPix3' in layer_strs and 'FPix1' in layer_strs: + print "B3-F1" + elif 'FPix1' in layer_strs and 'FPix2' in layer_strs: + print "F1-F2" + else: + print "B1-B2 Other" else: - print "Other" - ''' - - if start_tolerance == 0: # The end of the particle was reached - print("Match is not a real match :\\") - if len(hit_candidates)<3 or not start_flag: - print("No hit candidates from a match") - print([hit.index() for hit in fake.hits() if hit.isValidHit()]) - print(particle_hit_indexes) - print([hit.index() for hit in hit_candidates]) - print(start_tolerance) - print(start_flag) - return -1, -1 - return nPix, nPixLayers + print "Other" + ''' + + if start_tolerance == 0: # The end of the particle was reached + print("Match is not a real match :\\") + if len(hit_candidates)<3 or not start_flag: + print("No hit candidates from a match") + print([hit.index() for hit in fake.hits() if hit.isValidHit()]) + print(particle_hit_indexes) + print([hit.index() for hit in hit_candidates]) + print(start_tolerance) + print(start_flag) + return -1, -1 + return nPix, nPixLayers if CRITERION == "NLay": - particle_hits = [hit for hit in particle.hits() if hit.isValidHit()] - track_hits = [hit for hit in fake.hits() if hit.isValidHit()] - particle_hit_indexes = [hit.index() for hit in particle.hits() if hit.isValidHit()] - #print particle_hits - #print track_hits - i = 0 - hit_candidates = [] - start_flag = False - - layer_strs = [] - nPix = 0 - - while i <= len(track_hits)-1: - if track_hits[i].index() in particle_hit_indexes: - hit_candidates.append(track_hits[i]) - if "Pix" in hit.layerStr(): - start_flag = True - i += 1 - elif start_flag: - # End the iteration - break - else: - i += 1 + particle_hits = [hit for hit in particle.hits() if hit.isValidHit()] + track_hits = [hit for hit in fake.hits() if hit.isValidHit()] + particle_hit_indexes = [hit.index() for hit in particle.hits() if hit.isValidHit()] + #print particle_hits + #print track_hits + i = 0 + hit_candidates = [] + start_flag = False + + layer_strs = [] + nPix = 0 + + while i <= len(track_hits)-1: + if track_hits[i].index() in particle_hit_indexes: + hit_candidates.append(track_hits[i]) + if "Pix" in hit.layerStr(): + start_flag = True + i += 1 + elif start_flag: + # End the iteration + break + else: + i += 1 # Analyse the results, end the iteration - for hit in hit_candidates: - if "Pix" in hit.layerStr(): - if hit.layerStr() not in layer_strs: - layer_strs.append(hit.layerStr()) - nPix += 1 - else: - break - nPixLayers = len(layer_strs) - - return nPix, nPixLayers + for hit in hit_candidates: + if "Pix" in hit.layerStr(): + if hit.layerStr() not in layer_strs: + layer_strs.append(hit.layerStr()) + nPix += 1 + else: + break + nPixLayers = len(layer_strs) + + return nPix, nPixLayers return -1, -1 # Something failed, unknown match criterion @@ -533,8 +533,8 @@ def MaxSharedHits(fake, fraction = False): shared, nTrack, nParticle = SharedHitFrac(fake, particle, 1) frac = 1.0*shared/nParticle if shared > max_shared: - max_shared = shared - max_frac = frac + max_shared = shared + max_frac = frac if fraction: return max_shared, max_frac return max_shared @@ -545,74 +545,74 @@ def StopReason(track): ''' Converts track stop reason index to string ''' reason = track.stopReason() if reason == 0: - return "UNINITIALIZED" + return "UNINITIALIZED" if reason == 1: - return "MAX_HITS" + return "MAX_HITS" if reason == 2: - return "MAX_LOST_HITS" + return "MAX_LOST_HITS" if reason == 3: - return "MAX_CONSECUTIVE_LOST_HITS" + return "MAX_CONSECUTIVE_LOST_HITS" if reason == 4: - return "LOST_HIT_FRACTION" + return "LOST_HIT_FRACTION" if reason == 5: - return "MIN_PT" + return "MIN_PT" if reason == 6: - return "CHARGE_SIGNIFICANCE" + return "CHARGE_SIGNIFICANCE" if reason == 7: - return "LOOPER" + return "LOOPER" if reason == 8: - return "MAX_CCC_LOST_HITS" + return "MAX_CCC_LOST_HITS" if reason == 9: - return "NO_SEGMENTS_FOR_VALID_LAYERS" + return "NO_SEGMENTS_FOR_VALID_LAYERS" if reason == 10: - return "SEED_EXTENSION" + return "SEED_EXTENSION" if reason == 255: - return "NOT_STOPPED" + return "NOT_STOPPED" else: - return "UNDEFINED STOPPING REASON" + return "UNDEFINED STOPPING REASON" def PrintTrackInfo(track, fake = None, frac = 0, fake_info = None): ''' Prints info on the track. Called from PlotFakes method in graphics.py. ''' if isinstance(track, Track): - if track.nMatchedTrackingParticles() == 0: # FAKE - print(str(track.index()) + ": FAKE \nSTOP REASON: " + StopReason(track)) - print("Has " + str(track.nValid()) + " valid hits") - if fake_info: - fake_info.Print() - else: # RECONSTRUCTED - reco_str = str(track.index()) + ": RECOVERED " - for info in track.matchedTrackingParticleInfos(): - reco_str += str(info.trackingParticle().index()) + " " + str(info.shareFrac()) + "\nSTOP REASON: " + StopReason(track) # sharefrac()[0] old version - print(reco_str) + if track.nMatchedTrackingParticles() == 0: # FAKE + print(str(track.index()) + ": FAKE \nSTOP REASON: " + StopReason(track)) + print("Has " + str(track.nValid()) + " valid hits") + if fake_info: + fake_info.Print() + else: # RECONSTRUCTED + reco_str = str(track.index()) + ": RECOVERED " + for info in track.matchedTrackingParticleInfos(): + reco_str += str(info.trackingParticle().index()) + " " + str(info.shareFrac()) + "\nSTOP REASON: " + StopReason(track) # sharefrac()[0] old version + print(reco_str) else: # REAL - print(str(track.index()) + ": REAL") - if track.nMatchedTracks() == 0: print("NOT RECOVERED") - elif track.nMatchedTracks() == 1: print("RECOVERED") - else: print("RECOVERED " + str(track.nMatchedTracks()) + " TIMES") - decaycount = 0 - for decay in track.decayVertices(): decaycount += 1 - if decaycount: print("DECAYED " + str(decaycount) + " TIMES") + print(str(track.index()) + ": REAL") + if track.nMatchedTracks() == 0: print("NOT RECOVERED") + elif track.nMatchedTracks() == 1: print("RECOVERED") + else: print("RECOVERED " + str(track.nMatchedTracks()) + " TIMES") + decaycount = 0 + for decay in track.decayVertices(): decaycount += 1 + if decaycount: print("DECAYED " + str(decaycount) + " TIMES") if fake: # tell the shared hit fraction compared to fake - if frac: - num, div, npar = SharedHitFrac(fake, track, 1) - print("Fake share fraction: " + str(num) + " / " + str(div) + ", track has " + str(npar) + " hits") - else: - dec = SharedHitFrac(fake, track, 0) - print("Fake shares " + str(dec) + " fraction of hits with track") - print("Shared hits from beginning: " + str(SharedHitsFromBeginning(track, fake, 10))) + if frac: + num, div, npar = SharedHitFrac(fake, track, 1) + print("Fake share fraction: " + str(num) + " / " + str(div) + ", track has " + str(npar) + " hits") + else: + dec = SharedHitFrac(fake, track, 0) + print("Fake shares " + str(dec) + " fraction of hits with track") + print("Shared hits from beginning: " + str(SharedHitsFromBeginning(track, fake, 10))) if isinstance(track, TrackingParticle): - print("Parameters:") - print("px : " + str(track.px()) + " py : " + str(track.py()) + " pz : " + str(track.pz())) - print("pt : " + str(track.pca_pt()) + " eta : " + str(track.pca_eta()) + " phi : " + str(track.pca_phi())) - print("dxy : " + str(track.pca_dxy()) + " dz : " + str(track.pca_dz()) + " q : " + str(track.q()) + "\n") + print("Parameters:") + print("px : " + str(track.px()) + " py : " + str(track.py()) + " pz : " + str(track.pz())) + print("pt : " + str(track.pca_pt()) + " eta : " + str(track.pca_eta()) + " phi : " + str(track.pca_phi())) + print("dxy : " + str(track.pca_dxy()) + " dz : " + str(track.pca_dz()) + " q : " + str(track.q()) + "\n") else: - print("Parameters:") - print("px : " + str(track.px()) + " py : " + str(track.py()) + " pz : " + str(track.pz())) - print("pt : " + str(track.pt()) + " eta : " + str(track.eta()) + " phi : " + str(track.phi())) - print("dxy : " + str(track.dxy()) + " dz : " + str(track.dz()) + " q : " + str(track.q()) + "\n") + print("Parameters:") + print("px : " + str(track.px()) + " py : " + str(track.py()) + " pz : " + str(track.pz())) + print("pt : " + str(track.pt()) + " eta : " + str(track.eta()) + " phi : " + str(track.phi())) + print("dxy : " + str(track.dxy()) + " dz : " + str(track.dz()) + " q : " + str(track.q()) + "\n") ##### CLASSIFICATION ##### @@ -624,198 +624,198 @@ class FakeInfo(object): The results can then be obtained from object attributes. ''' def __init__(self, fake, real_criterion = ["consecutive", 3], end_criterion = ["nMissing", 1]): - self.fake = fake + self.fake = fake self.index = fake.index() - self.nHits = fake.nValid() - self.nMatches = 0 - self.matches = [] - self.nReconstructed = 0 # Number of reconstructed matched particles - self.nDecays = 0 # Number of decayed matched particles + self.nHits = fake.nValid() + self.nMatches = 0 + self.matches = [] + self.nReconstructed = 0 # Number of reconstructed matched particles + self.nDecays = 0 # Number of decayed matched particles - start = next(iter(fake.hits())) - self.start_loc = [start.x(), start.y(), start.z()] + start = next(iter(fake.hits())) + self.start_loc = [start.x(), start.y(), start.z()] - self.stop_reason = fake.stopReason() + self.stop_reason = fake.stopReason() # Classify the fake - self.FindMatches(fake, real_criterion, end_criterion) - self.fake_class, self.fake_class_str = self.Classify() + self.FindMatches(fake, real_criterion, end_criterion) + self.fake_class, self.fake_class_str = self.Classify() def FindMatches(self, fake, real_criterion, end_criterion): - ''' Finds matches for the fake track. ''' - matched_particles = MatchedParticles(fake, real_criterion) - self.nMatches = len(matched_particles) + ''' Finds matches for the fake track. ''' + matched_particles = MatchedParticles(fake, real_criterion) + self.nMatches = len(matched_particles) self.nIncludedDecayParticles = 0 - self.decayLinks = [] - - if matched_particles: - for particle in matched_particles: - self.matches.append(MatchInfo(particle, fake, real_criterion, end_criterion)) - for match in self.matches: - if match.nReconstructed > 0: - self.nReconstructed += 1 - if match.nDecays > 0: - self.nDecays += 1 - if match.nDaughters > 0: - for another_match in self.matches: - if another_match.parentVtxIndex in match.decayVtxIndexes: - self.nIncludedDecayParticles += 1 - self.decayLinks.append([match.index, another_match.index]) - + self.decayLinks = [] + + if matched_particles: + for particle in matched_particles: + self.matches.append(MatchInfo(particle, fake, real_criterion, end_criterion)) + for match in self.matches: + if match.nReconstructed > 0: + self.nReconstructed += 1 + if match.nDecays > 0: + self.nDecays += 1 + if match.nDaughters > 0: + for another_match in self.matches: + if another_match.parentVtxIndex in match.decayVtxIndexes: + self.nIncludedDecayParticles += 1 + self.decayLinks.append([match.index, another_match.index]) + # The following 3 lines: define how many hits does an unmatched fake have with any particles at maximum (-1 for having matches) - self.unmatched_max_shared = -1 - else: - self.unmatched_max_shared = MaxSharedHits(fake) - self.max_shared, self.max_frac = MaxSharedHits(fake, True) + self.unmatched_max_shared = -1 + else: + self.unmatched_max_shared = MaxSharedHits(fake) + self.max_shared, self.max_frac = MaxSharedHits(fake, True) - if not self.nMatches and not IsUnmatched(fake): - self.nMatches = -1 # UNCLASSIFIED + if not self.nMatches and not IsUnmatched(fake): + self.nMatches = -1 # UNCLASSIFIED def Classify(self): ''' Classify the fake after analysis ''' - if self.nMatches == -1: - return -1, "UNCLASSIFIED" - if self.nMatches == 0: - return 0, "UNMATCHED" - if self.nMatches >= 2: - if self.decayLinks: - return 21, "MERGED DECAY TRACK MATCHES" - elif self.nReconstructed >= self.nMatches: - return 22, "MULTIPLE ALL RECONSTRUCTED MATCHES" - elif self.nReconstructed > 0: - return 23, "MULTIPLE PARTIALLY RECONSTRUCTED MATCHES" - else: - return 20, "MULTIPLE UNRECONSTRUCTED MATCHES" - if self.nMatches == 1: - if self.nReconstructed > 0 and self.nDecays > 0: - return 11, "RECONSTRUCTED AND DECAYED MATCH" - if self.nReconstructed > 0: - return 12, "RECONSTRUCTED MATCH" - if self.nDecays > 0: - return 13, "DECAYED MATCH" - else: - return 10, "MATCH" + if self.nMatches == -1: + return -1, "UNCLASSIFIED" + if self.nMatches == 0: + return 0, "UNMATCHED" + if self.nMatches >= 2: + if self.decayLinks: + return 21, "MERGED DECAY TRACK MATCHES" + elif self.nReconstructed >= self.nMatches: + return 22, "MULTIPLE ALL RECONSTRUCTED MATCHES" + elif self.nReconstructed > 0: + return 23, "MULTIPLE PARTIALLY RECONSTRUCTED MATCHES" + else: + return 20, "MULTIPLE UNRECONSTRUCTED MATCHES" + if self.nMatches == 1: + if self.nReconstructed > 0 and self.nDecays > 0: + return 11, "RECONSTRUCTED AND DECAYED MATCH" + if self.nReconstructed > 0: + return 12, "RECONSTRUCTED MATCH" + if self.nDecays > 0: + return 13, "DECAYED MATCH" + else: + return 10, "MATCH" def Print(self): - ''' Prints fake track classification info with matched particle infos. ''' + ''' Prints fake track classification info with matched particle infos. ''' print("CLASS: " + str(self.fake_class) + " WITH " + str(self.nMatches) + " MATCHES") - print("Has " + str(self.nIncludedDecayParticles) + " included decay particles, with links: " + str(self.decayLinks)) - for match in self.matches: match.Print() + print("Has " + str(self.nIncludedDecayParticles) + " included decay particles, with links: " + str(self.decayLinks)) + for match in self.matches: match.Print() class MatchInfo(object): ''' A storage and analysis class for TrackingParticles matched to a fake track. ''' def __init__(self, match, fake, real_criterion = ["consecutive", 3], end_criterion = ["nMissing", 2]): - ''' match = the matched TrackingParticle ''' - self.index = match.index() - self.particle = match + ''' match = the matched TrackingParticle ''' + self.index = match.index() + self.particle = match # Find out the daughter particles - self.decayVertices = [[vtx.x(), vtx.y(), vtx.z()] for vtx in match.decayVertices()] - self.nDecays = len(self.decayVertices) - self.decayVtxIndexes = [vtx.index() for vtx in match.decayVertices()] + self.decayVertices = [[vtx.x(), vtx.y(), vtx.z()] for vtx in match.decayVertices()] + self.nDecays = len(self.decayVertices) + self.decayVtxIndexes = [vtx.index() for vtx in match.decayVertices()] - self.shared_hits, un, needed = SharedHitFrac(fake, match, 1) + self.shared_hits, un, needed = SharedHitFrac(fake, match, 1) - self.daughterIndexes = [] - for vtx in match.decayVertices(): - for particle in vtx.daughterTrackingParticles(): - self.daughterIndexes.append(particle.index()) - self.nDaughters = len(self.daughterIndexes) - vtx = match.parentVertex() - self.parentVtx = [vtx.x(), vtx.y(), vtx.z()] - self.parentVtxIndex = vtx.index() + self.daughterIndexes = [] + for vtx in match.decayVertices(): + for particle in vtx.daughterTrackingParticles(): + self.daughterIndexes.append(particle.index()) + self.nDaughters = len(self.daughterIndexes) + vtx = match.parentVertex() + self.parentVtx = [vtx.x(), vtx.y(), vtx.z()] + self.parentVtxIndex = vtx.index() self.nReconstructed = match.nMatchedTracks() # more reconstruction analysis here # Check how many pixelhits or pixellayers in match - self.nPix, self.nPixLayers = MatchPixelHits(fake, match, real_criterion) - - # Check where tracking ended - last, fake_end, particle_end, self.end_class = FindEndOfTracking(fake, match, end_criterion) - if last.isValidHit(): self.last_loc = [last.x(), last.y(), last.z()] - else: self.last_loc = [0,0,0] - if fake_end.isValidHit(): self.fake_end_loc = [fake_end.x(), fake_end.y(), fake_end.z()] - else: self.fake_end_loc = [0,0,0] - if particle_end.isValidHit(): self.particle_end_loc = [particle_end.x(), particle_end.y(), particle_end.z()] + self.nPix, self.nPixLayers = MatchPixelHits(fake, match, real_criterion) + + # Check where tracking ended + last, fake_end, particle_end, self.end_class = FindEndOfTracking(fake, match, end_criterion) + if last.isValidHit(): self.last_loc = [last.x(), last.y(), last.z()] + else: self.last_loc = [0,0,0] + if fake_end.isValidHit(): self.fake_end_loc = [fake_end.x(), fake_end.y(), fake_end.z()] + else: self.fake_end_loc = [0,0,0] + if particle_end.isValidHit(): self.particle_end_loc = [particle_end.x(), particle_end.y(), particle_end.z()] else: self.particle_end_loc = [0,0,0] - self.last_detId = last.detId() - self.fake_end_detId = fake_end.detId() - self.particle_end_detId = particle_end.detId() + self.last_detId = last.detId() + self.fake_end_detId = fake_end.detId() + self.particle_end_detId = particle_end.detId() self.particle_pdgId = match.pdgId() - self.particle_pt = match.pt() - - if isinstance(last, GluedHit): - self.last_str = last.monoHit().layerStr() - else: - self.last_str = last.layerStr() - if isinstance(fake_end, GluedHit): - self.fake_end_str = fake_end.monoHit().layerStr() - else: - self.fake_end_str = fake_end.layerStr() - if isinstance(particle_end, GluedHit): - self.particle_end_str = particle_end.monoHit().layerStr() - else: - self.particle_end_str = particle_end.layerStr() + self.particle_pt = match.pt() + + if isinstance(last, GluedHit): + self.last_str = last.monoHit().layerStr() + else: + self.last_str = last.layerStr() + if isinstance(fake_end, GluedHit): + self.fake_end_str = fake_end.monoHit().layerStr() + else: + self.fake_end_str = fake_end.layerStr() + if isinstance(particle_end, GluedHit): + self.particle_end_str = particle_end.monoHit().layerStr() + else: + self.particle_end_str = particle_end.layerStr() def Print(self): - ''' Prints match info. ''' + ''' Prints match info. ''' print("Match " + str(self.index) + ": nReconstructed " + str(self.nReconstructed) +\ - ", daughters: " + str(self.daughterIndexes) +\ - ", tracking failed in " + self.last_str + ", to " + self.particle_end_str + ", wrong hit in " + self.fake_end_str) + ", daughters: " + str(self.daughterIndexes) +\ + ", tracking failed in " + self.last_str + ", to " + self.particle_end_str + ", wrong hit in " + self.fake_end_str) ##### STORAGE CLASSES ##### class EndInfo(object): ''' Storage class for end of tracking information for a matched fake ''' def __init__(self): - self.last = [] - self.fake_end = [] - self.particle_end = [] - self.last_str = "" - self.fake_end_str = "" - self.particle_end_str = "" - self.fake_class = -1 - self.end_class = -1 - self.last_detid = -1 - self.fake_end_detid = -1 - self.particle_end_detid = -1 - self.particle_pdgId = -1 - self.particle_pt = -1 + self.last = [] + self.fake_end = [] + self.particle_end = [] + self.last_str = "" + self.fake_end_str = "" + self.particle_end_str = "" + self.fake_class = -1 + self.end_class = -1 + self.last_detid = -1 + self.fake_end_detid = -1 + self.particle_end_detid = -1 + self.particle_pdgId = -1 + self.particle_pt = -1 class ResolutionData(object): ''' Storage class for matched fake track resolutions ''' def __init__(self): - self.pt_rec = [] - self.pt_sim = [] + self.pt_rec = [] + self.pt_sim = [] self.pt_delta = [] - self.eta = [] - self.Lambda = [] - self.cotTheta = [] - self.phi = [] - self.dxy = [] - self.dz = [] - self.fake_class = [] + self.eta = [] + self.Lambda = [] + self.cotTheta = [] + self.phi = [] + self.dxy = [] + self.dz = [] + self.fake_class = [] def __iter__(self): for i in range(len(self.pt_rec)): - yield ResolutionItem(self.pt_rec[i], self.pt_sim[i], self.pt_delta[i], self.eta[i], self.Lambda[i], self.cotTheta[i], self.phi[i], self.dxy[i], self.dz[i], self.fake_class[i]) + yield ResolutionItem(self.pt_rec[i], self.pt_sim[i], self.pt_delta[i], self.eta[i], self.Lambda[i], self.cotTheta[i], self.phi[i], self.dxy[i], self.dz[i], self.fake_class[i]) class ResolutionItem(object): ''' A storage class for ResolutionData iteration ''' def __init__(self, pt_rec, pt_sim, pt_delta, eta, Lambda, cotTheta, phi, dxy, dz, fake_class): - self.pt_rec = pt_rec - self.pt_sim = pt_sim + self.pt_rec = pt_rec + self.pt_sim = pt_sim self.pt_delta = pt_delta - self.eta = eta - self.Lambda = Lambda - self.cotTheta = cotTheta - self.phi = phi - self.dxy = dxy - self.dz = dz - self.fake_class = fake_class + self.eta = eta + self.Lambda = Lambda + self.cotTheta = cotTheta + self.phi = phi + self.dxy = dxy + self.dz = dz + self.fake_class = fake_class ##### ANALYSIS WORKROUNDS ##### @@ -828,19 +828,19 @@ def ClassifyEventFakes(ntuple_file, nEvents = 100, return_fakes = False, real_cr results = {class_item: 0 for class_item in classes} # This line has issues with the python3 version, worked with Python 2.17.12. Comment something to compile with older version fake_list = [] for event in ntuple_file: - fakes = FindFakes(event) - for fake in fakes: - info = FakeInfo(fake, real_criterion) - results[info.fake_class] += 1 + fakes = FindFakes(event) + for fake in fakes: + info = FakeInfo(fake, real_criterion) + results[info.fake_class] += 1 - if return_fakes: - fake_list.append(info) + if return_fakes: + fake_list.append(info) i += 1 - if i >= nEvents: - break + if i >= nEvents: + break if return_fakes: - return results, fake_list + return results, fake_list return results def Calculate_MaxMatchedHits(ntuple_file, nEvents = 100): @@ -851,18 +851,18 @@ def Calculate_MaxMatchedHits(ntuple_file, nEvents = 100): i = 0 results = [] for event in ntuple_file: - fakes = FindFakes(event) - for fake in fakes: - res_temp = 0 - for particle in FindAssociatedParticles(fake): - shared, par, nAll = SharedHitFrac(fake, particle, 1) - if shared > res_temp: - res_temp = shared - results.append(res_temp) - - i += 1 - if i >= nEvents: - break + fakes = FindFakes(event) + for fake in fakes: + res_temp = 0 + for particle in FindAssociatedParticles(fake): + shared, par, nAll = SharedHitFrac(fake, particle, 1) + if shared > res_temp: + res_temp = shared + results.append(res_temp) + + i += 1 + if i >= nEvents: + break return results @@ -875,42 +875,42 @@ def Calculate_MaxMatchedConsecutiveHits(ntuple_file, nEvents = 100, frac = False i = 0 results = [] for event in ntuple_file: - fakes = FindFakes(event) - for fake in fakes: - res_temp = 0 - #fake_temp = fake - for particle in FindAssociatedParticles(fake): - tolerance_mask = SharedHitsFromBeginning(particle, fake, fake.nValid()) - diff = [abs(tolerance_mask[j+1] - tolerance_mask[j]) for j in range(len(tolerance_mask)-1)] - if frac: - if diff and 1.0*max(diff)/fake.nValid() > res_temp: - res_temp = 1.0*max(diff)/fake.nValid() - elif 1.0*tolerance_mask[0]/fake.nValid() > res_temp: - res_temp = 1.0*tolerance_mask[0]/fake.nValid() - else: - if diff and max(diff) > res_temp: - res_temp = max(diff) - elif tolerance_mask[0] > res_temp: - res_temp = tolerance_mask[0] - ''' Uncomment to debug - if frac: - if 1.0*res_temp/fake.nValid() > 0.75: - print 1.0*res_temp/fake.nValid() - print res_temp - print [hit.index() for hit in fake.hits()] - print [hit.index() for hit in particle.hits()] - print tolerance_mask - print diff - print fake.nValid() - print particle.nValid() - - results.append(1.0*res_temp/fake.nValid()) - ''' - results.append(res_temp) - - i += 1 - if i >= nEvents: - break + fakes = FindFakes(event) + for fake in fakes: + res_temp = 0 + #fake_temp = fake + for particle in FindAssociatedParticles(fake): + tolerance_mask = SharedHitsFromBeginning(particle, fake, fake.nValid()) + diff = [abs(tolerance_mask[j+1] - tolerance_mask[j]) for j in range(len(tolerance_mask)-1)] + if frac: + if diff and 1.0*max(diff)/fake.nValid() > res_temp: + res_temp = 1.0*max(diff)/fake.nValid() + elif 1.0*tolerance_mask[0]/fake.nValid() > res_temp: + res_temp = 1.0*tolerance_mask[0]/fake.nValid() + else: + if diff and max(diff) > res_temp: + res_temp = max(diff) + elif tolerance_mask[0] > res_temp: + res_temp = tolerance_mask[0] + ''' Uncomment to debug + if frac: + if 1.0*res_temp/fake.nValid() > 0.75: + print 1.0*res_temp/fake.nValid() + print res_temp + print [hit.index() for hit in fake.hits()] + print [hit.index() for hit in particle.hits()] + print tolerance_mask + print diff + print fake.nValid() + print particle.nValid() + + results.append(1.0*res_temp/fake.nValid()) + ''' + results.append(res_temp) + + i += 1 + if i >= nEvents: + break return results @@ -921,19 +921,19 @@ def Calculate_MaxMatchedHits_RealTracks(ntuple_file, nEvents = 100): i = 0 results = [] for event in ntuple_file: - for track in event.tracks(): - if track.nMatchedTrackingParticles() >= 1: - res_temp = 0 - for info in track.matchedTrackingParticleInfos(): - particle = info.trackingParticle() - shared, par, nAll = SharedHitFrac(track, particle, 1) - if shared > res_temp: - res_temp = shared - results.append(res_temp) - - i += 1 - if i >= nEvents: - break + for track in event.tracks(): + if track.nMatchedTrackingParticles() >= 1: + res_temp = 0 + for info in track.matchedTrackingParticleInfos(): + particle = info.trackingParticle() + shared, par, nAll = SharedHitFrac(track, particle, 1) + if shared > res_temp: + res_temp = shared + results.append(res_temp) + + i += 1 + if i >= nEvents: + break return results @@ -944,23 +944,23 @@ def Calculate_MaxMatchedConsecutiveHits_RealTracks(ntuple_file, nEvents = 100): i = 0 results = [] for event in ntuple_file: - for track in event.tracks(): - if track.nMatchedTrackingParticles() >= 1: - res_temp = 0 - for info in track.matchedTrackingParticleInfos(): - particle = info.trackingParticle() - tolerance_mask = SharedHitsFromBeginning(particle, track, track.nValid()) - diff = [abs(tolerance_mask[j+1] - tolerance_mask[j]) for j in range(len(tolerance_mask)-1)] - if diff and max(diff) > res_temp: - res_temp = max(diff) - elif tolerance_mask[0] > res_temp: - res_temp = tolerance_mask[0] - #print res_temp - results.append(res_temp) - - i += 1 - if i >= nEvents: - break + for track in event.tracks(): + if track.nMatchedTrackingParticles() >= 1: + res_temp = 0 + for info in track.matchedTrackingParticleInfos(): + particle = info.trackingParticle() + tolerance_mask = SharedHitsFromBeginning(particle, track, track.nValid()) + diff = [abs(tolerance_mask[j+1] - tolerance_mask[j]) for j in range(len(tolerance_mask)-1)] + if diff and max(diff) > res_temp: + res_temp = max(diff) + elif tolerance_mask[0] > res_temp: + res_temp = tolerance_mask[0] + #print res_temp + results.append(res_temp) + + i += 1 + if i >= nEvents: + break return results @@ -973,17 +973,17 @@ def Calculate_MatchPixelHits(ntuple_file, nEvents = 100, fake_mask = []): nPix_data = [] nLay_data = [] for event in ntuple_file: - fakes = FindFakes(event) - for fake in fakes: - info = FakeInfo(fake) - if not fake_mask or info.fake_class in fake_mask: - for match in info.matches: - nPix_data.append(match.nPix) - nLay_data.append(match.nPixLayers) + fakes = FindFakes(event) + for fake in fakes: + info = FakeInfo(fake) + if not fake_mask or info.fake_class in fake_mask: + for match in info.matches: + nPix_data.append(match.nPix) + nLay_data.append(match.nPixLayers) i += 1 - if i >= nEvents: - break + if i >= nEvents: + break return nPix_data, nLay_data @@ -995,14 +995,14 @@ def Calculate_UnmatchedSharedHits(ntuple_file, nEvents = 100, fake_mask = [0, -1 results = [] i = 0 for event in ntuple_file: - fakes = FindFakes(event) - for fake in fakes: - info = FakeInfo(fake) - if info.fake_class in fake_mask: - results.append(info.unmatched_max_shared) - i += 1 - if i >= nEvents: - break + fakes = FindFakes(event) + for fake in fakes: + info = FakeInfo(fake) + if info.fake_class in fake_mask: + results.append(info.unmatched_max_shared) + i += 1 + if i >= nEvents: + break return results @@ -1016,15 +1016,15 @@ def Calculate_SharedHits(ntuple_file, nEvents = 100, mask = []): hit_fractions = [] i = 0 for event in ntuple_file: - fakes = FindFakes(event) - for fake in fakes: - info = FakeInfo(fake) - if not mask or info.fake_class in mask: - hits_shared.append(info.max_shared) - hit_fractions.append(info.max_frac) - i += 1 - if i >= nEvents: - break + fakes = FindFakes(event) + for fake in fakes: + info = FakeInfo(fake) + if not mask or info.fake_class in mask: + hits_shared.append(info.max_shared) + hit_fractions.append(info.max_frac) + i += 1 + if i >= nEvents: + break return hits_shared, hit_fractions @@ -1036,15 +1036,15 @@ def Calculate_SharedHits_RealTracks(ntuple_file, nEvents = 100): hits_shared = [] hit_fractions = [] i = 0 - for event in ntuple_file: - for track in event.tracks(): - if track.nMatchedTrackingParticles() >= 1: - info = FakeInfo(track) - hits_shared.append(info.max_shared) - hit_fractions.append(info.max_frac) - i += 1 - if i >= nEvents: - break + for event in ntuple_file: + for track in event.tracks(): + if track.nMatchedTrackingParticles() >= 1: + info = FakeInfo(track) + hits_shared.append(info.max_shared) + hit_fractions.append(info.max_frac) + i += 1 + if i >= nEvents: + break return hits_shared, hit_fractions @@ -1054,32 +1054,32 @@ def Calculate_IndludedDecayHitFractions(ntuple_file, nEvents = 100): to analyse the multiple matches class "fake includes a decay interaction". Returns: daughter_frac = fraction of daughter particle hits from fake parent_frac = fraction of parent particle hits from fake - total_frac = the sum of these daughter and parent fractions + total_frac = the sum of these daughter and parent fractions ''' daughter_frac = [] parent_frac = [] total_frac = [] i = 0 for event in ntuple_file: - fakes = FindFakes(event) - for fake in fakes: - info = FakeInfo(fake) - if info.fake_class == 21: - if len(info.decayLinks) >= 2: print("Double or more decays!!!11") - for link in info.decayLinks: - par_ind = link[0] - dau_ind = link[1] - for match in info.matches: - if match.index == par_ind: par_hits = match.shared_hits - if match.index == dau_ind: dau_hits = match.shared_hits - fake_hits = info.nHits - - parent_frac.append(1.0*par_hits/fake_hits) - daughter_frac.append(1.0*dau_hits/fake_hits) - total_frac.append(1.0*(dau_hits + par_hits)/fake_hits) - i += 1 - if i >= nEvents: - break + fakes = FindFakes(event) + for fake in fakes: + info = FakeInfo(fake) + if info.fake_class == 21: + if len(info.decayLinks) >= 2: print("Double or more decays!!!11") + for link in info.decayLinks: + par_ind = link[0] + dau_ind = link[1] + for match in info.matches: + if match.index == par_ind: par_hits = match.shared_hits + if match.index == dau_ind: dau_hits = match.shared_hits + fake_hits = info.nHits + + parent_frac.append(1.0*par_hits/fake_hits) + daughter_frac.append(1.0*dau_hits/fake_hits) + total_frac.append(1.0*(dau_hits + par_hits)/fake_hits) + i += 1 + if i >= nEvents: + break return daughter_frac, parent_frac, total_frac @@ -1090,30 +1090,30 @@ def Get_EndOfTrackingPoints(ntuple_file, nEvents = 100, mask = []): end_infos = [] i = 0 for event in ntuple_file: - fakes = FindFakes(event) - for fake in fakes: - info = FakeInfo(fake) - if not mask or info.fake_class in mask: - for match in info.matches: - end = EndInfo() - end.last = match.last_loc - end.fake_end = match.fake_end_loc - end.particle_end = match.particle_end_loc - end.end_class = match.end_class - end.fake_class = info.fake_class - end.last_str = match.last_str - end.fake_end_str = match.fake_end_str - end.particle_end_str = match.particle_end_str - end.last_detId = match.last_detId - end.fake_end_detId = match.fake_end_detId - end.particle_end_detId = match.particle_end_detId - end.particle_pdgId = match.particle_pdgId - end.particle_pt = match.particle_pt - - end_infos.append(end) - i += 1 - if i >= nEvents: - break + fakes = FindFakes(event) + for fake in fakes: + info = FakeInfo(fake) + if not mask or info.fake_class in mask: + for match in info.matches: + end = EndInfo() + end.last = match.last_loc + end.fake_end = match.fake_end_loc + end.particle_end = match.particle_end_loc + end.end_class = match.end_class + end.fake_class = info.fake_class + end.last_str = match.last_str + end.fake_end_str = match.fake_end_str + end.particle_end_str = match.particle_end_str + end.last_detId = match.last_detId + end.fake_end_detId = match.fake_end_detId + end.particle_end_detId = match.particle_end_detId + end.particle_pdgId = match.particle_pdgId + end.particle_pt = match.particle_pt + + end_infos.append(end) + i += 1 + if i >= nEvents: + break return end_infos @@ -1124,30 +1124,30 @@ def Get_EndOfTrackingPointsReal(ntuple_file, nEvents = 100): end_infos = [] i = 0 for event in ntuple_file: - trues = FindTrues(event) - for true in trues: - for info in true.matchedTrackingParticleInfos(): - particle = info.trackingParticle() - last, track_end, particle_end, end_class = FindEndOfTracking(true, particle) - end = EndInfo() - if last.isValidHit(): end.last = [last.x(), last.y(), last.z()] - if track_end.isValidHit(): end.fake_end = [track_end.x(), track_end.y(), track_end.z()] - if particle_end.isValidHit(): end.particle_end = [particle_end.x(), particle_end.y(), particle_end.z()] - end.end_class = end_class - end.fake_class = -1 - end.last_str = last.layerStr() - end.fake_end_str = track_end.layerStr() - end.particle_end_str = particle_end.layerStr() - end.last_detId = last.detId() - end.fake_end_detId = track_end.detId() - end.particle_end_detId = particle_end.detId() - end.particle_pdgId = particle.pdgId() - end.particle_pt = particle.pt() - - end_infos.append(end) - i += 1 - if i >= nEvents: - break + trues = FindTrues(event) + for true in trues: + for info in true.matchedTrackingParticleInfos(): + particle = info.trackingParticle() + last, track_end, particle_end, end_class = FindEndOfTracking(true, particle) + end = EndInfo() + if last.isValidHit(): end.last = [last.x(), last.y(), last.z()] + if track_end.isValidHit(): end.fake_end = [track_end.x(), track_end.y(), track_end.z()] + if particle_end.isValidHit(): end.particle_end = [particle_end.x(), particle_end.y(), particle_end.z()] + end.end_class = end_class + end.fake_class = -1 + end.last_str = last.layerStr() + end.fake_end_str = track_end.layerStr() + end.particle_end_str = particle_end.layerStr() + end.last_detId = last.detId() + end.fake_end_detId = track_end.detId() + end.particle_end_detId = particle_end.detId() + end.particle_pdgId = particle.pdgId() + end.particle_pt = particle.pt() + + end_infos.append(end) + i += 1 + if i >= nEvents: + break return end_infos @@ -1162,16 +1162,16 @@ def Save_Normalisation_Coefficients(ntuple_file): print(sum([val for ind, val in norm_c.items()])) for event in ntuple_file: - print(event.entry()+1) - for particle in event.trackingParticles(): - for hit in particle.hits(): - if hit.isValidHit(): - norm_c[layer_names_rev[hit.layerStr()]] += 1 + print(event.entry()+1) + for particle in event.trackingParticles(): + for hit in particle.hits(): + if hit.isValidHit(): + norm_c[layer_names_rev[hit.layerStr()]] += 1 norm_sum = sum([val for ind, val in norm_c.items()]) print(norm_sum) print(norm_c) for i, c in norm_c.items(): - norm_c[i] = 1.0*c/norm_sum + norm_c[i] = 1.0*c/norm_sum #normalisation = [1.0*c/norm_sum for c in norm_c] print("normalisation_coefficients.dmp") print(norm_c) @@ -1196,29 +1196,29 @@ def Resolution_Analysis_Fakes(ntuple_file, nEvents = 100, real_criterion = ["con res = ResolutionData() i = 0 for event in ntuple_file: - #print event.entry() + 1 - fakes = FindFakes(event) - for fake in fakes: - info = FakeInfo(fake, real_criterion) - for match in info.matches: - par = match.particle - if par.pca_pt() == 0: continue - - res.pt_rec.append(fake.pt()) - res.pt_sim.append(par.pca_pt()) - res.pt_delta.append(fake.pt() - par.pca_pt()) - res.eta.append(fake.eta() - par.pca_eta()) - res.Lambda.append(getattr(fake, 'lambda')() - par.pca_lambda()) - res.cotTheta.append(fake.cotTheta() - par.pca_cotTheta()) - res.phi.append(fake.phi() - par.pca_phi()) - res.dxy.append(fake.dxy() - par.pca_dxy()) - res.dz.append(fake.dz() - par.pca_dz()) - - res.fake_class.append(info.fake_class) - - i += 1 - if i >= nEvents: - break + #print event.entry() + 1 + fakes = FindFakes(event) + for fake in fakes: + info = FakeInfo(fake, real_criterion) + for match in info.matches: + par = match.particle + if par.pca_pt() == 0: continue + + res.pt_rec.append(fake.pt()) + res.pt_sim.append(par.pca_pt()) + res.pt_delta.append(fake.pt() - par.pca_pt()) + res.eta.append(fake.eta() - par.pca_eta()) + res.Lambda.append(getattr(fake, 'lambda')() - par.pca_lambda()) + res.cotTheta.append(fake.cotTheta() - par.pca_cotTheta()) + res.phi.append(fake.phi() - par.pca_phi()) + res.dxy.append(fake.dxy() - par.pca_dxy()) + res.dz.append(fake.dz() - par.pca_dz()) + + res.fake_class.append(info.fake_class) + + i += 1 + if i >= nEvents: + break return res def Resolution_Analysis_Trues(ntuple_file, nEvents = 100): @@ -1228,35 +1228,35 @@ def Resolution_Analysis_Trues(ntuple_file, nEvents = 100): res = ResolutionData() i = 0 for event in ntuple_file: - #print event.entry() + 1 - trues = FindTrues(event) - for true in trues: - for info in true.matchedTrackingParticleInfos(): - par = info.trackingParticle() - if par.pca_pt() == 0: continue - - res.pt_rec.append(true.pt()) - res.pt_sim.append(par.pca_pt()) - res.pt_delta.append(true.pt() - par.pca_pt()) - res.eta.append(true.eta() - par.pca_eta()) - res.Lambda.append(getattr(true, 'lambda')() - par.pca_lambda()) - res.cotTheta.append(true.cotTheta() - par.pca_cotTheta()) - res.phi.append(true.phi() - par.pca_phi()) - res.dxy.append(true.dxy() - par.pca_dxy()) - res.dz.append(true.dz() - par.pca_dz()) - - res.fake_class.append(-1) - - i += 1 - if i >= nEvents: - break + #print event.entry() + 1 + trues = FindTrues(event) + for true in trues: + for info in true.matchedTrackingParticleInfos(): + par = info.trackingParticle() + if par.pca_pt() == 0: continue + + res.pt_rec.append(true.pt()) + res.pt_sim.append(par.pca_pt()) + res.pt_delta.append(true.pt() - par.pca_pt()) + res.eta.append(true.eta() - par.pca_eta()) + res.Lambda.append(getattr(true, 'lambda')() - par.pca_lambda()) + res.cotTheta.append(true.cotTheta() - par.pca_cotTheta()) + res.phi.append(true.phi() - par.pca_phi()) + res.dxy.append(true.dxy() - par.pca_dxy()) + res.dz.append(true.dz() - par.pca_dz()) + + res.fake_class.append(-1) + + i += 1 + if i >= nEvents: + break return res def Calculate_AmountOfFakes(ntuple_file): ''' Calculated the amount of fakes in the data. ''' n = 0 for event in ntuple_file: - n += len(FindFakes(event)) + n += len(FindFakes(event)) return n def Analyse_EOT_Error(end_list, bpix3_mask = False, detId_mask = "all", pt_mask = False): @@ -1270,25 +1270,25 @@ def Analyse_EOT_Error(end_list, bpix3_mask = False, detId_mask = "all", pt_mask ''' error = [] for end in end_list: - if end.fake_end != [0,0,0] and end.particle_end != [0,0,0]: - if pt_mask and end.particle_pt < 0.7: continue - - if bpix3_mask and end.end_class == 0 and end.last_str == "BPix3" and end.particle_end_str == "TIB1": - if detId_mask == "same" and end.fake_end_detId == end.particle_end_detId: - error.append(Distance(end.fake_end[0:2], end.particle_end[0:2])) - elif detId_mask == "different" and end.fake_end_detId != end.particle_end_detId: - error.append(Distance(end.fake_end, end.particle_end)) - elif detId_mask == "all": - error.append(Distance(end.fake_end, end.particle_end)) - if error and error[-1] == 0.0: print("Error is 0.0?!") - if error and error[-1] > 10: print(str(end.fake_end_detId) + " and " + str(end.particle_end_detId) + ": " + str(error[-1]) + " z: " + str(end.fake_end[2]) + " " + str(end.particle_end[2])) - elif not bpix3_mask: - if detId_mask == "same" and end.fake_end_detId == end.particle_end_detId: - error.append(Distance(end.fake_end[0:2], end.particle_end[0:2])) - elif detId_mask == "different" and end.fake_end_detId != end.particle_end_detId: - error.append(Distance(end.fake_end, end.particle_end)) - elif detId_mask == "all": - error.append(Distance(end.fake_end, end.particle_end)) + if end.fake_end != [0,0,0] and end.particle_end != [0,0,0]: + if pt_mask and end.particle_pt < 0.7: continue + + if bpix3_mask and end.end_class == 0 and end.last_str == "BPix3" and end.particle_end_str == "TIB1": + if detId_mask == "same" and end.fake_end_detId == end.particle_end_detId: + error.append(Distance(end.fake_end[0:2], end.particle_end[0:2])) + elif detId_mask == "different" and end.fake_end_detId != end.particle_end_detId: + error.append(Distance(end.fake_end, end.particle_end)) + elif detId_mask == "all": + error.append(Distance(end.fake_end, end.particle_end)) + if error and error[-1] == 0.0: print("Error is 0.0?!") + if error and error[-1] > 10: print(str(end.fake_end_detId) + " and " + str(end.particle_end_detId) + ": " + str(error[-1]) + " z: " + str(end.fake_end[2]) + " " + str(end.particle_end[2])) + elif not bpix3_mask: + if detId_mask == "same" and end.fake_end_detId == end.particle_end_detId: + error.append(Distance(end.fake_end[0:2], end.particle_end[0:2])) + elif detId_mask == "different" and end.fake_end_detId != end.particle_end_detId: + error.append(Distance(end.fake_end, end.particle_end)) + elif detId_mask == "all": + error.append(Distance(end.fake_end, end.particle_end)) print(sum(error)/len(error)) return error @@ -1300,11 +1300,11 @@ def EndOfTrackingDetectorInfo(end_list, end_mask = [0], BPix3mask = False): ''' data = [] for end in end_list: - if (not end_mask or end.end_class in end_mask) and (not BPix3mask or (end.last_str == "BPix3" and end.particle_end_str == "TIB1")): - if end.particle_end_detId == end.fake_end_detId: - data.append(1) - else: - data.append(0) + if (not end_mask or end.end_class in end_mask) and (not BPix3mask or (end.last_str == "BPix3" and end.particle_end_str == "TIB1")): + if end.particle_end_detId == end.fake_end_detId: + data.append(1) + else: + data.append(0) print("Same detector id between fake end and particle end: " + str(sum(data))) print("Different detector id: " + str(len(data)-sum(data))) @@ -1316,11 +1316,11 @@ def Analyse_EOT_ParticleDoubleHit(end_list, layer = "BPix3", end_mask = [0,4]): doubles = 0 all_particles = 0 for end in end_list: - if (not end_mask or end.end_class in end_mask) and (layer in end.last_str): - if end.last_str == end.particle_end_str: - doubles += 1 - #print end.end_class - all_particles += 1 + if (not end_mask or end.end_class in end_mask) and (layer in end.last_str): + if end.last_str == end.particle_end_str: + doubles += 1 + #print end.end_class + all_particles += 1 print("In layer " + layer + " there are " + str(doubles) + " end of trackings out of " + str(all_particles) + " (" + str(100.0*doubles/all_particles) + ") which have a double hit in the EOT layer") @@ -1332,17 +1332,17 @@ def TrackPt(ntuple_file, nEvents = 100): true_pts = [] i = 0 - for event in ntuple_file: - print("Event: " + str(i)) - for track in event.tracks(): - if track.nMatchedTrackingParticles() == 0: - fake_pts.append(track.pt()) + for event in ntuple_file: + print("Event: " + str(i)) + for track in event.tracks(): + if track.nMatchedTrackingParticles() == 0: + fake_pts.append(track.pt()) else: - true_pts.append(track.pt()) + true_pts.append(track.pt()) - i += 1 - if i >= nEvents: - break + i += 1 + if i >= nEvents: + break return fake_pts, true_pts diff --git a/Validation/RecoTrack/test/fakeAnalysis/graphics.py b/Validation/RecoTrack/test/fakeAnalysis/graphics.py index fdaaa7850e85d..11f223ea2d7c4 100644 --- a/Validation/RecoTrack/test/fakeAnalysis/graphics.py +++ b/Validation/RecoTrack/test/fakeAnalysis/graphics.py @@ -20,1146 +20,1146 @@ class EventPlotter(object): ''' def __init__(self): self.plots_2D = [] - self.plots_3D = [] - c = ROOT.TColor() + self.plots_3D = [] + c = ROOT.TColor() self.colors_G = [c.GetColor(0,255,0), c.GetColor(0,185,0), c.GetColor(50,255,50), \ - c.GetColor(0,100,0), c.GetColor(50,155,0), c.GetColor(0,70,155), \ - c.GetColor(0,255,0), c.GetColor(0,255,0), c.GetColor(0,255,0)] - self.colors_B = [c.GetColor(0,0,255), c.GetColor(0,0,155), c.GetColor(50,50,255), \ - c.GetColor(0,0,80), c.GetColor(50,0,155), c.GetColor(0,70,155), \ - c.GetColor(0,0,255), c.GetColor(0,0,255), c.GetColor(0,0,255)] + c.GetColor(0,100,0), c.GetColor(50,155,0), c.GetColor(0,70,155), \ + c.GetColor(0,255,0), c.GetColor(0,255,0), c.GetColor(0,255,0)] + self.colors_B = [c.GetColor(0,0,255), c.GetColor(0,0,155), c.GetColor(50,50,255), \ + c.GetColor(0,0,80), c.GetColor(50,0,155), c.GetColor(0,70,155), \ + c.GetColor(0,0,255), c.GetColor(0,0,255), c.GetColor(0,0,255)] def Reset(self): self.plots_2D = [] - self.plots_3D = [] + self.plots_3D = [] ###### OLD UNNECESSARY FUNCTIONS ###### def PlotEvent3DHits(self, event, flag="PSG"): - ''' - Plots the 3D hits of an event. - flag is an string which defines which hit types to plot - (p for pixel, s for strip, g for glued) - ''' - if('p' in flag or 'P' in flag): - pixel_hits = event.pixelHits() - pix_coords = [] - for hit in pixel_hits: - pix_coords.append(hit.z()) - pix_coords.append(hit.x()) - pix_coords.append(hit.y()) - pix_plot = ROOT.TPolyMarker3D(len(pix_coords)/3, array('f', pix_coords), 1) - pix_plot.SetMarkerColor(4) - - if('s' in flag or 'S' in flag): - strip_hits = event.stripHits() - str_coords = [] - for hit in strip_hits: - str_coords.append(hit.z()) - str_coords.append(hit.x()) - str_coords.append(hit.y()) - str_plot = ROOT.TPolyMarker3D(len(str_coords)/3, array('f', str_coords), 1) - str_plot.SetMarkerColor(2) - - if('g' in flag or 'G' in flag): - glued_hits = event.gluedHits() - glu_coords = [] - for hit in glued_hits: - glu_coords.append(hit.z()) - glu_coords.append(hit.x()) - glu_coords.append(hit.y()) - glu_plot = ROOT.TPolyMarker3D(len(glu_coords)/3, array('f', glu_coords), 1) - glu_plot.SetMarkerColor(3) - - if('p' in flag or 'P' in flag): self.plots_3D.append(pix_plot) - if('s' in flag or 'S' in flag): self.plots_3D.append(str_plot) - if('g' in flag or 'G' in flag): self.plots_3D.append(glu_plot) + ''' + Plots the 3D hits of an event. + flag is an string which defines which hit types to plot + (p for pixel, s for strip, g for glued) + ''' + if('p' in flag or 'P' in flag): + pixel_hits = event.pixelHits() + pix_coords = [] + for hit in pixel_hits: + pix_coords.append(hit.z()) + pix_coords.append(hit.x()) + pix_coords.append(hit.y()) + pix_plot = ROOT.TPolyMarker3D(len(pix_coords)/3, array('f', pix_coords), 1) + pix_plot.SetMarkerColor(4) + + if('s' in flag or 'S' in flag): + strip_hits = event.stripHits() + str_coords = [] + for hit in strip_hits: + str_coords.append(hit.z()) + str_coords.append(hit.x()) + str_coords.append(hit.y()) + str_plot = ROOT.TPolyMarker3D(len(str_coords)/3, array('f', str_coords), 1) + str_plot.SetMarkerColor(2) + + if('g' in flag or 'G' in flag): + glued_hits = event.gluedHits() + glu_coords = [] + for hit in glued_hits: + glu_coords.append(hit.z()) + glu_coords.append(hit.x()) + glu_coords.append(hit.y()) + glu_plot = ROOT.TPolyMarker3D(len(glu_coords)/3, array('f', glu_coords), 1) + glu_plot.SetMarkerColor(3) + + if('p' in flag or 'P' in flag): self.plots_3D.append(pix_plot) + if('s' in flag or 'S' in flag): self.plots_3D.append(str_plot) + if('g' in flag or 'G' in flag): self.plots_3D.append(glu_plot) def PlotXY(self, event, limits=[-1000,1000], flag="PSG"): - ''' - Plots the hits of an event in an XY plane. - flag is an string which defines which hit types to plot - (p for pixel, s for strip, g for glued) - ''' - - if('p' in flag or 'P' in flag): - pixel_hits = event.pixelHits() - pix_x = [] - pix_y = [] - for hit in pixel_hits: - if(limits[0] < hit.z() < limits[1]): - pix_x.append(hit.x()) - pix_y.append(hit.y()) - pix_plot = ROOT.TGraph(len(pix_x), array('f', pix_x), array('f', pix_y)) - pix_plot.SetMarkerColor(4) - - if('s' in flag or 'S' in flag): - strip_hits = event.stripHits() - str_x = [] - str_y = [] - for hit in strip_hits: - if(limits[0] < hit.z() < limits[1]): - str_x.append(hit.x()) - str_y.append(hit.y()) - str_plot = ROOT.TGraph(len(str_x), array('f', str_x), array('f', str_y)) - str_plot.SetMarkerColor(2) - - if('g' in flag or 'G' in flag): - glued_hits = event.gluedHits() - glu_x = [] - glu_y = [] - for hit in glued_hits: - if(limits[0] < hit.z() < limits[1]): - glu_x.append(hit.x()) - glu_y.append(hit.y()) - glu_plot = ROOT.TGraph(len(glu_x), array('f', glu_x), array('f', glu_y)) - glu_plot.SetMarkerColor(3) - - plot = ROOT.TMultiGraph() - - if('p' in flag or 'P' in flag): plot.Add(pix_plot,"P") - if('s' in flag or 'S' in flag): plot.Add(str_plot,"P") - if('g' in flag or 'G' in flag): plot.Add(glu_plot,"P") - self.plots_2D.append(plot) + ''' + Plots the hits of an event in an XY plane. + flag is an string which defines which hit types to plot + (p for pixel, s for strip, g for glued) + ''' + + if('p' in flag or 'P' in flag): + pixel_hits = event.pixelHits() + pix_x = [] + pix_y = [] + for hit in pixel_hits: + if(limits[0] < hit.z() < limits[1]): + pix_x.append(hit.x()) + pix_y.append(hit.y()) + pix_plot = ROOT.TGraph(len(pix_x), array('f', pix_x), array('f', pix_y)) + pix_plot.SetMarkerColor(4) + + if('s' in flag or 'S' in flag): + strip_hits = event.stripHits() + str_x = [] + str_y = [] + for hit in strip_hits: + if(limits[0] < hit.z() < limits[1]): + str_x.append(hit.x()) + str_y.append(hit.y()) + str_plot = ROOT.TGraph(len(str_x), array('f', str_x), array('f', str_y)) + str_plot.SetMarkerColor(2) + + if('g' in flag or 'G' in flag): + glued_hits = event.gluedHits() + glu_x = [] + glu_y = [] + for hit in glued_hits: + if(limits[0] < hit.z() < limits[1]): + glu_x.append(hit.x()) + glu_y.append(hit.y()) + glu_plot = ROOT.TGraph(len(glu_x), array('f', glu_x), array('f', glu_y)) + glu_plot.SetMarkerColor(3) + + plot = ROOT.TMultiGraph() + + if('p' in flag or 'P' in flag): plot.Add(pix_plot,"P") + if('s' in flag or 'S' in flag): plot.Add(str_plot,"P") + if('g' in flag or 'G' in flag): plot.Add(glu_plot,"P") + self.plots_2D.append(plot) def PlotZY(self, event, limits=[-1000,1000], flag="PSG"): - ''' - Plots the hits of an event in an ZR plane. - flag is an string which defines which hit types to plot - (p for pixel, s for strip, g for glued) - ''' - - if('p' in flag or 'P' in flag): - pixel_hits = event.pixelHits() - pix_z = [] - pix_y = [] - for hit in pixel_hits: - if(limits[0] < hit.z() < limits[1]): - pix_z.append(hit.z()) - pix_y.append(hit.y()) - pix_plot = ROOT.TGraph(len(pix_z), array('f', pix_z), array('f', pix_y)) - pix_plot.SetMarkerColor(4) - - if('s' in flag or 'S' in flag): - strip_hits = event.stripHits() - str_z = [] - str_y = [] - for hit in strip_hits: - if(limits[0] < hit.z() < limits[1]): - str_z.append(hit.z()) - str_y.append(hit.y()) - str_plot = ROOT.TGraph(len(str_z), array('f', str_z), array('f', str_y)) - str_plot.SetMarkerColor(2) - - if('g' in flag or 'G' in flag): - glued_hits = event.gluedHits() - glu_z = [] - glu_y = [] - for hit in glued_hits: - if(limits[0] < hit.z() < limits[1]): - glu_z.append(hit.z()) - glu_y.append(hit.y()) - glu_plot = ROOT.TGraph(len(glu_z), array('f', glu_z), array('f', glu_y)) - glu_plot.SetMarkerColor(3) - - plot = ROOT.TMultiGraph() - - if('p' in flag or 'P' in flag): plot.Add(pix_plot,"P") - if('s' in flag or 'S' in flag): plot.Add(str_plot,"P") - if('g' in flag or 'G' in flag): plot.Add(glu_plot,"P") - self.plots_2D.append(plot) + ''' + Plots the hits of an event in an ZR plane. + flag is an string which defines which hit types to plot + (p for pixel, s for strip, g for glued) + ''' + + if('p' in flag or 'P' in flag): + pixel_hits = event.pixelHits() + pix_z = [] + pix_y = [] + for hit in pixel_hits: + if(limits[0] < hit.z() < limits[1]): + pix_z.append(hit.z()) + pix_y.append(hit.y()) + pix_plot = ROOT.TGraph(len(pix_z), array('f', pix_z), array('f', pix_y)) + pix_plot.SetMarkerColor(4) + + if('s' in flag or 'S' in flag): + strip_hits = event.stripHits() + str_z = [] + str_y = [] + for hit in strip_hits: + if(limits[0] < hit.z() < limits[1]): + str_z.append(hit.z()) + str_y.append(hit.y()) + str_plot = ROOT.TGraph(len(str_z), array('f', str_z), array('f', str_y)) + str_plot.SetMarkerColor(2) + + if('g' in flag or 'G' in flag): + glued_hits = event.gluedHits() + glu_z = [] + glu_y = [] + for hit in glued_hits: + if(limits[0] < hit.z() < limits[1]): + glu_z.append(hit.z()) + glu_y.append(hit.y()) + glu_plot = ROOT.TGraph(len(glu_z), array('f', glu_z), array('f', glu_y)) + glu_plot.SetMarkerColor(3) + + plot = ROOT.TMultiGraph() + + if('p' in flag or 'P' in flag): plot.Add(pix_plot,"P") + if('s' in flag or 'S' in flag): plot.Add(str_plot,"P") + if('g' in flag or 'G' in flag): plot.Add(glu_plot,"P") + self.plots_2D.append(plot) def PlotTracksXY(self, tracks): - ''' Plots tracks like polyline graphs in the XY plane. tracks is an iterable for tracks. ''' - plot = ROOT.TMultiGraph() + ''' Plots tracks like polyline graphs in the XY plane. tracks is an iterable for tracks. ''' + plot = ROOT.TMultiGraph() - for track in tracks: - X = []; Y = []; - for hit in track.hits(): - if(hit.isValidHit()): - X.append(hit.x()) - Y.append(hit.y()) - plot.Add(ROOT.TGraph(len(X),array("f",X),array("f",Y)),"L") + for track in tracks: + X = []; Y = []; + for hit in track.hits(): + if(hit.isValidHit()): + X.append(hit.x()) + Y.append(hit.y()) + plot.Add(ROOT.TGraph(len(X),array("f",X),array("f",Y)),"L") - self.plots_2D.append(plot) + self.plots_2D.append(plot) def PlotTracksZY(self, tracks): - ''' Plots tracks like polyline graphs in the ZY plane. tracks is an iterable for tracks. ''' - plot = ROOT.TMultiGraph() - - for track in tracks: - Y = []; Z = []; - for hit in track.hits(): - if(hit.isValidHit()): - Y.append(hit.y()) - Z.append(hit.z()) - plot.Add(ROOT.TGraph(len(Z),array("f",Z),array("f",Y)),"L") - - self.plots_2D.append(plot) + ''' Plots tracks like polyline graphs in the ZY plane. tracks is an iterable for tracks. ''' + plot = ROOT.TMultiGraph() + + for track in tracks: + Y = []; Z = []; + for hit in track.hits(): + if(hit.isValidHit()): + Y.append(hit.y()) + Z.append(hit.z()) + plot.Add(ROOT.TGraph(len(Z),array("f",Z),array("f",Y)),"L") + + self.plots_2D.append(plot) def PlotTracks3D(self, tracks): - for track in tracks: - X = []; Y = []; Z = []; - for hit in track.hits(): - if(hit.isValidHit()): - X.append(hit.x()) - Y.append(hit.y()) - Z.append(hit.z()) - if(X): - self.plots_3D.append(ROOT.TPolyLine3D(len(X),array("f",Z),array("f",X),array("f",Y))) - + for track in tracks: + X = []; Y = []; Z = []; + for hit in track.hits(): + if(hit.isValidHit()): + X.append(hit.x()) + Y.append(hit.y()) + Z.append(hit.z()) + if(X): + self.plots_3D.append(ROOT.TPolyLine3D(len(X),array("f",Z),array("f",X),array("f",Y))) + def PlotPixelTracks3D(self, tracks): - for track in tracks: - X = []; Y = []; Z = []; - for hit in track.pixelHits(): - if(hit.isValidHit()): - X.append(hit.x()) - Y.append(hit.y()) - Z.append(hit.z()) - if(X): - self.plots_3D.append(ROOT.TPolyLine3D(len(X),array("f",Z),array("f",X),array("f",Y))) + for track in tracks: + X = []; Y = []; Z = []; + for hit in track.pixelHits(): + if(hit.isValidHit()): + X.append(hit.x()) + Y.append(hit.y()) + Z.append(hit.z()) + if(X): + self.plots_3D.append(ROOT.TPolyLine3D(len(X),array("f",Z),array("f",X),array("f",Y))) def PlotPixelGluedTracks3D(self, tracks): - for track in tracks: - X = []; Y = []; Z = []; - for hit in track.hits(): - if(hit.isValidHit() and hit.hitType != 1): - X.append(hit.x()) - Y.append(hit.y()) - Z.append(hit.z()) - if(X): - self.plots_3D.append(ROOT.TPolyLine3D(len(X),array("f",Z),array("f",X),array("f",Y))) + for track in tracks: + X = []; Y = []; Z = []; + for hit in track.hits(): + if(hit.isValidHit() and hit.hitType != 1): + X.append(hit.x()) + Y.append(hit.y()) + Z.append(hit.z()) + if(X): + self.plots_3D.append(ROOT.TPolyLine3D(len(X),array("f",Z),array("f",X),array("f",Y))) def PlotTrack3D(self, track, color = 1): - '''Plots a single track as a polyline and prints track info''' - # Not so hasardous experimental edit: - #hits = sorted([hit for hit in track.hits()], key = lambda hit: hit.index()) - #print [hit.index() for hit in hits] - X = []; Y = []; Z = []; - for hit in track.hits(): #hits: #track.hits(): - if(hit.isValidHit()): - X.append(hit.x()) - Y.append(hit.y()) - Z.append(hit.z()) - if(not X): - print("Track has no valid points") - return - plot = ROOT.TPolyLine3D(len(X),array("f",Z),array("f",X),array("f",Y)) - plot.SetLineColor(color) - self.plots_3D.append(plot) - - ''' Uncomment to print track info - print "Track parameters:" - print "px : " + str(track.px()) - print "py : " + str(track.py()) - print "pz : " + str(track.pz()) - print "pt : " + str(track.pt()) - print "eta : " + str(track.eta()) - print "phi : " + str(track.phi()) - print "dxy : " + str(track.dxy()) - print "dz : " + str(track.dz()) - print "q : " + str(track.q()) - ''' + '''Plots a single track as a polyline and prints track info''' + # Not so hasardous experimental edit: + #hits = sorted([hit for hit in track.hits()], key = lambda hit: hit.index()) + #print [hit.index() for hit in hits] + X = []; Y = []; Z = []; + for hit in track.hits(): #hits: #track.hits(): + if(hit.isValidHit()): + X.append(hit.x()) + Y.append(hit.y()) + Z.append(hit.z()) + if(not X): + print("Track has no valid points") + return + plot = ROOT.TPolyLine3D(len(X),array("f",Z),array("f",X),array("f",Y)) + plot.SetLineColor(color) + self.plots_3D.append(plot) + + ''' Uncomment to print track info + print "Track parameters:" + print "px : " + str(track.px()) + print "py : " + str(track.py()) + print "pz : " + str(track.pz()) + print "pt : " + str(track.pt()) + print "eta : " + str(track.eta()) + print "phi : " + str(track.phi()) + print "dxy : " + str(track.dxy()) + print "dz : " + str(track.dz()) + print "q : " + str(track.q()) + ''' ###### METHODS USED BY PLOTFAKES ###### def TrackHelix(self, track, color = 1, style = 0): - ''' - Creates a THelix object which can be plotted with Draw() method. - - NOTE: The helixes are better drawn with the vertical z-axis. - Even then the helixes are not drawn exactly correct. - ''' - if isinstance(track, TrackingParticle): - phi = track.pca_phi() - dxy = track.pca_dxy() - dz = track.pca_dz() - else: - phi = track.phi() - dxy = track.dxy() - dz = track.dz() - xyz = array("d", [-dxy*ROOT.TMath.Sin(phi), dxy*ROOT.TMath.Cos(phi), dz])# [dz, -dxy*ROOT.TMath.Sin(phi), dxy*ROOT.TMath.Cos(phi)]) - v = array("d", [track.py(), track.px(), track.pz()]) #[track.px(), track.py(), track.pz()]) #[track.pz(), track.px(), track.py()]) - w = 0.3*3.8*track.q()*0.01 #Angular frequency = 0.3*B*q*hattuvakio, close enough - z_last = dz - for hit in track.hits(): - if(hit.isValidHit()): z_last = hit.z() - - helix = ROOT.THelix(xyz, v, w)#, array("d", [dz, z_last]))#, ROOT.kHelixX, array("d", [1,0,0])) - helix.SetAxis(array("d", [-1,0,0])) - helix.SetRange(z_last, dz, ROOT.kHelixX) - helix.SetLineColor(color) - if style == 1: helix.SetLineStyle(9) - if style == 2: helix.SetLineStyle(7) - return helix - - def Plot3DHelixes(self, tracks, color = 1, style = 0): - ''' Plots 3D helixes from a track iterable ''' - for track in tracks: - if(track.hits()): - self.plots_3D.append(self.TrackHelix(track, color, style)) - - def Plot3DHelix(self, track, color = 1, style = 0): - ''' Plots a single track helix ''' - if(track.hits()): - self.plots_3D.append(self.TrackHelix(track, color, style)) + ''' + Creates a THelix object which can be plotted with Draw() method. + + NOTE: The helixes are better drawn with the vertical z-axis. + Even then the helixes are not drawn exactly correct. + ''' + if isinstance(track, TrackingParticle): + phi = track.pca_phi() + dxy = track.pca_dxy() + dz = track.pca_dz() + else: + phi = track.phi() + dxy = track.dxy() + dz = track.dz() + xyz = array("d", [-dxy*ROOT.TMath.Sin(phi), dxy*ROOT.TMath.Cos(phi), dz])# [dz, -dxy*ROOT.TMath.Sin(phi), dxy*ROOT.TMath.Cos(phi)]) + v = array("d", [track.py(), track.px(), track.pz()]) #[track.px(), track.py(), track.pz()]) #[track.pz(), track.px(), track.py()]) + w = 0.3*3.8*track.q()*0.01 #Angular frequency = 0.3*B*q*hattuvakio, close enough + z_last = dz + for hit in track.hits(): + if(hit.isValidHit()): z_last = hit.z() + + helix = ROOT.THelix(xyz, v, w)#, array("d", [dz, z_last]))#, ROOT.kHelixX, array("d", [1,0,0])) + helix.SetAxis(array("d", [-1,0,0])) + helix.SetRange(z_last, dz, ROOT.kHelixX) + helix.SetLineColor(color) + if style == 1: helix.SetLineStyle(9) + if style == 2: helix.SetLineStyle(7) + return helix + + def Plot3DHelixes(self, tracks, color = 1, style = 0): + ''' Plots 3D helixes from a track iterable ''' + for track in tracks: + if(track.hits()): + self.plots_3D.append(self.TrackHelix(track, color, style)) + + def Plot3DHelix(self, track, color = 1, style = 0): + ''' Plots a single track helix ''' + if(track.hits()): + self.plots_3D.append(self.TrackHelix(track, color, style)) def Plot3DHits(self, track, color = 1, style = 0): - ''' - Plots the 3D hits from a track. - ''' - pix_coords = [] - for hit in track.pixelHits(): - if hit.isValidHit(): - pix_coords.append(hit.z()) - pix_coords.append(hit.x()) - pix_coords.append(hit.y()) - if pix_coords: - pix_plot = ROOT.TPolyMarker3D(len(pix_coords)/3, array('f', pix_coords), 2) - pix_plot.SetMarkerColor(color) - if style == 1: pix_plot.SetMarkerStyle(5) - if style == 2: pix_plot.SetMarkerStyle(4) - self.plots_3D.append(pix_plot) - - for hit in track.gluedHits(): - if hit.isValidHit(): - x = hit.x(); y = hit.y(); z = hit.z() - if hit.isBarrel(): - X = [x, x] - Y = [y, y] - Z = [z - sqrt(hit.zz()), z + sqrt(hit.zz())] - else: - X = [x - copysign(sqrt(hit.xx()),x), x + copysign(sqrt(hit.xx()),x)] - Y = [y - copysign(sqrt(hit.yy()),y), y + copysign(sqrt(hit.yy()),y)] - Z = [hit.z(), hit.z()] - glu_plot = ROOT.TPolyLine3D(len(X),array("f",Z),array("f",X),array("f",Y)) - #glu_plot.SetLineStyle(2) - if style == 1: glu_plot.SetLineStyle(2) - if style == 2: glu_plot.SetLineStyle(3) - glu_plot.SetLineColor(color) - self.plots_3D.append(glu_plot) - - for hit in track.stripHits(): - if hit.isValidHit(): - x = hit.x(); y = hit.y(); z = hit.z() - if hit.isBarrel(): - X = [x, x] - Y = [y, y] - Z = [z - 1.5*sqrt(hit.zz()), z + 1.5*sqrt(hit.zz())] - else: - X = [x - 1.5*copysign(sqrt(hit.xx()),x), x + 1.5*copysign(sqrt(hit.xx()),x)] - Y = [y - 1.5*copysign(sqrt(hit.yy()),y), y + 1.5*copysign(sqrt(hit.yy()),y)] - Z = [hit.z(), hit.z()] - str_plot = ROOT.TPolyLine3D(len(X),array("f",Z),array("f",X),array("f",Y)) - if style == 1: str_plot.SetLineStyle(2) - if style == 2: str_plot.SetLineStyle(3) - str_plot.SetLineColor(color) - self.plots_3D.append(str_plot) + ''' + Plots the 3D hits from a track. + ''' + pix_coords = [] + for hit in track.pixelHits(): + if hit.isValidHit(): + pix_coords.append(hit.z()) + pix_coords.append(hit.x()) + pix_coords.append(hit.y()) + if pix_coords: + pix_plot = ROOT.TPolyMarker3D(len(pix_coords)/3, array('f', pix_coords), 2) + pix_plot.SetMarkerColor(color) + if style == 1: pix_plot.SetMarkerStyle(5) + if style == 2: pix_plot.SetMarkerStyle(4) + self.plots_3D.append(pix_plot) + + for hit in track.gluedHits(): + if hit.isValidHit(): + x = hit.x(); y = hit.y(); z = hit.z() + if hit.isBarrel(): + X = [x, x] + Y = [y, y] + Z = [z - sqrt(hit.zz()), z + sqrt(hit.zz())] + else: + X = [x - copysign(sqrt(hit.xx()),x), x + copysign(sqrt(hit.xx()),x)] + Y = [y - copysign(sqrt(hit.yy()),y), y + copysign(sqrt(hit.yy()),y)] + Z = [hit.z(), hit.z()] + glu_plot = ROOT.TPolyLine3D(len(X),array("f",Z),array("f",X),array("f",Y)) + #glu_plot.SetLineStyle(2) + if style == 1: glu_plot.SetLineStyle(2) + if style == 2: glu_plot.SetLineStyle(3) + glu_plot.SetLineColor(color) + self.plots_3D.append(glu_plot) + + for hit in track.stripHits(): + if hit.isValidHit(): + x = hit.x(); y = hit.y(); z = hit.z() + if hit.isBarrel(): + X = [x, x] + Y = [y, y] + Z = [z - 1.5*sqrt(hit.zz()), z + 1.5*sqrt(hit.zz())] + else: + X = [x - 1.5*copysign(sqrt(hit.xx()),x), x + 1.5*copysign(sqrt(hit.xx()),x)] + Y = [y - 1.5*copysign(sqrt(hit.yy()),y), y + 1.5*copysign(sqrt(hit.yy()),y)] + Z = [hit.z(), hit.z()] + str_plot = ROOT.TPolyLine3D(len(X),array("f",Z),array("f",X),array("f",Y)) + if style == 1: str_plot.SetLineStyle(2) + if style == 2: str_plot.SetLineStyle(3) + str_plot.SetLineColor(color) + self.plots_3D.append(str_plot) def PlotVertex3D(self, vertex, color=1): - ''' Plots a single vertex object ''' - plot = ROOT.TPolyMarker3D(1, array('f', [vertex.z(), vertex.x(), vertex.y()]),3) - plot.SetMarkerColor(color) + ''' Plots a single vertex object ''' + plot = ROOT.TPolyMarker3D(1, array('f', [vertex.z(), vertex.x(), vertex.y()]),3) + plot.SetMarkerColor(color) self.plots_3D.append(plot) def PlotPoint3D(self, point, color=1): ''' Plots a single 3D point from a 3-element list ''' - plot = ROOT.TPolyMarker3D(1, array('f', [point[2], point[0], point[1]]),3) - plot.SetMarkerColor(color) + plot = ROOT.TPolyMarker3D(1, array('f', [point[2], point[0], point[1]]),3) + plot.SetMarkerColor(color) self.plots_3D.append(plot) def PlotTrackingFail(self, match): ''' - Plots the end of tracking hits for a fake. - This is drawn with thick red lines from last shared hit to following fake and particle hits, - and the particle hit is indicated with a purple star marker. - ''' - X = array('f', [match.fake_end_loc[0], match.last_loc[0], match.particle_end_loc[0]]) - Y = array('f', [match.fake_end_loc[1], match.last_loc[1], match.particle_end_loc[1]]) - Z = array('f', [match.fake_end_loc[2], match.last_loc[2], match.particle_end_loc[2]]) + Plots the end of tracking hits for a fake. + This is drawn with thick red lines from last shared hit to following fake and particle hits, + and the particle hit is indicated with a purple star marker. + ''' + X = array('f', [match.fake_end_loc[0], match.last_loc[0], match.particle_end_loc[0]]) + Y = array('f', [match.fake_end_loc[1], match.last_loc[1], match.particle_end_loc[1]]) + Z = array('f', [match.fake_end_loc[2], match.last_loc[2], match.particle_end_loc[2]]) plot = ROOT.TPolyLine3D(3, Z, X, Y) - plot.SetLineWidth(3) - plot.SetLineColor(2) + plot.SetLineWidth(3) + plot.SetLineColor(2) self.plots_3D.append(plot) - self.PlotPoint3D(match.last_loc, 2) - self.PlotPoint3D(match.particle_end_loc, 6) + self.PlotPoint3D(match.last_loc, 2) + self.PlotPoint3D(match.particle_end_loc, 6) def PlotFakes(self, event, reconstructed = 1, fake_filter = None, end_filter = None, last_filter = None, particle_end_filter = None): - ''' + ''' This is the main function to plot fakes in 3D with related TrackingParticles and tracks. - Fake track is drawn as red, TrackingParticles as green and reconstructed tracks as blue. - The detector scheme is also drawn with black circles. - The decay vertices (yellow) and reconstructed collision vertices (colour of the track) are also drawn. - Alongside with the fake plotting, the track and particle informations are printed. + Fake track is drawn as red, TrackingParticles as green and reconstructed tracks as blue. + The detector scheme is also drawn with black circles. + The decay vertices (yellow) and reconstructed collision vertices (colour of the track) are also drawn. + Alongside with the fake plotting, the track and particle informations are printed. - Set reconstructed to false for not drawing other reconstructed tracks related to a fake, - use filters (lists of class indexes or detector layer strings) to filter out everything else from plotting. - ''' - iterative = 1 # simple edits for not needing to refactorise code + Set reconstructed to false for not drawing other reconstructed tracks related to a fake, + use filters (lists of class indexes or detector layer strings) to filter out everything else from plotting. + ''' + iterative = 1 # simple edits for not needing to refactorise code fakes = analysis.FindFakes(event) - if iterative: + if iterative: # Plot fakes one by one - for fake in fakes: - fake_info = analysis.FakeInfo(fake) + for fake in fakes: + fake_info = analysis.FakeInfo(fake) # Check for filter - if fake_filter and fake_info.fake_class not in fake_filter: - continue - if last_filter or particle_end_filter: - found_flag = False - for match in fake_info.matches: - if (not end_filter or match.end_class in end_filter) and (not last_filter or last_filter in match.last_str) and (not particle_end_filter or particle_end_filter in match.particle_end_str): - found_flag = True - if not found_flag: - continue - - self.Reset() - self.Plot3DHelixes([fake],2) - self.Plot3DHits(fake, 2) - #self.PlotVertex3D(vertex,2) - analysis.PrintTrackInfo(fake, None, 0, fake_info) + if fake_filter and fake_info.fake_class not in fake_filter: + continue + if last_filter or particle_end_filter: + found_flag = False + for match in fake_info.matches: + if (not end_filter or match.end_class in end_filter) and (not last_filter or last_filter in match.last_str) and (not particle_end_filter or particle_end_filter in match.particle_end_str): + found_flag = True + if not found_flag: + continue + + self.Reset() + self.Plot3DHelixes([fake],2) + self.Plot3DHits(fake, 2) + #self.PlotVertex3D(vertex,2) + analysis.PrintTrackInfo(fake, None, 0, fake_info) if fake_info.matches: - for match in fake_info.matches: - self.PlotTrackingFail(match) - #self.PlotPoint3D(fake_info.end_loc, 2) + for match in fake_info.matches: + self.PlotTrackingFail(match) + #self.PlotPoint3D(fake_info.end_loc, 2) # Find real particle tracks which include fake tracks hits - icol = 0 - particle_inds = [] - particles = [] - reco_inds = [] - recos = [] - for hit in fake.hits(): - if hit.isValidHit() and hit.nSimHits() >= 0: - for simHit in hit.simHits(): - particle = simHit.trackingParticle() - if particle.index() not in particle_inds: - particle_inds.append(particle.index()) - particles.append(particle) - if reconstructed and particle.nMatchedTracks() > 0: - for info in particle.matchedTrackInfos(): - track = info.track() - if track.index() not in reco_inds: - reco_inds.append(track.index()) - recos.append(track) - - - # Find reconstructed tracks included in fakes hits - if hit.isValidHit() and reconstructed and hit.ntracks() > 0: - for track in hit.tracks(): - #track = info.track() - if (track.index() not in reco_inds) and track.index() != fake.index(): - reco_inds.append(track.index()) - recos.append(track) + icol = 0 + particle_inds = [] + particles = [] + reco_inds = [] + recos = [] + for hit in fake.hits(): + if hit.isValidHit() and hit.nSimHits() >= 0: + for simHit in hit.simHits(): + particle = simHit.trackingParticle() + if particle.index() not in particle_inds: + particle_inds.append(particle.index()) + particles.append(particle) + if reconstructed and particle.nMatchedTracks() > 0: + for info in particle.matchedTrackInfos(): + track = info.track() + if track.index() not in reco_inds: + reco_inds.append(track.index()) + recos.append(track) + + + # Find reconstructed tracks included in fakes hits + if hit.isValidHit() and reconstructed and hit.ntracks() > 0: + for track in hit.tracks(): + #track = info.track() + if (track.index() not in reco_inds) and track.index() != fake.index(): + reco_inds.append(track.index()) + recos.append(track) # Plot the particles and reconstructed tracks - icol = 0 - self.ParticleTest(particles, draw=False) + icol = 0 + self.ParticleTest(particles, draw=False) for particle in particles: - self.Plot3DHelix(particle, self.colors_G[icol], 1) - self.plots_3D[-1].SetLineStyle(5) - self.Plot3DHits(particle, self.colors_G[icol], 1) - self.PlotVertex3D(particle.parentVertex(),self.colors_G[icol]) + self.Plot3DHelix(particle, self.colors_G[icol], 1) + self.plots_3D[-1].SetLineStyle(5) + self.Plot3DHits(particle, self.colors_G[icol], 1) + self.PlotVertex3D(particle.parentVertex(),self.colors_G[icol]) # EXPERIMENTAL LINE: #self.PlotTrack3D(particle, self.colors_G[icol]) - for decay in particle.decayVertices(): - self.PlotVertex3D(decay, 5) - analysis.PrintTrackInfo(particle, fake) - icol += 1 - icol = 0 - for track in recos: - self.Plot3DHelix(track,self.colors_B[icol],2) - self.Plot3DHits(track,self.colors_B[icol],2) - #self.PlotVertex3D(vertex,self.colors_B[icol]) - analysis.PrintTrackInfo(track, fake) - icol += 1 - - if hit.isValidHit() and hit.z() >= 0: self.PlotDetectorRange("p",4) - elif hit.isValidHit() and hit.z() < 0: self.PlotDetectorRange("n",4) - else: self.PlotDetectorRange("b",4) + for decay in particle.decayVertices(): + self.PlotVertex3D(decay, 5) + analysis.PrintTrackInfo(particle, fake) + icol += 1 + icol = 0 + for track in recos: + self.Plot3DHelix(track,self.colors_B[icol],2) + self.Plot3DHits(track,self.colors_B[icol],2) + #self.PlotVertex3D(vertex,self.colors_B[icol]) + analysis.PrintTrackInfo(track, fake) + icol += 1 + + if hit.isValidHit() and hit.z() >= 0: self.PlotDetectorRange("p",4) + elif hit.isValidHit() and hit.z() < 0: self.PlotDetectorRange("n",4) + else: self.PlotDetectorRange("b",4) print("****************************\n") - self.Draw() + self.Draw() return def DrawTrackTest(self, track): - self.PlotDetectorRange("b", 4) - self.PlotTrack3D(track) + self.PlotDetectorRange("b", 4) + self.PlotTrack3D(track) def ParticleTest(self, particles, draw=False): - for particle in particles: - print("\nPARTICLE " + str(particle.index())) - for hit in particle.hits(): - tof = -1 - for simHit in hit.simHits(): - if simHit.trackingParticle().index() == particle.index(): - #if len(info.tof()): - tof = simHit.tof() - print("Index: " + str(hit.index()) + ", Layer: " + str(hit.layerStr()) + ", TOF: " + str(tof) +\ - " XY distance: " + str(sqrt(hit.x()**2 + hit.y()**2)) + ", Z: " + str(hit.z())) - self.DrawTrackTest(particle) - if draw: - self.Draw() - self.Reset() + for particle in particles: + print("\nPARTICLE " + str(particle.index())) + for hit in particle.hits(): + tof = -1 + for simHit in hit.simHits(): + if simHit.trackingParticle().index() == particle.index(): + #if len(info.tof()): + tof = simHit.tof() + print("Index: " + str(hit.index()) + ", Layer: " + str(hit.layerStr()) + ", TOF: " + str(tof) +\ + " XY distance: " + str(sqrt(hit.x()**2 + hit.y()**2)) + ", Z: " + str(hit.z())) + self.DrawTrackTest(particle) + if draw: + self.Draw() + self.Reset() def PlotEndOfTrackingPoints3D(self, last, fail, fake_classes = [], color = ROOT.kBlue): - alpha = 0.01 + alpha = 0.01 for i in range(len(last)): if fail and last[i] != fail[i]: - X = array('f', [last[i][0], fail[i][0]]) - Y = array('f', [last[i][1], fail[i][1]]) - Z = array('f', [last[i][2], fail[i][2]]) - line = ROOT.TPolyLine3D(2, Z, X, Y) - line.SetLineWidth(1) - line.SetLineColorAlpha(color, alpha) - self.plots_3D.append(line) - else: - point = ROOT.TPolyMarker3D(1, array('f', [last[i][2], last[i][0], last[i][1]])) - point.SetMarkerColorAlpha(color, alpha) - self.plots_3D.append(point) + X = array('f', [last[i][0], fail[i][0]]) + Y = array('f', [last[i][1], fail[i][1]]) + Z = array('f', [last[i][2], fail[i][2]]) + line = ROOT.TPolyLine3D(2, Z, X, Y) + line.SetLineWidth(1) + line.SetLineColorAlpha(color, alpha) + self.plots_3D.append(line) + else: + point = ROOT.TPolyMarker3D(1, array('f', [last[i][2], last[i][0], last[i][1]])) + point.SetMarkerColorAlpha(color, alpha) + self.plots_3D.append(point) def PlotEndOfTracking3D(self, last, fake_ends, particle_ends, end_classes = [], fake_classes = [], end_mask = [], fake_mask = []): - ''' - Plots the end of tracking hits in 3D - ''' - alpha = 0.01 + ''' + Plots the end of tracking hits in 3D + ''' + alpha = 0.01 for i in range(len(last)): - if (not end_mask or end_classes[i] in end_mask) and (not fake_mask or fake_classes[i] in fake_mask): - point = ROOT.TPolyMarker3D(1, array('f', [last[i][2], last[i][0], last[i][1]])) - point.SetMarkerColorAlpha(4, alpha) - self.plots_3D.append(point) + if (not end_mask or end_classes[i] in end_mask) and (not fake_mask or fake_classes[i] in fake_mask): + point = ROOT.TPolyMarker3D(1, array('f', [last[i][2], last[i][0], last[i][1]])) + point.SetMarkerColorAlpha(4, alpha) + self.plots_3D.append(point) - point = ROOT.TPolyMarker3D(1, array('f', [fake_ends[i][2], fake_ends[i][0], fake_ends[i][1]])) - point.SetMarkerColorAlpha(2, alpha) - self.plots_3D.append(point) + point = ROOT.TPolyMarker3D(1, array('f', [fake_ends[i][2], fake_ends[i][0], fake_ends[i][1]])) + point.SetMarkerColorAlpha(2, alpha) + self.plots_3D.append(point) - point = ROOT.TPolyMarker3D(1, array('f', [particle_ends[i][2], particle_ends[i][0], particle_ends[i][1]])) - point.SetMarkerColorAlpha(3, alpha) - self.plots_3D.append(point) + point = ROOT.TPolyMarker3D(1, array('f', [particle_ends[i][2], particle_ends[i][0], particle_ends[i][1]])) + point.SetMarkerColorAlpha(3, alpha) + self.plots_3D.append(point) def PlotEndOfTrackingPoints2D(self, last, fail, classes = [], color = ROOT.kBlue): - alpha = 0.5 - plot = ROOT.TMultiGraph() + alpha = 0.5 + plot = ROOT.TMultiGraph() for i in range(len(last)): if fail and last[i] != fail[i]: - #c = ROOT.TCanvas("s","S",1000,1000) - R = array('f', [sqrt(last[i][0]**2 + last[i][1]**2), sqrt(fail[i][0]**2 + fail[i][1]**2)]) - Z = array('f', [last[i][2], fail[i][2]]) - #line = ROOT.TPolyLine(2, Z, R, "L") - line = ROOT.TGraph(2, Z, R) - line.SetLineWidth(1) - line.SetLineColorAlpha(color, alpha) - plot.Add(line, "L") - #self.plots_2D.append(line) - else: - #point = ROOT.TMarker(array("f", [last[i][2]]), array("f", [sqrt(last[i][0]**2 + last[i][1]**2)]), 1) - #point = ROOT.TMarker(last[i][2], sqrt(last[i][0]**2 + last[i][1]**2), 1) - point = ROOT.TGraph(1, array("f", [last[i][2]]), array("f", [sqrt(last[i][0]**2 + last[i][1]**2)])) - #point.SetDrawOption("*") - point.SetMarkerColorAlpha(color, alpha) - plot.Add(point, "P") - #self.plots_2D.append(point) - self.plots_2D.append(plot) - + #c = ROOT.TCanvas("s","S",1000,1000) + R = array('f', [sqrt(last[i][0]**2 + last[i][1]**2), sqrt(fail[i][0]**2 + fail[i][1]**2)]) + Z = array('f', [last[i][2], fail[i][2]]) + #line = ROOT.TPolyLine(2, Z, R, "L") + line = ROOT.TGraph(2, Z, R) + line.SetLineWidth(1) + line.SetLineColorAlpha(color, alpha) + plot.Add(line, "L") + #self.plots_2D.append(line) + else: + #point = ROOT.TMarker(array("f", [last[i][2]]), array("f", [sqrt(last[i][0]**2 + last[i][1]**2)]), 1) + #point = ROOT.TMarker(last[i][2], sqrt(last[i][0]**2 + last[i][1]**2), 1) + point = ROOT.TGraph(1, array("f", [last[i][2]]), array("f", [sqrt(last[i][0]**2 + last[i][1]**2)])) + #point.SetDrawOption("*") + point.SetMarkerColorAlpha(color, alpha) + plot.Add(point, "P") + #self.plots_2D.append(point) + self.plots_2D.append(plot) + def PlotDetectorRange(self, area="b", plates = 6): - ''' - Plots the detector schematic layout. - Area means which part to plot (p = positive side, n = negative side, b = both) - Plates means how many detector circle schemes to plot per side. - ''' + ''' + Plots the detector schematic layout. + Area means which part to plot (p = positive side, n = negative side, b = both) + Plates means how many detector circle schemes to plot per side. + ''' r = [17, 17, 57, 57, 112, 112] - z = [30, 70, 70, 120, 120, 280] - for i in range(plates): - X = []; Y = []; Z = []; ZN = [] - for t in range(0,101): - X.append(r[i]*cos(2*pi*t/100)) - Y.append(r[i]*sin(2*pi*t/100)) - Z.append(z[i]*1.0) - ZN.append(-1.0*z[i]) - plot = ROOT.TPolyLine3D(len(X),array("f",Z),array("f",X),array("f",Y),"S") - nplot = ROOT.TPolyLine3D(len(X),array("f",ZN),array("f",X),array("f",Y),"S") - plot.SetLineStyle(3) - nplot.SetLineStyle(3) - if area == "p": self.plots_3D.append(plot) - if area == "n": self.plots_3D.append(nplot) - if area == "b": - self.plots_3D.append(plot) - self.plots_3D.append(nplot) + z = [30, 70, 70, 120, 120, 280] + for i in range(plates): + X = []; Y = []; Z = []; ZN = [] + for t in range(0,101): + X.append(r[i]*cos(2*pi*t/100)) + Y.append(r[i]*sin(2*pi*t/100)) + Z.append(z[i]*1.0) + ZN.append(-1.0*z[i]) + plot = ROOT.TPolyLine3D(len(X),array("f",Z),array("f",X),array("f",Y),"S") + nplot = ROOT.TPolyLine3D(len(X),array("f",ZN),array("f",X),array("f",Y),"S") + plot.SetLineStyle(3) + nplot.SetLineStyle(3) + if area == "p": self.plots_3D.append(plot) + if area == "n": self.plots_3D.append(nplot) + if area == "b": + self.plots_3D.append(plot) + self.plots_3D.append(nplot) ###### HISTOGRAM PLOTTING METHODS ###### def ClassHistogram(self, data, name = "Histogram", labels = False, ready = False, logy = False, xmin = None, xmax = None, nbin = None, small = False): ''' A method for drawing histograms with several types of data. - Data can be in two different forms: - A dictionary (used for labeled data) - Raw numerical data + Data can be in two different forms: + A dictionary (used for labeled data) + Raw numerical data + + In the case of the dictionary, labels (ordered dictionary) should contain class indexes with class names. + Also if ready = True, the observations for classes are already calculated. + ''' + if ready: + if labels: + keys = [key for key in data] + hist_labels = [labels[key] for key in keys] + hist_data = [data[key] for key in keys] + else: + hist_labels = [key for key in data] + hist_data = [data[key] for key in hist_labels] + + if small: c1 = ROOT.TCanvas(name, name, 500, 500) + else: c1 = ROOT.TCanvas(name, name, 700, 500) + c1.SetGrid() + #c1.SetTopMargin(0.15) + if ready: hist = ROOT.TH1F(name, name, 30,0,30)#, 3,0,3) + else: + if xmin != None and xmax != None and nbin != None: + hist = ROOT.TH1F(name, name, nbin, xmin, xmax) + elif "fraction" in name or isinstance(data[0], float): + hist = ROOT.TH1F(name, name, 41,0,1.025)#100,0,5)#max(data)+0.0001)#11,0,1.1)#21,0,1.05)#41*(max(data)+1)/max(data))#, max(data)+1,-0.5,max(data)+0.5) #### EXPERIMENT!!!111 + elif isinstance(data[0], int): hist = ROOT.TH1F(name, name, max(data)-min(data)+1, min(data)-0.5,max(data)+0.5) + else: hist = ROOT.TH1F(name, name, 3,0,3) + #c1.SetLogy() + #hist.SetBinsLength(1) + if logy: c1.SetLogy() - In the case of the dictionary, labels (ordered dictionary) should contain class indexes with class names. - Also if ready = True, the observations for classes are already calculated. - ''' - if ready: - if labels: - keys = [key for key in data] - hist_labels = [labels[key] for key in keys] - hist_data = [data[key] for key in keys] - else: - hist_labels = [key for key in data] - hist_data = [data[key] for key in hist_labels] - - if small: c1 = ROOT.TCanvas(name, name, 500, 500) - else: c1 = ROOT.TCanvas(name, name, 700, 500) - c1.SetGrid() - #c1.SetTopMargin(0.15) - if ready: hist = ROOT.TH1F(name, name, 30,0,30)#, 3,0,3) - else: - if xmin != None and xmax != None and nbin != None: - hist = ROOT.TH1F(name, name, nbin, xmin, xmax) - elif "fraction" in name or isinstance(data[0], float): - hist = ROOT.TH1F(name, name, 41,0,1.025)#100,0,5)#max(data)+0.0001)#11,0,1.1)#21,0,1.05)#41*(max(data)+1)/max(data))#, max(data)+1,-0.5,max(data)+0.5) #### EXPERIMENT!!!111 - elif isinstance(data[0], int): hist = ROOT.TH1F(name, name, max(data)-min(data)+1, min(data)-0.5,max(data)+0.5) - else: hist = ROOT.TH1F(name, name, 3,0,3) - #c1.SetLogy() - #hist.SetBinsLength(1) - if logy: c1.SetLogy() - hist.SetStats(0); hist.SetFillColor(38); - hist.SetCanExtend(ROOT.TH1.kAllAxes); - if ready: # cumulative results already calculated in data - for i in range(len(hist_labels)): - #hist.Fill(hist_labels[i],hist_data[i]) - [hist.Fill(hist_labels[i],1) for j in range(hist_data[i])] - elif not ready and labels: - for entry in data: hist.Fill(labels[entry],1) - hist.LabelsOption(">") - else: # data is in samples, not in cumulative results - for entry in data: hist.Fill(entry,1) - hist.LabelsOption("a") - hist.LabelsDeflate() - if name == "Classification of all fakes": pass - #hist.SetLabelSize(0.05) - #hist.GetXaxis().SetRange(0,10) - hist.Draw() - - input("Press any key to continue") + hist.SetCanExtend(ROOT.TH1.kAllAxes); + if ready: # cumulative results already calculated in data + for i in range(len(hist_labels)): + #hist.Fill(hist_labels[i],hist_data[i]) + [hist.Fill(hist_labels[i],1) for j in range(hist_data[i])] + elif not ready and labels: + for entry in data: hist.Fill(labels[entry],1) + hist.LabelsOption(">") + else: # data is in samples, not in cumulative results + for entry in data: hist.Fill(entry,1) + hist.LabelsOption("a") + hist.LabelsDeflate() + if name == "Classification of all fakes": pass + #hist.SetLabelSize(0.05) + #hist.GetXaxis().SetRange(0,10) + hist.Draw() + + input("Press any key to continue") def EndOfTrackingHistogram(self, end_list, hist_type="end_class", end_mask = [], fake_mask = [], normalised = False, BPix3mask = False): - ''' Plots several types of histograms related to end of tracking analysis ''' - data = [] + ''' Plots several types of histograms related to end of tracking analysis ''' + data = [] if hist_type == "end_class": # Classification of end of trackings - for end in end_list: - if (not end_mask or end.end_class in end_mask) and (not fake_mask or end.fake_class in fake_mask) and (not BPix3mask or "BPix3" in end.last_str): - data.append(end.end_class) - self.ClassHistogram(data, "End of tracking classes", analysis.end_class_names, False) - elif hist_type == "particle_pdgId": - ids = OrderedDict() - for end in end_list: - if (not end_mask or end.end_class in end_mask) and (not fake_mask or end.fake_class in fake_mask) and (not BPix3mask or "BPix3" in end.last_str): - data.append(end.particle_pdgId) - if str(end.particle_pdgId) not in ids: - ids[end.particle_pdgId] = str(end.particle_pdgId) - self.ClassHistogram(data, "Particle pdgId", ids, False) - elif "invalid" not in hist_type: - for end in end_list: - if (not end_mask or end.end_class in end_mask) and (not fake_mask or end.fake_class in fake_mask) and (not BPix3mask or "BPix3" in end.last_str): - if hist_type == "last_layer": data.append(end.last_str.split()[0]) # split()[0] for taking only the name of the layer, skipping reason for invalid hit - elif hist_type == "fake_end_layer": data.append(end.fake_end_str.split()[0]) - elif hist_type == "particle_end_layer": data.append(end.particle_end_str.split()[0]) + for end in end_list: + if (not end_mask or end.end_class in end_mask) and (not fake_mask or end.fake_class in fake_mask) and (not BPix3mask or "BPix3" in end.last_str): + data.append(end.end_class) + self.ClassHistogram(data, "End of tracking classes", analysis.end_class_names, False) + elif hist_type == "particle_pdgId": + ids = OrderedDict() + for end in end_list: + if (not end_mask or end.end_class in end_mask) and (not fake_mask or end.fake_class in fake_mask) and (not BPix3mask or "BPix3" in end.last_str): + data.append(end.particle_pdgId) + if str(end.particle_pdgId) not in ids: + ids[end.particle_pdgId] = str(end.particle_pdgId) + self.ClassHistogram(data, "Particle pdgId", ids, False) + elif "invalid" not in hist_type: + for end in end_list: + if (not end_mask or end.end_class in end_mask) and (not fake_mask or end.fake_class in fake_mask) and (not BPix3mask or "BPix3" in end.last_str): + if hist_type == "last_layer": data.append(end.last_str.split()[0]) # split()[0] for taking only the name of the layer, skipping reason for invalid hit + elif hist_type == "fake_end_layer": data.append(end.fake_end_str.split()[0]) + elif hist_type == "particle_end_layer": data.append(end.particle_end_str.split()[0]) data_dict = copy(analysis.layer_data_tmp) - for entry in data: - #print entry - data_dict[analysis.layer_names_rev[entry]] += 1 - - if normalised: - norm_cff = analysis.Get_Normalisation_Coefficients() - for i, v in data_dict.items(): - data_dict[i] = int(round(v*norm_cff[i])) + for entry in data: + #print entry + data_dict[analysis.layer_names_rev[entry]] += 1 + + if normalised: + norm_cff = analysis.Get_Normalisation_Coefficients() + for i, v in data_dict.items(): + data_dict[i] = int(round(v*norm_cff[i])) - name = "" - if hist_type == "last_layer": name = "End of tracking layers" - elif hist_type == "fake_end_layer": name = "Fake end of tracking layers" - elif hist_type == "particle_end_layer": name = "Particle end of tracking layers" - if normalised: name += " normalised" + name = "" + if hist_type == "last_layer": name = "End of tracking layers" + elif hist_type == "fake_end_layer": name = "Fake end of tracking layers" + elif hist_type == "particle_end_layer": name = "Particle end of tracking layers" + if normalised: name += " normalised" - self.ClassHistogram(data_dict, name, analysis.layer_names , True) + self.ClassHistogram(data_dict, name, analysis.layer_names , True) - else: - if hist_type == "invalid_reason_fake": - data_dict = copy(analysis.invalid_types_tmp) - for end in end_list: - if (not end_mask or end.end_class in end_mask) and (not fake_mask or end.fake_class in fake_mask) and (not BPix3mask or "BPix3" in end.last_str): + else: + if hist_type == "invalid_reason_fake": + data_dict = copy(analysis.invalid_types_tmp) + for end in end_list: + if (not end_mask or end.end_class in end_mask) and (not fake_mask or end.fake_class in fake_mask) and (not BPix3mask or "BPix3" in end.last_str): if "missing" in end.fake_end_str: data_dict[1] += 1; #print end.fake_end_str - elif "inactive" in end.fake_end_str: data_dict[2] += 1; #print end.fake_end_str - elif "bad" in end.fake_end_str: data_dict[3] += 1; #print end.fake_end_str - elif "missing_inner" in end.fake_end_str: data_dict[4] += 1; #print end.fake_end_str - elif "missing_outer" in end.fake_end_str: data_dict[5] += 1; #print end.fake_end_str - else: data_dict[0] += 1 # valid hit - - self.ClassHistogram(data_dict, "Invalid hit reasons in fake EOT", analysis.invalid_types, True) - elif hist_type == "invalid_reason_last": - data_dict = copy(analysis.invalid_types_tmp) - for end in end_list: - if (not end_mask or end.end_class in end_mask) and (not fake_mask or end.fake_class in fake_mask) and (not BPix3mask or "BPix3" in end.last_str): + elif "inactive" in end.fake_end_str: data_dict[2] += 1; #print end.fake_end_str + elif "bad" in end.fake_end_str: data_dict[3] += 1; #print end.fake_end_str + elif "missing_inner" in end.fake_end_str: data_dict[4] += 1; #print end.fake_end_str + elif "missing_outer" in end.fake_end_str: data_dict[5] += 1; #print end.fake_end_str + else: data_dict[0] += 1 # valid hit + + self.ClassHistogram(data_dict, "Invalid hit reasons in fake EOT", analysis.invalid_types, True) + elif hist_type == "invalid_reason_last": + data_dict = copy(analysis.invalid_types_tmp) + for end in end_list: + if (not end_mask or end.end_class in end_mask) and (not fake_mask or end.fake_class in fake_mask) and (not BPix3mask or "BPix3" in end.last_str): if "missing" in end.last_str: data_dict[1] += 1 - elif "inactive" in end.last_str: data_dict[2] += 1 - elif "bad" in end.last_str: data_dict[3] += 1 - elif "missing_inner" in end.last_str: data_dict[4] += 1 - elif "missing_outer" in end.last_str: data_dict[5] += 1 - else: data_dict[0] += 1 # valid hit - - self.ClassHistogram(data_dict, "Invalid hit reasons in EOT last shared hit", analysis.invalid_types, True) - elif hist_type == "invalid_reason_particle": - data_dict = copy(analysis.invalid_types_tmp) - for end in end_list: - if (not end_mask or end.end_class in end_mask) and (not fake_mask or end.fake_class in fake_mask) and (not BPix3mask or "BPix3" in end.last_str): + elif "inactive" in end.last_str: data_dict[2] += 1 + elif "bad" in end.last_str: data_dict[3] += 1 + elif "missing_inner" in end.last_str: data_dict[4] += 1 + elif "missing_outer" in end.last_str: data_dict[5] += 1 + else: data_dict[0] += 1 # valid hit + + self.ClassHistogram(data_dict, "Invalid hit reasons in EOT last shared hit", analysis.invalid_types, True) + elif hist_type == "invalid_reason_particle": + data_dict = copy(analysis.invalid_types_tmp) + for end in end_list: + if (not end_mask or end.end_class in end_mask) and (not fake_mask or end.fake_class in fake_mask) and (not BPix3mask or "BPix3" in end.last_str): if "missing" in end.particle_end_str: data_dict[1] += 1 - elif "inactive" in end.particle_end_str: data_dict[2] += 1 - elif "bad" in end.particle_end_str: data_dict[3] += 1 - elif "missing_inner" in end.particle_end_str: data_dict[4] += 1 - elif "missing_outer" in end.particle_end_str: data_dict[5] += 1 - else: data_dict[0] += 1 # valid hit + elif "inactive" in end.particle_end_str: data_dict[2] += 1 + elif "bad" in end.particle_end_str: data_dict[3] += 1 + elif "missing_inner" in end.particle_end_str: data_dict[4] += 1 + elif "missing_outer" in end.particle_end_str: data_dict[5] += 1 + else: data_dict[0] += 1 # valid hit - self.ClassHistogram(data_dict, "Invalid hit reasons in particle EOT", analysis.invalid_types, True) + self.ClassHistogram(data_dict, "Invalid hit reasons in particle EOT", analysis.invalid_types, True) def ResolutionHistograms(self, res_data, tracks = "fake", fake_mask = [], draw = True, skip = True, normalised = False): - ''' - Returns (and possibly draws) resolution histograms for the ResolutionData object. ''' - if tracks == "fake": - if fake_mask: - res_tmp = analysis.ResolutionData() - for i in range(len(res_data)): - if res_data.fake_class in fake_mask: - res_tmp.pt.append(res_data.pt[i]) - res_tmp.eta.append(res_data.eta[i]) - res_tmp.Lambda.append(res_data.Lambda[i]) - res_tmp.cotTheta.append(res_data.cotTheta[i]) - res_tmp.phi.append(res_data.phi[i]) - res_tmp.dxy.append(res_data.dxy[i]) - res_tmp.dz.append(res_data.dz[i]) - res_tmp.fake_class.append(res_data.fake_class[i]) - - res_data = res_tmp - color = ROOT.kRed - elif tracks == "true": - if normalised: color = ROOT.kBlue - else: color = 38 - else: - print("Unspecified data type") - return - - c1 = ROOT.TCanvas("Resolution_histograms","Resolution histograms", 1000, 900) - c1.Divide(3,3) - c1.SetGrid() - #c1.SetLogy() + Returns (and possibly draws) resolution histograms for the ResolutionData object. + ''' + if tracks == "fake": + if fake_mask: + res_tmp = analysis.ResolutionData() + for i in range(len(res_data)): + if res_data.fake_class in fake_mask: + res_tmp.pt.append(res_data.pt[i]) + res_tmp.eta.append(res_data.eta[i]) + res_tmp.Lambda.append(res_data.Lambda[i]) + res_tmp.cotTheta.append(res_data.cotTheta[i]) + res_tmp.phi.append(res_data.phi[i]) + res_tmp.dxy.append(res_data.dxy[i]) + res_tmp.dz.append(res_data.dz[i]) + res_tmp.fake_class.append(res_data.fake_class[i]) + + res_data = res_tmp + color = ROOT.kRed + elif tracks == "true": + if normalised: color = ROOT.kBlue + else: color = 38 + else: + print("Unspecified data type") + return + + c1 = ROOT.TCanvas("Resolution_histograms","Resolution histograms", 1000, 900) + c1.Divide(3,3) + c1.SetGrid() + #c1.SetLogy() histograms = [] - c1.cd(1) - histograms.append( self.Histogram1D([res.pt_delta/res.pt_rec for res in res_data], "Resolution of #Delta p_{t}/p_{t,rec} in " + tracks + " tracks", 100, -0.15, 0.15, "p_{t}/p_{t,rec}", color, draw, normalised) ) - c1.GetPad(1).SetLogy() - c1.cd(2) - if not skip: histograms.append( self.Histogram1D(res_data.eta, "Resolution of #eta in " + tracks + " tracks", 100, -0.02, 0.02, "#eta", color, draw, normalised) ) - c1.GetPad(2).SetLogy() - c1.cd(3) - if not skip: histograms.append( self.Histogram1D(res_data.Lambda, "Resolution of #lambda in " + tracks + " tracks", 100, -0.015, 0.015, "#lambda", color, draw, normalised) ) - c1.GetPad(3).SetLogy() - c1.cd(4) - histograms.append( self.Histogram1D(res_data.cotTheta, "Resolution of cot(#theta) in " + tracks + " tracks", 100, -0.03, 0.03, "cot(#theta)", color, draw, normalised) ) - c1.GetPad(4).SetLogy() - c1.cd(5) - histograms.append( self.Histogram1D(res_data.phi, "Resolution of #phi in " + tracks + " tracks", 100, -0.03, 0.03, "#phi", color, draw, normalised) ) - c1.GetPad(5).SetLogy() - c1.cd(6) - histograms.append( self.Histogram1D(res_data.dxy, "Resolution of dxy in " + tracks + " tracks", 100, -0.15, 0.15, "dxy", color, draw, normalised) ) - c1.GetPad(6).SetLogy() - c1.cd(7) - histograms.append( self.Histogram1D(res_data.dz, "Resolution of dz in " + tracks + " tracks", 100, -0.15, 0.15, "dz", color, draw, normalised) ) - c1.GetPad(7).SetLogy() - #c1.SetLogy() - if draw: - c1.Draw() - input("Press enter to continue") - - return histograms + c1.cd(1) + histograms.append( self.Histogram1D([res.pt_delta/res.pt_rec for res in res_data], "Resolution of #Delta p_{t}/p_{t,rec} in " + tracks + " tracks", 100, -0.15, 0.15, "p_{t}/p_{t,rec}", color, draw, normalised) ) + c1.GetPad(1).SetLogy() + c1.cd(2) + if not skip: histograms.append( self.Histogram1D(res_data.eta, "Resolution of #eta in " + tracks + " tracks", 100, -0.02, 0.02, "#eta", color, draw, normalised) ) + c1.GetPad(2).SetLogy() + c1.cd(3) + if not skip: histograms.append( self.Histogram1D(res_data.Lambda, "Resolution of #lambda in " + tracks + " tracks", 100, -0.015, 0.015, "#lambda", color, draw, normalised) ) + c1.GetPad(3).SetLogy() + c1.cd(4) + histograms.append( self.Histogram1D(res_data.cotTheta, "Resolution of cot(#theta) in " + tracks + " tracks", 100, -0.03, 0.03, "cot(#theta)", color, draw, normalised) ) + c1.GetPad(4).SetLogy() + c1.cd(5) + histograms.append( self.Histogram1D(res_data.phi, "Resolution of #phi in " + tracks + " tracks", 100, -0.03, 0.03, "#phi", color, draw, normalised) ) + c1.GetPad(5).SetLogy() + c1.cd(6) + histograms.append( self.Histogram1D(res_data.dxy, "Resolution of dxy in " + tracks + " tracks", 100, -0.15, 0.15, "dxy", color, draw, normalised) ) + c1.GetPad(6).SetLogy() + c1.cd(7) + histograms.append( self.Histogram1D(res_data.dz, "Resolution of dz in " + tracks + " tracks", 100, -0.15, 0.15, "dz", color, draw, normalised) ) + c1.GetPad(7).SetLogy() + #c1.SetLogy() + if draw: + c1.Draw() + input("Press enter to continue") + + return histograms def ResolutionHistogramsCombine(self, res_data_trues, res_data_fakes, fake_mask = [], draw = True): - ''' + ''' Combines resolutionhistograms for true and matched fake tracks to a single set of histograms. - ''' - true_hists = self.ResolutionHistograms(res_data_trues, "true", [], False, True) - fake_hists = self.ResolutionHistograms(res_data_fakes, "fake", fake_mask, False, True) + ''' + true_hists = self.ResolutionHistograms(res_data_trues, "true", [], False, True) + fake_hists = self.ResolutionHistograms(res_data_fakes, "fake", fake_mask, False, True) - c1 = ROOT.TCanvas("Resolution_histograms","Resolution histograms", 700, 900) - c1.Divide(2,3) - c1.SetGrid() + c1 = ROOT.TCanvas("Resolution_histograms","Resolution histograms", 700, 900) + c1.Divide(2,3) + c1.SetGrid() histograms = [] - for i in range(len(true_hists)): - c1.cd(i+1) - histograms.append( self.Histogram1DStacked(true_hists[i], fake_hists[i], true_hists[i].GetName() + " stacked") ) - c1.GetPad(i+1).SetLogy() + for i in range(len(true_hists)): + c1.cd(i+1) + histograms.append( self.Histogram1DStacked(true_hists[i], fake_hists[i], true_hists[i].GetName() + " stacked") ) + c1.GetPad(i+1).SetLogy() - - c1.cd(i+2) + + c1.cd(i+2) leg = ROOT.TLegend(0.,0.2,0.99,0.8) - leg.AddEntry(true_hists[0], "True tracks", "F") - leg.AddEntry(fake_hists[0], "Fake tracks", "F") - leg.Draw() - + leg.AddEntry(true_hists[0], "True tracks", "F") + leg.AddEntry(fake_hists[0], "Fake tracks", "F") + leg.Draw() + - if draw: - c1.Draw() - input("Press enter to continue") - - return histograms + if draw: + c1.Draw() + input("Press enter to continue") + + return histograms def ResolutionHistogramsNormalised(self, res_data_trues, res_data_fakes, fake_mask = [], draw = True): - ''' + ''' Plots the resolution histograms of true tracks and matched fake tracks, normalised to have an area of 1. - ''' - true_hists = self.ResolutionHistograms(res_data_trues, "true", [], False, True, True) - fake_hists = self.ResolutionHistograms(res_data_fakes, "fake", fake_mask, False, True, True) + ''' + true_hists = self.ResolutionHistograms(res_data_trues, "true", [], False, True, True) + fake_hists = self.ResolutionHistograms(res_data_fakes, "fake", fake_mask, False, True, True) - c1 = ROOT.TCanvas("Resolution_histograms","Resolution histograms", 1100, 700) #700, 900) - c1.Divide(3,2) - c1.SetGrid() + c1 = ROOT.TCanvas("Resolution_histograms","Resolution histograms", 1100, 700) #700, 900) + c1.Divide(3,2) + c1.SetGrid() #histograms = [] - for i in range(len(true_hists)): - c1.cd(i+1) - #true_hists[i].SetTitle("#splitline{True tracks: " + true_hists[i].GetTitle() + "}{Fake tracks: " + fake_hists[i].GetTitle() + "}") - true_hists[i].SetTitle("Resolution of " + fake_hists[i].GetXaxis().GetTitle()) - true_hists[i].GetXaxis().SetTitle("#Delta" + true_hists[i].GetXaxis().GetTitle()) - #true_hists[i].SetTitleOffset(1.2) - #c1.SetTopMargin(0.9) - true_hists[i].DrawNormalized("") - fake_hists[i].DrawNormalized("Same") - #histograms.append( self.Histogram1DStacked(true_hists[i], fake_hists[i], true_hists[i].GetName() + " stacked") ) - #c1.GetPad(i+1).SetLogy() - - - c1.cd(i+2) + for i in range(len(true_hists)): + c1.cd(i+1) + #true_hists[i].SetTitle("#splitline{True tracks: " + true_hists[i].GetTitle() + "}{Fake tracks: " + fake_hists[i].GetTitle() + "}") + true_hists[i].SetTitle("Resolution of " + fake_hists[i].GetXaxis().GetTitle()) + true_hists[i].GetXaxis().SetTitle("#Delta" + true_hists[i].GetXaxis().GetTitle()) + #true_hists[i].SetTitleOffset(1.2) + #c1.SetTopMargin(0.9) + true_hists[i].DrawNormalized("") + fake_hists[i].DrawNormalized("Same") + #histograms.append( self.Histogram1DStacked(true_hists[i], fake_hists[i], true_hists[i].GetName() + " stacked") ) + #c1.GetPad(i+1).SetLogy() + + + c1.cd(i+2) leg = ROOT.TLegend(0.1,0.3,0.9,0.7) - leg.AddEntry(true_hists[0], "True tracks", "L") - leg.AddEntry(fake_hists[0], "Fake tracks", "L") - leg.Draw() - - - if draw: - c1.Draw() - input("Press enter to continue") - - #return histograms + leg.AddEntry(true_hists[0], "True tracks", "L") + leg.AddEntry(fake_hists[0], "Fake tracks", "L") + leg.Draw() + + + if draw: + c1.Draw() + input("Press enter to continue") + + #return histograms def ResolutionHistogramsNormalisedCumulative(self, res_data_trues, res_data_fakes, fake_mask = [], draw = True): - ''' + ''' Plots the cumulative resolution histograms of true tracks and matched fake tracks from the normalised histograms from the previous method. - ''' - true_hists = self.ResolutionHistograms(res_data_trues, "true", [], False, True, True) - fake_hists = self.ResolutionHistograms(res_data_fakes, "fake", fake_mask, False, True, True) + ''' + true_hists = self.ResolutionHistograms(res_data_trues, "true", [], False, True, True) + fake_hists = self.ResolutionHistograms(res_data_fakes, "fake", fake_mask, False, True, True) - c1 = ROOT.TCanvas("Resolution_histograms","Resolution histograms", 1100, 700) #700, 900) - c1.Divide(3,2) - c1.SetGrid() + c1 = ROOT.TCanvas("Resolution_histograms","Resolution histograms", 1100, 700) #700, 900) + c1.Divide(3,2) + c1.SetGrid() #histograms = [] - for i in range(len(true_hists)): - c1.cd(i+1) - true_hists[i].SetTitle("Cumulative resolution of " + fake_hists[i].GetXaxis().GetTitle()) - true_hists[i].GetXaxis().SetTitle("#Delta" + true_hists[i].GetXaxis().GetTitle()) - #true_hists[i].SetTitleOffset(1.2) - #c1.SetTopMargin(0.9) - for res in res_data_trues: - if i == 0 and res.pt_delta/res.pt_rec < -0.15: true_hists[i].Fill(-0.15) - if i == 1 and res.cotTheta < -0.03: true_hists[i].Fill(-0.03) - if i == 2 and res.phi < -0.03: true_hists[i].Fill(-0.03) - if i == 3 and res.dxy < -0.15: true_hists[i].Fill(-0.15) - if i == 4 and res.dz < -0.15: true_hists[i].Fill(-0.15) - for res in res_data_fakes: - if i == 0 and res.pt_delta/res.pt_rec < -0.15: fake_hists[i].Fill(-0.15) - if i == 1 and res.cotTheta < -0.03: fake_hists[i].Fill(-0.03) - if i == 2 and res.phi < -0.03: fake_hists[i].Fill(-0.03) - if i == 3 and res.dxy < -0.15: fake_hists[i].Fill(-0.15) - if i == 4 and res.dz < -0.15: fake_hists[i].Fill(-0.15) - true_hists[i].Scale(1.0/len(res_data_trues.pt_rec)) - fake_hists[i].Scale(1.0/len(res_data_fakes.pt_rec)) - #c1.GetPad(i+1).Clear() - true_hists[i].GetCumulative().Draw("") - fake_hists[i].GetCumulative().Draw("Same") - - c1.cd(i+2) + for i in range(len(true_hists)): + c1.cd(i+1) + true_hists[i].SetTitle("Cumulative resolution of " + fake_hists[i].GetXaxis().GetTitle()) + true_hists[i].GetXaxis().SetTitle("#Delta" + true_hists[i].GetXaxis().GetTitle()) + #true_hists[i].SetTitleOffset(1.2) + #c1.SetTopMargin(0.9) + for res in res_data_trues: + if i == 0 and res.pt_delta/res.pt_rec < -0.15: true_hists[i].Fill(-0.15) + if i == 1 and res.cotTheta < -0.03: true_hists[i].Fill(-0.03) + if i == 2 and res.phi < -0.03: true_hists[i].Fill(-0.03) + if i == 3 and res.dxy < -0.15: true_hists[i].Fill(-0.15) + if i == 4 and res.dz < -0.15: true_hists[i].Fill(-0.15) + for res in res_data_fakes: + if i == 0 and res.pt_delta/res.pt_rec < -0.15: fake_hists[i].Fill(-0.15) + if i == 1 and res.cotTheta < -0.03: fake_hists[i].Fill(-0.03) + if i == 2 and res.phi < -0.03: fake_hists[i].Fill(-0.03) + if i == 3 and res.dxy < -0.15: fake_hists[i].Fill(-0.15) + if i == 4 and res.dz < -0.15: fake_hists[i].Fill(-0.15) + true_hists[i].Scale(1.0/len(res_data_trues.pt_rec)) + fake_hists[i].Scale(1.0/len(res_data_fakes.pt_rec)) + #c1.GetPad(i+1).Clear() + true_hists[i].GetCumulative().Draw("") + fake_hists[i].GetCumulative().Draw("Same") + + c1.cd(i+2) leg = ROOT.TLegend(0.1,0.3,0.9,0.7) - leg.AddEntry(true_hists[0], "True tracks", "L") - leg.AddEntry(fake_hists[0], "Fake tracks", "L") - leg.Draw() - + leg.AddEntry(true_hists[0], "True tracks", "L") + leg.AddEntry(fake_hists[0], "Fake tracks", "L") + leg.Draw() + - if draw: - c1.Draw() - input("Press enter to continue") + if draw: + c1.Draw() + input("Press enter to continue") def Histogram1D(self, data, name = "Histogram", nbins = 100, xmin = -1, xmax = 1, xlabel = "", color = 38, draw = True, normalised = False): - ''' Creates a single histogram of resolutions for one parameter list ''' - - hist = ROOT.TH1F(name, name, nbins, xmin, xmax) - - hist.SetStats(0); - if normalised: - hist.SetLineColor(color) - hist.SetLineWidth(1) - else: - hist.SetFillColor(color); - hist.GetXaxis().SetTitle(xlabel) - #hist.SetCanExtend(ROOT.TH1.kAllAxes); - for entry in data: hist.Fill(entry,1) - - f = ROOT.TF1("f1", "gaus", xmin, xmax) - hist.Fit(f,"0") - - hist.SetTitle("#sigma(#Delta" + xlabel + ") = " + str(f.GetParameter("Sigma"))[0:8]) - - if draw: hist.Draw() - return hist - - #input("Press any key to continue") + ''' Creates a single histogram of resolutions for one parameter list ''' + + hist = ROOT.TH1F(name, name, nbins, xmin, xmax) + + hist.SetStats(0); + if normalised: + hist.SetLineColor(color) + hist.SetLineWidth(1) + else: + hist.SetFillColor(color); + hist.GetXaxis().SetTitle(xlabel) + #hist.SetCanExtend(ROOT.TH1.kAllAxes); + for entry in data: hist.Fill(entry,1) + + f = ROOT.TF1("f1", "gaus", xmin, xmax) + hist.Fit(f,"0") + + hist.SetTitle("#sigma(#Delta" + xlabel + ") = " + str(f.GetParameter("Sigma"))[0:8]) + + if draw: hist.Draw() + return hist + + #input("Press any key to continue") def HistogramSigmaPt(self, data, name = "Sigma(Pt) vs Pt"): # Old function - c1 = ROOT.TCanvas(name, name, 700, 500) - c1.SetLogx() - c1.SetLogy() - - hist = ROOT.TH2F(name, name, 10, array("d",[10**(i/10.0) for i in range(-10, 12, 2)]), 100, -0.15, 0.15) - - for res in data: - hist.Fill(res.pt_sim, res.pt_delta/res.pt_rec) - - hist.FitSlicesY() - hist_2 = ROOT.gDirectory.Get(name + "_2") + c1 = ROOT.TCanvas(name, name, 700, 500) + c1.SetLogx() + c1.SetLogy() + + hist = ROOT.TH2F(name, name, 10, array("d",[10**(i/10.0) for i in range(-10, 12, 2)]), 100, -0.15, 0.15) + + for res in data: + hist.Fill(res.pt_sim, res.pt_delta/res.pt_rec) + + hist.FitSlicesY() + hist_2 = ROOT.gDirectory.Get(name + "_2") - hist_2.GetXaxis().SetTitle("p_{t,sim}") - hist_2.GetYaxis().SetTitle("#sigma(#Delta p_{t}/p_{t,res})") + hist_2.GetXaxis().SetTitle("p_{t,sim}") + hist_2.GetYaxis().SetTitle("#sigma(#Delta p_{t}/p_{t,res})") - hist_2.Draw() + hist_2.Draw() - input("Press enter to continue") + input("Press enter to continue") def HistogramSigmaPtCombined(self, data1, data2, name = "Sigma(Pt) vs Pt"): # Old function - c1 = ROOT.TCanvas(name, name, 700, 500) - c1.SetLogx() - c1.SetLogy() - - hist = ROOT.TH2F(name, name, 10, array("d",[10**(i/10.0) for i in range(-10, 12, 2)]), 100, -0.15, 0.15) - - for res in data1: - hist.Fill(res.pt_sim, res.pt_delta/res.pt_rec) - for res in data2: - hist.Fill(res.pt_sim, res.pt_delta/res.pt_rec) - - hist.FitSlicesY() - hist_2 = ROOT.gDirectory.Get(name + "_2") - - hist_2.GetXaxis().SetTitle("p_{t,sim}") - hist_2.GetYaxis().SetTitle("#sigma(#Delta p_{t}/p_{t,rec})") - - hist_2.Draw() - - input("Press enter to continue") + c1 = ROOT.TCanvas(name, name, 700, 500) + c1.SetLogx() + c1.SetLogy() + + hist = ROOT.TH2F(name, name, 10, array("d",[10**(i/10.0) for i in range(-10, 12, 2)]), 100, -0.15, 0.15) + + for res in data1: + hist.Fill(res.pt_sim, res.pt_delta/res.pt_rec) + for res in data2: + hist.Fill(res.pt_sim, res.pt_delta/res.pt_rec) + + hist.FitSlicesY() + hist_2 = ROOT.gDirectory.Get(name + "_2") + + hist_2.GetXaxis().SetTitle("p_{t,sim}") + hist_2.GetYaxis().SetTitle("#sigma(#Delta p_{t}/p_{t,rec})") + + hist_2.Draw() + + input("Press enter to continue") def HistogramSigmaPtDual(self, data1, data2, parameter = "pt", pad = None, name = "Sigma(parameter) vs Pt"): - ''' - Plots the sigma parameter from Gaussian fits to a single parameter resolution with respect to simulated particle pt. + ''' + Plots the sigma parameter from Gaussian fits to a single parameter resolution with respect to simulated particle pt. - data1 = True tracks, data2 = Fake track - ''' - + data1 = True tracks, data2 = Fake track + ''' + - if not pad: - c1 = ROOT.TCanvas(name, name, 700, 500) - c1.SetLogx() - c1.SetLogy() - else: - pad.SetLogx() - pad.SetLogy() - - hist1 = ROOT.TH2F(name, name, 10, array("d",[10**(i/10.0) for i in range(-10, 12, 2)]), 100, -0.15, 0.15) - hist2 = ROOT.TH2F(name + "_h2", name + "_h2", 10, array("d",[10**(i/10.0) for i in range(-10, 12, 2)]), 100, -0.15, 0.15) - hist3 = ROOT.TH2F(name + "_h3", name + "_h3", 10, array("d",[10**(i/10.0) for i in range(-10, 12, 2)]), 100, -0.15, 0.15) - - #print min(data.pt_sim) - for res in data1: - if parameter == "pt": hist1.Fill(res.pt_sim, res.pt_delta/res.pt_rec) - if parameter == "cotTheta": hist1.Fill(res.pt_sim, res.cotTheta) - if parameter == "phi": hist1.Fill(res.pt_sim, res.phi) - if parameter == "dxy": hist1.Fill(res.pt_sim, res.dxy) - if parameter == "dz": hist1.Fill(res.pt_sim, res.dz) - for res in data2: - if parameter == "pt": hist2.Fill(res.pt_sim, res.pt_delta/res.pt_rec) - if parameter == "cotTheta": hist2.Fill(res.pt_sim, res.cotTheta) - if parameter == "phi": hist2.Fill(res.pt_sim, res.phi) - if parameter == "dxy": hist2.Fill(res.pt_sim, res.dxy) - if parameter == "dz": hist2.Fill(res.pt_sim, res.dz) + if not pad: + c1 = ROOT.TCanvas(name, name, 700, 500) + c1.SetLogx() + c1.SetLogy() + else: + pad.SetLogx() + pad.SetLogy() + + hist1 = ROOT.TH2F(name, name, 10, array("d",[10**(i/10.0) for i in range(-10, 12, 2)]), 100, -0.15, 0.15) + hist2 = ROOT.TH2F(name + "_h2", name + "_h2", 10, array("d",[10**(i/10.0) for i in range(-10, 12, 2)]), 100, -0.15, 0.15) + hist3 = ROOT.TH2F(name + "_h3", name + "_h3", 10, array("d",[10**(i/10.0) for i in range(-10, 12, 2)]), 100, -0.15, 0.15) + + #print min(data.pt_sim) + for res in data1: + if parameter == "pt": hist1.Fill(res.pt_sim, res.pt_delta/res.pt_rec) + if parameter == "cotTheta": hist1.Fill(res.pt_sim, res.cotTheta) + if parameter == "phi": hist1.Fill(res.pt_sim, res.phi) + if parameter == "dxy": hist1.Fill(res.pt_sim, res.dxy) + if parameter == "dz": hist1.Fill(res.pt_sim, res.dz) + for res in data2: + if parameter == "pt": hist2.Fill(res.pt_sim, res.pt_delta/res.pt_rec) + if parameter == "cotTheta": hist2.Fill(res.pt_sim, res.cotTheta) + if parameter == "phi": hist2.Fill(res.pt_sim, res.phi) + if parameter == "dxy": hist2.Fill(res.pt_sim, res.dxy) + if parameter == "dz": hist2.Fill(res.pt_sim, res.dz) hist3.Add(hist1) - hist3.Add(hist2) + hist3.Add(hist2) - hist1.FitSlicesY() - hist1_2 = ROOT.gDirectory.Get(name + "_2") + hist1.FitSlicesY() + hist1_2 = ROOT.gDirectory.Get(name + "_2") hist1_2.SetLineColor(ROOT.kBlue) - #hist1_2.GetYaxis().SetRange(0.01, 1) - - hist2.FitSlicesY() - hist2_2 = ROOT.gDirectory.Get(name + "_h2" + "_2") - hist2_2.SetLineColor(ROOT.kRed) - - hist2_2.GetXaxis().SetTitle("p_{t,sim}") - hist2_2.SetTitleSize(0.04,"xy") - if parameter == "pt": - hist2_2.GetYaxis().SetTitle("#sigma(#Delta p_{t}/p_{t,rec})") - hist2_2.SetMaximum(1.5) - hist2_2.SetMinimum(0.003) - if parameter == "cotTheta": - hist2_2.GetYaxis().SetTitle("#sigma(#Delta cot(#theta))") - hist2_2.SetMaximum(1.0) - hist2_2.SetMinimum(0.0005) - if parameter == "phi": - hist2_2.GetYaxis().SetTitle("#sigma(#Delta #phi)") - hist2_2.SetMaximum(1.0) - hist2_2.SetMinimum(0.0005) - if parameter == "dxy": - hist2_2.GetYaxis().SetTitle("#sigma(#Delta dxy)") - hist2_2.SetMaximum(1.3) - hist2_2.SetMinimum(0.0005) - if parameter == "dz": - hist2_2.GetYaxis().SetTitle("#sigma(#Delta dz)") - hist2_2.SetMaximum(1.5) - hist2_2.SetMinimum(0.0005) - - - hist2_2.SetStats(0) - hist2_2.SetTitle("") - - hist3.FitSlicesY() - hist3_2 = ROOT.gDirectory.Get(name + "_h3" + "_2") - hist3_2.SetLineColor(ROOT.kViolet) - - hist2_2.Draw() - hist3_2.Draw("Same") - hist1_2.Draw("Same") + #hist1_2.GetYaxis().SetRange(0.01, 1) + + hist2.FitSlicesY() + hist2_2 = ROOT.gDirectory.Get(name + "_h2" + "_2") + hist2_2.SetLineColor(ROOT.kRed) + + hist2_2.GetXaxis().SetTitle("p_{t,sim}") + hist2_2.SetTitleSize(0.04,"xy") + if parameter == "pt": + hist2_2.GetYaxis().SetTitle("#sigma(#Delta p_{t}/p_{t,rec})") + hist2_2.SetMaximum(1.5) + hist2_2.SetMinimum(0.003) + if parameter == "cotTheta": + hist2_2.GetYaxis().SetTitle("#sigma(#Delta cot(#theta))") + hist2_2.SetMaximum(1.0) + hist2_2.SetMinimum(0.0005) + if parameter == "phi": + hist2_2.GetYaxis().SetTitle("#sigma(#Delta #phi)") + hist2_2.SetMaximum(1.0) + hist2_2.SetMinimum(0.0005) + if parameter == "dxy": + hist2_2.GetYaxis().SetTitle("#sigma(#Delta dxy)") + hist2_2.SetMaximum(1.3) + hist2_2.SetMinimum(0.0005) + if parameter == "dz": + hist2_2.GetYaxis().SetTitle("#sigma(#Delta dz)") + hist2_2.SetMaximum(1.5) + hist2_2.SetMinimum(0.0005) + + + hist2_2.SetStats(0) + hist2_2.SetTitle("") + + hist3.FitSlicesY() + hist3_2 = ROOT.gDirectory.Get(name + "_h3" + "_2") + hist3_2.SetLineColor(ROOT.kViolet) + + hist2_2.Draw() + hist3_2.Draw("Same") + hist1_2.Draw("Same") + + ''' + leg = ROOT.TLegend(0.25,0.75,0.45,0.9) + leg.AddEntry(hist1_2, "True tracks", "L") + leg.AddEntry(hist2_2, "Fake tracks", "L") + leg.AddEntry(hist3_2, "Both", "L") + leg.Draw() - ''' - leg = ROOT.TLegend(0.25,0.75,0.45,0.9) - leg.AddEntry(hist1_2, "True tracks", "L") - leg.AddEntry(hist2_2, "Fake tracks", "L") - leg.AddEntry(hist3_2, "Both", "L") - leg.Draw() - - input("Press enter to continue") - ''' - return [hist1_2, hist2_2, hist3_2] + input("Press enter to continue") + ''' + return [hist1_2, hist2_2, hist3_2] def ResolutionsSigmaVsPt(self, res_data_trues, res_data_fakes, fake_mask = [], draw = True): ''' Plots the sigma parameter from Gaussian fits to all parameter resolutions with respect to simulated particle pt. - ''' + ''' - c1 = ROOT.TCanvas("Resolution_sigma_vs_pt","Resolution_sigma_vs_pt", 1100, 700) #700, 900) - c1.Divide(3,2) - c1.SetGrid() + c1 = ROOT.TCanvas("Resolution_sigma_vs_pt","Resolution_sigma_vs_pt", 1100, 700) #700, 900) + c1.Divide(3,2) + c1.SetGrid() hists_tmp = [] - pad = c1.cd(1) - hists_tmp.append(self.HistogramSigmaPtDual(res_data_trues, res_data_fakes, "pt", pad, "pt")) - pad = c1.cd(2) - hists_tmp.append(self.HistogramSigmaPtDual(res_data_trues, res_data_fakes, "cotTheta", pad, "cotTheta")) - pad = c1.cd(3) - hists_tmp.append(self.HistogramSigmaPtDual(res_data_trues, res_data_fakes, "phi", pad, "phi")) - pad = c1.cd(4) - hists_tmp.append(self.HistogramSigmaPtDual(res_data_trues, res_data_fakes, "dxy", pad, "dxy")) - pad = c1.cd(5) - hists = self.HistogramSigmaPtDual(res_data_trues, res_data_fakes, "dz", pad, "dz") - hists_tmp.append(hists) - - c1.cd(6) + pad = c1.cd(1) + hists_tmp.append(self.HistogramSigmaPtDual(res_data_trues, res_data_fakes, "pt", pad, "pt")) + pad = c1.cd(2) + hists_tmp.append(self.HistogramSigmaPtDual(res_data_trues, res_data_fakes, "cotTheta", pad, "cotTheta")) + pad = c1.cd(3) + hists_tmp.append(self.HistogramSigmaPtDual(res_data_trues, res_data_fakes, "phi", pad, "phi")) + pad = c1.cd(4) + hists_tmp.append(self.HistogramSigmaPtDual(res_data_trues, res_data_fakes, "dxy", pad, "dxy")) + pad = c1.cd(5) + hists = self.HistogramSigmaPtDual(res_data_trues, res_data_fakes, "dz", pad, "dz") + hists_tmp.append(hists) + + c1.cd(6) leg = ROOT.TLegend(0.1,0.3,0.9,0.7) - leg.AddEntry(hists[0], "True tracks", "L") - leg.AddEntry(hists[1], "Fake tracks", "L") - leg.AddEntry(hists[2], "Both", "L") - leg.Draw() - + leg.AddEntry(hists[0], "True tracks", "L") + leg.AddEntry(hists[1], "Fake tracks", "L") + leg.AddEntry(hists[2], "Both", "L") + leg.Draw() + - if draw: - c1.Draw() - input("Press enter to continue") - + if draw: + c1.Draw() + input("Press enter to continue") + def Histogram1DStacked(self, hist1, hist2, name): # Old function hist_stack = ROOT.THStack(name, name) - hist_stack.Add(hist2) - hist_stack.Add(hist1) - - hist = ROOT.TH1F(hist1) - hist.Add(hist2) - f = ROOT.TF1("f1", "gaus", hist.GetXaxis().GetXmin(), hist.GetXaxis().GetXmax()) - hist.Fit(f,"0") - hist_stack.SetTitle("#sigma(" + hist.GetXaxis().GetTitle() + ") = " + str(f.GetParameter("Sigma"))) - hist_stack.Draw()#("nostack") - hist_stack.GetXaxis().SetTitle(hist.GetXaxis().GetTitle()) - - #hist_stack.Draw("nostack") - return hist_stack + hist_stack.Add(hist2) + hist_stack.Add(hist1) + + hist = ROOT.TH1F(hist1) + hist.Add(hist2) + f = ROOT.TF1("f1", "gaus", hist.GetXaxis().GetXmin(), hist.GetXaxis().GetXmax()) + hist.Fit(f,"0") + hist_stack.SetTitle("#sigma(" + hist.GetXaxis().GetTitle() + ") = " + str(f.GetParameter("Sigma"))) + hist_stack.Draw()#("nostack") + hist_stack.GetXaxis().SetTitle(hist.GetXaxis().GetTitle()) + + #hist_stack.Draw("nostack") + return hist_stack def Histogram1D_Draw(self, data, name = "Histogram", nbins = 10): # Old function - c1 = ROOT.TCanvas(name, name, 700, 500) - #if "pt " in name: c1.SetLogx() - c1.SetGrid() - - hist = ROOT.TH1F(name, name, nbins, min(data),max(data)) - c1.SetLogy() - - hist.SetStats(0); + c1 = ROOT.TCanvas(name, name, 700, 500) + #if "pt " in name: c1.SetLogx() + c1.SetGrid() + + hist = ROOT.TH1F(name, name, nbins, min(data),max(data)) + c1.SetLogy() + + hist.SetStats(0); hist.SetFillColor(38); - #hist.SetCanExtend(ROOT.TH1.kAllAxes); - for entry in data: hist.Fill(entry,1) - hist.Draw() + #hist.SetCanExtend(ROOT.TH1.kAllAxes); + for entry in data: hist.Fill(entry,1) + hist.Draw() def Draw(self): ''' Draws everything else except histograms. ''' - if self.plots_3D: - c3 = ROOT.TCanvas("3D Plot","3D Plot", 1200, 1200) - axis = ROOT.TAxis3D() - axis.SetXTitle("z") - axis.SetYTitle("x") - axis.SetZTitle("y") - #axis.GetZaxis().RotateTitle() - - for plot in self.plots_3D: - if plot: plot.Draw() - #axis.SetAxisRange(-278,278,"Z") - axis.Draw() - axis.ToggleZoom() - - if self.plots_2D: - c2 = ROOT.TCanvas("2D Plot","2D Plot", 1200, 1200) - #axis = ROOT.TAxis() - - for plot in self.plots_2D: - plot.Draw("A") - #axis.Draw() - - ''' - plots = ROOT.TMultiGraph() - for plot in self.plots_2D: - plots.Add(plot) #plot.Draw("A") + if self.plots_3D: + c3 = ROOT.TCanvas("3D Plot","3D Plot", 1200, 1200) + axis = ROOT.TAxis3D() + axis.SetXTitle("z") + axis.SetYTitle("x") + axis.SetZTitle("y") + #axis.GetZaxis().RotateTitle() + + for plot in self.plots_3D: + if plot: plot.Draw() + #axis.SetAxisRange(-278,278,"Z") + axis.Draw() + axis.ToggleZoom() + + if self.plots_2D: + c2 = ROOT.TCanvas("2D Plot","2D Plot", 1200, 1200) + #axis = ROOT.TAxis() + + for plot in self.plots_2D: + plot.Draw("A") + #axis.Draw() + + ''' + plots = ROOT.TMultiGraph() + for plot in self.plots_2D: + plots.Add(plot) #plot.Draw("A") plots.Draw("A") - ''' + ''' input("Press any key to continue") diff --git a/Validation/RecoTrack/test/fakeAnalysis/graphics_vertical.py b/Validation/RecoTrack/test/fakeAnalysis/graphics_vertical.py index db81bd2593fb8..ffd4582a34c44 100644 --- a/Validation/RecoTrack/test/fakeAnalysis/graphics_vertical.py +++ b/Validation/RecoTrack/test/fakeAnalysis/graphics_vertical.py @@ -14,656 +14,656 @@ class EventPlotter(object): def __init__(self): self.plots_2D = [] - self.plots_3D = [] - c = ROOT.TColor() + self.plots_3D = [] + c = ROOT.TColor() self.colors_G = [c.GetColor(0,255,0), c.GetColor(0,185,0), c.GetColor(50,255,50), \ - c.GetColor(0,100,0), c.GetColor(50,155,0), c.GetColor(0,70,155), \ - c.GetColor(0,255,0), c.GetColor(0,255,0), c.GetColor(0,255,0)] - self.colors_B = [c.GetColor(0,0,255), c.GetColor(0,0,155), c.GetColor(50,50,255), \ - c.GetColor(0,0,80), c.GetColor(50,0,155), c.GetColor(0,70,155), \ - c.GetColor(0,0,255), c.GetColor(0,0,255), c.GetColor(0,0,255)] + c.GetColor(0,100,0), c.GetColor(50,155,0), c.GetColor(0,70,155), \ + c.GetColor(0,255,0), c.GetColor(0,255,0), c.GetColor(0,255,0)] + self.colors_B = [c.GetColor(0,0,255), c.GetColor(0,0,155), c.GetColor(50,50,255), \ + c.GetColor(0,0,80), c.GetColor(50,0,155), c.GetColor(0,70,155), \ + c.GetColor(0,0,255), c.GetColor(0,0,255), c.GetColor(0,0,255)] def Reset(self): self.plots_2D = [] - self.plots_3D = [] + self.plots_3D = [] def PlotEvent3DHits(self, event, flag="PSG"): - ''' - Plots the 3D hits of an event. - flag is an string which defines which hit types to plot - (p for pixel, s for strip, g for glued) - ''' - if('p' in flag or 'P' in flag): - pixel_hits = event.pixelHits() - pix_coords = [] - for hit in pixel_hits: - pix_coords.append(hit.x()) - pix_coords.append(hit.y()) - pix_coords.append(hit.z()) - pix_plot = ROOT.TPolyMarker3D(len(pix_coords)/3, array('f', pix_coords), 1) - pix_plot.SetMarkerColor(4) - - if('s' in flag or 'S' in flag): - strip_hits = event.stripHits() - str_coords = [] - for hit in strip_hits: - str_coords.append(hit.x()) - str_coords.append(hit.y()) - str_coords.append(hit.z()) - str_plot = ROOT.TPolyMarker3D(len(str_coords)/3, array('f', str_coords), 1) - str_plot.SetMarkerColor(2) - - if('g' in flag or 'G' in flag): - glued_hits = event.gluedHits() - glu_coords = [] - for hit in glued_hits: - glu_coords.append(hit.x()) - glu_coords.append(hit.y()) - glu_coords.append(hit.z()) - glu_plot = ROOT.TPolyMarker3D(len(glu_coords)/3, array('f', glu_coords), 1) - glu_plot.SetMarkerColor(3) - - if('p' in flag or 'P' in flag): self.plots_3D.append(pix_plot) - if('s' in flag or 'S' in flag): self.plots_3D.append(str_plot) - if('g' in flag or 'G' in flag): self.plots_3D.append(glu_plot) + ''' + Plots the 3D hits of an event. + flag is an string which defines which hit types to plot + (p for pixel, s for strip, g for glued) + ''' + if('p' in flag or 'P' in flag): + pixel_hits = event.pixelHits() + pix_coords = [] + for hit in pixel_hits: + pix_coords.append(hit.x()) + pix_coords.append(hit.y()) + pix_coords.append(hit.z()) + pix_plot = ROOT.TPolyMarker3D(len(pix_coords)/3, array('f', pix_coords), 1) + pix_plot.SetMarkerColor(4) + + if('s' in flag or 'S' in flag): + strip_hits = event.stripHits() + str_coords = [] + for hit in strip_hits: + str_coords.append(hit.x()) + str_coords.append(hit.y()) + str_coords.append(hit.z()) + str_plot = ROOT.TPolyMarker3D(len(str_coords)/3, array('f', str_coords), 1) + str_plot.SetMarkerColor(2) + + if('g' in flag or 'G' in flag): + glued_hits = event.gluedHits() + glu_coords = [] + for hit in glued_hits: + glu_coords.append(hit.x()) + glu_coords.append(hit.y()) + glu_coords.append(hit.z()) + glu_plot = ROOT.TPolyMarker3D(len(glu_coords)/3, array('f', glu_coords), 1) + glu_plot.SetMarkerColor(3) + + if('p' in flag or 'P' in flag): self.plots_3D.append(pix_plot) + if('s' in flag or 'S' in flag): self.plots_3D.append(str_plot) + if('g' in flag or 'G' in flag): self.plots_3D.append(glu_plot) def PlotXY(self, event, limits=[-1000,1000], flag="PSG"): - ''' - Plots the hits of an event in an XY plane. - flag is an string which defines which hit types to plot - (p for pixel, s for strip, g for glued) - ''' - #ntuple.tree().GetBranch("pix_x") - if('p' in flag or 'P' in flag): - pixel_hits = event.pixelHits() - pix_x = [] - pix_y = [] - for hit in pixel_hits: - if(limits[0] < hit.z() < limits[1]): - pix_x.append(hit.x()) - pix_y.append(hit.y()) - pix_plot = ROOT.TGraph(len(pix_x), array('f', pix_x), array('f', pix_y)) - pix_plot.SetMarkerColor(4) - - if('s' in flag or 'S' in flag): - strip_hits = event.stripHits() - str_x = [] - str_y = [] - for hit in strip_hits: - if(limits[0] < hit.z() < limits[1]): - str_x.append(hit.x()) - str_y.append(hit.y()) - str_plot = ROOT.TGraph(len(str_x), array('f', str_x), array('f', str_y)) - str_plot.SetMarkerColor(2) - - if('g' in flag or 'G' in flag): - glued_hits = event.gluedHits() - glu_x = [] - glu_y = [] - for hit in glued_hits: - if(limits[0] < hit.z() < limits[1]): - glu_x.append(hit.x()) - glu_y.append(hit.y()) - glu_plot = ROOT.TGraph(len(glu_x), array('f', glu_x), array('f', glu_y)) - glu_plot.SetMarkerColor(3) - - plot = ROOT.TMultiGraph() - - if('p' in flag or 'P' in flag): plot.Add(pix_plot,"P") - if('s' in flag or 'S' in flag): plot.Add(str_plot,"P") - if('g' in flag or 'G' in flag): plot.Add(glu_plot,"P") - self.plots_2D.append(plot) + ''' + Plots the hits of an event in an XY plane. + flag is an string which defines which hit types to plot + (p for pixel, s for strip, g for glued) + ''' + #ntuple.tree().GetBranch("pix_x") + if('p' in flag or 'P' in flag): + pixel_hits = event.pixelHits() + pix_x = [] + pix_y = [] + for hit in pixel_hits: + if(limits[0] < hit.z() < limits[1]): + pix_x.append(hit.x()) + pix_y.append(hit.y()) + pix_plot = ROOT.TGraph(len(pix_x), array('f', pix_x), array('f', pix_y)) + pix_plot.SetMarkerColor(4) + + if('s' in flag or 'S' in flag): + strip_hits = event.stripHits() + str_x = [] + str_y = [] + for hit in strip_hits: + if(limits[0] < hit.z() < limits[1]): + str_x.append(hit.x()) + str_y.append(hit.y()) + str_plot = ROOT.TGraph(len(str_x), array('f', str_x), array('f', str_y)) + str_plot.SetMarkerColor(2) + + if('g' in flag or 'G' in flag): + glued_hits = event.gluedHits() + glu_x = [] + glu_y = [] + for hit in glued_hits: + if(limits[0] < hit.z() < limits[1]): + glu_x.append(hit.x()) + glu_y.append(hit.y()) + glu_plot = ROOT.TGraph(len(glu_x), array('f', glu_x), array('f', glu_y)) + glu_plot.SetMarkerColor(3) + + plot = ROOT.TMultiGraph() + + if('p' in flag or 'P' in flag): plot.Add(pix_plot,"P") + if('s' in flag or 'S' in flag): plot.Add(str_plot,"P") + if('g' in flag or 'G' in flag): plot.Add(glu_plot,"P") + self.plots_2D.append(plot) def PlotZY(self, event, limits=[-1000,1000], flag="PSG"): - ''' - Plots the hits of an event in an ZR plane. - flag is an string which defines which hit types to plot - (p for pixel, s for strip, g for glued) - ''' - #ntuple.tree().GetBranch("pix_x") - if('p' in flag or 'P' in flag): - pixel_hits = event.pixelHits() - pix_z = [] - pix_y = [] - for hit in pixel_hits: - if(limits[0] < hit.z() < limits[1]): - pix_z.append(hit.z()) - pix_y.append(hit.y()) - pix_plot = ROOT.TGraph(len(pix_z), array('f', pix_z), array('f', pix_y)) - pix_plot.SetMarkerColor(4) - - if('s' in flag or 'S' in flag): - strip_hits = event.stripHits() - str_z = [] - str_y = [] - for hit in strip_hits: - if(limits[0] < hit.z() < limits[1]): - str_z.append(hit.z()) - str_y.append(hit.y()) - str_plot = ROOT.TGraph(len(str_z), array('f', str_z), array('f', str_y)) - str_plot.SetMarkerColor(2) - - if('g' in flag or 'G' in flag): - glued_hits = event.gluedHits() - glu_z = [] - glu_y = [] - for hit in glued_hits: - if(limits[0] < hit.z() < limits[1]): - glu_z.append(hit.z()) - glu_y.append(hit.y()) - glu_plot = ROOT.TGraph(len(glu_z), array('f', glu_z), array('f', glu_y)) - glu_plot.SetMarkerColor(3) - - plot = ROOT.TMultiGraph() - - if('p' in flag or 'P' in flag): plot.Add(pix_plot,"P") - if('s' in flag or 'S' in flag): plot.Add(str_plot,"P") - if('g' in flag or 'G' in flag): plot.Add(glu_plot,"P") - self.plots_2D.append(plot) + ''' + Plots the hits of an event in an ZR plane. + flag is an string which defines which hit types to plot + (p for pixel, s for strip, g for glued) + ''' + #ntuple.tree().GetBranch("pix_x") + if('p' in flag or 'P' in flag): + pixel_hits = event.pixelHits() + pix_z = [] + pix_y = [] + for hit in pixel_hits: + if(limits[0] < hit.z() < limits[1]): + pix_z.append(hit.z()) + pix_y.append(hit.y()) + pix_plot = ROOT.TGraph(len(pix_z), array('f', pix_z), array('f', pix_y)) + pix_plot.SetMarkerColor(4) + + if('s' in flag or 'S' in flag): + strip_hits = event.stripHits() + str_z = [] + str_y = [] + for hit in strip_hits: + if(limits[0] < hit.z() < limits[1]): + str_z.append(hit.z()) + str_y.append(hit.y()) + str_plot = ROOT.TGraph(len(str_z), array('f', str_z), array('f', str_y)) + str_plot.SetMarkerColor(2) + + if('g' in flag or 'G' in flag): + glued_hits = event.gluedHits() + glu_z = [] + glu_y = [] + for hit in glued_hits: + if(limits[0] < hit.z() < limits[1]): + glu_z.append(hit.z()) + glu_y.append(hit.y()) + glu_plot = ROOT.TGraph(len(glu_z), array('f', glu_z), array('f', glu_y)) + glu_plot.SetMarkerColor(3) + + plot = ROOT.TMultiGraph() + + if('p' in flag or 'P' in flag): plot.Add(pix_plot,"P") + if('s' in flag or 'S' in flag): plot.Add(str_plot,"P") + if('g' in flag or 'G' in flag): plot.Add(glu_plot,"P") + self.plots_2D.append(plot) def PlotTracksXY(self, tracks): - plot = ROOT.TMultiGraph() + plot = ROOT.TMultiGraph() - for track in tracks: - X = []; Y = []; - for hit in track.hits(): - if(hit.isValid()): - X.append(hit.x()) - Y.append(hit.y()) - plot.Add(ROOT.TGraph(len(X),array("f",X),array("f",Y)),"L") + for track in tracks: + X = []; Y = []; + for hit in track.hits(): + if(hit.isValid()): + X.append(hit.x()) + Y.append(hit.y()) + plot.Add(ROOT.TGraph(len(X),array("f",X),array("f",Y)),"L") - self.plots_2D.append(plot) + self.plots_2D.append(plot) def PlotTracksZY(self, tracks): - plot = ROOT.TMultiGraph() + plot = ROOT.TMultiGraph() - for track in tracks: - Y = []; Z = []; - for hit in track.hits(): - if(hit.isValid()): - Y.append(hit.y()) - Z.append(hit.z()) - plot.Add(ROOT.TGraph(len(Z),array("f",Z),array("f",Y)),"L") + for track in tracks: + Y = []; Z = []; + for hit in track.hits(): + if(hit.isValid()): + Y.append(hit.y()) + Z.append(hit.z()) + plot.Add(ROOT.TGraph(len(Z),array("f",Z),array("f",Y)),"L") - self.plots_2D.append(plot) + self.plots_2D.append(plot) def PlotTracks3D(self, tracks): - for track in tracks: - X = []; Y = []; Z = []; - for hit in track.hits(): - if(hit.isValid()): - X.append(hit.x()) - Y.append(hit.y()) - Z.append(hit.z()) - if(X): - self.plots_3D.append(ROOT.TPolyLine3D(len(X),array("f",X),array("f",Y),array("f",Z))) - + for track in tracks: + X = []; Y = []; Z = []; + for hit in track.hits(): + if(hit.isValid()): + X.append(hit.x()) + Y.append(hit.y()) + Z.append(hit.z()) + if(X): + self.plots_3D.append(ROOT.TPolyLine3D(len(X),array("f",X),array("f",Y),array("f",Z))) + def PlotPixelTracks3D(self, tracks): - for track in tracks: - X = []; Y = []; Z = []; - for hit in track.pixelHits(): - if(hit.isValid()): - X.append(hit.x()) - Y.append(hit.y()) - Z.append(hit.z()) - if(X): - self.plots_3D.append(ROOT.TPolyLine3D(len(X),array("f",X),array("f",Y),array("f",Z))) + for track in tracks: + X = []; Y = []; Z = []; + for hit in track.pixelHits(): + if(hit.isValid()): + X.append(hit.x()) + Y.append(hit.y()) + Z.append(hit.z()) + if(X): + self.plots_3D.append(ROOT.TPolyLine3D(len(X),array("f",X),array("f",Y),array("f",Z))) def PlotPixelGluedTracks3D(self, tracks): - for track in tracks: - X = []; Y = []; Z = []; - for hit in track.hits(): - if(hit.isValid() and hit.hitType != 1): - X.append(hit.x()) - Y.append(hit.y()) - Z.append(hit.z()) - if(X): - self.plots_3D.append(ROOT.TPolyLine3D(len(X),array("f",X),array("f",Y),array("f",Z))) + for track in tracks: + X = []; Y = []; Z = []; + for hit in track.hits(): + if(hit.isValid() and hit.hitType != 1): + X.append(hit.x()) + Y.append(hit.y()) + Z.append(hit.z()) + if(X): + self.plots_3D.append(ROOT.TPolyLine3D(len(X),array("f",X),array("f",Y),array("f",Z))) def PlotTrack3D(self, track, color = 1): - '''Plots a single track and prints track info''' - # Not so hasardous experimental edit: - #hits = sorted([hit for hit in track.hits()], key = lambda hit: hit.index()) - #print [hit.index() for hit in hits] - X = []; Y = []; Z = []; - for hit in track.hits(): #hits: #track.hits(): - if(hit.isValid()): - X.append(hit.x()) - Y.append(hit.y()) - Z.append(hit.z()) - if(not X): - print("Track has no valid points") - return - plot = ROOT.TPolyLine3D(len(X),array("f",X),array("f",Y),array("f",Z)) - plot.SetLineColor(color) - self.plots_3D.append(plot) - - ''' - print "Track parameters:" - print "px : " + str(track.px()) - print "py : " + str(track.py()) - print "pz : " + str(track.pz()) - print "pt : " + str(track.pt()) - print "eta : " + str(track.eta()) - print "phi : " + str(track.phi()) - print "dxy : " + str(track.dxy()) - print "dz : " + str(track.dz()) - print "q : " + str(track.q()) - ''' + '''Plots a single track and prints track info''' + # Not so hasardous experimental edit: + #hits = sorted([hit for hit in track.hits()], key = lambda hit: hit.index()) + #print [hit.index() for hit in hits] + X = []; Y = []; Z = []; + for hit in track.hits(): #hits: #track.hits(): + if(hit.isValid()): + X.append(hit.x()) + Y.append(hit.y()) + Z.append(hit.z()) + if(not X): + print("Track has no valid points") + return + plot = ROOT.TPolyLine3D(len(X),array("f",X),array("f",Y),array("f",Z)) + plot.SetLineColor(color) + self.plots_3D.append(plot) + + ''' + print "Track parameters:" + print "px : " + str(track.px()) + print "py : " + str(track.py()) + print "pz : " + str(track.pz()) + print "pt : " + str(track.pt()) + print "eta : " + str(track.eta()) + print "phi : " + str(track.phi()) + print "dxy : " + str(track.dxy()) + print "dz : " + str(track.dz()) + print "q : " + str(track.q()) + ''' def TrackHelix(self, track, color = 1, style = 0): - '''Creates a THelix object which can be plotted with Draw() method.''' - if isinstance(track, TrackingParticle): - phi = track.pca_phi() - dxy = track.pca_dxy() - dz = track.pca_dz() - else: - phi = track.phi() - dxy = track.dxy() - dz = track.dz() - xyz = array("d", [-dxy*ROOT.TMath.Sin(phi), dxy*ROOT.TMath.Cos(phi), dz]) - v = array("d", [track.px(), track.py(), track.pz()]) - w = 0.3*3.8*track.q()*0.01 #Angular frequency = 0.3*B*q*hattuvakio, close enough - z_last = dz - for hit in track.hits(): - if(hit.isValidHit()): z_last = hit.z() - - helix = ROOT.THelix(xyz, v, w, array("d", [dz, z_last])) - helix.SetLineColor(color) - if style == 1: helix.SetLineStyle(9) - if style == 2: helix.SetLineStyle(7) - return helix - - def Plot3DHelixes(self, tracks, color = 1, style = 0): - for track in tracks: - if(track.hits()): - self.plots_3D.append(self.TrackHelix(track, color, style)) - - def Plot3DHelix(self, track, color = 1, style = 0): - if(track.hits()): - self.plots_3D.append(self.TrackHelix(track, color, style)) + '''Creates a THelix object which can be plotted with Draw() method.''' + if isinstance(track, TrackingParticle): + phi = track.pca_phi() + dxy = track.pca_dxy() + dz = track.pca_dz() + else: + phi = track.phi() + dxy = track.dxy() + dz = track.dz() + xyz = array("d", [-dxy*ROOT.TMath.Sin(phi), dxy*ROOT.TMath.Cos(phi), dz]) + v = array("d", [track.px(), track.py(), track.pz()]) + w = 0.3*3.8*track.q()*0.01 #Angular frequency = 0.3*B*q*hattuvakio, close enough + z_last = dz + for hit in track.hits(): + if(hit.isValidHit()): z_last = hit.z() + + helix = ROOT.THelix(xyz, v, w, array("d", [dz, z_last])) + helix.SetLineColor(color) + if style == 1: helix.SetLineStyle(9) + if style == 2: helix.SetLineStyle(7) + return helix + + def Plot3DHelixes(self, tracks, color = 1, style = 0): + for track in tracks: + if(track.hits()): + self.plots_3D.append(self.TrackHelix(track, color, style)) + + def Plot3DHelix(self, track, color = 1, style = 0): + if(track.hits()): + self.plots_3D.append(self.TrackHelix(track, color, style)) def Plot3DHits(self, track, color = 1, style = 0): - ''' - Plots the 3D hits from a track. - ''' - pix_coords = [] - for hit in track.pixelHits(): - if hit.isValid(): - pix_coords.append(hit.x()) - pix_coords.append(hit.y()) - pix_coords.append(hit.z()) - if pix_coords: - pix_plot = ROOT.TPolyMarker3D(len(pix_coords)/3, array('f', pix_coords), 2) - pix_plot.SetMarkerColor(color) - if style == 1: pix_plot.SetMarkerStyle(5) - if style == 2: pix_plot.SetMarkerStyle(4) - self.plots_3D.append(pix_plot) - - for hit in track.gluedHits(): - if hit.isValid(): - x = hit.x(); y = hit.y(); z = hit.z() - if hit.isBarrel(): - X = [x, x] - Y = [y, y] - Z = [z - sqrt(hit.zz()), z + sqrt(hit.zz())] - else: - X = [x - copysign(sqrt(hit.xx()),x), x + copysign(sqrt(hit.xx()),x)] - Y = [y - copysign(sqrt(hit.yy()),y), y + copysign(sqrt(hit.yy()),y)] - Z = [hit.z(), hit.z()] - glu_plot = ROOT.TPolyLine3D(len(X),array("f",X),array("f",Y),array("f",Z)) - #glu_plot.SetLineStyle(2) - if style == 1: glu_plot.SetLineStyle(2) - if style == 2: glu_plot.SetLineStyle(3) - glu_plot.SetLineColor(color) - self.plots_3D.append(glu_plot) - - for hit in track.stripHits(): - if hit.isValid(): - x = hit.x(); y = hit.y(); z = hit.z() - if hit.isBarrel(): - X = [x, x] - Y = [y, y] - Z = [z - 1.5*sqrt(hit.zz()), z + 1.5*sqrt(hit.zz())] - else: - X = [x - 1.5*copysign(sqrt(hit.xx()),x), x + 1.5*copysign(sqrt(hit.xx()),x)] - Y = [y - 1.5*copysign(sqrt(hit.yy()),y), y + 1.5*copysign(sqrt(hit.yy()),y)] - Z = [hit.z(), hit.z()] - str_plot = ROOT.TPolyLine3D(len(X),array("f",X),array("f",Y),array("f",Z)) - if style == 1: str_plot.SetLineStyle(2) - if style == 2: str_plot.SetLineStyle(3) - str_plot.SetLineColor(color) - self.plots_3D.append(str_plot) + ''' + Plots the 3D hits from a track. + ''' + pix_coords = [] + for hit in track.pixelHits(): + if hit.isValid(): + pix_coords.append(hit.x()) + pix_coords.append(hit.y()) + pix_coords.append(hit.z()) + if pix_coords: + pix_plot = ROOT.TPolyMarker3D(len(pix_coords)/3, array('f', pix_coords), 2) + pix_plot.SetMarkerColor(color) + if style == 1: pix_plot.SetMarkerStyle(5) + if style == 2: pix_plot.SetMarkerStyle(4) + self.plots_3D.append(pix_plot) + + for hit in track.gluedHits(): + if hit.isValid(): + x = hit.x(); y = hit.y(); z = hit.z() + if hit.isBarrel(): + X = [x, x] + Y = [y, y] + Z = [z - sqrt(hit.zz()), z + sqrt(hit.zz())] + else: + X = [x - copysign(sqrt(hit.xx()),x), x + copysign(sqrt(hit.xx()),x)] + Y = [y - copysign(sqrt(hit.yy()),y), y + copysign(sqrt(hit.yy()),y)] + Z = [hit.z(), hit.z()] + glu_plot = ROOT.TPolyLine3D(len(X),array("f",X),array("f",Y),array("f",Z)) + #glu_plot.SetLineStyle(2) + if style == 1: glu_plot.SetLineStyle(2) + if style == 2: glu_plot.SetLineStyle(3) + glu_plot.SetLineColor(color) + self.plots_3D.append(glu_plot) + + for hit in track.stripHits(): + if hit.isValid(): + x = hit.x(); y = hit.y(); z = hit.z() + if hit.isBarrel(): + X = [x, x] + Y = [y, y] + Z = [z - 1.5*sqrt(hit.zz()), z + 1.5*sqrt(hit.zz())] + else: + X = [x - 1.5*copysign(sqrt(hit.xx()),x), x + 1.5*copysign(sqrt(hit.xx()),x)] + Y = [y - 1.5*copysign(sqrt(hit.yy()),y), y + 1.5*copysign(sqrt(hit.yy()),y)] + Z = [hit.z(), hit.z()] + str_plot = ROOT.TPolyLine3D(len(X),array("f",X),array("f",Y),array("f",Z)) + if style == 1: str_plot.SetLineStyle(2) + if style == 2: str_plot.SetLineStyle(3) + str_plot.SetLineColor(color) + self.plots_3D.append(str_plot) def PlotVertex3D(self, vertex, color=1): - plot = ROOT.TPolyMarker3D(1, array('f', [vertex.x(), vertex.y(), vertex.z()]),3) - plot.SetMarkerColor(color) + plot = ROOT.TPolyMarker3D(1, array('f', [vertex.x(), vertex.y(), vertex.z()]),3) + plot.SetMarkerColor(color) self.plots_3D.append(plot) def PlotPoint3D(self, point, color=1): - plot = ROOT.TPolyMarker3D(1, array('f', [point[0], point[1], point[2]]),3) - plot.SetMarkerColor(color) + plot = ROOT.TPolyMarker3D(1, array('f', [point[0], point[1], point[2]]),3) + plot.SetMarkerColor(color) self.plots_3D.append(plot) def PlotTrackingFail(self, match): - X = array('f', [match.last_loc[0], match.fail_loc[0]]) - Y = array('f', [match.last_loc[1], match.fail_loc[1]]) - Z = array('f', [match.last_loc[2], match.fail_loc[2]]) + X = array('f', [match.last_loc[0], match.fail_loc[0]]) + Y = array('f', [match.last_loc[1], match.fail_loc[1]]) + Z = array('f', [match.last_loc[2], match.fail_loc[2]]) plot = ROOT.TPolyLine3D(2, X, Y, Z) - plot.SetLineWidth(3) - plot.SetLineColor(2) + plot.SetLineWidth(3) + plot.SetLineColor(2) self.plots_3D.append(plot) - self.PlotPoint3D(match.last_loc, 2) + self.PlotPoint3D(match.last_loc, 2) def PlotFakes_MatchedRecos(self, event, iterative = 1, reconstructed = 0): fakes = analysis.FindFakes(event) - if iterative: + if iterative: # Plot fakes one by one - for fake in fakes: - self.Reset() - self.Plot3DHelixes([fake],2) - self.Plot3DHits(fake, 2) + for fake in fakes: + self.Reset() + self.Plot3DHelixes([fake],2) + self.Plot3DHits(fake, 2) # Plot real particle tracks which include fake tracks hits - icol = 0 - particle_inds = [] - particles = [] - reco_inds = [] - recos = [] - for hit in fake.hits(): - if hit.isValid() and hit.nSimHits() >= 0: - for simHit in hit.simHits(): - particle = simHit.trackingParticle() - if particle.index() not in particle_inds: - particle_inds.append(particle.index()) - particles.append(particle) - - ''' - self.Plot3DHelix(particle, ROOT.TColor().GetColor(0,255,0), 1) # kAzure color, maybe ;) - self.Plot3DHits(particle, 3+icol, 1) - icol += 1 - - print "Number of matched tracks to real particle: " + str(particle.nMatchedTracks()) - ''' + icol = 0 + particle_inds = [] + particles = [] + reco_inds = [] + recos = [] + for hit in fake.hits(): + if hit.isValid() and hit.nSimHits() >= 0: + for simHit in hit.simHits(): + particle = simHit.trackingParticle() + if particle.index() not in particle_inds: + particle_inds.append(particle.index()) + particles.append(particle) + + ''' + self.Plot3DHelix(particle, ROOT.TColor().GetColor(0,255,0), 1) # kAzure color, maybe ;) + self.Plot3DHits(particle, 3+icol, 1) + icol += 1 + + print "Number of matched tracks to real particle: " + str(particle.nMatchedTracks()) + ''' # Plot reconstructed tracks of these real particle tracks - if reconstructed and particle.nMatchedTracks() > 0: - for info in particle.matchedTrackInfos(): - track = info.track() - if track.index() not in reco_inds: - reco_inds.append(track.index()) - recos.append(track) - - ''' - if particle.nMatchedTracks() == 1: - self.Plot3DHelix(track,1,2) - self.Plot3DHits(track,1,2) - else: - self.Plot3DHelix(track,5,2) - self.Plot3DHits(track,5,2) - ''' - icol = 0 + if reconstructed and particle.nMatchedTracks() > 0: + for info in particle.matchedTrackInfos(): + track = info.track() + if track.index() not in reco_inds: + reco_inds.append(track.index()) + recos.append(track) + + ''' + if particle.nMatchedTracks() == 1: + self.Plot3DHelix(track,1,2) + self.Plot3DHits(track,1,2) + else: + self.Plot3DHelix(track,5,2) + self.Plot3DHits(track,5,2) + ''' + icol = 0 for particle in particles: - self.Plot3DHelix(particle, self.colors_G[icol], 1) # kAzure color, maybe ;) - self.Plot3DHits(particle, self.colors_G[icol], 1) - icol += 1 - for track in recos: - self.Plot3DHelix(track,1,2) - self.Plot3DHits(track,1,2) - ''' - if track.trackingParticle().nMatchedTracks() == 1: - self.Plot3DHelix(track,1,2) - self.Plot3DHits(track,1,2) - else: - self.Plot3DHelix(track,5,2) - self.Plot3DHits(track,5,2) - ''' - - self.Draw() + self.Plot3DHelix(particle, self.colors_G[icol], 1) # kAzure color, maybe ;) + self.Plot3DHits(particle, self.colors_G[icol], 1) + icol += 1 + for track in recos: + self.Plot3DHelix(track,1,2) + self.Plot3DHits(track,1,2) + ''' + if track.trackingParticle().nMatchedTracks() == 1: + self.Plot3DHelix(track,1,2) + self.Plot3DHits(track,1,2) + else: + self.Plot3DHelix(track,5,2) + self.Plot3DHits(track,5,2) + ''' + + self.Draw() return # the following is useless by now # Plot all fakes at once (messy picture) - ''' - self.Plot3DHelixes(fakes,2) - for fake in fakes: - self.Plot3DHits(fake, 2) + ''' + self.Plot3DHelixes(fakes,2) + for fake in fakes: + self.Plot3DHits(fake, 2) # Plot real particle tracks which include fake tracks hits - for hit in fake.hits(): - if hit.isValid() and hit.nMatchedTrackingParticles() >= 0: - for info in hit.matchedTrackingParticleInfos(): - particle = info.trackingParticle() - self.Plot3DHelix(particle,3,1) - self.Plot3DHits(particle,3,1) + for hit in fake.hits(): + if hit.isValid() and hit.nMatchedTrackingParticles() >= 0: + for info in hit.matchedTrackingParticleInfos(): + particle = info.trackingParticle() + self.Plot3DHelix(particle,3,1) + self.Plot3DHits(particle,3,1) - print "Number of matched tracks to real particle: " + str(particle.nMatchedTracks()) - # Plot reconstructed tracks of these real particle tracks - if reconstructed and particle.nMatchedTracks() > 0: - for info in particle.matchedTrackInfos(): - track = info.track() - if particle.nMatchedTracks() == 1: - self.Plot3DHelix(track,1,2) - self.Plot3DHits(track,1,2) - else: - self.Plot3DHelix(track,5,2) - self.Plot3DHits(track,5,2) + print "Number of matched tracks to real particle: " + str(particle.nMatchedTracks()) + # Plot reconstructed tracks of these real particle tracks + if reconstructed and particle.nMatchedTracks() > 0: + for info in particle.matchedTrackInfos(): + track = info.track() + if particle.nMatchedTracks() == 1: + self.Plot3DHelix(track,1,2) + self.Plot3DHits(track,1,2) + else: + self.Plot3DHelix(track,5,2) + self.Plot3DHits(track,5,2) ''' def PlotFakes(self, event, reconstructed = 1, fake_filter = None, end_filter = None, last_filter = None, particle_end_filter = None): - iterative = 1 + iterative = 1 fakes = analysis.FindFakes(event) - if iterative: + if iterative: # Plot fakes one by one - for fake in fakes: + for fake in fakes: # Check for filter - if fake_filter: - info = analysis.FakeInfo(fake) - if info.fake_class not in fake_filter: - continue - - self.Reset() - self.Plot3DHelixes([fake],2) - self.Plot3DHits(fake, 2) - #self.PlotVertex3D(vertex,2) - fake_info = analysis.FakeInfo(fake) - analysis.PrintTrackInfo(fake, None, 0, fake_info) + if fake_filter: + info = analysis.FakeInfo(fake) + if info.fake_class not in fake_filter: + continue + + self.Reset() + self.Plot3DHelixes([fake],2) + self.Plot3DHits(fake, 2) + #self.PlotVertex3D(vertex,2) + fake_info = analysis.FakeInfo(fake) + analysis.PrintTrackInfo(fake, None, 0, fake_info) if fake_info.matches: - for match in fake_info.matches: - continue #self.PlotTrackingFail(match) - #self.PlotPoint3D(fake_info.end_loc, 2) + for match in fake_info.matches: + continue #self.PlotTrackingFail(match) + #self.PlotPoint3D(fake_info.end_loc, 2) # Find real particle tracks which include fake tracks hits - icol = 0 - particle_inds = [] - particles = [] - reco_inds = [] - recos = [] - for hit in fake.hits(): - if hit.isValid() and hit.nMatchedTrackingParticles() >= 0: - for info in hit.matchedTrackingParticleInfos(): - particle = info.trackingParticle() - if particle.index() not in particle_inds: - particle_inds.append(particle.index()) - particles.append(particle) - if reconstructed and particle.nMatchedTracks() > 0: - for info in particle.matchedTrackInfos(): - track = info.track() - if track.index() not in reco_inds: - reco_inds.append(track.index()) - recos.append(track) - - - # Find reconstructed tracks included in fakes hits - if hit.isValid() and reconstructed and hit.ntracks() > 0: - for track in hit.tracks(): - #track = info.track() - if (track.index() not in reco_inds) and track.index() != fake.index(): - reco_inds.append(track.index()) - recos.append(track) + icol = 0 + particle_inds = [] + particles = [] + reco_inds = [] + recos = [] + for hit in fake.hits(): + if hit.isValid() and hit.nMatchedTrackingParticles() >= 0: + for info in hit.matchedTrackingParticleInfos(): + particle = info.trackingParticle() + if particle.index() not in particle_inds: + particle_inds.append(particle.index()) + particles.append(particle) + if reconstructed and particle.nMatchedTracks() > 0: + for info in particle.matchedTrackInfos(): + track = info.track() + if track.index() not in reco_inds: + reco_inds.append(track.index()) + recos.append(track) + + + # Find reconstructed tracks included in fakes hits + if hit.isValid() and reconstructed and hit.ntracks() > 0: + for track in hit.tracks(): + #track = info.track() + if (track.index() not in reco_inds) and track.index() != fake.index(): + reco_inds.append(track.index()) + recos.append(track) # Plot the particles and reconstructed tracks - icol = 0 - self.ParticleTest(particles, draw=False) + icol = 0 + self.ParticleTest(particles, draw=False) for particle in particles: - self.Plot3DHelix(particle, self.colors_G[icol], 1) - self.plots_3D[-1].SetLineStyle(5) - self.Plot3DHits(particle, self.colors_G[icol], 1) - self.PlotVertex3D(particle.parentVertex(),self.colors_G[icol]) + self.Plot3DHelix(particle, self.colors_G[icol], 1) + self.plots_3D[-1].SetLineStyle(5) + self.Plot3DHits(particle, self.colors_G[icol], 1) + self.PlotVertex3D(particle.parentVertex(),self.colors_G[icol]) # EXPERIMENTAL LINE: #self.PlotTrack3D(particle, self.colors_G[icol]) - for decay in particle.decayVertices(): - self.PlotVertex3D(decay, 5) - analysis.PrintTrackInfo(particle, fake) - icol += 1 - icol = 0 - for track in recos: - self.Plot3DHelix(track,self.colors_B[icol],2) - self.Plot3DHits(track,self.colors_B[icol],2) - #self.PlotVertex3D(vertex,self.colors_B[icol]) - analysis.PrintTrackInfo(track, fake) - icol += 1 - - if hit.isValid() and hit.z() >= 0: self.PlotDetectorRange("p",4) - elif hit.isValid() and hit.z() < 0: self.PlotDetectorRange("n",4) - else: self.PlotDetectorRange("b",4) + for decay in particle.decayVertices(): + self.PlotVertex3D(decay, 5) + analysis.PrintTrackInfo(particle, fake) + icol += 1 + icol = 0 + for track in recos: + self.Plot3DHelix(track,self.colors_B[icol],2) + self.Plot3DHits(track,self.colors_B[icol],2) + #self.PlotVertex3D(vertex,self.colors_B[icol]) + analysis.PrintTrackInfo(track, fake) + icol += 1 + + if hit.isValid() and hit.z() >= 0: self.PlotDetectorRange("p",4) + elif hit.isValid() and hit.z() < 0: self.PlotDetectorRange("n",4) + else: self.PlotDetectorRange("b",4) print("****************************\n") - self.Draw() + self.Draw() return def DrawTrackTest_old(self, track): c3 = ROOT.TCanvas("3D Plot","3D Plot", 1200, 1200) - self.PlotDetectorRange("b", 4) - for i in range(8): self.plots_3D[i].Draw() - axis = ROOT.TAxis3D() - axis.Draw() - for hit in track.hits(): - if hit.isValid(): - point = ROOT.TPolyMarker3D(1, array('f', [hit.x(), hit.y(), hit.z()]), 2) - point.Draw() - input("continue") - #axis.SetAxisRange(-278,278,"Z") - - axis.ToggleZoom() + self.PlotDetectorRange("b", 4) + for i in range(8): self.plots_3D[i].Draw() + axis = ROOT.TAxis3D() + axis.Draw() + for hit in track.hits(): + if hit.isValid(): + point = ROOT.TPolyMarker3D(1, array('f', [hit.x(), hit.y(), hit.z()]), 2) + point.Draw() + input("continue") + #axis.SetAxisRange(-278,278,"Z") + + axis.ToggleZoom() def DrawTrackTest(self, track): - self.PlotDetectorRange("b", 4) - self.PlotTrack3D(track) - #self.Draw() - ''' - for hit in track.hits(): - if hit.isValid(): - - point = ROOT.TPolyMarker3D(1, array('f', [hit.x(), hit.y(), hit.z()]), 2) - self.plots_3D.append(point) - self.Draw() - ''' + self.PlotDetectorRange("b", 4) + self.PlotTrack3D(track) + #self.Draw() + ''' + for hit in track.hits(): + if hit.isValid(): + + point = ROOT.TPolyMarker3D(1, array('f', [hit.x(), hit.y(), hit.z()]), 2) + self.plots_3D.append(point) + self.Draw() + ''' def ParticleTest(self, particles, draw=False): - for particle in particles: - print("\nPARTICLE " + str(particle.index())) - for hit in particle.hits(): - tof = -1 - for info in hit.matchedTrackingParticleInfos(): - if info.trackingParticle().index() == particle.index(): - #if len(info.tof()): - tof = info.tof() - print("Index: " + str(hit.index()) + ", Layer: " + str(hit.layerStr()) + ", TOF: " + str(tof) +\ - " XY distance: " + str(sqrt(hit.x()**2 + hit.y()**2)) + ", Z: " + str(hit.z())) - self.DrawTrackTest(particle) - if draw: - self.Draw() - self.Reset() + for particle in particles: + print("\nPARTICLE " + str(particle.index())) + for hit in particle.hits(): + tof = -1 + for info in hit.matchedTrackingParticleInfos(): + if info.trackingParticle().index() == particle.index(): + #if len(info.tof()): + tof = info.tof() + print("Index: " + str(hit.index()) + ", Layer: " + str(hit.layerStr()) + ", TOF: " + str(tof) +\ + " XY distance: " + str(sqrt(hit.x()**2 + hit.y()**2)) + ", Z: " + str(hit.z())) + self.DrawTrackTest(particle) + if draw: + self.Draw() + self.Reset() def PlotDetectorRange(self, area="b", plates = 6): - ''' - Plots the detector schematic layout. - Area means which part to plot (p = positive side, n = negative side, b = both) - Plates means how many detector circle schemes to plot per side. - ''' + ''' + Plots the detector schematic layout. + Area means which part to plot (p = positive side, n = negative side, b = both) + Plates means how many detector circle schemes to plot per side. + ''' r = [17, 17, 57, 57, 112, 112] - z = [30, 70, 70, 120, 120, 280] - for i in range(plates): - X = []; Y = []; Z = []; ZN = [] - for t in range(0,101): - X.append(r[i]*cos(2*pi*t/100)) - Y.append(r[i]*sin(2*pi*t/100)) - Z.append(z[i]*1.0) - ZN.append(-1.0*z[i]) - plot = ROOT.TPolyLine3D(len(X),array("f",X),array("f",Y),array("f",Z),"S") - nplot = ROOT.TPolyLine3D(len(X),array("f",X),array("f",Y),array("f",ZN),"S") - plot.SetLineStyle(3) - nplot.SetLineStyle(3) - if area == "p": self.plots_3D.append(plot) - if area == "n": self.plots_3D.append(nplot) - if area == "b": - self.plots_3D.append(plot) - self.plots_3D.append(nplot) + z = [30, 70, 70, 120, 120, 280] + for i in range(plates): + X = []; Y = []; Z = []; ZN = [] + for t in range(0,101): + X.append(r[i]*cos(2*pi*t/100)) + Y.append(r[i]*sin(2*pi*t/100)) + Z.append(z[i]*1.0) + ZN.append(-1.0*z[i]) + plot = ROOT.TPolyLine3D(len(X),array("f",X),array("f",Y),array("f",Z),"S") + nplot = ROOT.TPolyLine3D(len(X),array("f",X),array("f",Y),array("f",ZN),"S") + plot.SetLineStyle(3) + nplot.SetLineStyle(3) + if area == "p": self.plots_3D.append(plot) + if area == "n": self.plots_3D.append(nplot) + if area == "b": + self.plots_3D.append(plot) + self.plots_3D.append(nplot) def ClassHistogram(self, data, name = "Histogram", labels = False, ready = False): ''' - Draws histogram with data. Data is in form of a dictionary, - labels assigned to amount of hits. If labels is defined, it - defines the labels assigned to data. - ''' - if ready: - if labels: - keys = [key for key in data] - hist_labels = [labels[key] for key in keys] - hist_data = [data[key] for key in keys] - else: - hist_labels = [key for key in data] - hist_data = [data[key] for key in hist_labels] - - c1 = ROOT.TCanvas(name, name, 700, 500) - c1.SetGrid() - #c1.SetTopMargin(0.15) - hist = ROOT.TH1F(name, name, 30,0,30)#, 3,0,3) + Draws histogram with data. Data is in form of a dictionary, + labels assigned to amount of hits. If labels is defined, it + defines the labels assigned to data. + ''' + if ready: + if labels: + keys = [key for key in data] + hist_labels = [labels[key] for key in keys] + hist_data = [data[key] for key in keys] + else: + hist_labels = [key for key in data] + hist_data = [data[key] for key in hist_labels] + + c1 = ROOT.TCanvas(name, name, 700, 500) + c1.SetGrid() + #c1.SetTopMargin(0.15) + hist = ROOT.TH1F(name, name, 30,0,30)#, 3,0,3) hist.SetStats(0); hist.SetFillColor(38); - hist.SetCanExtend(ROOT.TH1.kAllAxes); - if ready: # cumulative results already calculated in data - for i in range(len(hist_labels)): - #hist.Fill(hist_labels[i],hist_data[i]) - [hist.Fill(hist_labels[i],1) for j in range(hist_data[i])] - else: # data is in samples, not in cumulative results - for entry in data: hist.Fill(entry,1) - hist.LabelsDeflate() - #hist.SetLabelSize(0.05) - hist.Draw() + hist.SetCanExtend(ROOT.TH1.kAllAxes); + if ready: # cumulative results already calculated in data + for i in range(len(hist_labels)): + #hist.Fill(hist_labels[i],hist_data[i]) + [hist.Fill(hist_labels[i],1) for j in range(hist_data[i])] + else: # data is in samples, not in cumulative results + for entry in data: hist.Fill(entry,1) + hist.LabelsDeflate() + #hist.SetLabelSize(0.05) + hist.Draw() - input("Press any key to continue") + input("Press any key to continue") def Draw(self): - if self.plots_3D: - c3 = ROOT.TCanvas("3D Plot","3D Plot", 1200, 1200) - view = ROOT.TView3D() - axis = ROOT.TAxis3D() - axis.SetXTitle("x") - axis.SetYTitle("y") - axis.SetZTitle("z") - #axis.GetZaxis().RotateTitle() - - for plot in self.plots_3D: - if plot: plot.Draw() - - #view.DefineViewDirection(array("d",[1,1,1]),array("d",[0,0,0]),1.0,0.0,0.0,1.0,0.0,1.0)#,array("d",[-1,-1,-1]),array("d",[1,1,1])) - axis.Draw() - #view.SetAxisNDC(array("d",[0,0,0]),array("d",[0,1,0]),array("d",[0,0,0]),array("d",[0,0,1]),array("d",[0,0,0]),array("d",[1,0,0])) + if self.plots_3D: + c3 = ROOT.TCanvas("3D Plot","3D Plot", 1200, 1200) + view = ROOT.TView3D() + axis = ROOT.TAxis3D() + axis.SetXTitle("x") + axis.SetYTitle("y") + axis.SetZTitle("z") + #axis.GetZaxis().RotateTitle() + + for plot in self.plots_3D: + if plot: plot.Draw() + + #view.DefineViewDirection(array("d",[1,1,1]),array("d",[0,0,0]),1.0,0.0,0.0,1.0,0.0,1.0)#,array("d",[-1,-1,-1]),array("d",[1,1,1])) + axis.Draw() + #view.SetAxisNDC(array("d",[0,0,0]),array("d",[0,1,0]),array("d",[0,0,0]),array("d",[0,0,1]),array("d",[0,0,0]),array("d",[1,0,0])) - #view.SetPsi(30) - #view.SetView(0,0,pi/2,ROOT.Long()) - #view.DefineViewDirection(0,0,pi/2) - #view.RotateView(pi/2,pi/2) - axis.ToggleZoom() + #view.SetPsi(30) + #view.SetView(0,0,pi/2,ROOT.Long()) + #view.DefineViewDirection(0,0,pi/2) + #view.RotateView(pi/2,pi/2) + axis.ToggleZoom() - if self.plots_2D: - c2 = ROOT.TCanvas("2D Plot","2D Plot", 1200, 1200) + if self.plots_2D: + c2 = ROOT.TCanvas("2D Plot","2D Plot", 1200, 1200) - for plot in self.plots_2D: plot.Draw("A") + for plot in self.plots_2D: plot.Draw("A") - input("Press any key to continue") + input("Press any key to continue") diff --git a/Validation/RecoTrack/test/fakeAnalysis/main.py b/Validation/RecoTrack/test/fakeAnalysis/main.py index d6fb287282150..0449287b1fc53 100644 --- a/Validation/RecoTrack/test/fakeAnalysis/main.py +++ b/Validation/RecoTrack/test/fakeAnalysis/main.py @@ -67,7 +67,7 @@ def main(): #PlotTracks3D(FindUntrackedParticles(event)) #EfficiencyRate(ntuple, 100) #for track in an.FindFakes(event): -# pl.DrawTrackTest(track) +# pl.DrawTrackTest(track) #pl.PlotEvent3DHits(event) @@ -77,12 +77,12 @@ def main(): pl.Draw() for track in tracks: - if track.hits(): - #pl.PlotTrack3D(track) - pl.Plot3DHelixes([track]) - pl.Plot3DHits(track) - #pl.Plot3DHelixes(an.FindFakes(event)) - pl.Draw() + if track.hits(): + #pl.PlotTrack3D(track) + pl.Plot3DHelixes([track]) + pl.Plot3DHits(track) + #pl.Plot3DHelixes(an.FindFakes(event)) + pl.Draw() ''' #pl.ParticleTest(event.trackingParticles(),True) #pl.PlotFakes(event,1,1,None)#[]) @@ -106,7 +106,7 @@ def PlotFakes(ntuple): pl = gr.EventPlotter() for event in ntuple: # Fill the filters with corresponding class indexes or detector layers to filter everything else from the plotting - pl.PlotFakes(event, True, fake_filter = [], end_filter = [], last_filter = "", particle_end_filter = "") + pl.PlotFakes(event, True, fake_filter = [], end_filter = [], last_filter = "", particle_end_filter = "") def Create_PtHistograms(ntuple): ''' Creates pt histograms for fake and true tracks. ''' @@ -179,13 +179,13 @@ def Create_EndOfTrackingHistograms(ntuple): #end_list = Load_File("End_list_file_real_invalid.dmp") ''' for end in end_list: - if end.end_class == 0 and end.last_str == end.particle_end_str and end.last_str == "BPix3": - print end.last - print end.particle_end - print end.fake_end - print end.last_str, end.particle_end_str, end.fake_end_str - print end.end_class - print "*****" + if end.end_class == 0 and end.last_str == end.particle_end_str and end.last_str == "BPix3": + print end.last + print end.particle_end + print end.fake_end + print end.last_str, end.particle_end_str, end.fake_end_str + print end.end_class + print "*****" ''' an.Analyse_EOT_ParticleDoubleHit(end_list) pl.EndOfTrackingHistogram(end_list, "end_class",[],[], False, False) #last false will adjust the bpix3 filter @@ -220,13 +220,13 @@ def Create_EndOfTrackingHistogramsReal(ntuple): ''' for end in end_list: - if end.end_class == 0 and end.last_str == end.particle_end_str and end.last_str == "BPix3": - print end.last - print end.particle_end - print end.fake_end - print end.last_str, end.particle_end_str, end.fake_end_str - print end.end_class - print "*****" + if end.end_class == 0 and end.last_str == end.particle_end_str and end.last_str == "BPix3": + print end.last + print end.particle_end + print end.fake_end + print end.last_str, end.particle_end_str, end.fake_end_str + print end.end_class + print "*****" ''' pl.EndOfTrackingHistogram(end_list, "end_class",[],[]) pl.EndOfTrackingHistogram(end_list, "last_layer",[0],[],False) @@ -250,11 +250,11 @@ def Create_EndOfTrackingPointsPlot(ntuple): end_list = an.Get_EndOfTrackingPoints(ntuple, 100, []) last = [], fake_ends = [], particle_ends = [], end_classes = [], fake_classes = [] for end in end_list: - last.append(end.last) - fake_ends.append(end.fake_end) - particle_ends.append(end.particle_end) - end_classes.append(end.end_class) - fake_classes.append(end.fake_class) + last.append(end.last) + fake_ends.append(end.fake_end) + particle_ends.append(end.particle_end) + end_classes.append(end.end_class) + fake_classes.append(end.fake_class) ''' pl.PlotEndOfTrackingPoints3D(last,[])#, fail) diff --git a/Validation/RecoVertex/test/V0PerformanceValidation.py b/Validation/RecoVertex/test/V0PerformanceValidation.py index abe7e4e1e7aaa..d700eae5feda0 100644 --- a/Validation/RecoVertex/test/V0PerformanceValidation.py +++ b/Validation/RecoVertex/test/V0PerformanceValidation.py @@ -117,7 +117,7 @@ def do_validation(samples, GlobalTag): harvestedfile = './DQM_V0001_R000000001__' + GlobalTag + '__' + sample + '__Validation.root' if(( Sequence == "harvesting" and os.path.isfile(harvestedfile)) == False): # cmd = 'dbsql "find dataset.createdate, dataset where dataset like *' - cmd = 'dbsql "find dataset where dataset like *' + cmd = 'dbsql "find dataset where dataset like *' cmd += sample + '/' + NewRelease + '_' + GlobalTag + '*GEN-SIM-RECO*" ' cmd += '| grep ' + sample + ' | grep -v test | sort | tail -1 | cut -f2 ' print(cmd)