Exemplo n.º 1
0
    def Loop(self):
		
	afile = TFile(self.Filename)
	afilename = self.Filename
	stripfilename = afilename

	try:
	    if self.TagOption:
		stripfilename = self.tag
	except:
	    stripfilename = afilename.split('/')[len(afilename.split('/')) -1]
	    stripfilename = stripfilename[0:(len(stripfilename)-5)]
	
	alist = self.dir.GetListOfKeys()

	for i in alist:
	    aobj = i.ReadObj()
	    if aobj.IsA().InheritsFrom("TDirectory"):
		if self.Verbose:
		    print ' found directory: '+i.GetName()

		if self.XML:
		    print '   <!-- '+i.GetName()+' -->'

		bdir = self.dir
		afile.GetObject(i.GetName(),bdir)
		blist = bdir.GetListOfKeys()
		for j in blist:
		    bobj = j.ReadObj()
		    if bobj.IsA().InheritsFrom(ROOT.TH1.Class()):
			if self.Verbose:
			    print '  --> found TH1: name = '+j.GetName() + ' title = '+j.GetTitle()
			if self.XML:
			    print '   <TH1 name=\"'+stripfilename+'_'+j.GetName()+'\" source=\"'+'/'+i.GetName()+'/'+j.GetName()+'\"/>'
Exemplo n.º 2
0
def eventdisplay(inputfile, outputfile, histoname):
	#inputfile = raw_input("Insert root file: ")
	inputfile = TFile(datapath+inputfile)
	tree = TTree()
	inputfile.GetObject("B4", tree)

	#outputfile = raw_input("Insert root output file: ")
	displayfile = TFile(outputfile+".root","RECREATE")

	#loop over events
	for Event in range(int(tree.GetEntries())):

		tree.GetEntry(Event)

		#Set values of the tree
		PrimaryParticleName = tree.PrimaryParticleName # MC truth: primary particle Geant4 name
		PrimaryParticleEnergy = tree.PrimaryParticleEnergy
		EnergyTot = tree.EnergyTot # Total energy deposited in calorimeter
		Energyem = tree.Energyem # Energy deposited by the em component
		EnergyScin = tree.EnergyScin # Energy deposited in Scin fibers (not Birk corrected)
		EnergyCher = tree.EnergyCher # Energy deposited in Cher fibers (not Birk corrected)
		NofCherenkovDetected = tree.NofCherenkovDetected # Total Cher p.e. detected
		BarrelR_VectorSignals = tree.VectorSignalsR  # Vector of energy deposited in Scin fibers (Birk corrected)
		BarrelL_VectorSignals = tree.VectorSignalsL  # Vector of energy deposited in Scin fibers (Birk corrected)
		BarrelR_VectorSignalsCher = tree.VectorSignalsCherR # Vector of Cher p.e. detected in Cher fibers
		BarrelL_VectorSignalsCher = tree.VectorSignalsCherL 	
		VectorR = tree.VectorR
		VectorL = tree.VectorL		
		
		ROOTHistograms.create_eventdisplay_scin(PrimaryParticleName, BarrelR_VectorSignals, BarrelL_VectorSignals, histoname) 
Exemplo n.º 3
0
   def test1WriteTGraph( self ):
      """Write a TGraph object and read it back correctly"""

      gr = TGraph()
      ff = TFile( "test.root", "RECREATE" )
      ff.WriteObject( gr, "grname", "" )
      gr2 = TGraph()
      ff.GetObject( "grname", gr2 )
      os.remove( "test.root" )
Exemplo n.º 4
0
    def test08ReadNonTObject(self):
        """Test reading of a non-TObject derived instance"""

        f = TFile(self.fname)

        myarray = f.Get('myarray')
        self.assert_(isinstance(myarray, TArrayI))

        myarray = MakeNullPointer(TArrayI)
        f.GetObject('myarray', myarray)

        f.Close()
    def test1WriteTGraph(self):
        """Write a TGraph object and read it back correctly"""

        gr = TGraph()
        ff = TFile("test.root", "RECREATE")
        ff.WriteObject(gr, "grname", "")
        if exp_pyroot:
            # In new PyROOT, use a nicer way to get objects in files:
            # (1) getattr syntax
            ff.grname
            # (2) Get pythonisation
            ff.Get("grname")
        else:
            gr2 = TGraph()
            ff.GetObject("grname", gr2)
        os.remove("test.root")
Exemplo n.º 6
0
class rootFile:
    def __init__(self, fileName, scale=1.0, cuts=""):
        self.name = fileName
        self.scale = scale
        self.cuts = cuts
        self.file = TFile(fileName, "read")  # Open TFile
        if self.file.IsZombie():
            print "Error opening %s, exiting..." % self.name
            sys.exit(0)
        print "Opened %s, scale=%.2e, cuts='%s'" % (fileName, scale, cuts)
        self.ttree = TTree()  # Create empty TTree, and
        try:  # try to get TTree from file.
            self.file.GetObject(ttreeName,
                                self.ttree)  # ttreeName set in variables below
        except:
            print "Error: %s not found in %s, exiting..." % (ttreeName,
                                                             fileName)
            sys.exit(0)
Exemplo n.º 7
0
   def test08ReadNonTObject( self ):
      """Test reading of a non-TObject derived instance"""

      f = TFile( self.fname )

      myarray = f.Get( 'myarray' )
      self.assert_( isinstance( myarray, TArrayI ) )

      if exp_pyroot:
         # New PyROOT does not implement a pythonisation for GetObject.
         # Just use the getattr syntax, which is much nicer
         arr = f.myarray
         self.assert_( isinstance( arr, TArrayI ) )
      else:
         myarray = MakeNullPointer( TArrayI )
         f.GetObject( 'myarray', myarray )

      f.Close()
Exemplo n.º 8
0
def getsignals():
    inputfile = TFile(path)
    tree = TTree()
    inputfile.GetObject("B4", tree)

    outputfile = raw_input("Insert root output file: ")
    file = TFile(outputfile, "RECREATE")

    SignalScin = TH1F("SignalScin", "SignalScin", 100, 0., 30000.)
    SignalCher = TH1F("SignalCher", "SignalCher", 100, 0., 50000.)
    Energydep = TH1F("EnergyDep", "Energydep", 10000, 0., 100000.)
    #loop over events
    for Event in range(int(tree.GetEntries())):

        tree.GetEntry(Event)

        #Set values of the tree
        PrimaryParticleName = tree.PrimaryParticleName  # MC truth: primary particle Geant4 name
        PrimaryParticleEnergy = tree.PrimaryParticleEnergy
        EnergyTot = tree.EnergyTot  # Total energy deposited in calorimeter
        Energyem = tree.Energyem  # Energy deposited by the em component
        EnergyScin = tree.EnergyScin  # Energy deposited in Scin fibers (not Birk corrected)
        EnergyCher = tree.EnergyCher  # Energy deposited in Cher fibers (not Birk corrected)
        NofCherenkovDetected = tree.NofCherenkovDetected  # Total Cher p.e. detected
        BarrelR_VectorSignals = tree.VectorSignalsR  # Vector of energy deposited in Scin fibers (Birk corrected)
        BarrelL_VectorSignals = tree.VectorSignalsL  # Vector of energy deposited in Scin fibers (Birk corrected)
        BarrelR_VectorSignalsCher = tree.VectorSignalsCherR  # Vector of Cher p.e. detected in Cher fibers
        BarrelL_VectorSignalsCher = tree.VectorSignalsCherL  # Vecotr of Cher p.e. detected in Cher fibers
        VectorR = tree.VectorR  # Energy deposted
        VectorL = tree.VectorL  # Energy deposited

        S = sum(BarrelR_VectorSignals) + sum(BarrelL_VectorSignals)
        C = sum(BarrelR_VectorSignalsCher) + sum(BarrelL_VectorSignalsCher)
        E = sum(VectorR) + sum(VectorL)
        print S
        SignalScin.Fill(S)
        SignalCher.Fill(C)
        Energydep.Fill(E)

    SignalScin.Write()
    SignalCher.Write()
    Energydep.Write()

    file.Close()
Exemplo n.º 9
0
def make_files(filename, prfname, bkgname):
    """
	Generate files.
	
	Parameters:
	 filename - Performance file name
	 prfname  - Performance file name
	 bkgname  - File function filename
	"""
    # Open performance file and file function
    file = TFile(filename)
    fprf = open(prfname, "w")
    fbkg = open(bkgname, "w")

    # Write header
    fprf.write("log(E) Area  r68  r80  ERes. BG Rate  Diff Sens\n")
    #sys.stdout.write("log(E) Area  Area80  r68  r80  ERes. BG Rate  Diff Sens  BGRateSqDeg  BGInt  (BGIntControl)\n")

    # Get histograms. Konrad's root files do not have an EffectiveArea80
    # histogram, but his effective area is for 80% containment radius
    # anyways, so we simply read this histogram into aeff80.
    sens = TH1F()
    bgrate = TH1F()
    bgratesqdeg = TH1F()
    aeff = TH1F()
    aeff80 = TH1F()
    angres = TH1F()
    angres80 = TH1F()
    eres = TH1F()
    file.GetObject("DiffSens", sens)
    file.GetObject("BGRate", bgrate)
    file.GetObject("BGRatePerSqDeg", bgratesqdeg)
    file.GetObject("EffectiveArea", aeff)
    try:
        file.GetObject("EffectiveArea80", aeff80)
    except:
        file.GetObject("EffectiveArea", aeff80)
    file.GetObject("AngRes", angres)
    file.GetObject("AngRes80", angres80)
    file.GetObject("ERes", eres)

    # Setup vectors
    energies = bgrate.GetXaxis()
    nbins_eng = energies.GetNbins()
    for i in range(nbins_eng):

        # Get logE and background rate per squared degree
        logE = energies.GetBinCenter(i + 1)
        bgd = bgrate.GetBinContent(i + 1, 1)
        bgdsq = bgratesqdeg.GetBinContent(i + 1, 1)
        area = aeff.GetBinContent(i + 1, 1)
        area80 = aeff80.GetBinContent(i + 1, 1)
        r68 = angres.GetBinContent(i + 1, 1)
        r80 = angres80.GetBinContent(i + 1, 1)
        dE = eres.GetBinContent(i + 1, 1)
        diffs = sens.GetBinContent(i + 1, 1)

        # Skip any NaNs
        if math.isnan(area80):
            continue

        # Compute energy (in MeV)
        energy = math.pow(10.0, logE) * 1.0e6
        emin = math.pow(10.0, logE - 0.1) * 1.0e6
        emax = math.pow(10.0, logE + 0.1) * 1.0e6
        ewidth = emax - emin

        # Convert into background rate per steradian and MeV
        bkg_rate = bgdsq / (0.01745329 * 0.01745329) / ewidth

        # Compute control background rate (this only works for KB files
        # as they are for 80% containment radius). But we don't use this
        # anyways, it's just for control on display ...
        omega = 2.0 * math.pi * (1.0 - math.cos(math.radians(r80)))
        if omega > 0.0:
            bkg_rate2 = bgd / omega / ewidth
        else:
            bkg_rate2 = 0.0

        # Compute full effective area by dividing area80/0.80
        area = area80 / 0.80

        # Write results in file
        line = "%.1f  %.1f  %.4f  %.4f %.4f %.5e  %.5e" % \
              (logE, area, r68, r80, dE, bgd, diffs)
        fprf.write(line + "\n")
        fbkg.write(str(energy) + " " + str(bkg_rate) + "\n")

        # Show performance file
        #print "%.1f  %.1f  %.1f  %.4f  %.4f %.4f %.7f  %.5e  %.5e %.5e (%.5e)" % \
        #      (logE, area, area80, r68, r80, dE, bgd, diffs, bgdsq, bkg_rate, bkg_rate2)

    # Write trailer
    fprf.write("---------------------------------------------\n")
    fprf.write("Notes\n")
    fprf.write(" 1) log(E) = log10(E/TeV) - bin centre\n")
    fprf.write(
        " 2) Eff Area - in square metres after background cut (no theta cut)\n"
    )
    fprf.write(
        " 3) Ang. Res - 68% containment radius of gamma-ray PSF post cuts - in degrees\n"
    )
    fprf.write(
        " 4) Ang. Res - 80% containment radius of gamma-ray PSF post cuts - in degrees\n"
    )
    fprf.write(" 5) Fractional Energy Resolution (rms)\n")
    fprf.write(
        " 6) BG Rate  - inside point-source selection region - post call cuts - in Hz\n"
    )
    fprf.write(
        " 7) Diff Sens - differential sensitivity for this bin expressed as E^2 dN/dE\n"
    )
    fprf.write(
        " - in erg cm^-2 s^-1 - for a 50 hours exposure - 5 sigma significance including\n"
    )
    fprf.write(" systematics and statistics and at least 10 photons.\n")

    # Close files
    fprf.close()
    fbkg.close()

    # Return
    return
Exemplo n.º 10
0
n_trans_values = 3
trans_value_1 = 1.
trans_value_2 = 0.9995
trans_value_3 = 0.999
trans_values_x = [[0 for i in range(n_trans_values)] for j in range(len(lFilesIn))]
trans_values_y = [[0 for i in range(n_trans_values)] for j in range(len(lFilesIn))]
trans_values_error_y = [[0 for i in range(n_trans_values)] for j in range(len(lFilesIn))]

for i in range(0,len(lFilesIn)):
#for i in range(0,5):
        fIn = TFile(lFilesIn[i], 'read')
        ROC_curve = "LoopCut20Var2016/dataset_BDT_v"+str(i)+"/Method_BDT/BDT/MVA_BDT_rejBvsS"
	print ROC_curve
	h_ROC = TH1D("h_ROC","h_ROC",100,0,1) 
	fIn.GetObject(ROC_curve,h_ROC)

#	h_ROC.SetLineColor(i+1)
#	legend_ROC_overlay.AddEntry(h_ROC,lFilesIn[i],"l")
#	if i == 0:
#		c_ROC_overlay.Draw("")
#	else:
#		c_ROC_overlay.Draw("same")

	#get a value from each ROC curve and plot this on a single graph
	prev_bin_content = 1
	trans1Found = False
	trans2Found = False
	trans3Found = False
	for i_bins in range(1,h_ROC.GetXaxis().GetNbins()):
		bin_content = h_ROC.GetBinContent(i_bins)
Exemplo n.º 11
0
    def root2caldb(self, filename):
        """
        Generate files.

        Parameters:
         filename - Performance file name
        """
        # Open ROOT performance file
        rootfile = TFile(filename)

        # Set filenames
        ea_filename = self.bcf_path + "/" + self.ea_file
        psf_filename = self.bcf_path + "/" + self.psf_file
        edisp_filename = self.bcf_path + "/" + self.edisp_file
        bgd_filename = self.bcf_path + "/" + self.bgd_file

        # Open ASCII performance tables
        if self.ea_file == self.psf_file and \
           self.ea_file == self.edisp_file and \
           self.ea_file == self.bgd_file :
            split = False
            fprf = open(ea_filename, "w")
            files = [fprf]
        else:
            split = True
            fea = open(ea_filename, "w")
            fpsf = open(psf_filename, "w")
            fedisp = open(edisp_filename, "w")
            fbgd = open(bgd_filename, "w")
            files = [fea, fpsf, fedisp, fbgd]

        # Write header
        for file in files:
            file.write("log(E) Area  r68  r80  ERes. BG Rate  Diff Sens\n")

        # Get histograms. Konrad's root files do not have an EffectiveArea80
        # histogram, but his effective area is for 80% containment radius
        # anyways, so we simply read this histogram into aeff80.
        sens = TH1F()
        bgrate = TH1F()
        bgratesqdeg = TH1F()
        aeff = TH1F()
        aeff80 = TH1F()
        angres = TH1F()
        angres80 = TH1F()
        eres = TH1F()
        rootfile.GetObject("DiffSens", sens)
        rootfile.GetObject("BGRate", bgrate)
        rootfile.GetObject("BGRatePerSqDeg", bgratesqdeg)
        rootfile.GetObject("EffectiveArea", aeff)
        try:
            rootfile.GetObject("EffectiveArea80", aeff80)
        except:
            rootfile.GetObject("EffectiveArea", aeff80)
        rootfile.GetObject("AngRes", angres)
        rootfile.GetObject("AngRes80", angres80)
        rootfile.GetObject("ERes", eres)

        # Setup vectors
        energies = bgrate.GetXaxis()
        nbins_eng = energies.GetNbins()
        for i in range(nbins_eng):

            # Get logE and background rate per squared degree
            logE = energies.GetBinCenter(i + 1)
            bgd = bgrate.GetBinContent(i + 1, 1)
            bgdsq = bgratesqdeg.GetBinContent(i + 1, 1)
            area = aeff.GetBinContent(i + 1, 1)
            area80 = aeff80.GetBinContent(i + 1, 1)
            r68 = angres.GetBinContent(i + 1, 1)
            r80 = angres80.GetBinContent(i + 1, 1)
            dE = eres.GetBinContent(i + 1, 1)
            diffs = sens.GetBinContent(i + 1, 1)

            # Skip any NaNs
            if math.isnan(area80):
                continue

            # Compute energy (in MeV)
            energy = math.pow(10.0, logE) * 1.0e6
            emin = math.pow(10.0, logE - 0.1) * 1.0e6
            emax = math.pow(10.0, logE + 0.1) * 1.0e6
            ewidth = emax - emin

            # Convert into background rate per steradian and MeV
            bkg_rate = bgdsq / (0.01745329 * 0.01745329) / ewidth

            # Compute control background rate (this only works for KB files
            # as they are for 80% containment radius). But we don't use this
            # anyways, it's just for control on display ...
            omega = 2.0 * math.pi * (1.0 - math.cos(math.radians(r80)))
            if omega > 0.0:
                bkg_rate2 = bgd / omega / ewidth
            else:
                bkg_rate2 = 0.0

            # Compute full effective area by dividing area80/0.80
            area = area80 / 0.80

            # Write results in file
            line = "%.1f  %.1f  %.4f  %.4f %.4f %.5e  %.5e" % \
                   (logE, area, r68, r80, dE, bgd, diffs)
            for file in files:
                file.write(line + "\n")
            #fbkg.write(str(energy)+" "+str(bkg_rate)+"\n")

        # Write trailer
        for file in files:
            file.write("---------------------------------------------\n")
            file.write("Notes\n")
            file.write(" 1) log(E) = log10(E/TeV) - bin centre\n")
            file.write(
                " 2) Eff Area - in square metres after background cut (no theta cut)\n"
            )
            file.write(
                " 3) Ang. Res - 68% containment radius of gamma-ray PSF post cuts - in degrees\n"
            )
            file.write(
                " 4) Ang. Res - 80% containment radius of gamma-ray PSF post cuts - in degrees\n"
            )
            file.write(" 5) Fractional Energy Resolution (rms)\n")
            file.write(
                " 6) BG Rate  - inside point-source selection region - post call cuts - in Hz\n"
            )
            file.write(
                " 7) Diff Sens - differential sensitivity for this bin expressed as E^2 dN/dE\n"
            )
            file.write(
                " - in erg cm^-2 s^-1 - for a 50 hours exposure - 5 sigma significance including\n"
            )
            file.write(
                " systematics and statistics and at least 10 photons.\n")

        # Close files
        for file in files:
            file.close()

        # Close ROOT performance file
        rootfile.Close()

        # Add information to CIF. We do this now as before we did not
        # necessarily have all the information at hand (in particular
        # about the boundaries)
        self.add_cif_info()

        # Return
        return
Exemplo n.º 12
0
def calcSig(sigFileName):
    #    print sigFileName
    bkgFiles = [
        TFile("/afs/cern.ch/user/o/othrif/workarea/results/v48/" + Dirbase +
              "_Background/" + filename) for filename in bkgFilesNames
    ]
    sigFile = TFile(sigFileName)

    sigYield = MakeNullPointer(TH1F)
    sigFile.GetObject("hyield_weighted", sigYield)

    bkgYields = [MakeNullPointer(TH1F) for bkgFile in bkgFiles]
    for i in range(len(bkgFiles)):
        #        print bkgFilesNames[i]
        #        bkgFiles[i].GetObject("ayield_weighted",bkgYields[i])
        bkgFiles[i].GetObject("hyield_weighted", bkgYields[i])

    relativeBkgUncert = 0.3
    sigResults = []

    bin = 1
    for ilepptmax2 in range(0, len(lepptmax2_cut)):
        for ilepptmin2 in range(0, len(lepptmin2_cut)):
            for ilepptmax1 in range(0, len(lepptmax1_cut)):
                for ilepptmin1 in range(0, len(lepptmin1_cut)):
                    for ibjets in range(0, len(bjets_cut)):
                        for ibjetptmax in range(0, len(bjetptmax_cut)):
                            for ibjetptmin in range(0, len(bjetptmin_cut)):
                                for inbjets in range(0, len(nbjets_cut)):
                                    for ijetptmax in range(
                                            0, len(jetptmax_cut)):
                                        for ijetptmin in range(
                                                0, len(jetptmin_cut)):
                                            for injets in range(
                                                    0, len(njets_cut)):
                                                for imetmax in range(
                                                        0, len(metmax_cut)):
                                                    for imetmin in range(
                                                            0,
                                                            len(metmin_cut)):
                                                        baseMeff = metmin_cut[
                                                            imetmin] + njets_cut[
                                                                injets] * jetptmin_cut[
                                                                    ijetptmin] + lepptmin1_cut[
                                                                        ilepptmin1] + lepptmin2_cut[
                                                                            ilepptmin2]
                                                        for imtMmax in range(
                                                                0,
                                                                len(mtMmax_cut)
                                                        ):
                                                            for imtMmin in range(
                                                                    0,
                                                                    len(mtMmin_cut
                                                                        )):
                                                                for imeff in range(
                                                                        0,
                                                                        len(meff_cut
                                                                            )):
                                                                    for imetOmeff in range(
                                                                            0,
                                                                            len(
                                                                                metOmeff_cut
                                                                            )):
                                                                        sig = sigYield.GetAt(
                                                                            bin
                                                                        )  #*luminosity*1000
                                                                        bkg = 0.0
                                                                        statbkg = 0.0
                                                                        for ibkg in range(
                                                                                len(
                                                                                    bkgYields
                                                                                )
                                                                        ):
                                                                            #                                                                            bkgtmp = bkgYields[ibkg].GetAt(bin) #*luminosity*1000
                                                                            bkgtmp = bkgYields[
                                                                                ibkg].GetBinContent(
                                                                                    bin
                                                                                )  #*luminosity*1000
                                                                            bkgstattmp = bkgYields[
                                                                                ibkg].GetBinError(
                                                                                    bin
                                                                                )  #*luminosity*1000
                                                                            #                                                                            print bkgYields[ibkg].GetBinContent(bin), bkgYields[ibkg].GetBinError(bin)
                                                                            #    if (bkgtmp == 0):
                                                                            #        bkgtmp = useMinBkg[ibkg]
                                                                            #                                                                            print ibkg, bkgtmp
                                                                            bkg += bkgtmp
                                                                            statbkg += bkgstattmp * bkgstattmp
                                                                        statbkg = sqrt(
                                                                            statbkg
                                                                        )
                                                                        zObs = 0.0
                                                                        if (sig >=
                                                                                2
                                                                                and
                                                                                bkg
                                                                                >=
                                                                                0.8
                                                                                and
                                                                                statbkg
                                                                                /
                                                                                bkg
                                                                                <=
                                                                                0.3
                                                                            ):  # and statbkg/bkg <= 0.3
                                                                            #                                                                        if(sig>0 and bkg>0):
                                                                            zObs = RooStats.NumberCountingUtils.BinomialExpZ(
                                                                                sig,
                                                                                bkg,
                                                                                relativeBkgUncert
                                                                            )
#                                                                            print zObs, sig, bkg
                                                                        elif (bkg
                                                                              <
                                                                              0.8
                                                                              ):
                                                                            zObs = 0.01
                                                                        elif (sig
                                                                              <
                                                                              2
                                                                              ):
                                                                            zObs = 0.02
                                                                        elif (statbkg
                                                                              /
                                                                              bkg
                                                                              >
                                                                              0.3
                                                                              ):
                                                                            zObs = 0.03

#                                                                        if(zObs>0.0):
                                                                        if (zObs
                                                                                >
                                                                                0.0
                                                                                and
                                                                                inbjets
                                                                                !=
                                                                                2
                                                                            ):
                                                                            sigResults.append([
                                                                                zObs,
                                                                                [
                                                                                    lepptmax1_cut[
                                                                                        ilepptmax1],
                                                                                    lepptmin1_cut[
                                                                                        ilepptmin1],
                                                                                    lepptmax2_cut[
                                                                                        ilepptmax2],
                                                                                    lepptmin2_cut[
                                                                                        ilepptmin2],
                                                                                    bjets_cut[
                                                                                        ibjets],
                                                                                    bjetptmax_cut[
                                                                                        ibjetptmax],
                                                                                    bjetptmin_cut[
                                                                                        ibjetptmin],
                                                                                    nbjets_cut[
                                                                                        inbjets],
                                                                                    jetptmax_cut[
                                                                                        ijetptmax],
                                                                                    jetptmin_cut[
                                                                                        ijetptmin],
                                                                                    njets_cut[
                                                                                        injets],
                                                                                    metmax_cut[
                                                                                        imetmax],
                                                                                    metmin_cut[
                                                                                        imetmin],
                                                                                    mtMmax_cut[
                                                                                        imtMmax],
                                                                                    mtMmin_cut[
                                                                                        imtMmin],
                                                                                    meff_cut[
                                                                                        imeff],
                                                                                    meff_cut[
                                                                                        imeff]
                                                                                    +
                                                                                    baseMeff,
                                                                                    metOmeff_cut[
                                                                                        imetOmeff]
                                                                                ],
                                                                                sig,
                                                                                bkg
                                                                            ])
                                                                        #print bin, sig, bkg, zObs
                                                                        bin += 1
    sigResults.sort(key=lambda sig: sig[0])
    sigResults.reverse()
    return sigResults
Exemplo n.º 13
0
def ApplyAddCuts(InputFolder, OutputFolder, Campaign):

    ChannelList = ChannelList_MC16a

    if Campaign == "MC16d":
        ChannelList = ChannelList_MC16d
    if Campaign == "MC16e":
        ChannelList = ChannelList_MC16e

    TreeList = ["nominal"]

    if "SYSLJ" in InputFolder:
        TreeList = SystTreeList

    InputFiles = glob.glob(InputFolder + "/*root*")

    for InputFile in InputFiles:

        OutputFile = InputFile.replace(InputFolder, OutputFolder)

        if os.path.exists(OutputFile):
            continue

        fF = TFile(InputFile, "READ")

        fF_out = TFile(OutputFile, "RECREATE")

        # save sumWeights tree to new file
        fT_weight = fF.Get("sumWeights")
        fT_weight_out = fT_weight.CloneTree()

        fT_weight_out.Write()

        # save all bookkeeping histograms to new file
        for Channel in ChannelList:

            DIR = TDirectory()
            fF.GetObject(Channel, DIR)
            DIR.ReadAll()
            fF_out.mkdir(Channel)
            fF_out.cd(Channel)
            DIR_new = TDirectory()
            DIR.GetList().Write()
            DIR_new.Write()

            fF_out.cd()

        for TreeName in TreeList:

            print(
                "---------------------------------------------------------------------------> Running over tree = ",
                TreeName)

            if TreeName == "nominal_SYST":
                continue

            fT = fF.Get(TreeName)
            entries = fT.GetEntries()
            reader1 = TMVA.Reader()
            reader2 = TMVA.Reader()

            var_LL_1 = array('f', [0])
            reader1.AddVariable("klfitter_logLikelihood[0]", var_LL_1)
            var_EvtProb_1 = array('f', [0])
            reader1.AddVariable("klfitter_eventProbability[0]", var_EvtProb_1)
            var_WhadPt_1 = array('f', [0])
            reader1.AddVariable("klf_orig_Whad_pt", var_WhadPt_1)
            var_WlepPt_1 = array('f', [0])
            reader1.AddVariable("klf_orig_Wlep_pt", var_WlepPt_1)
            var_ThadPt_1 = array('f', [0])
            reader1.AddVariable("klf_orig_tophad_pt", var_ThadPt_1)
            var_TlepPt_1 = array('f', [0])
            reader1.AddVariable("klf_orig_toplep_pt", var_TlepPt_1)
            var_j_n_1 = array('f', [0])
            reader1.AddVariable("tma_njets", var_j_n_1)
            var_met_1 = array('f', [0])
            reader1.AddVariable("tma_met", var_met_1)
            var_TTbarPt_1 = array('f', [0])
            reader1.AddVariable("klf_orig_ttbar_pt", var_TTbarPt_1)
            var_mwt_1 = array('f', [0])
            reader1.AddVariable("tma_mtw", var_mwt_1)
            var_DRwjets_1 = array('f', [0])
            reader1.AddVariable("klf_orig_dR_qq_W", var_DRwjets_1)
            var_DRbjets_1 = array('f', [0])
            reader1.AddVariable("klf_orig_dR_bb", var_DRbjets_1)

            var_LL_2 = array('f', [0])
            reader2.AddVariable("klfitter_logLikelihood[0]", var_LL_2)
            var_EvtProb_2 = array('f', [0])
            reader2.AddVariable("klfitter_eventProbability[0]", var_EvtProb_2)
            var_WhadPt_2 = array('f', [0])
            reader2.AddVariable("klf_orig_Whad_pt", var_WhadPt_2)
            var_WlepPt_2 = array('f', [0])
            reader2.AddVariable("klf_orig_Wlep_pt", var_WlepPt_2)
            var_ThadPt_2 = array('f', [0])
            reader2.AddVariable("klf_orig_tophad_pt", var_ThadPt_2)
            var_TlepPt_2 = array('f', [0])
            reader2.AddVariable("klf_orig_toplep_pt", var_TlepPt_2)
            var_j_n_2 = array('f', [0])
            reader2.AddVariable("tma_njets", var_j_n_2)
            var_met_2 = array('f', [0])
            reader2.AddVariable("tma_met", var_met_2)
            var_TTbarPt_2 = array('f', [0])
            reader2.AddVariable("klf_orig_ttbar_pt", var_TTbarPt_2)
            var_mwt_2 = array('f', [0])
            reader2.AddVariable("tma_mtw", var_mwt_2)
            var_DRwjets_2 = array('f', [0])
            reader2.AddVariable("klf_orig_dR_qq_W", var_DRwjets_2)
            var_DRbjets_2 = array('f', [0])
            reader2.AddVariable("klf_orig_dR_bb", var_DRbjets_2)

            reader1.BookMVA(
                "BDT",
                "TrainingSteffenChristmas/weights_noWindowCuts/MassTraining_BDT.weights.xml"
            )
            reader2.BookMVA(
                "BDT",
                "TrainingSteffenChristmas/weights_withWindowCuts/MassTraining_BDT.weights.xml"
            )

            fT_out = fT.CloneTree(0)
            d_noWC = array('f', [0.])
            d_withWC = array('f', [0.])

            fT_out.Branch("bdtOutput_8TeVlike_noWC", d_noWC,
                          'bdtOutput_8TeVlike_noWC/F')
            fT_out.Branch("bdtOutput_8TeVlike_withWC", d_withWC,
                          'bdtOutput_8TeVlike_withWC/F')

            for i in range(0, entries):
                fT.GetEntry(i)

                var_LL_1[0] = fT.klfitter_logLikelihood[0]
                var_EvtProb_1[0] = fT.klfitter_eventProbability[0]
                var_WhadPt_1[0] = fT.klf_orig_Whad_pt
                var_WlepPt_1[0] = fT.klf_orig_Wlep_pt
                var_ThadPt_1[0] = fT.klf_orig_tophad_pt
                var_TlepPt_1[0] = fT.klf_orig_toplep_pt
                var_j_n_1[0] = fT.tma_njets
                var_met_1[0] = fT.tma_met
                var_TTbarPt_1[0] = fT.klf_orig_ttbar_pt
                var_mwt_1[0] = fT.tma_mtw
                var_DRwjets_1[0] = fT.klf_orig_dR_qq_W
                var_DRbjets_1[0] = fT.klf_orig_dR_bb

                var_LL_2[0] = fT.klfitter_logLikelihood[0]
                var_EvtProb_2[0] = fT.klfitter_eventProbability[0]
                var_WhadPt_2[0] = fT.klf_orig_Whad_pt
                var_WlepPt_2[0] = fT.klf_orig_Wlep_pt
                var_ThadPt_2[0] = fT.klf_orig_tophad_pt
                var_TlepPt_2[0] = fT.klf_orig_toplep_pt
                var_j_n_2[0] = fT.tma_njets
                var_met_2[0] = fT.tma_met
                var_TTbarPt_2[0] = fT.klf_orig_ttbar_pt
                var_mwt_2[0] = fT.tma_mtw
                var_DRwjets_2[0] = fT.klf_orig_dR_qq_W
                var_DRbjets_2[0] = fT.klf_orig_dR_bb

                d_noWC[0] = reader1.EvaluateMVA("BDT")
                d_withWC[0] = reader2.EvaluateMVA("BDT")

                #print d_noWC[0],"     ",d_withWC[0]

                fT_out.Fill()

            fT_out.Write()

        fF_out.Close()
Exemplo n.º 14
0
def jetdisplay():
    outputfile = "hznb"
    displayfile = TFile(outputfile + ".root", "RECREATE")

    inputfiles = ["hznb_noleakage_029/hznb.root"]

    #for geant4.10.5
    inputfiles = ["resultsgeant4.10.5/jetscan_leakage/hznb/hznb.root"]
    #end of geant4.10.5

    #for geant4.10.5 FTFPBERT
    inputfiles = ["results_FTFPBERT/noBnoX0/2j/hznb.root"]
    #end geant4.10.5 FTFPBERT

    for counter, inputfile in enumerate(inputfiles):
        inputfile = TFile(inputfile)
        print "Analyzing: " + str(inputfile) + " \n"
        tree = TTree()
        inputfile.GetObject("MyTree", tree)

        #graphEjet1 = TH1F("energyjet1", "energyjet1", 100, 0., 200.)
        #graphEjet2 = TH1F("energyjet2", "energyjet2", 100, 0., 200.)

        #graphEcherjet1 = TH1F("energycher1", "energycherjet", 100, 0., 200.)
        #graph3 = TH1F("energyscinjet", "energyscinjet", 100, 0., 200.)

        #graphmass = TH1F("mass_jet", "mass_jet", 100, 0., 200.)
        graphtest = TH1F("test", "test", 80, -40., 40.)
        graphenergy = TH1F("energy", "energy", 100, 60., 160.)
        graphenergytruth = TH1F("energytruth", "energytruth", 100, 60., 160.)
        graphjs = TH1F("energyjs", "energyjs", 200, 0., 100.)
        graphjc = TH1F("energyjc", "energyjc", 200, 0., 100.)

        #loop over events
        for Event in range(tree.GetEntries()):

            tree.GetEntry(Event)
            #print "Event "+str(Event)
            nmuon = tree.nmuon
            nneu = tree.nneu
            mjjr = tree.mjjr
            mjjt = tree.mjjt
            edep = tree.edep
            muene_che = tree.muene_che
            muene_sci = tree.muene_sci
            emcomp1 = tree.emcomp1
            emcomp2 = tree.emcomp2
            eleak = tree.eleak
            eleakn = tree.eleakn

            j1t_E = tree.j1t_E
            j1t_m = tree.j1t_m
            j1t_theta = tree.j1t_theta
            j1t_pt = tree.j1t_pt
            j1t_eta = tree.j1t_eta
            j1t_phi = tree.j1t_phi
            j2t_E = tree.j2t_E
            j2t_m = tree.j2t_m
            j2t_theta = tree.j2t_theta
            j2t_pt = tree.j2t_pt
            j2t_eta = tree.j2t_eta
            j2t_phi = tree.j2t_phi

            j1r_E = tree.j1r_E
            j1r_m = tree.j1r_m
            j1r_theta = tree.j1r_theta
            j1r_pt = tree.j1r_pt
            j1r_eta = tree.j1r_eta
            j1r_phi = tree.j1r_phi
            j2r_E = tree.j2r_E
            j2r_m = tree.j2r_m
            j2r_theta = tree.j2r_theta
            j2r_pt = tree.j2r_pt
            j2r_eta = tree.j2r_eta
            j2r_phi = tree.j2r_phi

            #deltaj1 = 0.04406*j1r_E+0.1158
            #deltaj1 = 0.04135*j1r_E+0.08789
            deltaj1 = 0.07113 * j1r_E + 0.5201
            j1 = TLorentzVector()
            j1.SetPtEtaPhiE(j1r_pt + deltaj1 * np.sin(j1r_theta), j1r_eta,
                            j1r_phi, j1r_E + deltaj1)
            #deltaj2 = 0.04406*j2r_E+0.1158
            #deltaj2 = 0.04135*j2r_E+0.08789
            deltaj2 = 0.07113 * j2r_E + 0.5201
            j2 = TLorentzVector()
            j2.SetPtEtaPhiE(j2r_pt + deltaj2 * np.sin(j2r_theta), j2r_eta,
                            j2r_phi, j2r_E + deltaj2)
            newmass = (j1 + j2).M()

            j1s_E = tree.j1s_E
            j1s_m = tree.j1s_m
            j1s_theta = tree.j1s_theta
            j1s_pt = tree.j1s_pt
            j1s_eta = tree.j1s_eta
            j1s_phi = tree.j1s_phi
            j2s_E = tree.j2s_E
            j2s_m = tree.j2s_m
            j2s_theta = tree.j2s_theta
            j2s_pt = tree.j2s_pt
            j2s_eta = tree.j2s_eta
            j2s_phi = tree.j2s_phi

            j1c_E = tree.j1c_E
            j1c_m = tree.j1c_m
            j1c_theta = tree.j1c_theta
            j1c_pt = tree.j1c_pt
            j1c_eta = tree.j1c_eta
            j1c_phi = tree.j1c_phi
            j2c_E = tree.j2c_E
            j2c_m = tree.j2c_m
            j2c_theta = tree.j2c_theta
            j2c_pt = tree.j2c_pt
            j2c_eta = tree.j2c_eta
            j2c_phi = tree.j2c_phi

            cut1 = nmuon == 0 and nneu == 2
            cut2 = abs(j1t_eta) < 2.0 and abs(j2t_eta) < 2.0
            cut3 = eleak < 1000.
            #cut4 = j1t_E+j2t_E>85.0
            cut4 = True
            #cut5 = edep>100
            cut5 = True
            if cut1 and cut2 and cut3 and cut4 and cut5:
                graphtest.Fill(j1r_E - j1t_E)
                graphtest.Fill(j2r_E - j2t_E)
                graphenergy.Fill(newmass)
                #graphenergy.Fill(j2r_E+deltaj2)
                #graphenergytruth.Fill(j1t_E)
                #graphenergytruth.Fill(j2t_E+j1t_E)
                graphenergytruth.Fill(mjjt)
                graphjs.Fill(j2s_E)
                graphjs.Fill(j1s_E)
                graphjc.Fill(j2c_E)
                graphjc.Fill(j1c_E)

        displayfile.cd()
        #graphtest.Write()
        scale = 1. / graphenergy.Integral()
        graphenergy.Scale(scale)
        graphenergy.Write()
        graphenergytruth.Write()
Exemplo n.º 15
0
def recenergy():
    outputfile = "EMEnergyRes"
    displayfile = TFile(outputfile + ".root", "RECREATE")

    MeanEnergyScin = array('d')
    MeanEnergyCher = array('d')
    Energy = array('d')
    energyfractionscin = array('d')
    energyfractioncher = array('d')
    energyfraction = array('d')
    resolutionscin = array('d')
    resolutioncher = array('d')
    resolution = array('d')

    energies = array(
        'd',
        [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150])
    energies = array('d', [40, 50, 60, 70, 80, 90, 100])
    energies = array('d', [5, 10, 40, 60, 80, 100, 150])
    sqrtenergies = array('d', [1 / (x**0.5) for x in energies])
    scin_sqrtenergies = array('d')
    cher_sqrtenergies = array('d')
    #inputfiles = sorted(glob.glob(datapath+"*"), key=os.path.getmtime) #get files from tower 1 to 75 ordered by creation time
    t = [5, 10, 40, 60, 80, 100, 150]
    inputfiles = [
        "/home/software/Calo/results/newenergyscan3_noangsmearing/Electron_" +
        str(i) + ".root" for i in t
    ]
    for counter, inputfile in enumerate(inputfiles):
        inputfile = TFile(inputfile)
        print "Analyzing: " + str(inputfile) + " \n"
        tree = TTree()
        inputfile.GetObject("B4", tree)

        ScinEnergyHist = TH1F("scinenergy_",
                              str(counter + 1) + "_scin", 500, 0., 200.)
        CherEnergyHist = TH1F("cherenergy_",
                              str(counter + 1) + "_cher", 500, 0., 200.)
        RecEnergyHist = TH1F("RecEnergy_",
                             str(counter + 1) + "_Energy", 500, 0., 200.)

        Signalscinhist = TH1F("scintot_",
                              str(counter + 1) + "_scin", 3000, 0., 30000)
        EnergyHist = TH1F("Energy_",
                          str(counter + 1) + "_Energy", 500, 0., 200.)

        #loop over events
        for Event in range(int(tree.GetEntries())):

            tree.GetEntry(Event)

            #Set values of the tree
            PrimaryParticleName = tree.PrimaryParticleName  # MC truth: primary particle Geant4 name
            PrimaryParticleEnergy = tree.PrimaryParticleEnergy
            EnergyTot = tree.EnergyTot  # Total energy deposited in calorimeter
            Energyem = tree.Energyem  # Energy deposited by the em component
            EnergyScin = tree.EnergyScin  # Energy deposited in Scin fibers (not Birk corrected)
            EnergyCher = tree.EnergyCher  # Energy deposited in Cher fibers (not Birk corrected)
            NofCherenkovDetected = tree.NofCherenkovDetected  # Total Cher p.e. detected
            BarrelR_VectorSignals = tree.VectorSignalsR  # Vector of energy deposited in Scin fibers (Birk corrected)
            BarrelL_VectorSignals = tree.VectorSignalsL  # Vector of energy deposited in Scin fibers (Birk corrected)
            BarrelR_VectorSignalsCher = tree.VectorSignalsCherR  # Vector of Cher p.e. detected in Cher fibers
            BarrelL_VectorSignalsCher = tree.VectorSignalsCherL
            VectorR = tree.VectorR
            VectorL = tree.VectorL

            totalsignalscin = sum(BarrelR_VectorSignals) + sum(
                BarrelL_VectorSignals)
            Signalscinhist.Fill(totalsignalscin)

            energytot = (sum(VectorR) + sum(VectorL)) / 1000
            EnergyHist.Fill(energytot)

            #apply calibrations
            Calib_BarrelL_VectorSignals = calibration.calibscin(
                BarrelL_VectorSignals)
            Calib_BarrelR_VectorSignals = calibration.calibscin(
                BarrelR_VectorSignals)
            Calib_BarrelL_VectorSignalsCher = calibration.calibcher(
                BarrelL_VectorSignalsCher)
            Calib_BarrelR_VectorSignalsCher = calibration.calibcher(
                BarrelR_VectorSignalsCher)
            #end of calibrations

            energyscin = sum(Calib_BarrelR_VectorSignals) + sum(
                Calib_BarrelL_VectorSignals)
            energycher = sum(Calib_BarrelR_VectorSignalsCher) + sum(
                Calib_BarrelL_VectorSignalsCher)

            ScinEnergyHist.Fill(energyscin)
            sigmascin = 0.15 * (energyscin**0.5) + 0.012 * energyscin
            CherEnergyHist.Fill(energycher)
            sigmacher = 0.18 * (energycher**0.5) + 0.0045 * energycher
            RecEnergyHist.Fill(
                (energyscin / (sigmascin**2) + energycher /
                 (sigmacher**2)) / (1 / sigmascin**2 + 1 / sigmacher**2))

        print energies[counter], ScinEnergyHist.GetMean(
        ), CherEnergyHist.GetMean()
        displayfile.cd()
        gStyle.SetOptStat(111)
        ScinEnergyHist.Fit("gaus")
        CherEnergyHist.Fit("gaus")
        RecEnergyHist.Fit("gaus")
        RecEnergyHist.Write()
        ScinEnergyHist.Write()
        CherEnergyHist.Write()
        Signalscinhist.Write()
        EnergyHist.Write()
        scin_sqrtenergies.append(
            1. / (ScinEnergyHist.GetFunction("gaus").GetParameter(1)**0.5))
        cher_sqrtenergies.append(
            1. / (CherEnergyHist.GetFunction("gaus").GetParameter(1)**0.5))
        MeanEnergyScin.append(
            ScinEnergyHist.GetFunction("gaus").GetParameter(1))
        MeanEnergyCher.append(
            CherEnergyHist.GetFunction("gaus").GetParameter(1))
        resolution.append(
            RecEnergyHist.GetFunction("gaus").GetParameter(2) /
            RecEnergyHist.GetFunction("gaus").GetParameter(1))
        energyfractionscin.append(
            ScinEnergyHist.GetFunction("gaus").GetParameter(1))
        energyfractioncher.append(
            CherEnergyHist.GetFunction("gaus").GetParameter(1))
        energyfraction.append(
            RecEnergyHist.GetFunction("gaus").GetParameter(1))
        resolutionscin.append(
            ScinEnergyHist.GetFunction("gaus").GetParameter(2) /
            ScinEnergyHist.GetFunction("gaus").GetParameter(1))
        resolutioncher.append(
            CherEnergyHist.GetFunction("gaus").GetParameter(2) /
            CherEnergyHist.GetFunction("gaus").GetParameter(1))

    LinearityGraph = TGraph(len(energies), energies, energyfraction)
    LinearityGraph.SetName("LinearityGraph")
    LinearityGraph.Write()
    LinearityGraphScin = TGraph(len(energies), energies, energyfractionscin)
    LinearityGraphCher = TGraph(len(energies), energies, energyfractioncher)
    LinearityGraphCher.SetName("LinearityGraphCher")
    LinearityGraphCher.Write()
    LinearityGraphScin.SetName("LinearityGraphScin")
    LinearityGraphScin.Write()

    ResolutionGraphScin = TGraph(len(energies), scin_sqrtenergies,
                                 resolutionscin)
    func = TF1("func", "[0]*x+[1]", 0.1, 0.45)
    ResolutionGraphCher = TGraph(len(energies), cher_sqrtenergies,
                                 resolutioncher)
    ResolutionGraphScin.Fit("func", "R")
    ResolutionGraphCher.Fit("func", "R")
    ResolutionGraphScin.SetName("ResolutionGraphScin")
    ResolutionGraphScin.Write()
    ResolutionGraphCher.SetName("ResolutionGraphCher")
    ResolutionGraphCher.Write()
    ResolutionGraph = TGraph(len(energies), sqrtenergies, resolution)
    ResolutionGraph.Fit("func", "R")
    ResolutionGraph.SetName("ResolutionGraph")
    ResolutionGraph.Write()

    rd52copper = array('d', [
        0.04478505426185217, 0.027392527130926082, 0.02420093893609386,
        0.02229837387624884, 0.020999999999999998
    ])

    rd52graph = TGraph(len(energies), sqrtenergies, rd52copper)
    rd52graph.SetName("rd52resolution")
    rd52graph.Write()

    EMResolutions = TMultiGraph()
    EMResolutions.Add(ResolutionGraphScin)
    EMResolutions.Add(ResolutionGraphCher)
    EMResolutions.Add(ResolutionGraph)
    EMResolutions.Add(rd52graph)
    EMResolutions.SetName("EMResolutions")
    EMResolutions.Write()

    Linearities = TMultiGraph()
    Linearities.Add(LinearityGraph)
    Linearities.Add(LinearityGraphScin)
    Linearities.Add(LinearityGraphCher)
    Linearities.SetName("Linearities")
    Linearities.Write()
Exemplo n.º 16
0
def jetdisplay():
    outputfile = "wwlj"
    displayfile = TFile(outputfile + ".root", "RECREATE")

    inputfiles = ["wwlj10k_leakage_029/wwlj.root"]
    #for geant4.10.5
    inputfiles = ["resultsgeant4.10.5/wwlj/wwlj.root"]
    inputfiles = ["resultsgeant4.10.5/jetscan_leakage_X0/wwlj/wwlj.root"]
    #end of geant4.10.5

    for counter, inputfile in enumerate(inputfiles):
        inputfile = TFile(inputfile)
        print "Analyzing: " + str(inputfile) + " \n"
        tree = TTree()
        inputfile.GetObject("MyTree", tree)

        #graphEjet1 = TH1F("energyjet1", "energyjet1", 100, 0., 200.)
        #graphEjet2 = TH1F("energyjet2", "energyjet2", 100, 0., 200.)

        #graphEcherjet1 = TH1F("energycher1", "energycherjet", 100, 0., 200.)
        #graph3 = TH1F("energyscinjet", "energyscinjet", 100, 0., 200.)

        #graphmass = TH1F("mass_jet", "mass_jet", 100, 0., 200.)
        graphtest = TH1F("test", "test", 80, -40., 40.)
        graphenergy = TH1F("energy", "energy", 90, 60., 120.)
        graphenergytruth = TH1F("energytruth", "energytruth", 90, 60., 120.)
        graphjs = TH1F("energyjs", "energyjs", 200, 0., 100.)
        graphjc = TH1F("energyjc", "energyjc", 200, 0., 100.)
        graphdiff = TH1F("diff_mass", "diff_mass", 40, -20., 20.)
        #loop over events
        for Event in range(tree.GetEntries()):

            tree.GetEntry(Event)
            #print "Event "+str(Event)
            nmuon = tree.nmuon
            nneu = tree.nneu
            mjjr = tree.mjjr
            mjjt = tree.mjjt
            edep = tree.edep
            muene_che = tree.muene_che
            muene_sci = tree.muene_sci
            emcomp1 = tree.emcomp1
            emcomp2 = tree.emcomp2
            eleak = tree.eleak
            eleakn = tree.eleakn
            drmmu = tree.drmmu
            emu = tree.emu
            enumu = tree.enumu

            j1t_E = tree.j1t_E
            j1t_m = tree.j1t_m
            j1t_theta = tree.j1t_theta
            j1t_pt = tree.j1t_pt
            j1t_eta = tree.j1t_eta
            j1t_phi = tree.j1t_phi
            j2t_E = tree.j2t_E
            j2t_m = tree.j2t_m
            j2t_theta = tree.j2t_theta
            j2t_pt = tree.j2t_pt
            j2t_eta = tree.j2t_eta
            j2t_phi = tree.j2t_phi

            j1r_E = tree.j1r_E
            j1r_m = tree.j1r_m
            j1r_theta = tree.j1r_theta
            j1r_pt = tree.j1r_pt
            j1r_eta = tree.j1r_eta
            j1r_phi = tree.j1r_phi
            j2r_E = tree.j2r_E
            j2r_m = tree.j2r_m
            j2r_theta = tree.j2r_theta
            j2r_pt = tree.j2r_pt
            j2r_eta = tree.j2r_eta
            j2r_phi = tree.j2r_phi

            deltaj1 = 0.04406 * j1r_E + 0.1158
            deltaj1 = 0.04135 * j1r_E + 0.08789
            deltaj1 = 0.04911 * j1r_E + 0.05723
            j1 = TLorentzVector()
            j1.SetPtEtaPhiE(j1r_pt + deltaj1 * np.sin(j1r_theta), j1r_eta,
                            j1r_phi, j1r_E + deltaj1)
            deltaj2 = 0.04406 * j2r_E + 0.1158
            deltaj2 = 0.04135 * j2r_E + 0.08789
            deltaj2 = 0.04911 * j2r_E + 0.05723
            j2 = TLorentzVector()
            j2.SetPtEtaPhiE(j2r_pt + deltaj2 * np.sin(j2r_theta), j2r_eta,
                            j2r_phi, j2r_E + deltaj2)
            newmass = (j1 + j2).M()

            j1s_E = tree.j1s_E
            j1s_m = tree.j1s_m
            j1s_theta = tree.j1s_theta
            j1s_pt = tree.j1s_pt
            j1s_eta = tree.j1s_eta
            j1s_phi = tree.j1s_phi
            j2s_E = tree.j2s_E
            j2s_m = tree.j2s_m
            j2s_theta = tree.j2s_theta
            j2s_pt = tree.j2s_pt
            j2s_eta = tree.j2s_eta
            j2s_phi = tree.j2s_phi

            j1c_E = tree.j1c_E
            j1c_m = tree.j1c_m
            j1c_theta = tree.j1c_theta
            j1c_pt = tree.j1c_pt
            j1c_eta = tree.j1c_eta
            j1c_phi = tree.j1c_phi
            j2c_E = tree.j2c_E
            j2c_m = tree.j2c_m
            j2c_theta = tree.j2c_theta
            j2c_pt = tree.j2c_pt
            j2c_eta = tree.j2c_eta
            j2c_phi = tree.j2c_phi

            cut1 = nmuon == 1 and nneu == 1
            cut2 = abs(j1t_phi - j2t_phi) > 0.1
            cut3 = enumu + j1t_E + j2t_E > 162.45
            cut4 = eleak / 1000. - emu + muene_sci < 5.
            cut5 = j1r_E + j2r_E > 68.0
            cut6 = muene_sci < 4.0

            if cut1 and cut2 and cut3 and cut4 and cut5 and cut6:
                graphtest.Fill(j1r_E - j1t_E)
                graphtest.Fill(j2r_E - j2t_E)
                deltaj1 = 0.02175 * j1r_E + 0.0808
                deltaj2 = 0.02175 * j2r_E + 0.0808
                graphenergy.Fill(newmass)
                #graphenergy.Fill(j2r_E+deltaj2)
                #graphenergytruth.Fill(j1t_E)
                #graphenergytruth.Fill(j2t_E+j1t_E)
                graphenergytruth.Fill(mjjt)
                graphdiff.Fill(newmass - mjjt)
                graphjs.Fill(j2s_E)
                graphjs.Fill(j1s_E)
                graphjc.Fill(j2c_E)
                graphjc.Fill(j1c_E)

        displayfile.cd()
        #graphtest.Write()
        graphenergy.Write()
        graphenergytruth.Write()
        graphdiff.Write()
Exemplo n.º 17
0
class CompareSpring15:
    def __init__(self):
        self.ref = ""
        self.test = ""

        self.cref = None
        self.ctest = None

        self.lref = []
        self.ltest = []

        self.ref_missing = []
        self.test_missing = []

        self.bad_events = []
        self.bad_leptons = []
        self.bad_met = []
        self.bad_mvamet = []
        self.bad_jets = []

        self.good_events = []

    def load(self, ref, test):
        self.ref = ref
        self.test = test

        #self.cref=TChain(ref.split(":")[1])
        #self.ctest=TChain(test.split(":")[1])

        #self.cref.Add(ref.split(":")[0])
        #self.ctest.Add(test.split(":")[0])

        self.fref = TFile(ref.split(":")[0])
        self.ftest = TFile(test.split(":")[0])

        self.cref = TTree()
        self.fref.GetObject(ref.split(":")[1], self.cref)

        self.ctest = TTree()
        self.ftest.GetObject(test.split(":")[1], self.ctest)

        self.lref = load_entries(self.cref)
        self.ltest = load_entries(self.ctest)

    def Compare(self):
        print self.cref.GetEntries(), self.ctest.GetEntries()

        self.ref_min_pt_1 = 9999999999.
        self.ref_min_pt_2 = 9999999999.

        self.test_min_pt_1 = 9999999999.
        self.test_min_pt_2 = 9999999999.

        iref = 0
        itest = 0

        self.cref.LoadBaskets(2000000000)
        self.ctest.LoadBaskets(2000000000)

        while (iref < len(self.lref)):
            ref_id = self.lref[iref][1]

            while (itest < len(self.ltest)):
                test_id = self.ltest[itest][1]

                if (test_id < ref_id):
                    self.ref_missing.append(self.ltest[itest])
                elif (test_id > ref_id):
                    self.test_missing.append(self.lref[iref])
                    break
                else:
                    break
                itest += 1

            if (test_id != ref_id):
                iref += 1
                continue

            if (self.cref.pt_1 < self.ref_min_pt_1):
                self.ref_min_pt_1 = self.cref.pt_1
            if (self.cref.pt_2 < self.ref_min_pt_2):
                self.ref_min_pt_2 = self.cref.pt_2

            if (self.ctest.pt_1 < self.test_min_pt_1):
                self.test_min_pt_1 = self.ctest.pt_1
            if (self.ctest.pt_2 < self.test_min_pt_2):
                self.test_min_pt_2 = self.ctest.pt_2

            isGood = True

            self.cref.GetEntry(self.lref[iref][0])
            self.ctest.GetEntry(self.ltest[itest][0])

            # compare leptons
            if (not areEqual(self.cref.pt_1, self.ctest.pt_1)
                    or not areEqual(self.cref.iso_1, self.ctest.iso_1)
                    or not areEqual(self.cref.pt_2, self.ctest.pt_2)
                    or not areEqual(self.cref.iso_2, self.ctest.iso_2)):

                isGood = False

                print "Event", self.lref[iref][1]
                print "    lep1: pt=",self.cref.pt_1, self.ctest.pt_1,\
                        ", eta=",self.cref.eta_1,self.ctest.eta_1,\
                        ", phi=",self.cref.phi_1,self.ctest.phi_1,\
                        ", iso=",self.cref.iso_1,self.ctest.iso_1,\
                        ", q=",self.cref.q_1,self.ctest.q_1
                print "    lep2: pt=",self.cref.pt_2, self.ctest.pt_2,\
                        ", eta=",self.cref.eta_2,self.ctest.eta_2,\
                        ", phi=",self.cref.phi_2,self.ctest.phi_2,\
                        ", iso=",self.cref.iso_2,self.ctest.iso_2,\
                        ", q=",self.cref.q_2,self.ctest.q_2

                refDR = deltaR(self.cref.eta_1, self.cref.phi_1,
                               self.cref.eta_2, self.cref.phi_2)
                testDR = deltaR(self.ctest.eta_1, self.ctest.phi_1,
                                self.ctest.eta_2, self.ctest.phi_2)
                print "    deltaR(lep1, lep2)=", refDR, testDR

                self.bad_leptons.append((self.lref[iref], self.ltest[itest]))

            # compare met
            if (not areEqual(self.cref.met, self.ctest.met)):

                isGood = False

                print "Event", self.lref[iref][1]
                print "    met: |met|=", self.cref.met, self.ctest.met

                self.bad_met.append((self.lref[iref], self.ltest[itest]))

            iref += 1
            itest += 1

    def Print(self):

        print len(self.ref_missing), "Events missing in ref tree"
        print len(self.test_missing), "Events missing in test tree"

        print "Events missing in test tree:"
        print[x[1] for x in self.test_missing]

        print
        print "Events missing in ref tree:"
        print[x[1] for x in self.ref_missing]

        print
        print len(self.bad_leptons), "Events with bad leptons"
        print[x[0][1] for x in self.bad_leptons]

        print
        print len(self.bad_met), "Events with bad pfmet"
        print[x[0][1] for x in self.bad_met]

        print self.ref_min_pt_1, self.test_min_pt_1
        print self.ref_min_pt_2, self.test_min_pt_2
Exemplo n.º 18
0
def jetdisplay():
	outputfile = "wwlj"
	displayfile = TFile(outputfile+".root","RECREATE")

	#for geant4.10.5 FTFPBERT
	inputfiles = ["Results/noBnoX0/2j_0.445/wwjl_0.445.root"]
	#end geant4.10.5 FTFPBERT

	for counter, inputfile in enumerate(inputfiles):
		inputfile = TFile(inputfile)
		print "Analyzing: "+str(inputfile)+" \n"
		tree = TTree()
		inputfile.GetObject("MyTree", tree)	

		#graphEjet1 = TH1F("energyjet1", "energyjet1", 100, 0., 200.)
		#graphEjet2 = TH1F("energyjet2", "energyjet2", 100, 0., 200.)
		
		#graphEcherjet1 = TH1F("energycher1", "energycherjet", 100, 0., 200.)
		#graph3 = TH1F("energyscinjet", "energyscinjet", 100, 0., 200.)
		
		#graphmass = TH1F("mass_jet", "mass_jet", 100, 0., 200.)
		graphtest = TH1F("test", "test", 80, -40., 40.)
		graphenergy = TH1F("energy", "energy", 100, 60., 160.)
		graphenergytruth = TH1F("energytruth", "energytruth", 100, 60., 160.) 
		graphjs = TH1F("energyjs", "energyjs", 200, 0., 100.) 
		graphjc = TH1F("energyjc", "energyjc", 200, 0., 100.) 
		graphdiff = TH1F("diff_mass", "diff_mass", 250, -25.,25.)
		#loop over events
		for Event in range(tree.GetEntries()):		

			tree.GetEntry(Event)	
			#print "Event "+str(Event)
			nmuon = tree.nmuon
			nneu = tree.nneu
			mjjr = tree.mjjr
			mjjt = tree.mjjt
			edep = tree.edep
			muene_che = tree.muene_che
			muene_sci = tree.muene_sci
			emcomp1 = tree.emcomp1
			emcomp2 = tree.emcomp2
			eleak = tree.eleak
			eleakn = tree.eleakn
			drmmu = tree.drmmu
			emu = tree.emu
			enumu = tree.enumu
			   
			j1t_E = tree.j1t_E
			j1t_m = tree.j1t_m
			j1t_theta = tree.j1t_theta
			j1t_pt = tree.j1t_pt
			j1t_eta = tree.j1t_eta
			j1t_phi = tree.j1t_phi
			j2t_E = tree.j2t_E
			j2t_m = tree.j2t_m
			j2t_theta = tree.j2t_theta
			j2t_pt = tree.j2t_pt
			j2t_eta = tree.j2t_eta
			j2t_phi = tree.j2t_phi	

			j1r_E = tree.j1r_E
			j1r_m = tree.j1r_m
			j1r_theta = tree.j1r_theta
			j1r_pt = tree.j1r_pt
			j1r_eta = tree.j1r_eta
			j1r_phi = tree.j1r_phi
			j2r_E = tree.j2r_E
			j2r_m = tree.j2r_m
			j2r_theta = tree.j2r_theta
			j2r_pt = tree.j2r_pt
			j2r_eta = tree.j2r_eta
			j2r_phi = tree.j2r_phi	

			
			#deltaj1 = 0.04406*j1r_E+0.1158
			#deltaj1 = 0.04135*j1r_E+0.08789
			deltaj1 = 0.07113*j1r_E+0.5201
			j1 = TLorentzVector()
			j1.SetPtEtaPhiE(j1r_pt, j1r_eta, j1r_phi, j1r_E)
			#deltaj2 = 0.04406*j2r_E+0.1158
			#deltaj2 = 0.04135*j2r_E+0.08789
			deltaj2 = 0.07113*j2r_E+0.5201
			j2 = TLorentzVector()
			j2.SetPtEtaPhiE(j2r_pt, j2r_eta, j2r_phi, j2r_E)
			newmass = (j1+j2).M()

			j1s_E = tree.j1s_E
			j1s_m = tree.j1s_m
			j1s_theta = tree.j1s_theta
			j1s_pt = tree.j1s_pt
			j1s_eta = tree.j1s_eta
			j1s_phi = tree.j1s_phi
			j2s_E = tree.j2s_E
			j2s_m = tree.j2s_m
			j2s_theta = tree.j2s_theta
			j2s_pt = tree.j2s_pt
			j2s_eta = tree.j2s_eta
			j2s_phi = tree.j2s_phi	

			j1c_E = tree.j1c_E
			j1c_m = tree.j1c_m
			j1c_theta = tree.j1c_theta
			j1c_pt = tree.j1c_pt
			j1c_eta = tree.j1c_eta
			j1c_phi = tree.j1c_phi
			j2c_E = tree.j2c_E
			j2c_m = tree.j2c_m
			j2c_theta = tree.j2c_theta
			j2c_pt = tree.j2c_pt
			j2c_eta = tree.j2c_eta
			j2c_phi = tree.j2c_phi	
			
			cut1 =  nmuon==1 and nneu==1
			cut2 =  abs(j1t_eta)<2.0 and abs(j2t_eta)<2.0
			#cut3 = enumu+j1t_E+j2t_E>162.45
			cut3 = True
			cut4 = eleak-emu+muene_sci<1.
			cut5 = j1r_E+j2r_E>68.0
			cut5 = True
		
			if cut1 and cut2 and cut3 and cut4 and cut5:
				graphtest.Fill(j1r_E-j1t_E)
				graphtest.Fill(j2r_E-j2t_E)
				deltaj1 = 0.02175*j1r_E+0.0808
				deltaj2 = 0.02175*j2r_E+0.0808
				graphenergy.Fill(newmass)
				#graphenergy.Fill(j2r_E+deltaj2)
				#graphenergytruth.Fill(j1t_E)
				#graphenergytruth.Fill(j2t_E+j1t_E)
				graphenergytruth.Fill(mjjt)
				graphdiff.Fill(newmass-mjjt)
				graphjs.Fill(j2s_E)
				graphjs.Fill(j1s_E)
				graphjc.Fill(j2c_E)
				graphjc.Fill(j1c_E)
			
		displayfile.cd()
		#graphtest.Write()
		scale = 1./graphenergy.Integral()
		graphenergy.Scale(scale)
		graphenergy.Write()
		graphenergytruth.Write()
		graphdiff.Write()
Exemplo n.º 19
0
def jetdisplay():

    inputfile1 = "wwlj_truth.root"
    inputfile2 = "wwlj.root"

    inputfile1 = TFile(inputfile1)
    inputfile2 = TFile(inputfile2)
    print "Analyzing: " + str(inputfile1) + " \n"
    tree1 = TTree()
    tree2 = TTree()
    inputfile1.GetObject("truth", tree1)
    inputfile2.GetObject("B4", tree2)
    tree1.AddFriend(tree2)

    outputfile = "wwlj_output"
    displayfile = TFile(outputfile + ".root", "RECREATE")

    graphmass = TH1F("mass_jet", "mass_jet", 100, 0., 200.)
    graphmass_truth = TH1F("mass_jet_truth", "mass_jet_truth", 100, 0., 200.)

    #loop over events
    for Event in range(int(10)):

        tree1.GetEntry(Event)

        #Set values of the tree
        numtru = tree1.mcs_n
        print numtru

        muvec = []
        inputparticles_tru = []
        nmuon = 0
        #loop over true particles
        for itru in range(0, numtru):
            partid = tree1.mcs_pdgId[itru]

            #for particle depositing in calo, store them as input for jet building
            if abs(partid) != 13 and abs(partid) != 12 and abs(
                    partid) != 14 and abs(partid) != 16:
                trup = TLorentzVector()
                trup.SetPtEtaPhiM(tree1.mcs_pt[itru], tree1.mcs_eta[itru],
                                  tree1.mcs_phi[itru], tree1.mcs_m[itru])
                inputparticles_tru.append(
                    fastjet.PseudoJet(trup.Px(), trup.Py(), trup.Pz(),
                                      trup.E()))
            #store muons in event
            if abs(partid) == 13:
                muon = TLorentzVector()
                muon.SetPtEtaPhiM(tree1.mcs_pt[itru], tree1.mcs_eta[itru],
                                  tree1.mcs_phi[itru], tree1.mcs_m[itru])
                muvec.append(muon)
                nmuon = nmuon + 1
        print " nmuon ", nmuon

        #now build truth jets
        jet_def = fastjet.JetDefinition(fastjet.ee_genkt_algorithm,
                                        2 * math.pi, 1.)
        clust_seq = fastjet.ClusterSequence(inputparticles_tru, jet_def)
        jetexc = fastjet.sorted_by_E(clust_seq.exclusive_jets(int(2)))
        print "*********** jets ************"
        for jet in jetexc:
            print jet.e(), jet.eta(), jet.phi()
        print "*********** muons ************"
        for muon in muvec:
            print muon.E(), muon.Eta(), muon.Phi()

        jet1_truth = jetexc[0]
        jet2_truth = jetexc[1]
        j = jet1_truth + jet2_truth
        graphmass_truth.Fill(j.m())

        # now handle calo sim
        BarrelR_VectorSignals = tree2.VectorSignalsR
        BarrelL_VectorSignals = tree2.VectorSignalsL
        BarrelR_VectorSignalsCher = tree2.VectorSignalsCherR
        BarrelL_VectorSignalsCher = tree2.VectorSignalsCherL
        VectorR = tree2.VectorR
        VectorL = tree2.VectorL

        Calib_BarrelL_VectorSignals = calibration.calibscin(
            BarrelL_VectorSignals)
        Calib_BarrelR_VectorSignals = calibration.calibscin(
            BarrelR_VectorSignals)
        Calib_BarrelL_VectorSignalsCher = calibration.calibcher(
            BarrelL_VectorSignalsCher)
        Calib_BarrelR_VectorSignalsCher = calibration.calibcher(
            BarrelR_VectorSignalsCher)

        energy = float(
            sum(Calib_BarrelR_VectorSignals) +
            sum(Calib_BarrelL_VectorSignals))
        print " simulated energy ", energy
        if (energy > 0):
            threshold = 0.1
            inputparticles_scin = []
            inputparticles_cher = []

            #right part
            for towerindex in range(75 * 36):
                theta, phi, eta = newmap_truth.maptower(towerindex, "right")
                energy_scin = Calib_BarrelR_VectorSignals[towerindex]
                pt_scin = energy_scin * np.sin(theta * math.pi / 180.)

                energy_cher = Calib_BarrelR_VectorSignalsCher[towerindex]
                pt_cher = energy_cher * np.sin(theta * math.pi / 180.)

                towerscin = TLorentzVector()
                towerscin.SetPtEtaPhiM(pt_scin, eta, phi * math.pi / 180., 0.)
                towercher = TLorentzVector()
                towercher.SetPtEtaPhiM(pt_cher, eta, phi * math.pi / 180., 0.)
                deltamumin = 999999.
                for muon in muvec:
                    deltaR = abs(towerscin.DeltaR(muon))
                    if deltaR < deltamumin:
                        deltamumin = deltaR
                if energy_scin > threshold:
                    if deltamumin < 0.1:
                        print " deltamumin ", deltamumin
                    if deltamumin > 0.1:
                        inputparticles_scin.append(
                            fastjet.PseudoJet(towerscin.Px(), towerscin.Py(),
                                              towerscin.Pz(), towerscin.E()))
                        inputparticles_cher.append(
                            fastjet.PseudoJet(towercher.Px(), towercher.Py(),
                                              towercher.Pz(), towercher.E()))

            #left part
            for towerindex in range(75 * 36):
                theta, phi, eta = newmap_truth.maptower(towerindex, "left")
                energy_scin = Calib_BarrelL_VectorSignals[towerindex]
                pt_scin = energy_scin * np.sin(theta * math.pi / 180.)

                energy_cher = Calib_BarrelL_VectorSignalsCher[towerindex]
                pt_cher = energy_cher * np.sin(theta * math.pi / 180.)

                towerscin = TLorentzVector()
                towerscin.SetPtEtaPhiM(pt_scin, eta, phi * math.pi / 180., 0.)
                towercher = TLorentzVector()
                towercher.SetPtEtaPhiM(pt_cher, eta, phi * math.pi / 180., 0.)
                deltamumin = 999999.
                for muon in muvec:
                    deltaR = abs(towerscin.DeltaR(muon))
                    if deltaR < deltamumin:
                        deltamumin = deltaR
                if energy_scin > threshold:
                    if deltamumin < 0.1:
                        print " deltamumin ", deltamumin
                    if deltamumin > 0.1:
                        inputparticles_scin.append(
                            fastjet.PseudoJet(towerscin.Px(), towerscin.Py(),
                                              towerscin.Pz(), towerscin.E()))
                        inputparticles_cher.append(
                            fastjet.PseudoJet(towercher.Px(), towercher.Py(),
                                              towercher.Pz(), towercher.E()))

        print "len: ", len(inputparticles_scin)
        print "lencher: ", len(inputparticles_cher)

        jet_def = fastjet.JetDefinition(fastjet.ee_genkt_algorithm,
                                        2 * math.pi, 1.)

        clust_seq = fastjet.ClusterSequence(inputparticles_scin, jet_def)
        clust_seq_cher = fastjet.ClusterSequence(inputparticles_cher, jet_def)

        print "n jet: ", len(clust_seq.exclusive_jets(int(2))), len(
            clust_seq_cher.exclusive_jets(int(2)))
        jet1_scin = clust_seq.exclusive_jets(int(2))[0]
        jet2_scin = clust_seq.exclusive_jets(int(2))[1]

        jet1_cher = clust_seq_cher.exclusive_jets(int(2))[0]
        jet2_cher = clust_seq_cher.exclusive_jets(int(2))[1]

        #merge jet
        jet1, jet2 = mergejet(jet1_scin, jet2_scin, jet1_cher, jet2_cher)
        jet = jet1 + jet2
        graphmass.Fill(jet.m())
    graphmass.Write()
    graphmass_truth.Write()
Exemplo n.º 20
0
def jetdisplay():
	outputfile = "zjj"
	displayfile = TFile(outputfile+".root","RECREATE")

	energies = [30,50,70,90, 150, 250]
	inputfiles = ["jetscan_leakage_029/jetscan_"+str(e)+".root" for e in energies]
	
	#for geant4.10.5
	inputfiles = ["resultsgeant4.10.5/jetscan/jetscan"+str(e)+".root" for e in energies]
	#end of geant4.10.5

	#for geant4.10.5 with X0 or B
	inputfiles = ["resultsgeant4.10.5/jetscan_leakage_X0/jetscan/jetscan"+str(e)+".root" for e in energies]
	#end of geant4.10.5 with X0 or B

	#for CaloLoop
	#inputfiles = ["/home/software/Calo/CaloLoop/CaloJet/resultsgeant4.10.5/jetscan_leakage_B/jetscan/jetscan"+str(e)+".root" for e in energies]
	#end CaloLoop

	for counter, inputfile in enumerate(inputfiles):
		inputfile = TFile(inputfile)
		print "Analyzing: "+str(inputfile)+" \n"
		tree = TTree()
		inputfile.GetObject("MyTree", tree)	

		#graphEjet1 = TH1F("energyjet1", "energyjet1", 100, 0., 200.)
		#graphEjet2 = TH1F("energyjet2", "energyjet2", 100, 0., 200.)
		
		#graphEcherjet1 = TH1F("energycher1", "energycherjet", 100, 0., 200.)
		#graph3 = TH1F("energyscinjet", "energyscinjet", 100, 0., 200.)
		
		#graphmass = TH1F("mass_jet", "mass_jet", 100, 0., 200.)
		graphtest = TH1F("test"+str(energies[counter]), "test"+str(energies[counter]), 80, -40., 40.)
		graphenergy = TH1F("energy"+str(energies[counter]), "energy"+str(energies[counter]), 200, 0., 300.)
		graphenergytruth = TH1F("energytruth"+str(energies[counter]), "energytruth"+str(energies[counter]), 200, 0., 300.) 
		graphjs = TH1F("energyjs"+str(energies[counter]), "energyjs"+str(energies[counter]), 200, 0., 300.) 
		graphjc = TH1F("energyjc"+str(energies[counter]), "energyjc"+str(energies[counter]), 200, 0., 300.) 
			
		graph_emcomp02 = TH1F("emcomp02_"+str(energies[counter]), "emcomp02"+str(energies[counter]), 80, -40, 40)
		graph_emcomp04 = TH1F("emcomp04_"+str(energies[counter]), "emcomp04"+str(energies[counter]), 80, -40, 40)
		graph_emcomp06 = TH1F("emcomp06_"+str(energies[counter]), "emcomp06"+str(energies[counter]), 80, -40, 40)
		graph_emcomp08 = TH1F("emcomp08_"+str(energies[counter]), "emcomp08"+str(energies[counter]), 80, -40, 40)
		graph_emcomp1 = TH1F("emcomp1_"+str(energies[counter]), "emcomp1"+str(energies[counter]), 80, -40, 40)
		
		#loop over events
		for Event in range(tree.GetEntries()):		

			tree.GetEntry(Event)	
			#print "Event "+str(Event)
			nmuon = tree.nmuon
			nneu = tree.nneu
			mjjr = tree.mjjr
			mjjt = tree.mjjt
			edep = tree.edep
			muene_che = tree.muene_che
			muene_sci = tree.muene_sci
			emcomp1 = tree.emcomp1
			emcomp2 = tree.emcomp2
			eleak = tree.eleak
			eleakn = tree.eleakn
			   
			j1t_E = tree.j1t_E
			j1t_m = tree.j1t_m
			j1t_theta = tree.j1t_theta
			j1t_pt = tree.j1t_pt
			j1t_eta = tree.j1t_eta
			j1t_phi = tree.j1t_phi
			j2t_E = tree.j2t_E
			j2t_m = tree.j2t_m
			j2t_theta = tree.j2t_theta
			j2t_pt = tree.j2t_pt
			j2t_eta = tree.j2t_eta
			j2t_phi = tree.j2t_phi	

			j1r_E = tree.j1r_E
			j1r_m = tree.j1r_m
			j1r_theta = tree.j1r_theta
			j1r_pt = tree.j1r_pt
			j1r_eta = tree.j1r_eta
			j1r_phi = tree.j1r_phi
			j2r_E = tree.j2r_E
			j2r_m = tree.j2r_m
			j2r_theta = tree.j2r_theta
			j2r_pt = tree.j2r_pt
			j2r_eta = tree.j2r_eta
			j2r_phi = tree.j2r_phi	

			j1s_E = tree.j1s_E
			j1s_m = tree.j1s_m
			j1s_theta = tree.j1s_theta
			j1s_pt = tree.j1s_pt
			j1s_eta = tree.j1s_eta
			j1s_phi = tree.j1s_phi
			j2s_E = tree.j2s_E
			j2s_m = tree.j2s_m
			j2s_theta = tree.j2s_theta
			j2s_pt = tree.j2s_pt
			j2s_eta = tree.j2s_eta
			j2s_phi = tree.j2s_phi	

			j1c_E = tree.j1c_E
			j1c_m = tree.j1c_m
			j1c_theta = tree.j1c_theta
			j1c_pt = tree.j1c_pt
			j1c_eta = tree.j1c_eta
			j1c_phi = tree.j1c_phi
			j2c_E = tree.j2c_E
			j2c_m = tree.j2c_m
			j2c_theta = tree.j2c_theta
			j2c_pt = tree.j2c_pt
			j2c_eta = tree.j2c_eta
			j2c_phi = tree.j2c_phi	

			cut1 =  nmuon==0 and nneu==0
			cut2 =  abs(j1t_eta)<2.0 and abs(j2t_eta)<2.0
			cut3 = eleak<3000.
			cut3 = True	
			cut4 = j1t_E+j2t_E>0.999*energies[counter]
			cut4= True
			cut5 = abs(j1t_E-j2t_E)<5.
			cut5 = abs(j1t_phi-j2t_phi)>0.1
			if cut1 and cut2 and cut3 and cut4 and cut5:
				deltaj1 = 0.04406*j1r_E+0.1158
				deltaj2 = 0.04406*j2r_E+0.1158
				deltaj1 = 0.03401*j1r_E+0.9152
				deltaj2 = 0.03401*j2r_E+0.9152
				deltaj1 = 0.04911*j1r_E+0.5723
				deltaj2 = 0.04911*j2r_E+0.5723
				graphtest.Fill(j1r_E+deltaj1-j1t_E)
				graphtest.Fill(j2r_E+deltaj2-j2t_E)
				#deltaj1_2 = 0.0098*(j1r_E+deltaj1)+0.186
				#deltaj2_2 = 0.0098*(j2r_E*deltaj2)+0.186
				'''
				if (emcomp1+emcomp2)<0.2*90.:
					graph_emcomp02.Fill(j1r_E+deltaj1-j1t_E)
					graph_emcomp02.Fill(j2r_E+deltaj2-j2t_E)
				if 0.2*90.<emcomp1+emcomp2<0.4*90.:
					graph_emcomp04.Fill(j1r_E+deltaj1-j1t_E)
					graph_emcomp04.Fill(j2r_E+deltaj2-j2t_E)
				if 0.4*90.<emcomp1+emcomp2<0.6*90.:
					graph_emcomp06.Fill(j1r_E+deltaj1-j1t_E)
					graph_emcomp06.Fill(j2r_E+deltaj2-j2t_E)				
				if 0.6*90.<emcomp1+emcomp2<0.8*90.:
					graph_emcomp08.Fill(j1r_E+deltaj1-j1t_E)
					graph_emcomp08.Fill(j2r_E+deltaj2-j2t_E)				
				if 0.8*90.<emcomp1+emcomp2<90.:
					graph_emcomp1.Fill(j1r_E+deltaj1-j1t_E)
					graph_emcomp1.Fill(j2r_E+deltaj2-j2t_E)				
				'''
				graphenergy.Fill(j1r_E+deltaj1)
				graphenergy.Fill(j2r_E+deltaj2)
				graphenergytruth.Fill(j1t_E)
				graphenergytruth.Fill(j2t_E)
				graphjs.Fill(j2s_E)
				graphjs.Fill(j1s_E)
				graphjc.Fill(j2c_E)
				graphjc.Fill(j1c_E)

		displayfile.cd()
		graphtest.Write()
		graphenergy.Write()
		graphenergytruth.Write()
		graphjs.Write()
		graphjc.Write()
Exemplo n.º 21
0
def recenergy(particle, name, chivalue):
    outputfile = str(particle) + "_Femanalysis" + str(chivalue) + "_" + str(
        name)
    displayfile = TFile(outputfile + ".root", "RECREATE")
    '''
	if name == "FTFPBERT":
		chi = 0.3
	if name == "FTFPBERTTRV":
		chi = 0.3
	if name == "QGSPBERT":
		chi = 0.3
	if name == "QBBC":
		chi = 0.3
	'''
    MeanEnergyScin = array('d')
    MeanEnergyCher = array('d')
    Energy = array('d')
    Energyerror = array('d')
    energyfractionscin = array('d')
    energyfractionscinerror = array('d')
    energyfractioncher = array('d')
    energyfractionchererror = array('d')
    energyfraction = array('d')
    energyfractionerror = array('d')
    resolutionscin = array('d')
    resolutionscinerror = array('d')
    resolutioncher = array('d')
    resolutionchererror = array('d')
    resolution = array('d')
    resolutionerror = array('d')
    chiarray = array('d')
    chierrorarray = array('d')
    zeros = array('d')
    containment = array('d')
    containmenterror = array('d')
    femvalues = array('d')
    zvalues = array('d')
    femvalueserror = array('d')
    zvalueserror = array('d')
    znormvalues = array('d')
    znormvalueserror = array('d')

    t = [10, 30, 50, 70, 100, 120, 140, 150]
    sqrtenergies = array('d', [1 / (x**0.5) for x in t])
    energies = array('d', t)
    #inputfiles = ["/home/software/Calo/results/energycont_2p0m/Pion_"+str(i)+".root" for i in t]
    #inputfiles = ["/home/software/Calo/results/pionenergyscan_QGSPBICHP/Pion_"+str(i)+".root" for i in t]
    #inputfiles = ["/home/lorenzo/Desktop/Calo/newresults/FTFPBERTTRV/Pion_"+str(i)+"_FTFPBERTTRV_office.root" for i in t]
    #inputfiles = ["/Users/lorenzo/Desktop/ToPC/newresults/"+str(name)+"/Pion_"+str(i)+".root" for i in t]
    if particle == "pion":
        inputfiles = [
            "/home/lorenzo/Calo/results/Pion_25_3_2020/" + str(name) + "" +
            "/Pion_" + str(i) + ".root" for i in t
        ]
    #inputfiles = ["/home/lorenzo/Calo/results/geant4.10.4.p01/Pion_30_4_2020/"+str(name)+""+"/Pion_"+str(i)+".root" for i in t]
    if particle == "proton":
        inputfiles = [
            "/home/lorenzo/Calo/results/Proton_25_3_2020/" + str(name) + "" +
            "/Proton_" + str(i) + ".root" for i in t
        ]
    if particle == "neutron":
        inputfiles = [
            "/home/lorenzo/Calo/results/Neutron_25_3_2020/" + str(name) + "" +
            "/Neutron_" + str(i) + ".root" for i in t
        ]
    if particle == "kaon":
        inputfiles = [
            "/home/lorenzo/Calo/results/Kaon_5_4_2020/" + str(name) + "" +
            "/Kaon_" + str(i) + ".root" for i in t
        ]

    for counter, inputfile in enumerate(inputfiles):
        inputfile = TFile(inputfile)
        print "Analyzing: " + str(inputfile) + " \n"
        tree = TTree()
        inputfile.GetObject("B4", tree)

        ScinEnergyHist = TH1F("scinenergy_" + str(t[counter]),
                              str(t[counter]) + "_scin", 400, 0., 200.)
        CherEnergyHist = TH1F("cherenergy_" + str(t[counter]),
                              str(t[counter]) + "_cher", 400, 0., 200.)
        RecEnergyHist = TH1F("RecEnergy_" + str(t[counter]),
                             str(t[counter]) + "_Energy", 400, 0., 200.)

        #Signalscinhist = TH1F("scintot_", str(counter+1)+"_scin", 3000, 0., 30000)
        EnergyHist = TH1F("Energy_" + str(t[counter]),
                          str(t[counter]) + "_Energy", 400, 0., 200.)
        LeakageHist = TH1F("Leak_" + str(t[counter]),
                           str(t[counter]) + "_Leak", 1000, 0., 100.)
        NeutrinoLeakageHist = TH1F("NeutrinoNeutrinoLeak_" + str(t[counter]),
                                   str(t[counter]) + "_Leak", 1000, 0., 100.)
        TotalLeakageHist = TH1F("TotalLeak_" + str(t[counter]),
                                str(t[counter]) + "_Leak", 1000, 0., 100.)
        ChiHist = TH1F("Chi_" + str(t[counter]),
                       str(t[counter]) + "_Chi", 200, 0., 2.)
        scatterplot = TH2F("scatterplot_" + str(t[counter]), str(t[counter]),
                           int(400), 0., 200., int(400), 0., 200.)
        EnergyContHist = TH1F("EnergyCont_" + str(t[counter]),
                              str(t[counter]) + "_EnergyCont", 400, 0., 200.)
        hesscatterplot = TH2F("H/E_S" + str(t[counter]),
                              "H/E_S" + str(t[counter]), 200, 0., 1.1, 200, 0.,
                              1.1)
        hecscatterplot = TH2F("H/E_C" + str(t[counter]),
                              "H/E_C" + str(t[counter]), 200, 0., 1.1, 200, 0.,
                              1.1)

        #fem and z histo
        femhisto = TH1F("fem_" + str(t[counter]),
                        str(t[counter]) + "_fem", 100, 0., 1.)
        zhisto = TH1F("z" + str(t[counter]),
                      str(t[counter]) + "_z", 100, 0., 1.)
        znormhisto = TH1F("z_norm" + str(t[counter]),
                          str(t[counter]) + "_z_norm", 200, 0., 2.)
        zfemhisto = TH2F("z_fem_histo" + str(t[counter]),
                         str(t[counter]) + "_z_fem_histo", 200, 0., 2., 200,
                         0., 2.)

        #loop over events
        entries = 50000
        for Event in range(entries):

            tree.GetEntry(Event)
            if Event % 1000 == 0:
                print Event

            #Set values of the tree
            PrimaryParticleName = tree.PrimaryParticleName  # MC truth: primary particle Geant4 name
            PrimaryParticleEnergy = tree.PrimaryParticleEnergy
            EnergyTot = tree.EnergyTot  # Total energy deposited in calorimeter
            Energyem = tree.Energyem  # Energy deposited by the em component
            EnergyScin = tree.EnergyScin  # Energy deposited in Scin fibers (not Birk corrected)
            EnergyCher = tree.EnergyCher  # Energy deposited in Cher fibers (not Birk corrected)
            NofCherenkovDetected = tree.NofCherenkovDetected  # Total Cher p.e. detected
            BarrelR_VectorSignals = tree.VectorSignalsR  # Vector of energy deposited in Scin fibers (Birk corrected)
            BarrelL_VectorSignals = tree.VectorSignalsL  # Vector of energy deposited in Scin fibers (Birk corrected)
            BarrelR_VectorSignalsCher = tree.VectorSignalsCherR  # Vector of Cher p.e. detected in Cher fibers
            BarrelL_VectorSignalsCher = tree.VectorSignalsCherL
            VectorR = tree.VectorR
            VectorL = tree.VectorL
            Leak = tree.leakage
            NeutrinoLeak = tree.neutrinoleakage

            #totalsignalscin = sum(BarrelR_VectorSignals)+sum(BarrelL_VectorSignals)
            #Signalscinhist.Fill(totalsignalscin)

            energytot = (sum(VectorR) + sum(VectorL)) / 1000
            EnergyHist.Fill(energytot)
            LeakageHist.Fill(Leak / 1000.)
            NeutrinoLeakageHist.Fill(NeutrinoLeak / 1000.)
            TotalLeakageHist.Fill(Leak / 1000. + NeutrinoLeak / 1000.)

            if float(t[counter]) < 12.:
                cutleak = 0.5
            if float(t[counter]) > 12. and float(t[counter]) < 50.:
                cutleak = 1.0
            if float(t[counter]) > 50.:
                cutleak = 3.0

            if (Leak / 1000. + NeutrinoLeak / 1000.) < cutleak:
                #apply calibrations
                Calib_BarrelL_VectorSignals = calibration.calibscin(
                    BarrelL_VectorSignals)
                Calib_BarrelR_VectorSignals = calibration.calibscin(
                    BarrelR_VectorSignals)
                Calib_BarrelL_VectorSignalsCher = calibration.calibcher(
                    BarrelL_VectorSignalsCher)
                Calib_BarrelR_VectorSignalsCher = calibration.calibcher(
                    BarrelR_VectorSignalsCher)
                #end of calibrations
                energyscin = sum(Calib_BarrelR_VectorSignals) + sum(
                    Calib_BarrelL_VectorSignals)
                energycher = sum(Calib_BarrelR_VectorSignalsCher) + sum(
                    Calib_BarrelL_VectorSignalsCher)
                e_c = float(t[counter]) - (Leak / 1000. + NeutrinoLeak / 1000.)

                hesscatterplot.Fill(Energyem / 1000. / e_c, energyscin / e_c)
                hecscatterplot.Fill(Energyem / 1000. / e_c, energycher / e_c)

                femhisto.Fill(Energyem / 1000. / e_c)
                z = (1. - energycher / energyscin) / (
                    1. - (chivalue * energycher / energyscin))
                zhisto.Fill(z)
                znormhisto.Fill(z / (1 - (Energyem / 1000. / e_c)))
                zfemhisto.Fill(z, (1 - (Energyem / 1000. / e_c)))
                EnergyContHist.Fill(e_c)
                ScinEnergyHist.Fill(energyscin)
                CherEnergyHist.Fill(energycher)
                scatterplot.Fill(energyscin / float(t[counter]),
                                 energycher / float(t[counter]))
                chi = chivalue
                newchi = (energyscin - e_c) / (energycher - e_c)
                ChiHist.Fill(newchi)
                RecEnergyHist.Fill(
                    1. / 0.99 * (energyscin - chi * energycher) / (1. - chi))

        print energies[counter], ScinEnergyHist.GetMean(
        ), CherEnergyHist.GetMean(), RecEnergyHist.GetMean()
        displayfile.cd()
        gStyle.SetOptStat(111)
        #ScinEnergyHist.Fit("gaus")
        #CherEnergyHist.Fit("gaus")
        #RecEnergyHist.Scale(1/RecEnergyHist.Integral())
        #print RecEnergyHist.Integral()
        RecEnergyHist.Fit("gaus")
        RecEnergyHist.Write()
        ScinEnergyHist.Write()
        CherEnergyHist.Write()
        #Signalscinhist.Write()
        EnergyHist.Write()
        EnergyContHist.Write()
        e_cont = EnergyContHist.GetMean()
        e_cont_error = EnergyContHist.GetRMS() / float(entries)**0.5
        scatterplot.Write()
        #cut1 = TCutG("cut1",4)
        #cut1.SetVarX("x")
        #cut1.SetVarY("y")
        #cut1.SetPoint(0,0.,0.)
        #cut1.SetPoint(1,1.,0.)
        #cut1.SetPoint(2,1.,1.)
        #cut1.SetPoint(3,0.,1.)
        #profile = scatterplot.ProfileX("",1,400,"[cut1]")
        #profile.GetYaxis().SetRangeUser(0.,1.5)
        #profile.Write()
        func2 = TF1("func2", '[0]+x*(1.-[0])', 0., 1.)
        pp = hesscatterplot.ProfileX()
        pp.Fit(func2)
        pp.Write()
        hesscatterplot.Write()
        hecscatterplot.Write()
        femhisto
        ppc = hecscatterplot.ProfileX()
        ppc.Fit(func2)
        ppc.Write()
        LeakageHist.Write()
        NeutrinoLeakageHist.Write()
        TotalLeakageHist.Write()
        ChiHist.Write()
        #scin_sqrtenergies.append(1./(ScinEnergyHist.GetFunction("gaus").GetParameter(1)**0.5))
        #cher_sqrtenergies.append(1./(CherEnergyHist.GetFunction("gaus").GetParameter(1)**0.5))
        Energy.append(RecEnergyHist.GetFunction("gaus").GetParameter(1))
        Energyerror.append(3. *
                           RecEnergyHist.GetFunction("gaus").GetParameter(2) /
                           float(entries)**0.5)
        MeanEnergyScin.append(ScinEnergyHist.GetMean())
        MeanEnergyCher.append(CherEnergyHist.GetMean())
        resolution.append(
            RecEnergyHist.GetFunction("gaus").GetParameter(2) /
            RecEnergyHist.GetFunction("gaus").GetParameter(1))
        sigma_energy_e = (
            (RecEnergyHist.GetFunction("gaus").GetParameter(2) /
             (float(entries)**0.5)) /
            RecEnergyHist.GetFunction("gaus").GetParameter(1) +
            RecEnergyHist.GetFunction("gaus").GetParError(2) /
            RecEnergyHist.GetFunction("gaus").GetParameter(2)) * (
                RecEnergyHist.GetFunction("gaus").GetParameter(2) /
                RecEnergyHist.GetFunction("gaus").GetParameter(1))
        resolutionerror.append(sigma_energy_e)
        energyfractionscin.append(ScinEnergyHist.GetMean() / float(t[counter]))
        energyfractionscinerror.append(
            3 * (ScinEnergyHist.GetRMS() / entries**0.5) / float(t[counter]))
        energyfractioncher.append(CherEnergyHist.GetMean() / float(t[counter]))
        energyfractionchererror.append(
            3 * (CherEnergyHist.GetRMS() / entries**0.5) / float(t[counter]))
        energyfraction.append(
            RecEnergyHist.GetFunction("gaus").GetParameter(1) /
            float(t[counter]))
        energyfractionerror.append(
            3 * (RecEnergyHist.GetFunction("gaus").GetParameter(2) /
                 entries**0.5) / float(t[counter]))
        resolutionscin.append(ScinEnergyHist.GetRMS() /
                              ScinEnergyHist.GetMean())
        sigma_energy_e = (
            ScinEnergyHist.GetMeanError() / ScinEnergyHist.GetMean() +
            ScinEnergyHist.GetRMSError() / ScinEnergyHist.GetRMS()) * (
                ScinEnergyHist.GetRMS() / ScinEnergyHist.GetMean())
        resolutionscinerror.append(sigma_energy_e)
        resolutioncher.append(CherEnergyHist.GetRMS() /
                              CherEnergyHist.GetMean())
        sigma_energy_e = (
            CherEnergyHist.GetMeanError() / CherEnergyHist.GetMean() +
            CherEnergyHist.GetRMSError() / CherEnergyHist.GetRMS()) * (
                CherEnergyHist.GetRMS() / CherEnergyHist.GetMean())
        resolutionchererror.append(sigma_energy_e)
        chiarray.append(ChiHist.GetBinCenter(ChiHist.GetMaximumBin()))
        chierrorarray.append(3 * ChiHist.GetRMS() / (entries**0.5))
        zeros.append(0.0)
        containment.append(e_cont / float(t[counter]))
        containmenterror.append(e_cont_error / float(t[counter]))
        femhisto.Write()
        zhisto.Write()
        zfemhisto.Write()
        znormhisto.Write()
        femvalues.append(femhisto.GetMean())
        zvalues.append(zhisto.GetMean())
        femvalueserror.append(femhisto.GetRMS() / (entries**0.5))
        zvalueserror.append(zhisto.GetRMS() / (entries**0.5))
        znormvalues.append(znormhisto.GetMean())
        znormvalueserror.append(znormhisto.GetRMS() / (entries**0.5))

    containmentgraph = TGraphErrors(len(energies), energies, containment,
                                    zeros, containmenterror)
    containmentgraph.SetName("containment")
    containmentgraph.Write()
    ChiGraph = TGraphErrors(len(energies), energies, chiarray, zeros,
                            chierrorarray)
    ChiGraph.SetName("Chi")
    ChiGraph.Write()
    LinearityGraph2 = TGraphErrors(len(energies), energies, Energy, zeros,
                                   Energyerror)
    LinearityGraph2.SetName("LinearityGraph2")
    LinearityGraph2.Write()
    LinearityGraph = TGraphErrors(len(energies), energies, energyfraction,
                                  zeros, energyfractionerror)
    LinearityGraph.SetName("LinearityGraph")
    LinearityGraph.Write()
    LinearityGraphScin = TGraphErrors(len(energies), energies,
                                      energyfractionscin, zeros,
                                      energyfractionscinerror)
    LinearityGraphCher = TGraphErrors(len(energies), energies,
                                      energyfractioncher, zeros,
                                      energyfractionchererror)
    LinearityGraphCher.SetName("LinearityGraphCher")
    LinearityGraphCher.Write()
    LinearityGraphScin.SetName("LinearityGraphScin")
    LinearityGraphScin.Write()

    ResolutionGraphScin = TGraphErrors(len(energies), sqrtenergies,
                                       resolutionscin, zeros,
                                       resolutionscinerror)
    func = TF1("func", "[0]/(x**0.5)+[1]", 10., 150.)
    ResolutionGraphCher = TGraphErrors(len(energies), sqrtenergies,
                                       resolutioncher, zeros,
                                       resolutionchererror)
    #ResolutionGraphScin.Fit("func", "R")
    #ResolutionGraphCher.Fit("func", "R")
    ResolutionGraphScin.SetName("ResolutionGraphScin")
    ResolutionGraphScin.Write()
    ResolutionGraphCher.SetName("ResolutionGraphCher")
    ResolutionGraphCher.Write()
    ResolutionGraph = TGraphErrors(len(energies), sqrtenergies, resolution,
                                   zeros, resolutionerror)
    #ResolutionGraph.Fit("func", "R")
    ResolutionGraph.SetName("ResolutionGraph")
    ResolutionGraph.Write()

    LinearityGraph.SetMinimum(0.976)  #0.976
    LinearityGraph.SetMaximum(1.024)  #1.024
    LinearityGraph.GetXaxis().SetLimits(0.0, 155.0)
    LinearityGraph.SetTitle("")
    LinearityGraph.GetXaxis().SetLabelSize(.105)
    LinearityGraph.GetYaxis().SetLabelSize(0.105)
    LinearityGraph.GetXaxis().SetNdivisions(520)
    LinearityGraph.GetYaxis().SetNdivisions(504)
    LinearityGraph2.SetTitle("")
    LinearityGraph2.SetMinimum(0.0)
    LinearityGraph2.SetMaximum(155.0)
    LinearityGraph2.GetXaxis().SetLimits(0.0, 155.0)
    LinearityGraph2.GetXaxis().SetLabelSize(0.)
    LinearityGraph2.GetXaxis().SetNdivisions(520)
    LinearityGraph2.GetYaxis().SetNdivisions(520)
    c = TCanvas("c", "canvas", 800, 800)
    # Upper histogram plot is pad1
    pad1 = TPad("pad1", "pad1", 0, 0.3, 1, 1.0)
    pad1.SetBottomMargin(0.02)  # joins upper and lower plot
    pad1.SetLeftMargin(0.1)
    pad1.SetRightMargin(0.1)
    pad1.Draw()
    # Lower ratio plot is pad2
    c.cd()  # returns to main canvas before defining pad2
    pad2 = TPad("pad2", "pad2", 0, 0.05, 1, 0.3)
    pad2.SetTopMargin(0.05)  # joins upper and lower plot
    pad2.SetBottomMargin(0.3)
    pad2.SetLeftMargin(0.1)
    pad2.SetRightMargin(0.1)
    pad2.Draw()
    pad1.cd()
    LinearityGraph2.Draw()
    pad2.cd()
    LinearityGraph.Draw("AP")
    ratioline = TF1("ratioline", str(np.mean(energyfraction)), 0., 160.)
    ratioline.SetLineColor(1)
    ratioline.SetLineWidth(1)
    ratioline.SetLineStyle(9)
    ratioline.Draw("same")
    ratioline.Write()
    c.Update()
    #c.SaveAs("MLratio.pdf")
    c.Write()

    femgraph = TGraphErrors(len(energies), energies, femvalues, zeros,
                            femvalueserror)
    femgraph.SetName("fem_graph")
    femfit = TF1("femfit", "1.-(x/[0])**([1]-1.)", 10., 150.)
    femgraph.Fit("femfit", "R")
    femgraph.Write()

    zvalues = array('d', [math.log(x) for x in zvalues])
    logenergies = array('d', [math.log(x) for x in energies])
    zgraph = TGraphErrors(len(logenergies), logenergies, zvalues, zeros,
                          zvalueserror)
    zgraph.SetName("z_graph")
    zfit = TF1("zfit", "pol1", 2.2, 5.1)
    zgraph.Fit("zfit", "R")
    zgraph.Write()

    znormgraph = TGraphErrors(len(energies), energies, znormvalues, zeros,
                              znormvalueserror)
    znormgraph.SetName("znorm_graph")
    znormgraph.Write()
    '''	
	Resolutions = TMultiGraph()
	Resolutions.Add(ResolutionGraphScin)
	Resolutions.Add(ResolutionGraphCher)
	Resolutions.Add(ResolutionGraph)
	Resolutions.SetName("EMResolutions")
	Resolutions.Write()

	Linearities = TMultiGraph()
	Linearities.Add(LinearityGraph)
	Linearities.Add(LinearityGraphScin)
	Linearities.Add(LinearityGraphCher)
	Linearities.SetName("Linearities")
	Linearities.Write()
	'''
    return RecEnergyHist.GetFunction("gaus").GetParameter(
        2), RecEnergyHist.GetFunction("gaus").GetParameter(
            1), RecEnergyHist.GetFunction("gaus").GetChisquare()
Exemplo n.º 22
0
def energylinearity():
    outputfile = "EMLinearityEnergyRes"
    displayfile = TFile(outputfile + ".root", "RECREATE")

    MeanEnergyScin = array('d')
    MeanEnergyCher = array('d')
    MeanEnergy = array('d')
    resolutionscin = array('d')
    resolutioncher = array('d')
    resolution = array('d')
    towers = array('d')
    ##inputfiles = sorted(glob.glob(datapath+"*"), key=os.path.getmtime) #get files from tower 1 to 75 ordered by creation time
    inputfiles = [
        "/home/software/Calo/results/newresults/barrel2/Barrel_" + str(i) +
        ".root" for i in range(1, 76)
    ]
    #inputfiles = ["/home/software/Calo/results/NewTowerScan4/Barrel_"+str(i)+".root" for i in range(1,76)]
    #inputfiles = ["/home/lorenzo/Desktop/Calo/results/NewTowerScan4/Barrel_"+str(i)+".root" for i in range(1,76)]

    for counter, inputfile in enumerate(inputfiles):
        inputfile = TFile(inputfile)
        print "Analyzing: " + str(inputfile) + " \n"
        tree = TTree()
        inputfile.GetObject("B4", tree)

        ScinEnergyHist = TH1F("scinenergy_",
                              str(counter + 1) + "_scin", 200, 0., 100.)
        CherEnergyHist = TH1F("cherenergy_",
                              str(counter + 1) + "_cher", 200, 0., 100.)
        RecEnergyHist = TH1F("RecEnergy_",
                             str(counter + 1) + "_Energy", 200, 0., 100.)
        Energytot = 0.0

        energy = 40.0
        sqrtenergy = 1 / (40.0**0.5)
        towers.append(counter + 1.)

        #loop over events
        for Event in range(int(tree.GetEntries())):

            tree.GetEntry(Event)

            #Set values of the tree
            PrimaryParticleName = tree.PrimaryParticleName  # MC truth: primary particle Geant4 name
            PrimaryParticleEnergy = tree.PrimaryParticleEnergy
            EnergyTot = tree.EnergyTot  # Total energy deposited in calorimeter
            Energyem = tree.Energyem  # Energy deposited by the em component
            EnergyScin = tree.EnergyScin  # Energy deposited in Scin fibers (not Birk corrected)
            EnergyCher = tree.EnergyCher  # Energy deposited in Cher fibers (not Birk corrected)
            NofCherenkovDetected = tree.NofCherenkovDetected  # Total Cher p.e. detected
            BarrelR_VectorSignals = tree.VectorSignalsR  # Vector of energy deposited in Scin fibers (Birk corrected)
            BarrelL_VectorSignals = tree.VectorSignalsL  # Vector of energy deposited in Scin fibers (Birk corrected)
            BarrelR_VectorSignalsCher = tree.VectorSignalsCherR  # Vector of Cher p.e. detected in Cher fibers
            BarrelL_VectorSignalsCher = tree.VectorSignalsCherL
            VectorR = tree.VectorR
            VectorL = tree.VectorL

            #apply calibrations
            Calib_BarrelL_VectorSignals = calibration2.calibscin(
                BarrelL_VectorSignals)
            Calib_BarrelR_VectorSignals = calibration2.calibscin(
                BarrelR_VectorSignals)
            Calib_BarrelL_VectorSignalsCher = calibration2.calibcher(
                BarrelL_VectorSignalsCher)
            Calib_BarrelR_VectorSignalsCher = calibration2.calibcher(
                BarrelR_VectorSignalsCher)
            #end of calibrations

            energyscin = sum(Calib_BarrelR_VectorSignals) + sum(
                Calib_BarrelL_VectorSignals)
            energycher = sum(Calib_BarrelR_VectorSignalsCher) + sum(
                Calib_BarrelL_VectorSignalsCher)

            ScinEnergyHist.Fill(energyscin)
            CherEnergyHist.Fill(energycher)

            #sigmascin = 0.15*(energyscin**0.5)+0.012*energyscin #old value
            #sigmacher = 0.18*(energycher**0.5)+0.0045*energycher #old value
            sigmascin = 0.177 * (energyscin**0.5) + 0.006 * energyscin
            sigmacher = 0.194 * (energycher**0.5) + 0.001 * energycher

            RecEnergyHist.Fill(
                (energyscin / (sigmascin**2) + energycher /
                 (sigmacher**2)) / (1 / sigmascin**2 + 1 / sigmacher**2))

            #RecEnergyHist.Fill((energyscin+energycher)/2)

            Energytot += (sum(VectorL) + sum(VectorR)) / 1000

        Energytot = Energytot / int(tree.GetEntries())
        print Energytot, ScinEnergyHist.GetMean(), CherEnergyHist.GetMean()
        displayfile.cd()
        gStyle.SetOptStat(111)
        ScinEnergyHist.Fit("gaus")
        CherEnergyHist.Fit("gaus")
        RecEnergyHist.Fit("gaus")
        RecEnergyHist.Write()
        ScinEnergyHist.Write()
        CherEnergyHist.Write()
        #MeanEnergyScin.append(ScinEnergyHist.GetFunction("gaus").GetParameter(1)/Energytot)
        MeanEnergyScin.append(ScinEnergyHist.GetMean() / energy)
        #MeanEnergyCher.append(CherEnergyHist.GetFunction("gaus").GetParameter(1)/Energytot)
        MeanEnergyCher.append(CherEnergyHist.GetMean() / energy)
        MeanEnergy.append(
            RecEnergyHist.GetFunction("gaus").GetParameter(1) / energy)
        resolution.append(
            RecEnergyHist.GetFunction("gaus").GetParameter(2) /
            RecEnergyHist.GetFunction("gaus").GetParameter(1))
        resolutionscin.append(
            ScinEnergyHist.GetFunction("gaus").GetParameter(2) /
            ScinEnergyHist.GetFunction("gaus").GetParameter(1))
        resolutioncher.append(
            CherEnergyHist.GetFunction("gaus").GetParameter(2) /
            CherEnergyHist.GetFunction("gaus").GetParameter(1))

    print MeanEnergyScin, MeanEnergyCher
    LinearityGraph = TGraph(len(towers), towers, MeanEnergy)
    LinearityGraph.SetName("LinearityGraph")
    LinearityGraph.Write()
    LinearityGraphScin = TGraph(len(towers), towers, MeanEnergyScin)
    LinearityGraphCher = TGraph(len(towers), towers, MeanEnergyCher)
    LinearityGraphCher.SetName("LinearityGraphCher")
    LinearityGraphCher.Write()
    LinearityGraphScin.SetName("LinearityGraphScin")
    LinearityGraphScin.Write()
    ResolutionGraphScin = TGraph(len(towers), towers, resolutionscin)
    ResolutionGraphCher = TGraph(len(towers), towers, resolutioncher)
    ResolutionGraphScin.SetName("ResolutionGraphScin")
    ResolutionGraphScin.Write()
    ResolutionGraphCher.SetName("ResolutionGraphCher")
    ResolutionGraphCher.Write()
    ResolutionGraph = TGraph(len(towers), towers, resolution)
    ResolutionGraph.SetName("ResolutionGraph")
    ResolutionGraph.Write()
    x2 = array('d', (0., 90., 90., 0.))
    y2 = array('d', (0.024, 0.024, 0.034, 0.034))
    Fillgraph2 = TGraph(4, x2, y2)
    Fillgraph2.SetName("ban")
    Fillgraph2.Write()
    linefill1 = TF1("1", str(1.0), 0., 90.)
    linefill1.Write()

    EMResolutions = TMultiGraph()
    EMResolutions.Add(ResolutionGraphScin)
    EMResolutions.Add(ResolutionGraphCher)
    EMResolutions.Add(ResolutionGraph)
    EMResolutions.SetName("EMResolutions")
    EMResolutions.Write()

    Linearities = TMultiGraph()
    Linearities.Add(LinearityGraph)
    Linearities.Add(LinearityGraphScin)
    Linearities.Add(LinearityGraphCher)
    Linearities.SetName("Linearities")
    Linearities.Write()
Exemplo n.º 23
0
                      default=-1,
                      help='Number of entries to copy (default all).')
optParse.add_argument("--selection",
                      default='',
                      help='Selection to apply (default none).')
optParse.add_argument(
    '--keepBranches',
    nargs='*',
    help='List of regexes to be matched to branches to be kept.')
optParse.add_argument(
    '--removeBranches',
    nargs='*',
    help='List of regexes to be matched to branches to be removed.')

args = optParse.parse_args()

from ROOT import TTree, TFile

inFile = TFile(options.inFile)
inTree = TTree()
inFile.GetObject(options.inTree, inTree)

outFile = TFile(options.outFile, "recreate")
outTree = copy_tree(inTree,
                    selection=args.selection,
                    nentries=args.nEntries,
                    keepbranches=args.keepBranches,
                    removebranches=args.removeBranches)
outTree.Write()
outFile.Close()
Exemplo n.º 24
0
def towercalibration():
	outputfile = "TowersRight"
	displayfile = TFile(outputfile+".root","RECREATE")

	MeanScin = array('d')
	MeanCher = array('d')
	RMSScin = array('d')
	RMSCher = array('d')
	Tower = array('d')
	EnergyTower = array('d')
	Zeros = array('d')
	errorsscin = array('d')
	errorscher = array('d')
	Energy = array('d')

	ResponseMeanScin = array('d')
	ResponseMeanCher = array('d')
	ResponseRMSScin = array('d')
	ResponseRMSCher = array('d')
	ResponseZeros = array('d')
	Responseerrorsscin = array('d')
	Responseerrorscher = array('d')
	energytot = array('d')
	scinsignaltot = array('d')
	chersignaltot = array('d')
	ScinSignalTot = array('d')
	

	#inputfiles = sorted(glob.glob(datapath+"*"), key=os.path.getmtime) #get files from tower 1 to 75 ordered by creation time
	inputfiles = ["/home/software/Calo/results/NewTowerScan4/Barrel_"+str(i)+".root" for i in range(1,76)]
	inputfiles = ["/home/software/Calo/results/newresults/barrel1/Barrel_"+str(i)+".root" for i in range(1,76)]
	#inputfiles = ["/home/lorenzo/Desktop/Calo/results/NewTowerScan4/Barrel_"+str(i)+".root" for i in range(1,76)]
	#inputfiles = ["/home/lorenzo/Desktop/Calo/results/SliceScan/Slice_"+str(i)+".root" for i in range(1,36)]
	#inputfiles = ["/home/lorenzo/Desktop/Calo/results/ScanInsideTower/Step_"+str(i)+".root" for i in range(0,11)]
	
	for counter, inputfile in enumerate(inputfiles):
		inputfile = TFile(inputfile)
		print "Analyzing: "+str(inputfile)+" \n"
		tree = TTree()
		inputfile.GetObject("B4", tree)	

		ScinHist = TH1F("scin_", str(counter+1)+"_scin", 1000, 0., 1000.)
		CherHist = TH1F("cher_", str(counter+1)+"_cher", 600, 0., 600.)	
		EnergyTowerHist = TH1F("Energy_",str(counter+1)+"_Energy", 200, 0., 200.)
		EnergyHist = TH1F("E_", str(counter+1)+"_Energy", 200, 0., 200.)
		ResponseScinHist = TH1F("responsescin_", str(counter+1)+"_scin", 1000, 0., 1000.)
		ResponseCherHist = TH1F("responsecher_", str(counter+1)+"_cher", 600, 0., 600.)

		Signalscinhist = TH1F("scintot_", str(counter+1)+"_scin", 3000, 0., 30000)

		#loop over events
		for Event in range(int(tree.GetEntries())):	

			tree.GetEntry(Event)	

			#Set values of the tree
			PrimaryParticleName = tree.PrimaryParticleName # MC truth: primary particle Geant4 name
			PrimaryParticleEnergy = tree.PrimaryParticleEnergy
			EnergyTot = tree.EnergyTot # Total energy deposited in calorimeter
			Energyem = tree.Energyem # Energy deposited by the em component
			EnergyScin = tree.EnergyScin # Energy deposited in Scin fibers (not Birk corrected)
			EnergyCher = tree.EnergyCher # Energy deposited in Cher fibers (not Birk corrected)
			NofCherenkovDetected = tree.NofCherenkovDetected # Total Cher p.e. detected
			BarrelR_VectorSignals = tree.VectorSignalsR  # Vector of energy deposited in Scin fibers (Birk corrected)
			BarrelL_VectorSignals = tree.VectorSignalsL  # Vector of energy deposited in Scin fibers (Birk corrected)
			BarrelR_VectorSignalsCher = tree.VectorSignalsCherR # Vector of Cher p.e. detected in Cher fibers
			BarrelL_VectorSignalsCher = tree.VectorSignalsCherL 	
			VectorR = tree.VectorR
			VectorL = tree.VectorL

			signalscin = max(BarrelR_VectorSignals)
			signalcher = max(BarrelR_VectorSignalsCher)
			energytower = max(VectorR)/1000
			totalenergy = (sum(VectorR)+sum(VectorL))/1000
			
			ScinHist.Fill(signalscin/energytower)	
			CherHist.Fill(signalcher/energytower)	
			EnergyTowerHist.Fill(energytower)

			totalsignalscin = sum(BarrelR_VectorSignals)+sum(BarrelL_VectorSignals)
			totalsignalcher = sum(BarrelR_VectorSignalsCher)+sum(BarrelL_VectorSignalsCher)
			
			EnergyHist.Fill(totalenergy)

			ResponseScinHist.Fill(totalsignalscin/totalenergy)
			ResponseCherHist.Fill(totalsignalcher/totalenergy)
			Signalscinhist.Fill(totalsignalscin)

			energytot.append(totalenergy)
			scinsignaltot.append(totalsignalscin)
			chersignaltot.append(totalsignalcher)
			if list(BarrelR_VectorSignals).index(max(BarrelR_VectorSignals)) != counter+1:
					print "WRONG!!!!!!!!!!!"	
			if Event < 1:
				print "Max found at: "+str(list(BarrelR_VectorSignals).index(signalscin))+str(list(BarrelR_VectorSignalsCher).index(signalcher))+str(list(VectorR).index(energytower*1000))+" for file "+str(counter+1) #to check tower mostly hitten is the correct one
				displayfile.cd()
				ROOTHistograms.create_eventdisplay_scin(PrimaryParticleName, BarrelR_VectorSignals, BarrelL_VectorSignals, str(counter), 0.0) 
				ROOTHistograms.create_eventdisplay_cher(PrimaryParticleName, BarrelR_VectorSignalsCher, BarrelL_VectorSignalsCher, str(counter), 0.0)

		print np.mean(energytot), np.mean(scinsignaltot), np.mean(chersignaltot)
		displayfile.cd()
		gStyle.SetOptStat(111)
		ScinHist.Fit("gaus")
		CherHist.Fit("gaus")
		ScinHist.Write()
		CherHist.Write()
		EnergyTowerHist.Write()
		#MeanScin.append(ScinHist.GetFunction("gaus").GetParameter(1))
		MeanScin.append(ScinHist.GetMean())
		#MeanCher.append(CherHist.GetFunction("gaus").GetParameter(1))
		MeanCher.append(CherHist.GetMean())
		RMSScin.append(ScinHist.GetRMS())
		RMSCher.append(CherHist.GetRMS())
		EnergyTower.append(EnergyTowerHist.GetMean()/40.0)
		Energy.append(EnergyHist.GetMean()/40.)
		ScinSignalTot.append(Signalscinhist.GetMean())
		Signalscinhist.Write()
		#print ScinHist.GetMean(), CherHist.GetMean(), EnergyTowerHist.GetMean()
		#print ScinHist.GetRMS(), CherHist.GetRMS()
		Tower.append(counter+1)
		Zeros.append(0.)
		errorsscin.append(ScinHist.GetRMS()/(3000**0.5))
		errorscher.append(CherHist.GetRMS()/(3000**0.5))

		ResponseScinHist.Fit("gaus")
		ResponseCherHist.Fit("gaus")
		ResponseScinHist.Write()
		ResponseCherHist.Write()
		#ResponseMeanScin.append(ResponseScinHist.GetFunction("gaus").GetParameter(1))
		ResponseMeanScin.append(ResponseScinHist.GetMean())
		#ResponseMeanCher.append(ResponseCherHist.GetFunction("gaus").GetParameter(1))
		ResponseMeanCher.append(ResponseCherHist.GetMean())
		ResponseRMSScin.append(ResponseScinHist.GetRMS())
		ResponseRMSCher.append(ResponseCherHist.GetRMS())
		Responseerrorsscin.append(ResponseScinHist.GetRMS()/(3000**0.5))
		Responseerrorscher.append(ResponseCherHist.GetRMS()/(3000**0.5))

	n = len(MeanCher)
	ScinTotGraph = TGraph(n, Tower, ScinSignalTot)
	ScinTotGraph.SetName("ScinTotGraph")
	ScinTotGraph.Write()
	EnergyGraph = TGraph(n, Tower, Energy)
	print "Energy containment: "+str(Energy)
	EnergyGraph.SetName("EnergyGraph")
	EnergyGraph.Write()
	EnergyTowerGraph = TGraph(n, Tower, EnergyTower)
	EnergyTowerGraph.SetName("EnergyTower")
	EnergyTowerGraph.Write()
	linefill36 = TF1("36gev", str(0.9), 0., 90.)
	linefill99 = TF1("99", str(0.99), 0., 90.)
	linefill99.Write()
	linefill36.Write()
	RMSGraphScin = TGraph(n, Tower, RMSScin)
	RMSGraphScin.SetName("Calibration_RMSGraphScin")
	RMSGraphCher = TGraph(n, Tower, RMSCher)
	RMSGraphCher.SetName("Calibration_RMSGraphCher")
	MeanGraphScin = TGraphErrors(n, Tower, MeanScin, Zeros, errorsscin)
	print "ScinCalibrations "+str(MeanScin)
	MeanGraphScin.SetName("Calibration_Scin")
	MeanGraphCher = TGraphErrors(n, Tower, MeanCher, Zeros, errorscher)
	print "CherCalibrations "+str(MeanCher)
	MeanGraphCher.SetName("Calibration_Cher")
	x = array('d', (0., 90., 90., 0.))
	y = array('d', (np.mean(MeanScin)-0.01*np.mean(MeanScin), np.mean(MeanScin)-0.01*np.mean(MeanScin), np.mean(MeanScin)+0.01*np.mean(MeanScin), np.mean(MeanScin)+0.01*np.mean(MeanScin)))
	Fillgraph = TGraph(4, x, y )
	Fillgraph.SetName("Calibration_banscin")
	linefillgraph = TF1("CalibrationMeanScin", str(np.mean(MeanScin)), 0., 90.)
	linefillgraph.Write()
	Fillgraph.Write()
	x2 = array('d', (0., 90., 90., 0.))
	y2 = array('d', (np.mean(MeanCher)-0.01*np.mean(MeanCher), np.mean(MeanCher)-0.01*np.mean(MeanCher), np.mean(MeanCher)+0.01*np.mean(MeanCher), np.mean(MeanCher)+0.01*np.mean(MeanCher)))
	Fillgraph2 = TGraph(4, x2, y2 )
	Fillgraph2.SetName("Calibration_bancher")
	linefillgraph2 = TF1("CalibrationMeanCher", str(np.mean(MeanCher)), 0., 90.)
	linefillgraph2.Write()
	Fillgraph2.Write()
	MeanGraphCher.Write()
	MeanGraphScin.Write()
	RMSGraphCher.Write()
	RMSGraphScin.Write()

	ResponseRMSGraphScin = TGraph(n, Tower, ResponseRMSScin)
	ResponseRMSGraphScin.SetName("ResponseRMSGraphScin")
	ResponseRMSGraphCher = TGraph(n, Tower, ResponseRMSCher)
	ResponseRMSGraphCher.SetName("ResponseRMSGraphCher")
	ResponseMeanGraphScin = TGraphErrors(n, Tower, ResponseMeanScin, Zeros, Responseerrorsscin)
	print "Response scin: "+str(ResponseMeanScin)
	ResponseMeanGraphScin.SetName("ResponseMeanGraphScin")
	ResponseMeanGraphCher = TGraphErrors(n, Tower, ResponseMeanCher, Zeros, Responseerrorscher)
	ResponseMeanGraphCher.SetName("ResponseMeanGraphCher")
	print "Response cher: "+str(ResponseMeanCher)
	x = array('d', (0., 90., 90., 0.))
	y = array('d', (np.mean(ResponseMeanScin)-0.01*np.mean(ResponseMeanScin), np.mean(ResponseMeanScin)-0.01*np.mean(ResponseMeanScin), np.mean(ResponseMeanScin)+0.01*np.mean(ResponseMeanScin), np.mean(ResponseMeanScin)+0.01*np.mean(ResponseMeanScin)))
	Fillgraph = TGraph(4, x, y )
	Fillgraph.SetName("ResponseBan_scin")
	linefillgraph = TF1("ResponseMeanScin", str(np.mean(ResponseMeanScin)), 0., 90.)
	linefillgraph.Write()
	Fillgraph.Write()
	x2 = array('d', (0., 90., 90., 0.))
	y2 = array('d', (np.mean(ResponseMeanCher)-0.01*np.mean(ResponseMeanCher), np.mean(ResponseMeanCher)-0.01*np.mean(ResponseMeanCher), np.mean(ResponseMeanCher)+0.01*np.mean(ResponseMeanCher), np.mean(ResponseMeanCher)+0.01*np.mean(ResponseMeanCher)))
	Fillgraph2 = TGraph(4, x2, y2 )
	Fillgraph2.SetName("ResponseBan_cher")
	linefillgraph2 = TF1("ResponseMeanCher", str(np.mean(ResponseMeanCher)), 0., 90.)
	linefillgraph2.Write()
	Fillgraph2.Write()
	ResponseMeanGraphCher.Write()
	ResponseMeanGraphScin.Write()
	ResponseRMSGraphCher.Write()
	ResponseRMSGraphScin.Write()
Exemplo n.º 25
0
#Run2016H_v2 (8.636/fb)
#Run2016H_v3 (0.221/fb)

w1 = (5.929 + 2.646 + 4.353 + 4.117 + 3.186) / (5.929 + 2.646 + 4.353 + 4.117 +
                                                3.186 + 7.721 + 8.636 + 0.221)
w2 = 1.0 - w1

TRSF1 = TFile(
    os.path.join(os.environ['CMSSW_BASE'],
                 'src/dafne/data/EfficienciesAndSF_TrigBF.root'))
TRSF2 = TFile(
    os.path.join(os.environ['CMSSW_BASE'],
                 'src/dafne/data/EfficienciesAndSF_TrigGH.root'))

TRsf1 = TH2F()
TRSF1.GetObject("Mu50_OR_TkMu50_PtEtaBins/abseta_pt_ratio", TRsf1)
TReffData1 = TH2F()
TRSF1.GetObject("Mu50_OR_TkMu50_PtEtaBins/efficienciesDATA/abseta_pt_DATA",
                TReffData1)
TReffMC1 = TH2F()
TRSF1.GetObject("Mu50_OR_TkMu50_PtEtaBins/efficienciesMC/abseta_pt_MC",
                TReffMC1)

TRsf2 = TH2F()
TRSF2.GetObject("Mu50_OR_TkMu50_PtEtaBins/abseta_pt_ratio", TRsf2)
TReffData2 = TH2F()
TRSF2.GetObject("Mu50_OR_TkMu50_PtEtaBins/efficienciesDATA/abseta_pt_DATA",
                TReffData2)
TReffMC2 = TH2F()
TRSF2.GetObject("Mu50_OR_TkMu50_PtEtaBins/efficienciesMC/abseta_pt_MC",
                TReffMC2)
Exemplo n.º 26
0
(options, args) = parser.parse_args()

#import pyroot_logon
import root_logon

from ROOT import gROOT

gROOT.ProcessLine('.L truncRMS.cc+')

from ROOT import TFile, TTree, gPad, TFitter, kBlue, kGreen, \
     Double, Long, \
     setData, hookupMinuit, makeHOFunc

dataf = TFile(args[0])
dataTree = TTree()
dataf.GetObject('plotanal/dataTree', dataTree)

mipE = options.mip
lblHB = 'HB_E'
lblEB = 'EB_E'
lblHO = '(HO_E'
cuts = '(HB_E9 + EB_E9 > 5)'
if (options.towers > 1):
    lblHB += str(options.towers)
    lblEB += str(options.towers)
    lblHO += str(options.towers)
lblHO += '/' + str(mipE) + ')'

barrelH = TH1D('barrelH', 'barrelH', 100, 0., hcalhits.GetMaximum(lblHB))
hcalhits.Draw(lblEB + ' + ' + lblHB + '>>barrelH', cuts)
gPad.Update()
Exemplo n.º 27
0
def jetdisplay():
	outputfile = "Jetdisplay"
	displayfile = TFile(outputfile+".root","RECREATE")

	inputfile = "wwlj1k.root"

	inputfile = TFile(inputfile)
	print "Analyzing: "+str(inputfile)+" \n"
	tree = TTree()
	inputfile.GetObject("B4", tree)	

	graph = TH1F("energyjet", "energyjet", 100, 0., 200.)
	graph2 = TH1F("energycherjet", "energycherjet", 100, 0., 200.)
	graph3 = TH1F("energyscinjet", "energyscinjet", 100, 0., 200.)
	graphmass = TH1F("mass_jet", "mass_jet", 100, 0., 200.)

	graph4 = TH1F("energy", "energy", 100, 0., 200.)
	graph5 = TH1F("energycher", "energycher", 100, 0., 200.)
	graph6 = TH1F("energyscin", "energyscin", 100, 0., 200.)

	#loop over events
	for Event in range(tree.GetEntries()):	

		tree.GetEntry(Event)	

		#Set values of the tree
		PrimaryParticleName = tree.PrimaryParticleName # MC truth: primary particle Geant4 name
		PrimaryParticleEnergy = tree.PrimaryParticleEnergy
		EnergyTot = tree.EnergyTot # Total energy deposited in calorimeter
		Energyem = tree.Energyem # Energy deposited by the em component
		EnergyScin = tree.EnergyScin # Energy deposited in Scin fibers (not Birk corrected)
		EnergyCher = tree.EnergyCher # Energy deposited in Cher fibers (not Birk corrected)
		NofCherenkovDetected = tree.NofCherenkovDetected # Total Cher p.e. detected
		BarrelR_VectorSignals = tree.VectorSignalsR  # Vector of energy deposited in Scin fibers (Birk corrected)
		BarrelL_VectorSignals = tree.VectorSignalsL  # Vector of energy deposited in Scin fibers (Birk corrected)
		BarrelR_VectorSignalsCher = tree.VectorSignalsCherR # Vector of Cher p.e. detected in Cher fibers
		BarrelL_VectorSignalsCher = tree.VectorSignalsCherL 	
		VectorR = tree.VectorR
		VectorL = tree.VectorL
		
		Calib_BarrelL_VectorSignals = calibration.calibscin(BarrelL_VectorSignals)
		Calib_BarrelR_VectorSignals = calibration.calibscin(BarrelR_VectorSignals)
		Calib_BarrelL_VectorSignalsCher = calibration.calibcher(BarrelL_VectorSignalsCher)
		Calib_BarrelR_VectorSignalsCher = calibration.calibcher(BarrelR_VectorSignalsCher)

		energy = float(sum(Calib_BarrelR_VectorSignals)+sum(Calib_BarrelL_VectorSignals))
		energycher = float(sum(Calib_BarrelR_VectorSignalsCher)+sum(Calib_BarrelL_VectorSignalsCher))
		threshold = 0.0 #(GeV)	

		if energy>70.:
			
			#event displays with signals (p.e.)
			#if Event < 1:
				#displayfile.cd()
				#ROOTHistograms.create_eventdisplay_scin("Jet", BarrelR_VectorSignals, BarrelL_VectorSignals, "signal"+str(Event)) 
				#ROOTHistograms.create_eventdisplay_cher("Jet", BarrelR_VectorSignalsCher, BarrelL_VectorSignalsCher, "signal"+str(Event))
		
			#event displays with energy (GeV)	
			if Event<10:
					displayfile.cd()
					ROOTHistograms.create_eventdisplay_scin("Jet_energy", Calib_BarrelR_VectorSignals, Calib_BarrelL_VectorSignals, "energy"+str(Event), threshold) 
					ROOTHistograms.create_eventdisplay_cher("Jet_energy", Calib_BarrelR_VectorSignalsCher, Calib_BarrelL_VectorSignalsCher, "energy"+str(Event), threshold)	
			
			inputparticles_scin = []
			inputparticles_cher = []

			#right part
			for towerindex in range(75*36):	
				theta, phi, eta = newmap.maptower(towerindex, "right")
				energy_scin = Calib_BarrelR_VectorSignals[towerindex]
				pt_scin = energy_scin*np.sin(theta*math.pi/180.)

				energy_cher = Calib_BarrelR_VectorSignalsCher[towerindex]
				pt_cher = energy_cher*np.sin(theta*math.pi/180.)
				
				towerscin = TLorentzVector()
				towerscin.SetPtEtaPhiM(pt_scin, eta, phi*math.pi/180., 0.)
				towercher = TLorentzVector()
				towercher.SetPtEtaPhiM(pt_cher, eta, phi*math.pi/180., 0.)	

				if energy_scin > threshold:
					#print "truth towers: "+str(energy_scin)+" "+str(eta)+" "+str(phi)
					inputparticles_scin.append(fastjet.PseudoJet(towerscin.Px(), towerscin.Py(), towerscin.Pz(), towerscin.E()))
					inputparticles_cher.append(fastjet.PseudoJet(towercher.Px(), towercher.Py(), towercher.Pz(), towercher.E()))
			
			#left part
			for towerindex in range(75*36):	
				theta, phi, eta = newmap.maptower(towerindex, "left")
				energy_scin = Calib_BarrelL_VectorSignals[towerindex]
				pt_scin = energy_scin*np.sin(theta*math.pi/180.)
				
				energy_cher = Calib_BarrelL_VectorSignalsCher[towerindex]
				pt_cher = energy_cher*np.sin(theta*math.pi/180.)
				
				towerscin = TLorentzVector()
				towerscin.SetPtEtaPhiM(pt_scin, eta, phi*math.pi/180., 0.)
				towercher = TLorentzVector()
				towercher.SetPtEtaPhiM(pt_cher, eta, phi*math.pi/180., 0.)	

				if energy_scin > threshold:
					#print "truth towers: "+str(energy_scin)+" "+str(eta)+" "+str(phi)
					inputparticles_scin.append(fastjet.PseudoJet(towerscin.Px(), towerscin.Py(), towerscin.Pz(), towerscin.E()))
					inputparticles_cher.append(fastjet.PseudoJet(towercher.Px(), towercher.Py(), towercher.Pz(), towercher.E()))

			jet_def = fastjet.JetDefinition(fastjet.ee_genkt_algorithm, 2*math.pi, 1.)
			
			clust_seq = fastjet.ClusterSequence(inputparticles_scin, jet_def)	

			print "Event: "+str(Event)+" energy (GeV): "+str(energy)+" n-jets: "+str(len(clust_seq.exclusive_jets(int(2))))+" truth: "+str(len(inputparticles_scin))
			
			clust_seq_cher = fastjet.ClusterSequence(inputparticles_cher, jet_def)

			jet1_scin = fastjet.sorted_by_E(clust_seq.exclusive_jets(int(2)))[0]
			jet2_scin = fastjet.sorted_by_E(clust_seq.exclusive_jets(int(2)))[1]

			jet1_cher = fastjet.sorted_by_E(clust_seq_cher.exclusive_jets(int(2)))[0]
			jet2_cher = fastjet.sorted_by_E(clust_seq_cher.exclusive_jets(int(2)))[1]

			print "DeltaR jet1_scin: "+str(jet1_scin.delta_R(jet1_cher))+" "+str(jet1_scin.delta_R(jet2_cher))

			c = 0.34 #chi factor

			jet1, jet2 = mergejet(jet1_scin, jet2_scin, jet1_cher, jet2_cher)

			graph.Fill(jet1.e()+jet2.e())
			graph3.Fill(jet1_scin.e()+jet2_scin.e())
			graph2.Fill(jet1_cher.e()+jet2_cher.e())
			j = jet1+jet2
			graphmass.Fill(j.m())
			
			graph4.Fill((energy-c*energycher)/(1.-c))
			graph5.Fill(energycher)
			graph6.Fill(energy)
	
	graph.Write()
	graph2.Write()
	graph3.Write()
	graph4.Write()
	graph5.Write()
	graph6.Write()
	graphmass.Write()
Exemplo n.º 28
0
#Hardcoded calibration constants and Chi factor
#You can estimate them with dedicated part
scincalibconstant = 23.92  #MeV/MeV
chercalibconstant = 23.00  #MeV/Cpe
Chi = 0.50  #to be better defined
HEcher = 0.360
HEscin = 0.679

#Set root file and tree to be analyzed
gROOT.Reset()
file = raw_input("Insert namefile: ")
filename = str(file) + "B4.root"
inputFile = TFile(str(filename))  #root input file
tree = TTree()  #Tree name B4
inputFile.GetObject("B4", tree)

#---------------------------------------------------------------------------------------------------
#Section used only if you want to estimate the calibration constants and Chi factor of a module.
#DREAM is calibrated with electrons. The input file must be from electron events with the same energy.
#To estimate h/e Cher and scin values and the Chi factor a second root file with pions (+ or -) is needed.

#To later perform h/e Cher and scin computation and Chi factor
print "You have given an electron file event, now pass a pion one for h/e estimation.\n"
namepionfile = raw_input("Insert name of ROOT pion (+ or -) file: ")

#Set parameters
NofEvents = tree.GetEntries()
fastchercalibconstant = 0  #Done without building clusters
fastscincalibconstant = 0  #Done without building clusters
fastChi = 0
Exemplo n.º 29
0
mainResultList = TList()

#number of tagging categories
numTagCat = 5

#parse etaHist directory for .root files
for i in fileList[:1]:
    if (i[-5:] != '.root'):
        continue
    print i
    inFile = TFile(i)
    inFile.GetListOfKeys().Print()
    inFile.ls()
    #s = raw_input("Press Enter to continue");
    theTH1DHist = TH1F()
    inFile.GetObject("etaHist", theTH1DHist)
    mainResultList.AddLast(
        divideEtaTH1Ds(theTH1DHist, numTagCat, i, None, True))

from ROOT import TFile
import time

os.chdir(os.environ['B2DXFITTERSROOT'] + '/tutorial')

if (not (os.path.isdir('fits'))):
    os.mkdir('fits')

os.chdir('fits')

mainResultList.Print("", 5)
Exemplo n.º 30
0
def jetdisplay():
    outputfile = "zjj"
    displayfile = TFile(outputfile + ".root", "RECREATE")

    energies = [30, 50, 70, 90, 150, 250]
    cut = [16.72, 31.115, 55.548, 58.715, 99.335, 160.8]
    inputfiles = [
        "jetscan_leakage_029/jetscan_" + str(e) + ".root" for e in energies
    ]

    #for geant4.10.5
    inputfiles = [
        "resultsgeant4.10.5/jetscan_leakage/jetscan/jetscan" + str(e) + ".root"
        for e in energies
    ]
    #end of geant4.10.5

    #for geant4.10.5 with X0 or B
    #inputfiles = ["resultsgeant4.10.5/jetscan_leakage_X0/jetscan/jetscan"+str(e)+".root" for e in energies]
    #end of geant4.10.5 with X0 or B

    #for CaloLoop
    #inputfiles = ["/home/software/Calo/CaloLoop/CaloJet/resultsgeant4.10.5/jetscan_leakage_B/jetscan/jetscan"+str(e)+".root" for e in energies]
    #end CaloLoop

    #for geant4.10.5.p01 FTFPBERT
    inputfiles = [
        "results_FTFPBERT/noBnoX0/jetscan/jetscan_" + str(e) + ".root"
        for e in energies
    ]
    #end geant4.10.5.p01 FTFPBERT

    for counter, inputfile in enumerate(inputfiles):
        inputfile = TFile(inputfile)
        print "Analyzing: " + str(inputfile) + " \n"
        tree = TTree()
        inputfile.GetObject("MyTree", tree)

        #graphEjet1 = TH1F("energyjet1", "energyjet1", 100, 0., 200.)
        #graphEjet2 = TH1F("energyjet2", "energyjet2", 100, 0., 200.)

        #graphEcherjet1 = TH1F("energycher1", "energycherjet", 100, 0., 200.)
        #graph3 = TH1F("energyscinjet", "energyscinjet", 100, 0., 200.)

        #graphmass = TH1F("mass_jet", "mass_jet", 100, 0., 200.)
        graphtest = TH1F("test" + str(energies[counter]),
                         "test" + str(energies[counter]), 80, -40., 40.)
        graphenergy = TH1F("energy" + str(energies[counter]),
                           "energy" + str(energies[counter]), 200, 0., 100.)
        graphenergytruth = TH1F("energytruth" + str(energies[counter]),
                                "energytruth" + str(energies[counter]), 200,
                                0., 100.)
        graphjs = TH1F("energyjs" + str(energies[counter]),
                       "energyjs" + str(energies[counter]), 200, 0., 100.)
        graphjc = TH1F("energyjc" + str(energies[counter]),
                       "energyjc" + str(energies[counter]), 200, 0., 100.)

        graph_emcomp02 = TH1F("emcomp02_" + str(energies[counter]),
                              "emcomp02" + str(energies[counter]), 80, -40, 40)
        graph_emcomp04 = TH1F("emcomp04_" + str(energies[counter]),
                              "emcomp04" + str(energies[counter]), 80, -40, 40)
        graph_emcomp06 = TH1F("emcomp06_" + str(energies[counter]),
                              "emcomp06" + str(energies[counter]), 80, -40, 40)
        graph_emcomp08 = TH1F("emcomp08_" + str(energies[counter]),
                              "emcomp08" + str(energies[counter]), 80, -40, 40)
        graph_emcomp1 = TH1F("emcomp1_" + str(energies[counter]),
                             "emcomp1" + str(energies[counter]), 80, -40, 40)

        scatterplot = TH2F("diff_" + str(energies[counter]),
                           "diff_" + str(energies[counter]), 70, -20., 50., 70,
                           -50., 20)
        scatterplotedep = TH2F("edep_" + str(energies[counter]),
                               "edep_" + str(energies[counter]), 100, 0.0,
                               100.0, 100, 0.0, 100.0)
        #loop over events
        for Event in range(tree.GetEntries()):

            tree.GetEntry(Event)
            #print "Event "+str(Event)
            nmuon = tree.nmuon
            nneu = tree.nneu
            mjjr = tree.mjjr
            mjjt = tree.mjjt
            edep = tree.edep
            muene_che = tree.muene_che
            muene_sci = tree.muene_sci
            emcomp1 = tree.emcomp1
            emcomp2 = tree.emcomp2
            eleak = tree.eleak
            eleakn = tree.eleakn

            j1t_E = tree.j1t_E
            j1t_m = tree.j1t_m
            j1t_theta = tree.j1t_theta
            j1t_pt = tree.j1t_pt
            j1t_eta = tree.j1t_eta
            j1t_phi = tree.j1t_phi
            j2t_E = tree.j2t_E
            j2t_m = tree.j2t_m
            j2t_theta = tree.j2t_theta
            j2t_pt = tree.j2t_pt
            j2t_eta = tree.j2t_eta
            j2t_phi = tree.j2t_phi

            j1r_E = tree.j1r_E
            j1r_m = tree.j1r_m
            j1r_theta = tree.j1r_theta
            j1r_pt = tree.j1r_pt
            j1r_eta = tree.j1r_eta
            j1r_phi = tree.j1r_phi
            j2r_E = tree.j2r_E
            j2r_m = tree.j2r_m
            j2r_theta = tree.j2r_theta
            j2r_pt = tree.j2r_pt
            j2r_eta = tree.j2r_eta
            j2r_phi = tree.j2r_phi

            j1s_E = tree.j1s_E
            j1s_m = tree.j1s_m
            j1s_theta = tree.j1s_theta
            j1s_pt = tree.j1s_pt
            j1s_eta = tree.j1s_eta
            j1s_phi = tree.j1s_phi
            j2s_E = tree.j2s_E
            j2s_m = tree.j2s_m
            j2s_theta = tree.j2s_theta
            j2s_pt = tree.j2s_pt
            j2s_eta = tree.j2s_eta
            j2s_phi = tree.j2s_phi

            j1c_E = tree.j1c_E
            j1c_m = tree.j1c_m
            j1c_theta = tree.j1c_theta
            j1c_pt = tree.j1c_pt
            j1c_eta = tree.j1c_eta
            j1c_phi = tree.j1c_phi
            j2c_E = tree.j2c_E
            j2c_m = tree.j2c_m
            j2c_theta = tree.j2c_theta
            j2c_pt = tree.j2c_pt
            j2c_eta = tree.j2c_eta
            j2c_phi = tree.j2c_phi

            cut1 = nmuon == 0 and nneu == 0
            cut2 = abs(j1t_eta) < 2.0 and abs(j2t_eta) < 2.0
            eleak = eleak / 1000.
            cut3 = eleak < 0.1
            #cut3 = True
            cut4 = j1s_E + j2s_E > cut[counter]
            cut4 = True
            #cut5 = abs(j1t_E-j2t_E)<5.
            #cut5 = abs(j1t_phi-j2t_phi)>0.1
            cut5 = True
            if cut1 and cut2 and cut3 and cut4 and cut5:
                #deltaj1 = 0.04406*j1r_E+0.1158
                #deltaj2 = 0.04406*j2r_E+0.1158
                #deltaj1 = 0.02825*j1r_E+0.4056
                #deltaj2 = 0.02825*j2r_E+0.4056
                #deltaj1 = 0.04135*j1r_E+0.08789
                #deltaj2 = 0.04135*j2r_E+0.08789
                #deltaj1 = 0.07113*j1r_E+0.5201
                #deltaj2 = 0.07113*j2r_E+0.5201
                deltaj1 = 0.0
                deltaj2 = 0.0
                graphtest.Fill(j1r_E + deltaj1 - j1t_E)
                graphtest.Fill(j2r_E + deltaj2 - j2t_E)
                '''
				if (emcomp1+emcomp2)<0.2*90.:
					graph_emcomp02.Fill(j1r_E+deltaj1-j1t_E)
					graph_emcomp02.Fill(j2r_E+deltaj2-j2t_E)
				if 0.2*90.<emcomp1+emcomp2<0.4*90.:
					graph_emcomp04.Fill(j1r_E+deltaj1-j1t_E)
					graph_emcomp04.Fill(j2r_E+deltaj2-j2t_E)
				if 0.4*90.<emcomp1+emcomp2<0.6*90.:
					graph_emcomp06.Fill(j1r_E+deltaj1-j1t_E)
					graph_emcomp06.Fill(j2r_E+deltaj2-j2t_E)				
				if 0.6*90.<emcomp1+emcomp2<0.8*90.:
					graph_emcomp08.Fill(j1r_E+deltaj1-j1t_E)
					graph_emcomp08.Fill(j2r_E+deltaj2-j2t_E)				
				if 0.8*90.<emcomp1+emcomp2<90.:
					graph_emcomp1.Fill(j1r_E+deltaj1-j1t_E)
					graph_emcomp1.Fill(j2r_E+deltaj2-j2t_E)				
				'''
                graphenergy.Fill(j1r_E + deltaj1)
                graphenergy.Fill(j2r_E + deltaj2)
                graphenergytruth.Fill(j1t_E)
                graphenergytruth.Fill(j2t_E)
                graphjs.Fill(j2s_E)
                graphjs.Fill(j1s_E)
                graphjc.Fill(j2c_E)
                graphjc.Fill(j1c_E)
                scatterplot.Fill(j2r_E + deltaj2 - j2t_E,
                                 j1r_E + deltaj1 - j1t_E)
                scatterplotedep.Fill(edep, j1s_E + j2s_E)
        displayfile.cd()
        graphtest.Write()
        graphenergy.Write()
        graphenergytruth.Write()
        graphjs.Write()
        graphjc.Write()
        #graph_emcomp02.Write()
        #graph_emcomp04.Write()
        #graph_emcomp06.Write()
        #graph_emcomp08.Write()
        #graph_emcomp1.Write()
        scatterplot.Write()
        scatterplotedep.Write()