Пример #1
0
def createPlots2D_(plot, compounddetectorname):
    """2D material budget map to know exactly what we are adding.
    """

    #IBs = ["InnerServices", "Phase2PixelBarrel", "TIB", "TIDF", "TIDB"]
    theDirname = "Figures"

    hist_X0_detectors = OrderedDict()
    if plot not in plots.keys():
        print("Error: chosen plot name not known %s" % plot)
        return

    # We need to keep the file content alive for the lifetime of the
    # full function....
    subDetectorFiles = []

    hist_X0_elements = OrderedDict()
    prof_X0_elements = OrderedDict()

    for subDetector, color in DETECTORS.items():
        subDetectorFilename = "matbdg_%s.root" % subDetector
        if not checkFile_(subDetectorFilename):
            print("Error opening file: %s" % subDetectorFilename)
            continue

        subDetectorFiles.append(TFile(subDetectorFilename))
        subDetectorFile = subDetectorFiles[-1]
        print("Opening file: %s" % subDetectorFilename)
        prof_X0_XXX = subDetectorFile.Get("%d" % plots[plot].plotNumber)

        #hist_X0_detectors[subDetector] = prof_X0_XXX
        hist_X0_detectors[subDetector] = prof_X0_XXX.ProjectionXY("_pxy", "B")
        print(subDetector)

    # First Plot: BeamPipe + Tracker + ECAL + HCal + HGCal + MB + MGNT

    # Create "null" histo
    minX = 1.03 * hist_X0_detectors["BeamPipe"].GetXaxis().GetXmin()
    maxX = 1.03 * hist_X0_detectors["BeamPipe"].GetXaxis().GetXmax()
    minY = 1.03 * hist_X0_detectors["BeamPipe"].GetYaxis().GetXmin()
    maxY = 1.03 * hist_X0_detectors["BeamPipe"].GetYaxis().GetXmax()

    frame = TH2F("frame", "", 10, minX, maxX, 10, minY, maxY)
    frame.SetMinimum(0.1)
    frame.SetMaximum(10.)
    frame.GetXaxis().SetTickLength(frame.GetXaxis().GetTickLength() * 0.50)
    frame.GetYaxis().SetTickLength(frame.GetXaxis().GetTickLength() / 4.)

    hist2d_X0_total = hist_X0_detectors["BeamPipe"]

    # stack
    hist2dTitle = (
        '%s %s;%s;%s;%s' %
        (plots[plot].quotaName, "All detectors", plots[plot].abscissa,
         plots[plot].ordinate, plots[plot].quotaName))

    hist2d_X0_total.SetTitle(hist2dTitle)
    frame.SetTitle(hist2dTitle)
    frame.SetTitleOffset(0.5, "Y")

    #If here you put different histomin,histomaxin plot_utils you won't see anything
    #for the material plots.
    if plots[plot].histoMin != -1.:
        hist2d_X0_total.SetMinimum(plots[plot].histoMin)
    if plots[plot].histoMax != -1.:
        hist2d_X0_total.SetMaximum(plots[plot].histoMax)

    #
    # canvas
    can_SubDetectors = TCanvas("can_SubDetectors", "can_SubDetectors",
                               2480 + 248, 580 + 58 + 58)
    can_SubDetectors.SetTopMargin(0.1)
    can_SubDetectors.SetBottomMargin(0.1)
    can_SubDetectors.SetLeftMargin(0.04)
    can_SubDetectors.SetRightMargin(0.06)
    can_SubDetectors.SetFillColor(kWhite)
    gStyle.SetOptStat(0)
    gStyle.SetTitleFillColor(0)
    gStyle.SetTitleBorderSize(0)
    gStyle.SetOptTitle(0)

    hist2d_X0_total.GetYaxis().SetTickLength(
        hist2d_X0_total.GetXaxis().GetTickLength() / 4.)
    hist2d_X0_total.GetYaxis().SetTickLength(
        hist2d_X0_total.GetXaxis().GetTickLength() / 4.)
    hist2d_X0_total.SetTitleOffset(0.5, "Y")
    hist2d_X0_total.GetYaxis().SetTitleOffset(0.50)
    #hist2d_X0_total.GetXaxis().SetTitleOffset(1.15);
    #hist2d_X0_total.GetXaxis().SetNoExponent(True)
    #hist2d_X0_total.GetYaxis().SetNoExponent(True)

    # colors
    for det, color in DETECTORS.items():
        hist_X0_detectors[det].SetMarkerColor(color)
        hist_X0_detectors[det].SetFillColor(color)

    for det, histo in hist_X0_detectors.items():
        print(det)
        histo.Draw("same")

    # Legenda
    theLegend_SubDetectors = TLegend(0.100, 0.7, 0.90,
                                     0.90)  #(0.180,0.8,0.98,0.90)
    theLegend_SubDetectors.SetNColumns(3)
    theLegend_SubDetectors.SetFillColor(0)
    theLegend_SubDetectors.SetFillStyle(0)
    theLegend_SubDetectors.SetBorderSize(0)

    for det, histo in hist_X0_detectors.items():
        theLegend_SubDetectors.AddEntry(histo, det, "f")
    #theLegend_SubDetectors.AddEntry(hgbound1, "HGCal Eta Boundaries [1.3, 3.0]",  "l")

    theLegend_SubDetectors.Draw()

    # text
    text_SubDetectors = TPaveText(0.100, 0.627, 0.322, 0.687,
                                  "NDC")  #(0.180,0.727,0.402,0.787,"NDC")
    text_SubDetectors.SetFillColor(0)
    text_SubDetectors.SetBorderSize(0)
    text_SubDetectors.AddText("CMS Simulation")
    text_SubDetectors.SetTextAlign(11)
    text_SubDetectors.Draw()

    #Add eta labels
    keep_alive = []
    if plots[plot].iDrawEta:
        keep_alive.extend(drawEtaValues())

    # Store
    can_SubDetectors.Update()
    if not checkFile_(theDirname):
        os.mkdir(theDirname)
    can_SubDetectors.SaveAs("%s/MaterialBdg_%s_%s.png" %
                            (theDirname, compounddetectorname, plot))
    #It seems that it is too heavy to create .pdf and .root
    #can_SubDetectors.SaveAs("%s/MaterialBdg_FromVertexToEndofHGCal_%s.pdf" % (theDirname, plot))
    #can_SubDetectors.SaveAs("%s/MaterialBdg_FromVertexToEndofHGCal_%s.root" % (theDirname, plot))

    hist2d_X0_total.GetXaxis().SetRangeUser(0., 7000.)
    #Draw eta values in the zoom case
    keep_alive = []
    keep_alive.extend(drawHalfEtaValues())
    #hist2d_X0_total.Draw("COLZ")
    can_SubDetectors.Update()
    can_SubDetectors.Modified()
    can_SubDetectors.SaveAs("%s/MaterialBdg_%s_%s_Zpluszoom.png" %
                            (theDirname, compounddetectorname, plot))
Пример #2
0
            eta_bins.append(float(l[0]))

        for n in range(int(len(l) / 3) - 1):
            pt_bins.append(float(l[3 * (n + 1)]))

        eta_bins.append(float(l[1]))
        pt_bins.append(10000.)

    nbinsx = len(pt_bins) - 1
    xbins = array('f', pt_bins)
    nbinsy = len(eta_bins) - 1
    ybins = array('f', eta_bins)
    dhn = 'hJetShift_' + key + '_Down'
    uhn = 'hJetShift_' + key + '_Up'

    hJetShiftDown = TH2F(dhn, dhn, nbinsx, xbins, nbinsy, ybins)
    hJetShiftUp = TH2F(uhn, uhn, nbinsx, xbins, nbinsy, ybins)

    with open(s['txt']) as f:
        next(f)  # skip first line
        for y_, line in enumerate(f):
            l = line.split()
            y = y_ + 1
            for x_, n in enumerate(range(int(len(l) / 3) - 1)):
                x = x_ + 1
                down = float(l[3 * (n + 1) + 1])
                up = float(l[3 * (n + 1) + 2])
                hJetShiftDown.SetBinContent(x, y, down)
                hJetShiftUp.SetBinContent(x, y, up)

    hists.append(hJetShiftDown.Clone(dhn))
def main():

    f = open(filelistStr,"r")
    rtfileoutput = TFile(rtfileoutputStr,"recreate")
    waveDir = rtfileoutput.mkdir("Waveforms")
    resultsDir = rtfileoutput.mkdir("Results")

    # prepare for histgorams
    hAmplitude_list = []
    hAmplitudeBin_list = []
    hWave_list = []
    hPedMean_list = []
    hPedWidth_list = []
    hFinalCharge_list = []
    hNbOfPulses_list = []
    hPulseStartTime_list = [] # start time of the pulse
    hPulseTimeDist_list = [] # time distribution of the pulses that are not due to fiber trigger (ie., dark pulses or else)
    hPulseWidth_list = [] # time distribution of the pulses that are not due to fiber trigger (ie., dark pulses or else)
    hPulseAmplitudeVsTime_list = [] # 2D histogram: pulse amplitude vs. pulse time bin
    hPulseAmplitudeVsWidth_list = [] # 2D histogram: pulse amplitude vs. pulse time bin
    hWaveAvg_list = [] # average of raw waveforms
    #special test on time difference between the first channel
    hTimeDiff = TH1F("hTimeDiff","Time diference",100,-10,10) # unit in ns
    hTimeDiff.SetXTitle("Time difference (ns)");
    hTimeDiff.SetYTitle("N");
    for i in range(0,NCH,1):
        # will keep a few waveforms 
        name = "Wave_" + str(i)
        hist = TH1F(name,"",NSamples,0,NSamples)
        hist.SetXTitle("Sample number")
        hist.SetYTitle("Amplitude (mV)")
        hist.SetLineColor(i+1)
        hWave_list.append(hist)
        # will keep average waveforms 
        name = "WaveAvg_" + str(i)
        hist = TH1F(name,"",NSamples,0,NSamples)
        hist.SetXTitle("Sample number")
        hist.SetYTitle("Amplitude (mV)")
        hist.SetLineColor(i+1)
        hWaveAvg_list.append(hist)
        # histogram of pulse baseline 
        name = "PedMean_" + str(i)
        hist = TH1F(name,"",1000,-5,5)
        hist.SetXTitle("Amplitude (mv)")
        hist.SetYTitle("Counts")
        hist.SetLineColor(i+1)
        hPedMean_list.append(hist)
        # histogram of pulse baseline width
        name = "PedWidth_" + str(i)
        hist = TH1F(name,"",1000,-5,5)
        hist.SetXTitle("Amplitude (mV)")
        hist.SetYTitle("Counts")
        hist.SetLineColor(i+1)
        hPedWidth_list.append(hist)
        # pulse charge due to fiber triggers, unit converted to fC
        name = "FinalCharge_" + str(i)
        # would be best to have different settings for LED on vs LED off
        if ledStatus == 0:
            hist = TH1F(name,"",80,-3,3)
        else:
            hist = TH1F(name,"",18,-4,50)
        hist.SetXTitle("Charge (pC)")
        hist.SetYTitle("Counts")
        hist.SetLineColor(i+1)
        hFinalCharge_list.append(hist)
        # pulse amplitude, or nimimum (because of negative pulse)
        name = "PulseAmplitude_" + str(i)
        hist = TH1F(name,"",500,0,500)
        hist.SetXTitle("Amplitude (mV)")
        hist.SetYTitle("Counts")
        hist.SetLineColor(i+1)
        hAmplitude_list.append(hist)
        # pulse width, or nimimum (because of negative pulse)
        name = "PulseWidth_" + str(i)
        hist = TH1F(name,"",100,0,100)
        hist.SetXTitle("Pulse width (ns)")
        hist.SetYTitle("Counts")
        #hist.SetLineColor(i+1)
        hPulseWidth_list.append(hist)
        # time bin where pulse amplitude is found, used to determine charge integration region
        name = "PulseAmplitudeBin_" + str(i)
        hist = TH1F(name,"",200,100,300)
        hist.SetXTitle("Amplitude bin number")
        hist.SetYTitle("Counts")
        hist.SetLineColor(i+1)
        hAmplitudeBin_list.append(hist)
        # number of pulses found in the waveform not in the fiber trigger region
        name = "NbOfPulses_" + str(i)
        hist = TH1F(name,"",20,0,20)
        hist.SetXTitle("Number of pulses in a 20 #mus window")
        hist.SetYTitle("Counts")
        hist.SetLineColor(i+1)
        hNbOfPulses_list.append(hist)
        # pulse start time, only choose those pulses above threshold
        name = "PulseStartTime_" + str(i)
        hist = TH1F(name,"",200,100,300)
        hist.SetXTitle("Pulse start time bin (1.6 ns/bin)")
        hist.SetYTitle("Counts")
        #hist.SetLineColor(i+1)
        hPulseStartTime_list.append(hist)
        # pulse time distributions for those pulses are 100 ns later than the fiber triggered pulse
        name = "PulseTimeDist_" + str(i)
        hist = TH1F(name,"",NSamples/10,0,NSamples)
        hist.SetXTitle("Pulse time bin (16 ns/bin)")
        hist.SetYTitle("Counts")
        hist.SetLineColor(i+1)
        hPulseTimeDist_list.append(hist)
        # pulse time distributions for those pulses are 100 ns later than the fiber triggered pulse
        name = "PulseAmpVsTimeBin_" + str(i)
        hist = TH2F(name,"",NSamples/10,0,NSamples,500,0,500)
        hist.SetXTitle("Pulse time bin")
        hist.SetYTitle("Pulse Amplitude (mV)")
        hist.SetLineColor(i+1)
        hPulseAmplitudeVsTime_list.append(hist)
        # pulse time distributions for those pulses are 100 ns later than the fiber triggered pulse
        name = "PulseAmpVsWidth_" + str(i)
        hist = TH2F(name,"",100,0,100,500,0,500)
        hist.SetXTitle("Pulse time bin")
        hist.SetYTitle("Pulse Amplitude (mV)")
        hPulseAmplitudeVsWidth_list.append(hist)

    #process the waveforms
    baseline_mean = 0.0
    baseline_width = 0.0
    threshold = 0.0
    sumwave = [[0 for x in range(NSamples)] for y in range(NCH)]
    #special test for time diff
    flag1 = [ False for x in range(Nwaves)]
    time1 = [ 0 for x in range(Nwaves)]
    flag2 = [ False for x in range(Nwaves)]
    time2 = [ 0 for x in range(Nwaves)]
    for ch in range(NCH):
        for waveNb in range(Nwaves):
            afilename = f.readline().rstrip()
            #print afilename
            #if waveNb>20:
            #    continue
            awave = np.asarray(decode_wfm(dataDirectory + afilename))
            #print "dump data "
            #for bin in range(NSamples):
            #    print awave[bin]
            #print NSamples, len(awave)
            baseline_mean = np.average(awave[NSamples-200:NSamples])
            baseline_width = np.std(awave[NSamples-200:NSamples])
            threshold = baseline_mean - Nsigma*baseline_width
            hPedMean_list[ch].Fill(baseline_mean)
            hPedWidth_list[ch].Fill(baseline_width)
            TimeBinOfAmplitude = np.argmin(awave[70:800]) + 70
            if ch == 0 and awave[TimeBinOfAmplitude]<threshold:
                flag1[waveNb] = True
                time1[waveNb] = TimeBinOfAmplitude
            if ch == 1 and awave[TimeBinOfAmplitude]<threshold:
                flag2[waveNb] = True
                time2[waveNb] = TimeBinOfAmplitude
            # get charge integration about the amplitude: 20.8 ns before to 36.8 ns after the amplitude
            #sumcharge = 0.0
            #if TimeBinOfAmplitude>=168 and TimeBinOfAmplitude<=180:
            sumcharge = np.sum(awave[TimeBinOfAmplitude-13:TimeBinOfAmplitude+23])
            pulsestartbin = TimeBinOfAmplitude
            while awave[pulsestartbin]<threshold and pulsestartbin>=TimeBinOfAmplitude-20:
                pulsestartbin -= 1
            hPulseStartTime_list[ch].Fill(pulsestartbin-1)                
            #else:
            #    sumcharge = np.sum(awave[172-13:172+23])
            fC = (sumcharge-baseline_mean*(23+13+1))*QFactor # convert charge involving the 50 Ohm impedience
            #if awave[TimeBinOfAmplitude] < threshold:
            hAmplitude_list[ch].Fill(-1000.0*(awave[TimeBinOfAmplitude]-baseline_mean))
            hAmplitudeBin_list[ch].Fill(TimeBinOfAmplitude)
            #print TimeBinOfAmplitude, awave[TimeBinOfAmplitude]
            hFinalCharge_list[ch].Fill(-1.0*fC)
            # search for number of pulses 
            peakindex = peakutils.peak.indexes(-1.0*awave[0:NSamples],thres=abs(threshold), min_dist=31, thres_abs=True)
            for pulse_i in range(len(peakindex)):
                if awave[peakindex[pulse_i]] > (baseline_mean - 2.0*Nsigma*baseline_width):
                    continue
                hPulseTimeDist_list[ch].Fill(peakindex[pulse_i]) #+TimeBinOfAmplitude+200
                hPulseAmplitudeVsTime_list[ch].Fill(peakindex[pulse_i], -1000.0*(awave[peakindex[pulse_i]]-baseline_mean))
                #determine the pulse width
                thisindex = peakindex[pulse_i]
                thiswidth = 0
                while awave[thisindex]<=threshold and thisindex>=2:
                    #print pulse_i, ch, thiswaveform[ch][thisindex], threshold[ch]
                    thiswidth += 1
                    thisindex -= 1
                    #if thisindex<=1:
                    #    print eventNb, ch, pulse_i, thiswaveform[ch][thisindex]
                thisindex = peakindex[pulse_i]
                while awave[thisindex+1]<=threshold and thisindex<=NSamples-3:
                    thiswidth += 1
                    thisindex += 1
                    #    if thisindex>=NSamples-2:
                    #        print eventNb, ch, pulse_i, thiswaveform[ch][thisindex]
                hPulseWidth_list[ch].Fill((thiswidth+2)*2)
                hPulseAmplitudeVsWidth_list[ch].Fill((thiswidth+2)*2, -1000.0*(awave[peakindex[pulse_i]]-baseline_mean))
            #print ch, waveNb, peakindex
            if waveNb%100 ==0:
                print ch, waveNb, afilename
                for bin in range(0,NSamples,1):
                    hWave_list[ch].SetBinContent(bin+1,-1000.0*(awave[bin]-baseline_mean))
                    #hWave_list[ch].SetBinContent(bin+1,awave[bin])
                waveDir.cd()
                lenname = int(len(afilename))
                newName = "Wave_Ch_" + str(ch) + "_" + str(waveNb)+afilename[lenname-4-17:lenname-4]
                titleName = "Evt "+str(waveNb)+"_Ch"+str(ch)+"_PulseBins_"
                for pulse_i in range(len(peakindex)):
                    titleName += str(peakindex[pulse_i])
                    titleName += "_"
                hWave_list[ch].SetName(newName)
                hWave_list[ch].SetTitle(titleName)
                hWave_list[ch].SetEntries(NSamples)
                hWave_list[ch].Write()
                #for bin in range(0,NSamples,1):
                #    hWave_list[ch].SetBinContent(bin+1,0);
                #if len(peakindex)>0:
            hNbOfPulses_list[ch].Fill( len(peakindex) )
            #average of raw waveforms for each PMT
            for bin in range(0,NSamples,1):
                sumwave[ch][bin] += 1000.0*(awave[bin]-baseline_mean)
    for ch in range(NCH):
        for bin in range(NSamples):
            hWaveAvg_list[ch].SetBinContent(bin+1,sumwave[ch][bin]/Nwaves)
        waveDir.cd()
        hWaveAvg_list[ch].Write()
    for waveNb in range(Nwaves):
        if flag1[waveNb] is True and flag2[waveNb] is True:
            hTimeDiff.Fill(time1[waveNb]-time2[waveNb])
    f.close()
    resultsDir.cd()
    for i in range(0,NCH,1):
        # fit the charge distributions with Poisson distribution plus exponetional background
        hFinalCharge_list[i].Write()
    for i in range(0,NCH,1):
        hAmplitude_list[i].Write()
    for i in range(0,NCH,1):
        hAmplitudeBin_list[i].Write()
    for i in range(0,NCH,1):
        hPedMean_list[i].Write()
    for i in range(0,NCH,1):
        hPulseStartTime_list[i].Write()
    for i in range(0,NCH,1):
        hPedWidth_list[i].Write()
    for i in range(0,NCH,1):
        hPulseTimeDist_list[i].Write()
        print "number of pulses: ", hPulseTimeDist_list[i].GetEntries()
    for i in range(0,NCH,1):
        hPulseWidth_list[i].Write()
    for i in range(0,NCH,1):
        hPulseAmplitudeVsTime_list[i].Write()
    for i in range(0,NCH,1):
        hPulseAmplitudeVsWidth_list[i].Write()
    for i in range(0,NCH,1):
        #darkrate = 0.0
        #for j in range(2,21):
        #    if hNbOfPulses_list[i].GetBinContent(j)>0:
        #        darkrate += hNbOfPulses_list[i].GetBinContent(j)*(j-1)
        #darkrate = darkrate/(10.0*1.0e-6*hNbOfPulses_list[i].GetEntries())
        #title = "dark rate on average " + str(darkrate) + " Hz"
        #hNbOfPulses_list[i].SetTitle(title)
        hNbOfPulses_list[i].Write()
    hTimeDiff.Write()
    rtfileoutput.Close()
Пример #4
0
        smoothed = smooth(data_mean, n // 5)
        pos_min = (np.diff(np.sign(np.diff(smoothed))) > 0).nonzero()[0] + 1
        pos_max = (np.diff(np.sign(np.diff(smoothed))) < 0).nonzero()[0] + 1
        pos_extrema = np.sort(np.concatenate((pos_min, pos_max)))
        pos_extrema = np.insert(pos_extrema, 0, 0)
        pos_extrema = np.append(pos_extrema, len(smoothed) - 1)
        extrema = list()
        for i, length in enumerate(np.diff(pos_extrema)):
            #Filter out extrema that are very close to one another
            if length > 10:
                extrema.append((int(pos_extrema[i + 1]), pos_extrema[i + 1]
                                in pos_max))

        print("Plotting...")
        c_diff = TCanvas("c_diff", "Differences", 200, 10, 700, 500)
        c_diff_hist = TH2F("h1", "Deviation", 10, -10, 30, 10, 0, 3)
        c_diff_hist.SetStats(False)
        c_diff_hist.Draw()

        diff_graphs = list()
        prev_pos = 0
        for pos_extremum, is_maximum in extrema:
            g_diff = TGraph(pos_extremum - prev_pos,
                            data_mean[prev_pos:pos_extremum],
                            data_std[prev_pos:pos_extremum])
            g_diff.SetTitle("Deviation")
            x_axis = g_diff.GetXaxis()
            #x_axis.SetTimeDisplay(1)
            #x_axis.SetTitle("Time")
            #x_axis.SetTimeFormat("%H:%M:%S")
            x_axis.SetTitle(field[2])
Пример #5
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()
Пример #6
0
def drawRoiDeltaR(geometry, is2016):
    def getTopoCell(mioct, etacode, phicode):
        global mioctTCmap
        mioctTCmap = {}
        mioctid = mioct['id']
        if not mioctid in mioctTCmap:
            d = {}
            for tc in mioct.Decode.TopoCells:
                key = (int(tc['etacode'], 16), int(tc['phicode'], 16))
                d[key] = tc
            mioctTCmap[mioctid] = d
        return mioctTCmap[mioctid][(etacode, phicode)]

    global h, c, hB, hEC, hFW

    gROOT.Reset()
    gStyle.SetOptStat(0)

    c = TCanvas('c', "Topo encoding", 1400, 950)
    c.Divide(2, 2)
    c.Draw()

    hB = TH2F(
        "hb", "Delta R between ROI and TopoCell %i in Barrel" %
        (2016 if is2016 else 2015), 64, 0, 64, 32, 0, 32)
    hB.SetXTitle("SL")
    hB.SetYTitle("ROI ID")

    hEC = TH2F(
        "hec", "Delta R between ROI and TopoCell %i in Endcap" %
        (2016 if is2016 else 2015), 96, 0, 96, 148, 0, 148)
    hEC.SetXTitle("SL")
    hEC.SetYTitle("ROI ID")

    hFW = TH2F(
        "hfw", "Delta R between ROI and TopoCell %i in Forward" %
        (2016 if is2016 else 2015), 48, 0, 48, 64, 0, 64)
    hFW.SetXTitle("SL")
    hFW.SetYTitle("ROI ID")

    for MioctID in drawOrder:
        mioct = geometry.getMIOCT(MioctID)

        for sector in mioct.Sectors:
            for roi in sector.ROIs:
                tc = getTopoCell(mioct, int(roi['etacode'], 16),
                                 int(roi['phicode'], 16))
                deltaEta = float(roi['eta']) - float(tc['ieta']) / 10.
                deltaPhi = float(roi['phi']) - float(tc['iphi']) / 10.
                if deltaPhi > math.pi:
                    deltaPhi -= 2 * math.pi  # some topocells are made up from ROIs that are on both sides of 0
                deltaR = math.sqrt(deltaEta * deltaEta + deltaPhi * deltaPhi)
                sectorid = int(sector['name'].lstrip('ABCDEF'))
                roiid = int(roi['roiid'])
                if sector['name'].startswith('B'):
                    hB.Fill(sectorid, roiid, deltaR)
                elif sector['name'].startswith('E'):
                    if sector['name'].startswith('EA'):
                        sectorid += 48
                    hEC.Fill(sectorid, roiid, deltaR)
                elif sector['name'].startswith('F'):
                    if sector['name'].startswith('FA'):
                        sectorid += 24
                    hFW.Fill(sectorid, roiid, deltaR)

    c.cd(1)
    hB.Draw("colz")
    c.cd(2)
    hEC.Draw("colz")
    c.cd(3)
    hFW.Draw("colz")
    c.Update()
    c.SaveAs("ROIDeltaR%s.pdf" % "2016" if is2016 else "2015")
Пример #7
0
   evt0 = 0
   evt1 = 0
   pidx0 = 0
   pidx1 = 0

   #initialize dicts
   datasetIDX_v_path = {'path': 0}
   get_gen_entries0_from_event = {0:0} #event number : entry number
   get_gen_entries1_from_event = {0:0}
   
   path_str_dict = {}#{'path':['dataset','module']}
   event_dict = {}#{'event':['changed','fired 0not1','fired 1not0']}
   output_list = [{} for i in xrange(11)]
   
   #make hists
   fired_rel0_not1_decayType_vs_dataset = TH2F("fired_rel0_didntfire_rel1_decay_type_vs_datasets","fired_rel0_didntfire_rel1_decay_type_vs_datasets",44,0,44,11,0,11)

   #set bin labels
   fired_rel0_not1_decayType_vs_dataset.GetYaxis().SetBinLabel(1,"Double Ele")
   fired_rel0_not1_decayType_vs_dataset.GetYaxis().SetBinLabel(2,"Double Mu")
   fired_rel0_not1_decayType_vs_dataset.GetYaxis().SetBinLabel(3,"Double Tau")
   fired_rel0_not1_decayType_vs_dataset.GetYaxis().SetBinLabel(4,"Ele + Mu")
   fired_rel0_not1_decayType_vs_dataset.GetYaxis().SetBinLabel(5,"Ele + Tau")
   fired_rel0_not1_decayType_vs_dataset.GetYaxis().SetBinLabel(6,"Mu + Tau")
   fired_rel0_not1_decayType_vs_dataset.GetYaxis().SetBinLabel(7,"Single Ele")
   fired_rel0_not1_decayType_vs_dataset.GetYaxis().SetBinLabel(8,"Single Mu")
   fired_rel0_not1_decayType_vs_dataset.GetYaxis().SetBinLabel(9,"Single Tau")
   fired_rel0_not1_decayType_vs_dataset.GetYaxis().SetBinLabel(10,"All Had")
   fired_rel0_not1_decayType_vs_dataset.SetTitle("lost counts going from " + rel0 + " to " + rel1 + ", ttbar decay vs dataset")
   fired_rel0_not1_decayType_vs_dataset.GetXaxis().SetLabelSize(0.03)
   fired_rel0_not1_decayType_vs_dataset.SetStats(0)
Пример #8
0
def hvt(benchmark = ['B3', 'A1']):
    
    hxs = {}
    hw = {}
    gxs = {}
    gw = {}
    mg = TMultiGraph()
    
    for m in massPoints:
        
        hxs[m] = TH2F("hxs_M%d" % m, ";;", 50, -0.04, 3.96, 100,  0., 2.)
        hw[m] = TH2F("hw_M%d" % m, ";;", 50, -0.04, 3.96, 50,  0., 2.)

    for m in massPoints:
        file = TFile.Open("HVT/scanHVT_M%s.root" % m, "READ")
        tree = file.Get("tree")
        for entry in range(tree.GetEntries()): # Fill mass points only if NOT excluded
            tree.GetEntry(entry)
            gH, gF = tree.gv*tree.ch, tree.g*tree.g*tree.cq/tree.gv
            XsBr = tree.CX0 * tree.BRbb * 1000. # in fb
            if XsBr < observed[m]: hxs[m].Fill(gH, gF)
            if tree.total_widthV0/float(m) < width: hw[m].Fill(gH, gF)

        
        for b in range(hxs[m].GetNbinsX()*hxs[m].GetNbinsY()):
            hxs[m].SetBinContent(b, 1. if hxs[m].GetBinContent(b)>0. else 0.)
            hw[m].SetBinContent(b, 1. if hw[m].GetBinContent(b)>0. else 0.)
        
        #hxs[m].Smooth(20)
        #hw[m].Smooth(20)
        
        gxs[m] = getCurve(hxs[m])
        for i, g in enumerate(gxs[m]):
            g.SetLineColor(massColors[m])
            g.SetFillColor(massColors[m])
            g.SetFillStyle(massFill[m]) #(3345 if i>1 else 3354)
            g.SetLineWidth(503*(1 if i<2 else -1))
            mg.Add(g)
        
        if m==3000:
            gw[m] = getCurve(hw[m])
            for i, g in enumerate(gw[m]):
                g.SetPoint(0, 0., g.GetY()[0])
                g.SetLineWidth(501*(1 if i<2 else -1))
                g.SetLineColor(920+2)
                g.SetFillColor(920+1)
                g.SetFillStyle(3003)
                mg.Add(g)
    
    if options.root:
        outFile = TFile("plotsLimit/Model.root", "RECREATE")
        outFile.cd()
        for m in massPoints:
            mg[m].Write("X_M%d" % m)
        mgW.Write("width")
        outFile.Close()
        print "Saved histogram in file plotsLimit/Model.root, exiting..."
        exit()
    
    
    ### plot ###
    
    c1 = TCanvas("c1", "HVT Exclusion Limits", 800, 600)
    c1.cd()
    c1.GetPad(0).SetTopMargin(0.06)
    c1.GetPad(0).SetRightMargin(0.05)
    c1.GetPad(0).SetTicks(1, 1)
    mg.Draw("AC")
    #mg.GetXaxis().SetTitle("g_{V} c_{H}")
    mg.GetXaxis().SetTitle("Higgs and vector boson coupling g_{H}")
    mg.GetXaxis().SetRangeUser(-3.,3.)
    mg.GetXaxis().SetLabelSize(0.045)
    mg.GetXaxis().SetTitleSize(0.045)
    mg.GetXaxis().SetTitleOffset(1.)
    #mg.GetYaxis().SetTitle("g^{2} c_{F} / g_{V}")
    mg.GetYaxis().SetTitle("Fermion coupling g_{F}")
    mg.GetYaxis().SetLabelSize(0.045)
    mg.GetYaxis().SetTitleSize(0.045)
    mg.GetYaxis().SetTitleOffset(1.)
    mg.GetYaxis().SetRangeUser(-1., 1.)
    mg.GetYaxis().SetNdivisions(505)
#    hxs[3500].Draw("CONTZ")
    
    drawCMS(LUMI, "", False) #Preliminary
#    drawAnalysis("XVH"+category, False)
#    latex = TLatex()
#    latex.SetNDC()
#    latex.SetTextFont(62)
#    latex.SetTextSize(0.06)
#    latex.DrawLatex(0.10, 0.925, "CMS")

    # model B
    g_model = {}
    for i, b in enumerate(benchmark):
        g_model[i] = TGraph(1)
        g_model[i].SetTitle(models_name[b])
        g_model[i].SetPoint(0, models_point[b][0], models_point[b][1])
        g_model[i].SetMarkerStyle(models_style[b])
        g_model[i].SetMarkerColor(models_color[b])
        g_model[i].SetMarkerSize(1.5)
        g_model[i].Draw("PSAME")
    
    # text
    latex = TLatex()
    latex.SetTextSize(0.045)
    latex.SetTextFont(42)
    latex.SetTextColor(630)
#    for b in benchmark: latex.DrawLatex(models_point[b][0]+0.02, models_point[b][1]+0.02, models_name[b])
    latex.SetTextColor(920+2)
    latex.DrawLatex(-2.8, -0.875, "#frac{#Gamma_{Z'}}{m_{Z'}} > %.0f%%" % (width*100, ))
    
    leg = TLegend(0.68, 0.60, 0.95, 0.94)
    leg.SetBorderSize(1)
    leg.SetFillStyle(1001)
    leg.SetFillColor(0)
    for m in massPoints:
        leg.AddEntry(gxs[m][0], "m_{Z'} = %.1f TeV" % (m/1000.), "fl")
    for i, b in enumerate(benchmark):
        leg.AddEntry(g_model[i], g_model[i].GetTitle(), "P")
    leg.SetY1(leg.GetY2()-leg.GetNRows()*0.050)
    leg.SetMargin(0.35)
    leg.Draw()
    
    gxs_ = gxs[massPoints[0]][0].Clone("gxs_")
    gxs_.SetLineColor(1)
#    gxs_.SetFillColor(1)
    
    latex.SetNDC()
    latex.SetTextColor(1)
    latex.SetTextSize(0.04)
    latex.SetTextFont(52)
    latex.DrawLatex(0.15, 0.95, "q#bar{q} #rightarrow Z' #rightarrow b#bar{b}")
    
    c1.Print("plots/model/HVT.png")
    c1.Print("plots/model/HVT.pdf")
    c1.Print("plots/model/HVT.root")
    c1.Print("plots/model/HVT.C")
    
    #g = 0.646879, cH = 0.976246, cF = 1.02433
    print "model B = [", 3*0.976246, ",", 0.646879*0.646879*1.02433/3, "]"
    
    if not gROOT.IsBatch(): raw_input("Press Enter to continue...")
Пример #9
0
def plot( sample, n, v, sel, hbins, hmin, hmax, hlog, xlabel, ylabel, dim ):

    #hlog=False;

    global output
    file = {}
    tree = {}
    hist = {}
    leaf = {}
    xsec = {}

    max = 0
    min = 1e99

    ROOT.gStyle.SetOptStat(1111)
    ROOT.gROOT.SetBatch(True)

    for i, s in enumerate(sample):
        file[s] = TFile( input + s + ".root", "READ")
        tree[s] = file[s].Get("Physics")
        if dim==1:
            hist[s] = TH1F(s, ";"+v, hbins, hmin , hmax)
            tree[s].Project(s, v, "%s"%sel)

            leaf[s] = tree[s].GetLeaf("xsec1")
            leaf[s].GetBranch().GetEntry(1)
            xsec[s] = leaf[s].GetValue()
            hist[s].SetLineColor(colour[i])
            
            hist[s].SetLineWidth(2)#3
            hist[s].SetFillColorAlpha(colour[i],0.35)
            hist[s].SetFillStyle(3005)

            if hist[s].GetMaximum() > max: max = hist[s].GetMaximum()*6
	    if hist[s].GetMinimum() < min: min = hist[s].GetMinimum()

            #leg = TLegend(0.4, 0.9-0.035*len(sample), 0.68, 0.89)

            c1 = TCanvas("c1", "Gen", 1600, 1200)
            c1.cd()
            
            hist[sample[0]].SetMaximum(max*1.2)
            hist[sample[0]].SetMinimum(min+1.e6)

            hist[sample[0]].GetXaxis().SetTitle("%s" %xlabel)
            hist[sample[0]].GetYaxis().SetTitle("%s" %ylabel)
            hist[sample[0]].SetTitle("%s" %n)

            if len(sample)>1:
                for i, s in enumerate(sample):
                    hist[s].Draw("HIST" if i==0 else "HIST, SAME")
            else:
                hist[s].Draw("HIST")
                
            if hlog:
                c1.GetPad(0).SetLogy()
                
        elif dim==2:
            if len(hbins)!=2 or len(hmin)!=2 or len(hmax)!=2:
                print "dimension of hbins, hmin, hmax does not correspond to\
                2 dimensional histogram parameters."; exit;
            else:
                #X axis parameters follow by Y axis parameters
                hist[s] = TH2F( s, ";"+v, hbins[0], hmin[0] , hmax[0], hbins[1], hmin[1] , hmax[1] )
                # v in the form of x:y
                tree[s].Project(s, v, "%s"%sel,"colz")

                c1 = TCanvas("c1", "Gen", 1600, 1200)
                c1.cd()

                hist[s].Draw("COLZ")
                #if hlog:
                #    c1.GetPad(0).SetLogy()
                #    c1.GetPad(0).SetLogx()
        else:
            print "Unkown dimension"
            exit;

        #leg.Draw()
        c1.Update()

        drawlabel( 0.37 , 0.934 , "CMS Simulation" )

        output+="VH/"+sample[0]+"/"
        if not hlog:
            output+="Lin/"
        elif hlog:
            output+="Log/"
        
        if not os.path.exists(output):
            os.makedirs(output)

        c1.Print( output + n + ".pdf")
        c1.Print( output + n + ".png")
Пример #10
0
def pullsVertical(fileName):
    
    content = filterPullFile(fileName)
    nbins, off = len(content), 0.10
    
    b_pulls = TH1F("b_pulls", ";;Pulls", nbins, 0.-off, nbins-off)
    s_pulls = TH1F("s_pulls", ";;Pulls", nbins, 0.+off, nbins+off) #

    for i, s in enumerate(content):
        l = s.split()
        b_pulls.GetXaxis().SetBinLabel(i+1, l[0])
        s_pulls.GetXaxis().SetBinLabel(i+1, l[0])
        b_pulls.SetBinContent(i+1, float(l[1]))
        b_pulls.SetBinError(i+1, float(l[2]))
        s_pulls.SetBinContent(i+1, float(l[3]))
        s_pulls.SetBinError(i+1, float(l[4]))
    
    b_pulls.SetFillStyle(3005)
    b_pulls.SetFillColor(923)
    b_pulls.SetLineColor(923)
    b_pulls.SetLineWidth(1)
    b_pulls.SetMarkerStyle(20)
    b_pulls.SetMarkerSize(1.25)
    
    s_pulls.SetLineColor(602)
    s_pulls.SetMarkerColor(602)
    s_pulls.SetMarkerStyle(24) #24
    s_pulls.SetLineWidth(1)
    
    b_pulls.GetYaxis().SetRangeUser(-2.5, 2.5)
    
    # Graphs
    h_pulls = TH2F("pulls", "", 6, -3., 3., nbins, 0, nbins)
    B_pulls = TGraphAsymmErrors(nbins)
    S_pulls = TGraphAsymmErrors(nbins)
    
    boxes = []
    
    canvas = TCanvas("canvas", "Pulls", 600, 150+nbins*10)#nbins*20)
    canvas.cd()
    canvas.SetGrid(0, 1)
    canvas.GetPad(0).SetTopMargin(0.01)
    canvas.GetPad(0).SetRightMargin(0.01)
    canvas.GetPad(0).SetBottomMargin(0.05)
    canvas.GetPad(0).SetLeftMargin(0.25)#(0.25)#(0.065)
    canvas.GetPad(0).SetTicks(1, 1)
    
    for i, s in enumerate(content):
        l = s.split()
        if "1034h" in l[0]: l[0]="CMS_PDF_13TeV"
        h_pulls.GetYaxis().SetBinLabel(i+1, l[0].replace('CMS2016_', ''))#C
        #y1 = gStyle.GetPadBottomMargin()
        #y2 = 1. - gStyle.GetPadTopMargin()
        #h = (y2 - y1) / float(nbins)
        #y1 = y1 + float(i) * h
        #y2 = y1 + h
        #box = TPaveText(0, y1, 1, y2, 'NDC')
        #box.SetFillColor(0)
        #box.SetTextSize(0.02)
        #box.SetBorderSize(0)
        #box.SetTextAlign(12)
        #box.SetMargin(0.005)
        #if i % 2 == 0:
        #    box.SetFillColor(18)
        #box.Draw()
        #boxes.append(box)
        B_pulls.SetPoint(i+1,float(l[1]),float(i+1)-0.3)#C
        B_pulls.SetPointError(i+1,float(l[2]),float(l[2]),0.,0.)#C
    
    for i, s in enumerate(content):
        l = s.split()
        S_pulls.SetPoint(i+1,float(l[3]),float(i+1)-0.7)#C
        S_pulls.SetPointError(i+1,float(l[4]),float(l[4]),0.,0.)#C
    
    h_pulls.GetXaxis().SetTitle("(#hat{#theta} - #theta_{0}) / #Delta#theta")
    h_pulls.GetXaxis().SetLabelOffset(-0.01)
    h_pulls.GetXaxis().SetTitleOffset(.6)
    h_pulls.GetYaxis().SetNdivisions(nbins, 0, 0)
    
    B_pulls.SetFillColor(1)
    B_pulls.SetLineColor(1)
    B_pulls.SetLineStyle(1)
    B_pulls.SetLineWidth(2)
    B_pulls.SetMarkerColor(1)
    B_pulls.SetMarkerStyle(20)
    B_pulls.SetMarkerSize(1)#(0.75)
    
    S_pulls.SetFillColor(629)
    S_pulls.SetLineColor(629)
    S_pulls.SetMarkerColor(629)
    S_pulls.SetLineWidth(2)
    S_pulls.SetMarkerStyle(20)
    S_pulls.SetMarkerSize(1)
    
    box1 = TBox(-1., 0., 1., nbins)
    box1.SetFillStyle(3001)
    #box1.SetFillStyle(0)
    box1.SetFillColor(417)
    box1.SetLineWidth(2)
    box1.SetLineStyle(2)
    box1.SetLineColor(417)
    
    box2 = TBox(-2., 0., 2., nbins)
    box2.SetFillStyle(3001)
    #box2.SetFillStyle(0)
    box2.SetFillColor(800)
    box2.SetLineWidth(2)
    box2.SetLineStyle(2)
    box2.SetLineColor(800)
    
    leg = TLegend(0.1, -0.05, 0.7, 0.08)
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)
    leg.SetFillColor(0)
    leg.SetNColumns(2)
    leg.AddEntry(B_pulls,  "B-only fit", "lp")
    leg.AddEntry(S_pulls,  "S+B fit", "lp")
    if text: leg.AddEntry(0, text, "")
    
    h_pulls.Draw("")
    box2.Draw()
    box1.Draw()
    B_pulls.Draw("P6SAME")
    S_pulls.Draw("P6SAME")
    leg.Draw()
    
#    drawCMS(35867, "Preliminary")
#    drawAnalysis("VH")
#    drawRegion(outName)
    
    canvas.Print(outName+".png")
    canvas.Print(outName+".pdf")

    if not gROOT.IsBatch(): raw_input("Press Enter to continue...")
Пример #11
0
def pullsVertical_noBonly(fileName):
    
    content = filterPullFile(fileName)
    nbins, off = len(content), 0.10
    
    # Graphs
    h_pulls = TH2F("pulls", "", 6, -3., 3., nbins, 0, nbins)
    S_pulls = TGraphAsymmErrors(nbins)
    
    boxes = []
    
    canvas = TCanvas("canvas", "Pulls", 720, 300+nbins*18)#nbins*20)
    canvas.cd()
    canvas.SetGrid(0, 1)
    canvas.SetTopMargin(0.01)
    canvas.SetRightMargin(0.01)
    canvas.SetBottomMargin(0.10)
    canvas.SetLeftMargin(0.40)
    canvas.SetTicks(1, 1)
    
    for i, s in enumerate(content):
        l = s.split()
        h_pulls.GetYaxis().SetBinLabel(i+1, l[0])
        S_pulls.SetPoint(i,float(l[3]),float(i+1)-0.5)
        S_pulls.SetPointError(i,float(l[4]),float(l[4]),0.,0.)
    
    h_pulls.GetXaxis().SetTitle("(#hat{#theta} - #theta_{0}) / #Delta#theta")
    h_pulls.GetXaxis().SetLabelOffset(0.0)
    h_pulls.GetXaxis().SetTitleOffset(0.8)
    h_pulls.GetXaxis().SetLabelSize(0.045)
    h_pulls.GetXaxis().SetTitleSize(0.050)
    h_pulls.GetYaxis().SetLabelSize(0.046)
    h_pulls.GetYaxis().SetNdivisions(nbins, 0, 0)
    
    S_pulls.SetFillColor(kBlack)
    S_pulls.SetLineColor(kBlack)
    S_pulls.SetMarkerColor(kBlack)
    S_pulls.SetLineWidth(2)
    S_pulls.SetMarkerStyle(20)
    S_pulls.SetMarkerSize(1)
    
    box1 = TBox(-1., 0., 1., nbins)
    #box1.SetFillStyle(3001) # 3001 checkered
    #box1.SetFillStyle(0)
    box1.SetFillColor(kGreen+1) # 417
    box1.SetLineWidth(2)
    box1.SetLineStyle(2)
    box1.SetLineColor(kGreen+1) # 417
    
    box2 = TBox(-2., 0., 2., nbins)
    #box2.SetFillStyle(3001) # 3001 checkered
    #box2.SetFillStyle(0)
    box2.SetFillColor(kOrange) # 800
    box2.SetLineWidth(2)
    box2.SetLineStyle(2)
    box2.SetLineColor(kOrange) # 800
    
    leg = TLegend(0.01, 0.01, 0.3, 0.15)
    leg.SetTextSize(0.05)
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)
    leg.SetFillColor(0)
    #leg.SetNColumns(2)
    leg.AddEntry(S_pulls, "S+B fit", "lp")
    if text: leg.AddEntry(0, text, "")
    
    h_pulls.Draw("")
    box2.Draw()
    box1.Draw()
    S_pulls.Draw("P6SAME")
    leg.Draw()
    canvas.RedrawAxis()
    
    canvas.Print(outName+".png")
    canvas.Print(outName+".pdf")
    
    if not gROOT.IsBatch(): raw_input("Press Enter to continue...")
Пример #12
0
def dqm_getSingleHist_json(server, run, dataset, hist, rootContent=False):
    postfix = "?rootcontent=1" if rootContent else ""
    datareq = urllib2.Request(('%s/jsonfairy/archive/%s/%s/%s%s') %
                              (server, run, dataset, hist, postfix))
    datareq.add_header('User-agent', ident)
    # Get data
    data = eval(
        re.sub(r"\bnan\b", "0",
               urllib2.build_opener(X509CertOpen()).open(datareq).read()),
        {"__builtins__": None}, {})
    histo = data['hist']
    # Now convert into real ROOT histogram object
    if 'TH1' in histo['type']:
        # The following assumes a TH1F object
        contents = histo['bins']['content']
        nbins = len(contents)
        xmin = histo['xaxis']['first']['value']
        xmax = histo['xaxis']['last']['value']
        roothist = TH1F(histo['stats']['name'], histo['title'], nbins, xmin,
                        xmax)
        for xx in range(1, nbins + 1):
            roothist.SetBinContent(xx, contents[xx - 1])
            roothist.SetBinError(xx, histo['bins']['error'][xx - 1])
        roothist.SetEntries(histo['stats']['entries'])
        stats = array('d')
        stats.append(histo['stats']['entries'])
        stats.append(histo['stats']['entries'])
        stats.append(histo['stats']['entries'] *
                     histo['stats']['mean']['X']['value'])
        stats.append(
            (histo['stats']['rms']['X']['value'] *
             histo['stats']['rms']['X']['value'] +
             histo['stats']['mean']['X']['value'] *
             histo['stats']['mean']['X']['value']) * histo['stats']['entries'])
        roothist.PutStats(stats)
    elif (histo['type'] == 'TProfile'):
        contents = histo['bins']['content']
        nbins = len(contents)
        xmin = histo['xaxis']['first']['value']
        xmax = histo['xaxis']['last']['value']
        roothist = TProfile(histo['stats']['name'], histo['title'], nbins,
                            xmin, xmax)
        roothist.SetErrorOption("g")
        for xx in range(0, nbins):
            if (histo['bins']['error'][xx] != 0):
                ww = 1. / (histo['bins']['error'][xx] *
                           histo['bins']['error'][xx])
            else:
                ww = 0.
            roothist.Fill(
                xmin + (2 * xx + 1) * ((xmax - xmin) / (nbins * 2.0)),
                contents[xx], ww)


#            roothist.SetBinContent(xx, contents[xx-1])
#            roothist.SetBinError(xx, histo['bins']['error'][xx-1])
        roothist.SetEntries(histo['stats']['entries'])
        stats = array('d')
        for i in range(0, 6):
            stats.append(i)
        roothist.GetStats(stats)
        stats[0] = (histo['stats']['entries'])
        stats[1] = (histo['stats']['entries'])
        stats[2] = (histo['stats']['entries'] *
                    histo['stats']['mean']['X']['value'])
        stats[3] = ((histo['stats']['rms']['X']['value'] *
                     histo['stats']['rms']['X']['value'] +
                     histo['stats']['mean']['X']['value'] *
                     histo['stats']['mean']['X']['value']) *
                    histo['stats']['entries'])
        roothist.PutStats(stats)
    elif 'TH2' in histo['type']:
        contents = histo['bins']['content']
        nbinsx = histo['xaxis']['last']['id']
        xmin = histo['xaxis']['first']['value']
        xmax = histo['xaxis']['last']['value']
        nbinsy = histo['yaxis']['last']['id']
        ymin = histo['yaxis']['first']['value']
        ymax = histo['yaxis']['last']['value']
        roothist = TH2F(histo['stats']['name'], histo['title'], nbinsx, xmin,
                        xmax, nbinsy, ymin, ymax)
        for xx in range(1, nbinsx + 1):
            for yy in range(1, nbinsy + 1):
                roothist.SetBinContent(xx, yy, contents[yy - 1][xx - 1])
        roothist.SetEntries(histo['stats']['entries'])
        stats = array('d')
        stats.append(histo['stats']['entries'])
        stats.append(histo['stats']['entries'])
        stats.append(histo['stats']['entries'] *
                     histo['stats']['mean']['X']['value'])
        stats.append(
            (histo['stats']['rms']['X']['value'] *
             histo['stats']['rms']['X']['value'] +
             histo['stats']['mean']['X']['value'] *
             histo['stats']['mean']['X']['value']) * histo['stats']['entries'])
        stats.append(histo['stats']['entries'] *
                     histo['stats']['mean']['Y']['value'])
        stats.append(
            (histo['stats']['rms']['Y']['value'] *
             histo['stats']['rms']['Y']['value'] +
             histo['stats']['mean']['Y']['value'] *
             histo['stats']['mean']['Y']['value']) * histo['stats']['entries'])
        roothist.PutStats(stats)

    elif (histo['type'] == 'TProfile2D'):
        contents = histo['bins']['content']
        nbinsx = histo['xaxis']['last']['id']
        xmin = histo['xaxis']['first']['value']
        xmax = histo['xaxis']['last']['value']
        nbinsy = histo['yaxis']['last']['id']
        ymin = histo['yaxis']['first']['value']
        ymax = histo['yaxis']['last']['value']
        roothist = TProfile2D(histo['stats']['name'], histo['title'], nbinsx,
                              xmin, xmax, nbinsy, ymin, ymax)
        for xx in range(0, nbinsx):
            for yy in range(0, nbinsy):
                roothist.Fill(
                    xmin + (2 * xx + 1) * ((xmax - xmin) / (nbinsx * 2.0)),
                    ymin + (2 * yy + 1) * ((ymax - ymin) / (nbinsy * 2.0)), 0,
                    1)
        for xx in range(1, nbinsx + 1):
            for yy in range(1, nbinsy + 1):
                roothist.SetBinContent(xx, yy, contents[yy - 1][xx - 1])
                roothist.SetEntries(histo['stats']['entries'])

    return roothist
Пример #13
0
def main():
    #############################################################################################
    # Options #
    #############################################################################################
    parser = argparse.ArgumentParser(
        description=
        'From given set of root files, make different histograms in a root file'
    )
    parser.add_argument('-m',
                        '--model',
                        action='store',
                        required=True,
                        type=str,
                        default='',
                        help='NN model to be used')
    parser.add_argument('-f',
                        '--file',
                        action='store',
                        required=False,
                        type=str,
                        default='',
                        help='File (full path) to be used')
    parser.add_argument('--mA',
                        action='store',
                        required=False,
                        type=int,
                        default=0,
                        help='Print as PDf only some of the mass config')
    parser.add_argument('--mH',
                        action='store',
                        required=False,
                        type=int,
                        default=0,
                        help='Print as PDf only some of the mass config')
    parser.add_argument('-n',
                        '--number',
                        action='store',
                        required=False,
                        type=int,
                        default=0,
                        help='Number of events to build the likelihood map')
    parser.add_argument('--xmax',
                        action='store',
                        required=False,
                        type=float,
                        default=1500,
                        help='Maximum values for mA in the graph')
    parser.add_argument('--ymax',
                        action='store',
                        required=False,
                        type=float,
                        default=1500,
                        help='Maximum values for mH in the graph')
    parser.add_argument('--xmin',
                        action='store',
                        required=False,
                        type=float,
                        default=0,
                        help='Minimum values for mA in the graph')
    parser.add_argument('--ymin',
                        action='store',
                        required=False,
                        type=float,
                        default=0,
                        help='Minimum values for mH in the graph')
    parser.add_argument('--zmin',
                        action='store',
                        required=False,
                        type=float,
                        default=0,
                        help='Minimum values for z axis in the graph')
    parser.add_argument('--zmax',
                        action='store',
                        required=False,
                        type=float,
                        default=None,
                        help='Maximum values for z axis in the graph')
    parser.add_argument('--bins',
                        action='store',
                        required=False,
                        type=int,
                        default=100,
                        help='Bins in both the graph axes')
    parser.add_argument(
        '--suffix',
        action='store',
        required=False,
        type=str,
        default='',
        help=
        'Suffix to be added to output name (likelihood_suffix.pdf/.root), default to empty string'
    )
    parser.add_argument('--PDF',
                        action='store_true',
                        required=False,
                        default=False,
                        help='Produce PDF from the root file')
    parser.add_argument(
        '--profile',
        action='store_true',
        required=False,
        default=False,
        help='Whether to make the profile likelihood starting from the TGraph2D'
    )
    parser.add_argument('--zoom',
                        action='store_true',
                        required=False,
                        default=False,
                        help='Zoom the TGraph2D according to given boundaries')
    parser.add_argument(
        '--norm',
        action='store_true',
        required=False,
        default=False,
        help='Use the normalization by the visible cross section')
    parser.add_argument('-v',
                        '--verbose',
                        action='store_true',
                        required=False,
                        default=False,
                        help='Show DEGUG logging')
    opt = parser.parse_args()

    # Logging #
    if opt.verbose:
        logging.basicConfig(level=logging.DEBUG,
                            format='%(asctime)s - %(levelname)s - %(message)s')
    else:
        logging.basicConfig(level=logging.INFO,
                            format='%(asctime)s - %(levelname)s - %(message)s')
    #############################################################################################
    # Get objects in TFile #
    #############################################################################################
    def getall(d, basepath="/"):
        "Generator function to recurse into a ROOT file/dir and yield (path, obj) pairs"
        for key in d.GetListOfKeys():
            kname = key.GetName()
            if key.IsFolder():
                for i in getall(d.Get(kname), basepath + kname + '/'):
                    yield i
            else:
                yield basepath + kname, d.Get(kname)

    #############################################################################################
    # Profile Likelihood #
    #############################################################################################
    if opt.profile:
        # Path to graph #
        path_root = os.path.abspath(
            os.path.join('PDF', opt.model,
                         'likelihood_' + opt.suffix + '.root'))
        path_out = os.path.abspath(os.path.join('PDF', opt.model))
        # Load TGraph2D #
        f = TFile(path_root)
        graphs = [(key, obj) for (key, obj) in getall(f)]
        for key, obj in graphs:
            if key.find('HToZA') == -1:
                continue
            mH_value = int(re.findall(r'\d+', key)[2])
            mA_value = int(re.findall(r'\d+', key)[3])

            if mH_value != opt.mH or mA_value != opt.mA:
                continue

            MakeProfile(graph=obj,
                        mH=mH_value,
                        mA=mA_value,
                        N=10000,
                        path=path_out,
                        step=5,
                        slices=10)
        sys.exit(0)

    #############################################################################################
    # Make PDF #
    #############################################################################################
    def ZoomHist(graph, bins, xmin, xmax, ymin, ymax):
        x = np.linspace(xmin, xmax, bins)
        y = np.linspace(ymin, ymax, bins)
        X, Y = np.meshgrid(x, y)
        X = X.ravel()
        Y = Y.ravel()
        valid = np.logical_and(np.greater_equal(Y, X),
                               np.greater_equal(Y, 125))
        X = X[valid]
        Y = Y[valid]
        N = X.shape[0]
        new_graph = TGraph2D(N)
        manager = enlighten.get_manager()
        pbar = manager.counter(total=N, desc='Progress', unit='Point')
        for i in range(N):
            content = graph.Interpolate(X[i], Y[i])
            if content != 0 or Y[i] > 125:
                new_graph.SetPoint(i, X[i], Y[i], content)
            pbar.update()
        new_graph.SetTitle(graph.GetTitle())
        return copy.deepcopy(new_graph)

    if opt.PDF or opt.zoom:
        path_root = os.path.abspath(
            os.path.join('PDF', opt.model,
                         'likelihood_' + opt.suffix + '.root'))
        path_pdf = os.path.abspath(
            os.path.join('PDF', opt.model,
                         'likelihood_' + opt.suffix + '.pdf'))
        path_zoom = os.path.abspath(
            os.path.join('PDF', opt.model,
                         'likelihood_' + opt.suffix + '_zoom.root'))
        f = TFile(path_root)
        if opt.PDF:
            c1 = TCanvas('c1', 'c1', 1100, 900)
            c1.SetGrid()
            #canvas = TCanvas('canvas','canvas',900,900)
            #canvas.Print(path_pdf+'[')
            c1.Print(path_pdf + '[')
            c1.SetTopMargin(0.05)
            c1.SetBottomMargin(0.18)
            c1.SetLeftMargin(0.18)
            c1.SetRightMargin(0.2)
        graphs = [(key, obj) for (key, obj) in getall(f)]
        graphs = sorted(graphs,
                        key=lambda tup: tup[0])  # Sort according to name
        for i, (key, obj) in enumerate(graphs):
            mH_value = 0
            mA_value = 0
            if key.find('DY') != -1:
                title = 'DY'
            elif key.find('TT') != -1:
                title = 'TT'
            else:
                mH_value = int(re.findall(r'\d+', key)[2])
                mA_value = int(re.findall(r'\d+', key)[3])
                title = 'HToZATo2L2B_mH_%d_mA_%d' % (mH_value, mA_value)

            if (mH_value != opt.mH
                    or mA_value != opt.mA) and opt.mA != 0 and opt.mH != 0:
                continue
            logging.info('Processing %s' % key)
            try:
                if opt.zoom:
                    new_graph = ZoomHist(obj, opt.bins, opt.xmin, opt.xmax,
                                         opt.ymin, opt.ymax)
                    if os.path.exists(path_zoom):
                        root_file = TFile(path_zoom, "update")
                        new_graph.Write(title, TObject.kOverwrite)
                        logging.info("Zoomed Graph saved in %s" % path_zoom)
                    else:
                        root_file = TFile(path_zoom, "recreate")
                        new_graph.Write(title)
                        logging.info("Zoomed Graph replaced in %s" % path_zoom)

                if opt.PDF:
                    base_hist = TH2F('', '', opt.bins, opt.xmin, opt.xmax,
                                     opt.bins, opt.ymin, opt.ymax)
                    obj.SetHistogram(base_hist)
                    hist = obj.GetHistogram()
                    hist.SetContour(1000)
                    hist.GetXaxis().SetRangeUser(opt.xmin, opt.xmax)
                    hist.GetYaxis().SetRangeUser(opt.ymin, opt.ymax)
                    hist.SetMinimum(max(opt.zmin, hist.GetMinimum()))
                    amax = hist.GetMaximum() if opt.zmax is None else opt.zmax
                    hist.SetMaximum(amax)
                    hist.SetTitle(";M_{A} [GeV];M_{H} [GeV];-2 log L")
                    hist.GetXaxis().SetTitleOffset(1.2)
                    hist.GetYaxis().SetTitleOffset(1.2)
                    hist.GetZaxis().SetTitleOffset(1.2)
                    hist.GetXaxis().SetLabelSize(0.04)
                    hist.GetYaxis().SetLabelSize(0.04)
                    hist.GetZaxis().SetLabelSize(0.04)
                    hist.GetXaxis().SetTitleSize(0.06)
                    hist.GetYaxis().SetTitleSize(0.06)
                    hist.GetZaxis().SetTitleSize(0.06)
                    hist.Draw('colz')
                    text = TPaveText(.55, .2, .80, .4, 'brNDC')
                    text.AddText("Events with")
                    text.AddText("M_{A} = %d GeV" % mA_value)
                    text.AddText("M_{H} = %d GeV" % mH_value)
                    text.SetTextColor(1)
                    text.SetFillStyle(4100)
                    text.Draw("same")

                    #hist.SetTitle(obj.GetTitle())
                    c1.Print(
                        path_pdf,
                        'Title:' + key.replace('.root', '').replace('/', ''))
            except Exception as e:
                logging.critical('Could not save %s due to error "%s"' %
                                 (key, e))
        if opt.PDF:
            #            canvas.Print(path_pdf)
            #            canvas.Print(path_pdf+']')
            logging.info('PDF saved as %s' % path_pdf)
            c1.Print(path_pdf + ']')

        sys.exit()
    #############################################################################################
    # Make likelihood map #
    #############################################################################################
    # Get events from tree #
    logging.info('Looking at file %s' % opt.file)
    variables = [
        'lep1_p4.Pt()',
        'lep1_p4.Eta()',
        'lep2_p4.Pt()',
        'lep2_p4.Eta()',
        'lep2_p4.Phi()-lep1_p4.Phi()',
        'jet1_p4.Pt()',
        'jet1_p4.Eta()',
        'jet1_p4.Phi()-lep1_p4.Phi()',
        'jet2_p4.Pt()',
        'jet2_p4.Eta()',
        'jet2_p4.Phi()-lep1_p4.Phi()',
        'met_pt',
        'met_phi-lep1_p4.Phi()',
    ]

    events = Tree2Pandas(input_file=opt.file,
                         variables=variables,
                         n=opt.number).values
    if events.shape[0] == 0:
        raise RuntimeError("Did you forget -n ?")

    # Instantiate the map #
    likelihood = LikelihoodMap(name=opt.model,
                               xmin=opt.xmin,
                               ymin=opt.ymin,
                               xmax=opt.xmax,
                               ymax=opt.ymax,
                               N=300,
                               normalize=opt.norm)

    # Loop over events #
    logging.info('Adding events')
    manager = enlighten.get_manager()
    pbar = manager.counter(total=opt.number, desc='Progress', unit='Event')
    for i in range(events.shape[0]):
        likelihood.AddEvent(events[i, :])
        pbar.update()
    manager.stop()

    # Make and print map #
    likelihood.MakeGraph(title=os.path.basename(opt.file), suffix=opt.suffix)
Пример #14
0
def create2DPlots(detector, plot, plotnum, plotmat, dosingledetector=True):
    """Produce the requested plot for the specified detector.

       Function that will plot the requested 2D-@plot for the
       specified @detector. The specified detector could either be a
       real detector or a compound one. The list of available plots
       are the keys of plots dictionary imported from plot_utils.
    """

    #gStyle.Reset()
    #Better to use an underscore.
    plotmat = plotmat.replace(" ", "_")

    if plotmat != "":
        theDirname = ('Images/%s' % plotmat).replace(" ", "")
    else:
        theDirname = 'Images'

    if not checkFile_(theDirname):
        os.mkdir(theDirname)
    if not os.path.isdir(('Images/%s/ZPlusZoom' % plotmat).replace(" ", "")):
        os.mkdir(('Images/%s/ZPlusZoom' % plotmat).replace(" ", ""))
    if not os.path.isdir(('Images/%s/ZMinusZoom' % plotmat).replace(" ", "")):
        os.mkdir(('Images/%s/ZMinusZoom' % plotmat).replace(" ", ""))

    goodToGo, theDetectorFilename = paramsGood_(detector, plot)
    if not goodToGo:
        return

    theDetectorFile = TFile(theDetectorFilename)

    prof2d_X0_det_total = TProfile2D()
    prof2d_X0_det_total.Reset()

    # get TProfiles
    #prof2d_X0_det_total = theDetectorFile.Get('%s' % plots[plot].plotNumber)
    prof2d_X0_det_total = theDetectorFile.Get('%s' % plotnum)
    print("==================================================================")
    print(plotnum)

    # histos
    prof2d_X0_det_total.__class__ = TProfile2D
    hist_X0_total = prof2d_X0_det_total.ProjectionXY()

    # keep files live forever
    files = []
    if detector in COMPOUNDS.keys() and not dosingledetector:
        #When the loop was:
        #for subDetector in COMPOUNDS[detector][1:]:
        #and the detector was single it never went in the loop and read the single file
        #from above. I alter this to COMPOUNDS[detector] to do the multi material budget plot.
        #This won't effect the single detector due to the alter in the if above
        for subDetector in COMPOUNDS[detector]:
            # filenames of single components
            subDetectorFilename = "matbdg_%s.root" % subDetector

            # open file
            if not checkFile_(subDetectorFilename):
                print("Error, missing file %s" % subDetectorFilename)
                continue

            subDetectorFile = TFile(subDetectorFilename)
            files.append(subDetectorFile)
            print("*** Open file... %s" % subDetectorFilename)

            # subdetector profiles
            prof2d_X0_det_total = subDetectorFile.Get('%s' %
                                                      plots[plot].plotNumber)
            prof2d_X0_det_total.__class__ = TProfile2D

            # add to summary histogram
            hist_X0_total.Add(
                prof2d_X0_det_total.ProjectionXY(
                    "B_%s" % prof2d_X0_det_total.GetName()), +1.000)

    # # properties
    #gStyle.SetPalette(1)
    gStyle.SetStripDecimals(False)
    # #

    # Create "null" histo
    minX = 1.03 * prof2d_X0_det_total.GetXaxis().GetXmin()
    maxX = 1.03 * prof2d_X0_det_total.GetXaxis().GetXmax()
    minY = 1.03 * prof2d_X0_det_total.GetYaxis().GetXmin()
    maxY = 1.03 * prof2d_X0_det_total.GetYaxis().GetXmax()

    frame = TH2F("frame", "", 10, minX, maxX, 10, minY, maxY)
    frame.SetMinimum(0.1)
    frame.SetMaximum(10.)
    frame.GetXaxis().SetTickLength(frame.GetXaxis().GetTickLength() * 0.50)
    frame.GetYaxis().SetTickLength(frame.GetXaxis().GetTickLength() / 4.)

    # Ratio
    if plots[plot].iRebin:
        prof2d_X0_det_total.Rebin2D()

    # stack
    hist2dTitle = ('%s %s;%s;%s;%s' %
                   (plots[plot].quotaName, detector, plots[plot].abscissa,
                    plots[plot].ordinate, plots[plot].quotaName))

    if dosingledetector:
        hist2d_X0_total = prof2d_X0_det_total
    else:
        hist2d_X0_total = hist_X0_total
    hist2d_X0_total.SetTitle(hist2dTitle)
    frame.SetTitle(hist2dTitle)
    frame.SetTitleOffset(0.5, "Y")

    #If here you put different histomin,histomaxin plot_utils you won't see anything
    #for the material plots.
    if plots[plot].histoMin != -1.:
        hist2d_X0_total.SetMinimum(plots[plot].histoMin)
    if plots[plot].histoMax != -1.:
        hist2d_X0_total.SetMaximum(plots[plot].histoMax)

    #
    can2name = "MBCan_2D_%s_%s_%s" % (detector, plot, plotmat)
    can2 = TCanvas(can2name, can2name, 2480 + 248, 580 + 58 + 58)
    can2.SetTopMargin(0.1)
    can2.SetBottomMargin(0.1)
    can2.SetLeftMargin(0.04)
    can2.SetRightMargin(0.06)
    can2.SetFillColor(kWhite)
    gStyle.SetOptStat(0)
    gStyle.SetTitleFillColor(0)
    gStyle.SetTitleBorderSize(0)

    #hist2d_X0_total.SetMaximum(hist2d_X0_total.GetMaximum())
    # Color palette
    # gStyle.SetPalette()#1
    acustompalette()
    ex1 = TExec("ex1", "acustompalette();")
    ex1.Draw()

    #for i in range(100): MyPaletteArray.append(i+1)

    #gStyle.SetPalette(first_color_number);

    # Log?
    can2.SetLogz(plots[plot].zLog)

    # Draw in colors
    #frame.Draw()
    #hist2d_X0_total.Draw("COLZsame") #Dummy draw to create the palette object
    hist2d_X0_total.Draw("COLZ")  #Dummy draw to create the palette object

    # Store
    can2.Update()

    #Aesthetic
    palette = hist2d_X0_total.GetListOfFunctions().FindObject("palette")
    if palette:
        palette.__class__ = TPaletteAxis
        palette.SetX1NDC(0.945)
        palette.SetX2NDC(0.96)
        palette.SetY1NDC(0.1)
        palette.SetY2NDC(0.9)
        palette.GetAxis().SetTickSize(.01)
        palette.GetAxis().SetTitle("")
        if plots[plot].zLog:
            palette.GetAxis().SetLabelOffset(-0.01)
    paletteTitle = TLatex(1.12 * maxX, maxY, plots[plot].quotaName)
    paletteTitle.SetTextAngle(90.)
    paletteTitle.SetTextSize(0.05)
    paletteTitle.SetTextAlign(31)
    paletteTitle.Draw()
    hist2d_X0_total.GetYaxis().SetTickLength(
        hist2d_X0_total.GetXaxis().GetTickLength() / 4.)
    hist2d_X0_total.GetYaxis().SetTickLength(
        hist2d_X0_total.GetXaxis().GetTickLength() / 4.)
    hist2d_X0_total.SetTitleOffset(0.5, "Y")
    hist2d_X0_total.GetYaxis().SetTitleOffset(0.45)
    #hist2d_X0_total.GetXaxis().SetTitleOffset(1.15);
    #hist2d_X0_total.GetXaxis().SetNoExponent(True)
    #hist2d_X0_total.GetYaxis().SetNoExponent(True)

    #Add eta labels
    keep_alive = []
    if plots[plot].iDrawEta:
        keep_alive.extend(drawEtaValues())

    can2.Modified()
    hist2d_X0_total.SetContour(255)

    # Store
    can2.Update()
    can2.Modified()

    can2.SaveAs("%s/%s_%s%s.pdf" % (theDirname, detector, plot, plotmat))
    can2.SaveAs("%s/%s_%s%s.png" % (theDirname, detector, plot, plotmat))
    #can2.SaveAs( "%s/%s_%s%s.root" % (theDirname, detector, plot, plotmat))

    #Zoom in a little bit
    if plot == "x_vs_z_vs_Rsum" or plot == "l_vs_z_vs_Rsum" or plot == "x_vs_z_vs_Rsumcos" or plot == "l_vs_z_vs_Rsumcos" or plot == "x_vs_z_vs_Rloc" or plot == "l_vs_z_vs_Rloc" or plot == "x_vs_z_vs_Rloccos" or plot == "l_vs_z_vs_Rloccos":
        #Z+
        #hist2d_X0_total.GetXaxis().SetLimits( 3100., 5200.)
        if dosingledetector:
            hist2d_X0_total.GetXaxis().SetRangeUser(3100., 5400.)
        else:
            hist2d_X0_total.GetXaxis().SetRangeUser(0., 7000.)
        #Do not draw eta values in the zoom case
        keep_alive = []
        #hist2d_X0_total.Draw("COLZ")
        can2.Update()
        can2.Modified()
        can2.SaveAs("%s/%s/%s_%s%s_ZplusZoom.pdf" %
                    (theDirname, "ZPlusZoom", detector, plot, plotmat))
        can2.SaveAs("%s/%s/%s_%s%s_ZplusZoom.png" %
                    (theDirname, "ZPlusZoom", detector, plot, plotmat))
        #Z-
        #hist2d_X0_total.GetXaxis().SetLimits( 3100., 5200.)
        if dosingledetector:
            hist2d_X0_total.GetXaxis().SetRangeUser(-5400., -3100.)
        else:
            hist2d_X0_total.GetXaxis().SetRangeUser(0., -7000.)
        #Do not draw eta values in the zoom case
        keep_alive = []
        #hist2d_X0_total.Draw("COLZ")
        can2.Update()
        can2.Modified()
        can2.SaveAs("%s/%s/%s_%s%s_ZminusZoom.pdf" %
                    (theDirname, "ZMinusZoom", detector, plot, plotmat))
        can2.SaveAs("%s/%s/%s_%s%s_ZminusZoom.png" %
                    (theDirname, "ZMinusZoom", detector, plot, plotmat))

    gStyle.SetStripDecimals(True)
Пример #15
0
def drawTopoGeometryEtaPhi(geometry, colorBy, is2016):

    if colorBy < ETACODE or colorBy > IPHI:
        return

    global box, c, h, leg

    gROOT.Reset()
    gStyle.SetOptStat(0)

    c = TCanvas('c', "MuCTPi to Topo Geometry", 1400, 950)
    c.Draw()

    h = TH2F("h", "Muon Topo Geometry %i" % (2016 if is2016 else 2015), 10,
             -2.6, 2.6, 10, -0.15, 6.4)
    h.SetXTitle("#eta")
    h.SetYTitle("#phi")
    h.Draw()

    box = TBox()
    box.SetFillStyle(0)
    box.SetLineColor(3)

    circle = TArc()

    if colorBy == IPHI:
        leg = TLegend(0.9, 0.1, 0.98, 0.9)
    else:
        leg = TLegend(0.8, 0.1, 0.9, 0.35)
    #leg.SetEntrySeparation(0.05)
    #leg.SetNColumns(2)

    codeInLegend = []
    for MioctID in drawOrder:
        #for MioctID in [3,4,5,6,7]:
        MIOCT = geometry.getMIOCT(MioctID)

        fillStyle = 3004
        for cellIdx, TopoCell in enumerate(MIOCT.Decode.TopoCells):

            if colorBy == ETACODE:
                code = int(TopoCell["etacode"], 16)
            elif colorBy == PHICODE:
                code = int(TopoCell["phicode"], 16)
            elif colorBy == IETA:
                code = abs(int(TopoCell["ieta"]))
            elif colorBy == IPHI:
                code = int(TopoCell["iphi"])
            else:
                raise RuntimeError(
                    "Don't know how to color the eta-phi map (%r)" % colorBy)
            color = colorMap2[code % len(colorMap2)]
            fillStyle = fillStyleMap2[code % 4]
            box.SetLineColor(color)
            box.SetFillColor(color)

            circle.SetLineColor(color)
            circle.SetFillColor(color)

            # corner 1
            c1_x = float(TopoCell["etamin"])
            c1_y = float(TopoCell["phimin"])
            # corner 2
            c2_x = float(TopoCell["etamax"])
            c2_y = float(TopoCell["phimax"])
            # center
            c_x = float(TopoCell["ieta"])
            c_y = float(TopoCell["iphi"])

            #if code>63:
            #    continue
            #print "cell %i : eta [%f - %f], phi [%f - %f]" % (cellIdx, c1_x, c2_x, c1_y, c2_y)

            box.SetFillStyle(fillStyle)
            b = box.DrawBox(c1_x, c1_y, c2_x, c2_y)
            box.SetFillStyle(0)
            box.DrawBox(c1_x, c1_y, c2_x, c2_y)

            circle.DrawArc(c_x / 10., c_y / 10., 0.02)

            if not code in codeInLegend:
                codeInLegend += [code]
                if colorBy == ETACODE:
                    leg.AddEntry(b, "etacode %i" % code, "lf")
                elif colorBy == PHICODE:
                    leg.AddEntry(b, "phicode %i" % code, "f")
                elif colorBy == IETA:
                    leg.AddEntry(b, "|ieta| %i" % code, "f")
                elif colorBy == IPHI:
                    leg.AddEntry(b, "iphi %i" % code, "f")

    leg.Draw()

    c.Update()
    if colorBy == ETACODE:
        ext = "EtaCode"
    elif colorBy == PHICODE:
        ext = "PhiCode"
    elif colorBy == IETA:
        ext = "Eta"
    elif colorBy == IPHI:
        ext = "Phi"

    c.SaveAs("TopoLayout%s%s.pdf" % ("2016" if is2016 else "2015", ext))
def analysis(hadron="Omega_ccc"):
    gStyle.SetOptStat(0)
    with open(r"databases/theory_yields.yaml") as fileparamyields:
        paramyields = yaml.safe_load(fileparamyields)
    models = paramyields["comparison_models_AA"][hadron]["models"]
    collisions = paramyields["comparison_models_AA"][hadron]["collisions"]
    brmodes = paramyields["comparison_models_AA"][hadron]["brmode"]
    yranges = paramyields["comparison_models_AA"][hadron]["yrange"]
    colors = paramyields["comparison_models_AA"][hadron]["colors"]
    useshape = paramyields["comparison_models_AA"][hadron]["useshape"]
    ymin = paramyields["comparison_models_AA"][hadron]["ymin"]
    ymax = paramyields["comparison_models_AA"][hadron]["ymax"]
    binanal = array("d", paramyields["comparison_models_AA"]["pt_binning"][hadron])

    with open(r"databases/general.yaml") as fileparamgen:
        paramgen = yaml.safe_load(fileparamgen)

    histolist = [None] * len(models)

    fin = TFile("../InputsTheory/" + useshape + ".root")
    histo_norm = fin.Get("hdNdpt_norm")  # this is the pT-shape normalized to unity

    for icase, _ in enumerate(models):
        histolist[icase] = histo_norm.Clone(
            "dNdpt%s%s%s" % (models[icase], collisions[icase], brmodes[icase])
        )
    canvas = TCanvas("canvas", "A Simple Graph Example", 881, 176, 668, 616)
    gStyle.SetOptStat(0)
    canvas.SetHighLightColor(2)
    canvas.Range(-1.25, -4.625, 11.25, 11.625)
    canvas.SetFillColor(0)
    canvas.SetBorderMode(0)
    canvas.SetBorderSize(2)
    canvas.SetLogy()
    canvas.SetFrameBorderMode(0)
    canvas.SetFrameBorderMode(0)
    canvas.cd()
    gPad.SetLogy()

    hempty = TH2F("hempty", ";p_{T};Yields", 100, 0.0, 10.0, 100, ymin, ymax)
    hempty.GetXaxis().SetTitle("p_{T}")
    hempty.GetXaxis().SetLabelFont(42)
    hempty.GetXaxis().SetTitleOffset(1)
    hempty.GetXaxis().SetTitleFont(42)
    hempty.GetYaxis().SetLabelFont(42)
    hempty.GetYaxis().SetTitleOffset(1.35)
    hempty.GetYaxis().SetTitleFont(42)
    hempty.GetZaxis().SetLabelFont(42)
    hempty.GetZaxis().SetTitleOffset(1)
    hempty.GetZaxis().SetTitleFont(42)
    hempty.Draw()

    leg = TLegend(0.1471471, 0.6108291, 0.3018018, 0.8747885, "", "brNDC")
    leg.SetBorderSize(1)
    leg.SetLineColor(0)
    leg.SetLineStyle(1)
    leg.SetLineWidth(1)
    leg.SetFillColor(0)
    leg.SetTextSize(0.022)
    leg.SetFillStyle(1001)

    # each case represents a combination of expected dNdy,
    # collision type and HP on the branching ratio.
    for icase, _ in enumerate(models):
        brmode = brmodes[icase]
        collision = collisions[icase]
        model = models[icase]
        yrange = yranges[icase]

        sigma_aa_b = paramgen["statistics"][collision]["sigmaAA_b"]
        lumiaa_monthi_invnb = paramgen["statistics"][collision]["lumiAA_monthi_invnb"]
        nevt = sigma_aa_b * lumiaa_monthi_invnb * 1e9  # luminosity given in nb-1
        bratio = paramgen["branchingratio"][hadron][brmode]
        yieldmid = paramyields[model][collision][yrange][hadron]
        text = "%s N_{ev}(%s) = %.1f B, BR=%.5f%%" % (
            model,
            collision,
            nevt / 1e9,
            bratio * 100,
        )
        scalef = bratio * nevt * yieldmid

        # before rebinning, the dNdpT is multiplied by the binwidth,
        # branching ratios, expected dN/dy and number of events
        # so that the yields can be simplied summed in rebinning process.
        for ibin in range(histolist[icase].GetNbinsX()):
            binwdith = histolist[icase].GetBinWidth(ibin + 1)
            yvalue = histolist[icase].GetBinContent(ibin + 1)
            histolist[icase].SetBinContent(ibin + 1, binwdith * scalef * yvalue)
        histolist[icase] = histolist[icase].Rebin(
            len(binanal) - 1, "histo_pred%s%s%s" % (model, collision, brmode), binanal
        )
        histolist[icase].SetLineColor(colors[icase])
        histolist[icase].SetMarkerColor(colors[icase])
        histolist[icase].SetLineWidth(2)
        histolist[icase].Draw("same")
        text = text + " Yield(tot)=%.2f" % (histolist[icase].Integral())
        leg.AddEntry(histolist[icase], text, "pF")
    leg.Draw()
    canvas.SaveAs(hadron + "_results.pdf")
    canvas.SaveAs(hadron + "_results.C")
    foutput = TFile("foutput" + hadron + ".root", "recreate")
    for icase, _ in enumerate(models):
        foutput.cd()
        histolist[icase].Write()
Пример #17
0
def drawROIGeometry(geometry, is2016):

    outfn = "ROILayout%s.pdf" % ("2016" if is2016 else "2015")

    global box, c, h, leg

    gROOT.Reset()
    gStyle.SetOptStat(0)

    c = TCanvas('c', "MuCTPi Geometry %s" % "2016" if is2016 else "2015", 1400,
                950)
    c.Draw()

    #h = TH2F("h","Muon Geometry",10,-2.6,2.6,10,-6.4,6.4)
    h = TH2F("h", "Muon Geometry %s" % "2016" if is2016 else "2015", 10, -2.6,
             2.6, 10, -0.15, 6.4)
    h.SetXTitle("#eta")
    h.SetYTitle("#phi")
    h.Draw()

    box = TBox()
    box.SetFillStyle(0)
    box.SetLineColor(3)
    box.SetLineColor(3)

    text = TLatex()
    text.SetTextSize(0.005)
    text.SetTextFont(42)
    text.SetTextAlign(22)

    secLabel = TLatex()
    secLabel.SetTextSize(0.008)
    secLabel.SetTextFont(42)
    secLabel.SetTextAlign(22)

    leg = TLegend(0.7, 0.1, 0.9, 0.4)
    leg.SetEntrySeparation(0.05)
    leg.SetNColumns(2)

    #for MIOCT in geometry.getMIOCTs():
    for colorIndex, MioctID in enumerate(drawOrder):
        MIOCT = geometry.getMIOCT(MioctID)
        firstBox = True
        color = colorMap[colorIndex % len(colorMap)]
        #print "Using color ",color
        box.SetLineColor(color)
        box.SetLineWidth(1)

        for Sector in MIOCT.Sectors:
            ymin = 10
            ymax = -10
            for ROI in Sector.ROIs:
                c1_x = float(ROI["etamin"])
                c1_y = float(ROI["phimin"])
                c2_x = float(ROI["etamax"])
                c2_y = float(ROI["phimax"])
                ymin = min(ymin, c1_y)
                ymax = max(ymax, c2_y)
                #print "eta [%f - %f], phi [%f - %f]" % (c1_x,c2_x,c1_y,c2_y)
                b = box.DrawBox(c1_x, c1_y, c2_x, c2_y)
                text.DrawText((c1_x + c2_x) / 2, (c1_y + c2_y) / 2,
                              ROI["roiid"])
                if firstBox:
                    firstBox = False
                    leg.AddEntry(b, "Slot %s" % MIOCT["slot"], "l")
            if Sector["name"].startswith("B"):
                if int(Sector["name"][1:]) < 32:
                    xpos = -0.02
                    ypos = (ymin + ymax) / 2 - 0.05
                else:
                    xpos = 0.02
                    ypos = (ymin + ymax) / 2 + 0.03
                secLabel.DrawText(xpos, ypos, Sector["name"])

    leg.Draw()

    c.Update()
    c.SaveAs(outfn)
Пример #18
0
    outfile_newF = TFile.Open('signal_proc_'+section+'.root','RECREATE')

#    print ('outfile_newF = signal_proc'+section+'.root');


    for i in range(1,len(bins)):
        
        if (model=="par1_TH1" or model=="par1_TF1"):
            theBaseData = TH1F('theBaseData_'+section+'_'+str(i),'Base Histogram for RooDataHist',
                               nGridPar1Bins,par1GridMin,par1GridMax)
            newFormatInput = TH1D('bin_content_par1_'+str(i),'bincontent',
                                  nGridPointsForNewF,par1GridMin,par1GridMax)
        elif (model=="par1par2_TH2" or model=="par1par2_TF2"):
            theBaseData = TH2F('theBaseData_'+section+'_'+str(i),'Base Histogram for RooDataHist',
                               nGridPar1Bins,par1GridMin,par1GridMax,
                               nGridPar2Bins,par2GridMin,par2GridMax)
            newFormatInput = TH2D('bin_content_par1_par2_'+str(i),'bincontent',
                                  nGridPointsForNewF,par1GridMin,par1GridMax,
                                  nGridPointsForNewF,par2GridMin,par2GridMax)
        elif (model=="par1par2par3_TH3" or model=="par1par2par3_TF3"):
            theBaseData = TH3F('theBaseData_'+section+'_'+str(i),'Base Histogram for RooDataHist',
                               nGridPar1Bins,par1GridMin,par1GridMax,
                               nGridPar2Bins,par2GridMin,par2GridMax,
                               nGridPar3Bins,par3GridMin,par3GridMax)
            newFormatInput = TH3D('bin_content_par1_par2_par3_'+str(i),'bincontent',
                                  nGridPointsForNewF,par1GridMin,par1GridMax,
                                  nGridPointsForNewF,par2GridMin,par2GridMax,
                                  nGridPointsForNewF,par3GridMin,par3GridMax)
        
        if i != len(bins) - 1:
    # Open a txt file to save the parameters value for each DC:
    myfile = open(
        Module_path + '/Outputfiles/Calibration_files/' + 'DC' + str(j) +
        'NoCorrected.cal', 'w')

    # Create a new canvas, and customize it.
    c1 = TCanvas('c1', 'DC' + str(j) + '_calibration', 400, 100, 1000, 700)
    c1.SetFillColor(0)
    c1.GetFrame().SetFillColor(21)
    c1.GetFrame().SetBorderSize(6)
    c1.GetFrame().SetBorderMode(-1)

    for i in range(0, 160):
        h_Q60vsQ = TH2F(
            'h_Q60vsQ',
            'DC' + str(j) + '_QV[60]:DC' + str(j) + '_QV[' + str(i) + ']',
            1000, 0, 3000, 1000, 0, 3000)
        h_Q60vsQ.SetFillColor(42)
        h_Q60vsQ.SetYTitle('DC' + str(j) + '_QV[60]')
        h_Q60vsQ.SetXTitle('DC' + str(j) + '_QV[' + str(i) + ']')
        #h_Q60vsQ.SetStats(1)
        gStyle.SetOptStat(1000000001)  #only write the name of the histogram

        mitree.Draw(
            "DC" + str(j) + "_QV[60]:DC" + str(j) + "_QV[" + str(i) +
            "]>>h_Q60vsQ", "", "col")
        func = TF1('func', '[0] + [1]*x', 0, 2500)
        fit = h_Q60vsQ.Fit('func', 'SQ')  #Q (quit) for turn off the statistics

        p0 = func.GetParameter(0)
        p1 = func.GetParameter(1)
Пример #20
0
def findElectrons(opts):
    
    ### Load Python modules

    import os
    import math
    import numpy as np
    from array import array
    from os.path import isdir, abspath

    ### Load ROOT modules
    from ROOT import TClonesArray, TFile, TTree, gSystem, gROOT, AddressOf
    from ROOT import TH2F, TH1F, TMath, TGraphAsymmErrors

    ###Load DAMPE libs

    gSystem.Load("libDmpEvent.so")
    gSystem.Load("libDmpEventFilter.so")
    
    gSystem.Load("libDmpKernel.so")
    gSystem.Load("libDmpService.so")

    ###Load DAMPE modules

    from ROOT import DmpChain, DmpEvent, DmpFilterOrbit, DmpPsdBase, DmpCore
    from ROOT import DmpSvcPsdEposCor, DmpVSvc   #DmpRecPsdManager
    import DMPSW

    gROOT.SetBatch(True)

    ############################# Searching for electrons

    ####### Reading input files

    #Creating DAMPE chain for input files
    dmpch = DmpChain("CollectionTree")
    
    #Reading input files
    if not opts.input:
        files = [f.replace("\n","") for f in open(opts.list,'r').readlines()]
        for ifile, f in enumerate(files):
            DMPSW.IOSvc.Set("InData/Read" if ifile == 0 else "InData/ReadMore",f)
            if os.path.isfile(f):
                dmpch.Add(f)
                if opts.verbose:
                    print('\nInput file read: {} -> {}'.format(ifile,f))
    else:
        DMPSW.IOSvc.Set("InData/Read",opts.input)
        if os.path.isfile(opts.input):
            dmpch.Add(opts.input)
            if opts.verbose:
                print('\nInput file read: {}'.format(opts.input))
    
    #Defining the total number of events
    nevents = dmpch.GetEntries()

    if opts.verbose:
        print('\nTotal number of events: {}'.format(nevents))
        print("\nPrinting the chain...\n")
        dmpch.Print()
    
    ####### Setting the output directory to the chain
    dmpch.SetOutputDir(abspath(opts.outputDir),"electrons")

    ####### Processing input files

    ###Histos

    #Defining log binning

    #np.logspace binning
    nBins=1000
    eMax=6
    eMin=0
    eBinning = np.logspace(eMin, eMax, num=(nBins+1))
    
    #custom binning
    ''' 
    nBins = 1000
    eMin=0.1
    eMax=1000000
    EDmax = []
    EDEdge = [] 
    EDstepX=np.log10(eMax/eMin)/nBins
    for iedge in range(0, nBins):
        EDEdge.append(eMin*pow(10,iedge*EDstepX))
        EDmax.append(eMin*pow(10,(iedge+1)*EDstepX))
    EDEdge.append(EDmax[-1])
    Edges= array('d',EDEdge) # this makes a bound array for TH1F
    '''

    #Pointing
    h_terrestrial_lat_vs_long =  TH2F("h_terrestrial_lat_vs_long","latitude vs longitude",360,0,360,180,-90,90)

    ## Energy
    h_energy_all = TH1F("h_energy_all","all particle energy",nBins,eBinning)
    h_energyCut = TH1F("h_energyCut","all particle energy - 20 GeV cut",nBins,eBinning)
    h_energyCut_SAAcut = TH1F("h_energyCut_SAAcut","all particle energy - 20 GeV cut (no SAA)",nBins,eBinning)
    h_energyCut_noTrack = TH1F("h_energyCut_noTrack","all particle energy - 20 GeV cut (NO TRACK)",nBins,eBinning)
    h_energyCut_Track = TH1F("h_energyCut_Track","all particle energy - 20 GeV cut (TRACK)",nBins,eBinning)
    h_energyCut_TrackMatch = TH1F("h_energyCut_TrackMatch","all particle energy - 20 GeV cut (TRACK match)",nBins,eBinning)
    
    ##BGO
    h_energyBGOl=[]  #energy of BGO vertical layer (single vertical plane)
    for BGO_idxl in range(14):
        histoName = "h_energyBGOl_" + str(BGO_idxl)
        histoTitle = "BGO energy deposit layer " + str(BGO_idxl)
        tmpHisto = TH1F(histoName,histoTitle,1000,0,1e+6)
        h_energyBGOl.append(tmpHisto)

    h_energyBGOb = [] #energy of BGO lateral layer (single bars of a plane)
    h_BGOb_maxEnergyFraction = [] #fraction of the maximum released energy for each bar on each layer of the BGO calorimeter

    for BGO_idxl in range(14):
        tmp_eLayer = []
        for BGO_idxb in range(23):
            histoName = "h_energyBGOl_" + str(BGO_idxl) + "_BGOb_" + str(BGO_idxb)
            histoTitle = "BGO energy deposit layer " + str(BGO_idxl) + " bar " + str(BGO_idxb)
            tmpHisto = TH1F(histoName,histoTitle,1000,0,1e+6)
            tmp_eLayer.append(tmpHisto)
            
        maxhistoName = "h_BGO_maxEnergyFraction_l_" + str(BGO_idxl)
        maxhistoTitle = "fraction of the maximum released energy layer " + str(BGO_idxl)
        tmpMaxHisto = TH1F(maxhistoName,maxhistoTitle,100,0,1)
        h_BGOb_maxEnergyFraction.append(tmpMaxHisto)
        h_energyBGOb.append(tmp_eLayer)

    h_BGOl_maxEnergyFraction = TH1F("h_BGOl_maxEnergyFraction","Fraction of the maximum released energy",100,0,1)

    h_thetaBGO = TH1F("h_thetaBGO","theta BGO",100,0,90)

    ##STK

    h_STK_nTracks = TH1F("h_STK_nTracks","number of tracks",1000,0,1000)
    h_STK_trackChi2norm = TH1F("h_STK_trackChi2norm","\chi^2/n track",100,0,200)
    h_STK_nTracksChi2Cut = TH1F("h_STK_nTracksChi2Cut","number of tracks (\chi^2 cut)",1000,0,1000)
        
    h_stk_cluster_XvsY = []
    for iLayer in range(6):
        hName = 'h_stkCluster_XvsY_l_'+str(iLayer)
        hTitle = 'cluster X vs Y - plane '+str(iLayer)
        tmpHisto = TH2F(hName,hTitle,1000,-500,500,1000,-500,500)
        h_stk_cluster_XvsY.append(tmpHisto)

    h_ThetaSTK = TH1F("h_ThetaSTK","theta STK",100,0,90)
    h_deltaTheta = TH1F("h_deltaTheta","\Delta theta",500,-100,100)
    
    h_resX_STK_BGO = TH1F("h_resX_STK_BGO","BGO/STK residue layer X",200,-1000,1000)
    h_resY_STK_BGO = TH1F("h_resY_STK_BGO","BGO/STK residue layer Y",200,-1000,1000)

    h_imapctPointSTK = TH2F("h_imapctPointSTK","STK impact point",1000,-500,500,1000,-500,500)

    h_stk_chargeClusterX = TH1F("h_stk_chargeClusterX","STK charge on cluster X",10000,0,10000)
    h_stk_chargeClusterY = TH1F("h_stk_chargeClusterY","STK charge on cluster Y",10000,0,10000)

    ##PSD

    h_psd_ChargeX = []
    for lidx in range (2):
        histoName = "h_psd_ChargeX_l" + str(lidx)
        histoTitle = "PSD X charge layer " + str(lidx)
        tmpHisto = TH1F(histoName,histoTitle,10000,0,10000)
        h_psd_ChargeX.append(tmpHisto)

    h_psd_ChargeY = []
    for lidx in range (2):
        histoName = "h_psd_ChargeY_l" + str(lidx)
        histoTitle = "PSD Y charge layer " + str(lidx)
        tmpHisto = TH1F(histoName,histoTitle,10000,0,10000)
        h_psd_ChargeY.append(tmpHisto)

    ###

    ### Analysis cuts

    eCut = 50       #Energy cut in GeV

    ### DAMPE geometry

    BGOzTop = 46.
    BGOzBot = 448.

    #Filtering for SAA
    if not opts.mc:
        DMPSW.IOSvc.Set("OutData/NoOutput", "True")
        DMPSW.IOSvc.Initialize()
        pFilter = DmpFilterOrbit("EventHeader")
        pFilter.ActiveMe()
    
    #Starting loop on files

    if opts.debug:
        if opts.verbose:
            print('\nDebug mode activated... the number of chain events is limited to 1000')
        nevents = 1000
    
    for iev in xrange(nevents):

        if opts.mc:
            DmpVSvc.gPsdECor.SetMCflag(1)
        pev=dmpch.GetDmpEvent(iev)

        #Get latitude and longitude
        longitude = pev.pEvtAttitude().lon_geo
        latitude = pev.pEvtAttitude().lat_geo

        #Get particle total energy
        etot=pev.pEvtBgoRec().GetTotalEnergy()/1000.
        h_energy_all.Fill(etot)
        if etot < eCut:
            continue
        h_energyCut.Fill(etot)

        #Get BGO energy deposit for each layer (vertical BGO shower profile)
        v_bgolayer  = np.array([pev.pEvtBgoRec().GetELayer(ibgo) for ibgo in range(14)])
        
        for BGO_idxl in range(14):
            h_energyBGOl[BGO_idxl].Fill(v_bgolayer[BGO_idxl])  

        #Get BGO energy deposit for each bar (lateral BGO shower profile) of each layer

        for ilay in xrange(0,14):
            v_bgolayer_bars  = np.array([pev.pEvtBgoRec().GetEdepPos(ilay,ibar) for ibar in xrange(0,23)])
            #Fraction of the maximum energy deposit of the particle crossing the BGO on a certain layer (single bars)
            h_BGOb_maxEnergyFraction[ilay].Fill(np.max(v_bgolayer_bars)/1000./etot)
            for idx_BGOb in range (23):
                h_energyBGOb[ilay][idx_BGOb].Fill(v_bgolayer_bars[idx_BGOb])
            

        #Fraction of the maximum energy deposit of the particle crossing the BGO
        h_BGOl_maxEnergyFraction.Fill(np.max(v_bgolayer)/1000./etot)

        #BGO acceptance projection
        
        projectionX_BGO_BGOTop =  pev.pEvtBgoRec().GetInterceptXZ() +BGOzTop  * pev.pEvtBgoRec().GetSlopeXZ()
        projectionY_BGO_BGOTop =  pev.pEvtBgoRec().GetInterceptYZ() +BGOzTop  * pev.pEvtBgoRec().GetSlopeYZ()


        #SAA filter
        if not opts.mc:
            inSAA = pFilter.IsInSAA(pev.pEvtHeader().GetSecond())
            #inSAA = False
            if (inSAA): 
                continue
            h_energyCut_SAAcut.Fill(etot)
            h_terrestrial_lat_vs_long.Fill(longitude,latitude)

        tgZ = math.atan(np.sqrt( (pev.pEvtBgoRec().GetSlopeXZ()*pev.pEvtBgoRec().GetSlopeXZ()) + (pev.pEvtBgoRec().GetSlopeYZ()*pev.pEvtBgoRec().GetSlopeYZ()) ) );
        theta_bgo = tgZ*180./math.pi

        h_thetaBGO.Fill(theta_bgo)

        #Tracks
        ntracks = pev.NStkKalmanTrack()

        if ntracks < 0:
            print "\nTRACK ERROR: number of tracks < 0 - ABORTING\n"
            break
        if ntracks == 0:
            h_energyCut_noTrack.Fill(etot)
        
        h_STK_nTracks.Fill(ntracks)
        h_energyCut_Track.Fill(etot)

        res_X_min = 1000
        res_Y_min = 1000
        trackID_X = -9
        trackID_Y = -9

        lTrackIDX = []
        lTrackIDY = []

        residueXmin = []
        residueYmin = []

        #Loop on STK tracks to get the STK charge measurement

        for iTrack in range(ntracks):
            tmpTrack = pev.pStkKalmanTrack(iTrack)
            chi2_norm = tmpTrack.getChi2()/(tmpTrack.getNhitX()+tmpTrack.getNhitY()-4)
            h_STK_trackChi2norm.Fill(chi2_norm)

            if chi2_norm > 25: 
                continue
        
            h_STK_nTracksChi2Cut.Fill(ntracks)

            l0ClusterX = l0ClusterY = False

            for iCluster in range(tmpTrack.GetNPoints()):
                clux = tmpTrack.pClusterX(iCluster)
                cluy = tmpTrack.pClusterY(iCluster)
                if clux and clux.getPlane() == 0:
                    l0ClusterX = True
                if cluy and cluy.getPlane() == 0:
                    l0ClusterY = True

                # check plot for the dead region of STK
                if(clux and cluy):
                    h_stk_cluster_XvsY[clux.getPlane()].Fill(clux.GetX(),cluy.GetY())


            if l0ClusterX == False and l0ClusterY == False:
                continue

            #### Tracks characteristics

            theta_stk =math.acos(tmpTrack.getDirection().CosTheta())*180./math.pi;

            delta_theta_STK_BGO = theta_stk - theta_bgo

            #STK impact point
            trackImpactPointX = tmpTrack.getImpactPoint().x()
            trackImpactPointY = tmpTrack.getImpactPoint().y()

            #Track projections
            trackProjX = tmpTrack.getDirection().x()*(BGOzTop - tmpTrack.getImpactPoint().z()) + tmpTrack.getImpactPoint().x()
            trackProjY = tmpTrack.getDirection().y()*(BGOzTop - tmpTrack.getImpactPoint().z()) + tmpTrack.getImpactPoint().y()

            #Track residues
            resX_STK_BGO = projectionX_BGO_BGOTop - trackProjX
            resY_STK_BGO = projectionY_BGO_BGOTop - trackProjY

            resX_STK_BGO_top = trackImpactPointX - (pev.pEvtBgoRec().GetInterceptXZ() + tmpTrack.getImpactPoint().z() * pev.pEvtBgoRec().GetSlopeXZ())
            resY_STK_BGO_top = trackImpactPointY - (pev.pEvtBgoRec().GetInterceptYZ() + tmpTrack.getImpactPoint().z() * pev.pEvtBgoRec().GetSlopeYZ())

            ####

            h_ThetaSTK.Fill(theta_stk)
            h_deltaTheta.Fill(delta_theta_STK_BGO)

            h_imapctPointSTK.Fill(trackImpactPointX,trackImpactPointY)
                
            h_resX_STK_BGO.Fill(tmpTrack.getImpactPoint().x() - (pev.pEvtBgoRec().GetInterceptXZ() + tmpTrack.getImpactPoint().z() * pev.pEvtBgoRec().GetSlopeXZ()))
            h_resY_STK_BGO.Fill(tmpTrack.getImpactPoint().y() - (pev.pEvtBgoRec().GetInterceptYZ() + tmpTrack.getImpactPoint().z() * pev.pEvtBgoRec().GetSlopeYZ()))
    
            if abs(theta_stk - theta_bgo) > 25:
                continue
                    
            #Selecting good tracks for charge measurement

            if abs(resX_STK_BGO_top) < 200 and abs(resX_STK_BGO) < 60:
                lTrackIDX.append(tmpTrack)
                residueXmin.append(res_X_min)
                if res_X_min > abs(resX_STK_BGO_top):
                    res_X_min = abs(resX_STK_BGO_top)
                    trackID_X = iTrack
                    

            if abs(resY_STK_BGO_top) < 200 and abs(resY_STK_BGO) < 60:
                lTrackIDY.append(tmpTrack)
                residueYmin.append(res_Y_min)
                if res_Y_min > abs(resY_STK_BGO_top):
                    res_Y_min = abs(resY_STK_BGO_top)
                    trackID_Y = iTrack

        if(trackID_X == -9): 
            continue
        if(trackID_Y == -9): 
            continue

        track_ID = -9
        #print trackID_X
        
        if(trackID_X == trackID_Y):
            track_ID = trackID_X
        else:
            trackX = pev.pStkKalmanTrack(trackID_X)
            trackY = pev.pStkKalmanTrack(trackID_Y)
            chi2X = trackX.getChi2() /(trackX.getNhitX()+trackX.getNhitY()-4);
            chi2Y = trackY.getChi2() /(trackY.getNhitX()+trackY.getNhitY()-4);
            npointX = trackX.GetNPoints()
            npointY = trackY.GetNPoints()

            if(npointX == npointY or abs(npointX - npointY) == 1):
                if(chi2X < chi2Y):
                    if trackID_X in lTrackIDY:
                        track_ID = trackID_X
                    elif trackID_Y in lTrackIDX:
                            track_ID = trackID_Y
                    else:
                        common_id = list(set(lTrackIDX).intersection(lTrackIDY))
                        searchForTrack(
                                        common_id,
                                        lTrackIDX,
                                        lTrackIDY,
                                        residueXmin,
                                        residueYmin,
                                        track_ID
                                    )
                else:
                    if trackID_Y in lTrackIDX:
                        track_ID = trackID_Y
                    elif trackID_X in lTrackIDY:
                            track_ID = trackID_X
                    else:
                        common_id = list(set(lTrackIDX).intersection(lTrackIDY))
                        searchForTrack(
                                        common_id,
                                        lTrackIDX,
                                        lTrackIDY,
                                        residueXmin,
                                        residueYmin,
                                        track_ID
                                    )
            else:
                if(npointX > npointY):
                    if trackID_X in lTrackIDY:
                        track_ID = trackID_X
                    elif trackID_Y in lTrackIDX:
                            track_ID = trackID_Y
                    else:
                        common_id = list(set(lTrackIDX).intersection(lTrackIDY))
                        searchForTrack(
                                        common_id,
                                        lTrackIDX,
                                        lTrackIDY,
                                        residueXmin,
                                        residueYmin,
                                        track_ID
                                    )
                else:
                    if trackID_Y in lTrackIDX:
                        track_ID = trackID_Y
                    elif trackID_X in lTrackIDY:
                            track_ID = trackID_X
                    else:
                        common_id = list(set(lTrackIDX).intersection(lTrackIDY))
                        searchForTrack(
                                        common_id,
                                        lTrackIDX,
                                        lTrackIDY,
                                        residueXmin,
                                        residueYmin,
                                        track_ID
                                    )
        if(track_ID == -9): 
            continue

        h_energyCut_TrackMatch.Fill(etot)

        #Select the matched track
        track_sel = pev.pStkKalmanTrack(track_ID)
        theta_track_sel =math.acos(track_sel.getDirection().CosTheta())*180./math.pi;
        deltaTheta_rec_sel = theta_bgo - theta_track_sel
        track_correction = track_sel.getDirection().CosTheta();

        cluChargeX = -1000
        cluChargeY = -1000

        for iclu in xrange(0,track_sel.GetNPoints()):
            clux = track_sel.pClusterX(iclu)
            cluy = track_sel.pClusterY(iclu)
            if (clux and clux.getPlane() == 0):
                cluChargeX = clux.getEnergy()*track_correction
            if (cluy and cluy.getPlane() == 0):
                cluChargeY = cluy.getEnergy()*track_correction
        
        h_stk_chargeClusterX.Fill(cluChargeX)
        h_stk_chargeClusterY.Fill(cluChargeY)


        #Loop on PSD hits to get PSD charge measurement
        
        '''

        #PSD fiducial volume cut

        psd_YZ_top = -324.7
        psd_XZ_top = -298.5
        stk_to_psd_topY = (track_sel.getDirection().y()*(psd_YZ_top - track_sel.getImpactPoint().z()) + track_sel.getImpactPoint().y())
        stk_to_psd_topX = (track_sel.getDirection().x()*(psd_XZ_top - track_sel.getImpactPoint().z()) + track_sel.getImpactPoint().x())

        if(abs(stk_to_psd_topX) > 400.): 
            continue
        if(abs(stk_to_psd_topY) > 400.): 
            continue

        '''
       

        PSDXlayer0 = -298.5
        PSDXlayer1 = -284.5

        PSDYlayer0 = -324.7
        PSDYlayer1 = -310.7
        
        psdChargeX     = [[]for _ in range(2)]
        psdGIDX        = [[]for _ in range(2)]
        psdPathlengthX = [[]for _ in range(2)]
        psdPositionX   = [[]for _ in range(2)]

        psdChargeY     = [[]for _ in range(2)]
        psdGIDY        = [[]for _ in range(2)]
        psdPathlengthY = [[]for _ in range(2)]
        psdPositionY   = [[]for _ in range(2)]

        for lPSD in xrange(0,pev.NEvtPsdHits()):
            
            if pev.pEvtPsdHits().IsHitMeasuringX(lPSD):
                crossingX = False
                lenghtX = [-99999.,-99999.]
                array_lenghtX = array('d',lenghtX)

                if(pev.pEvtPsdHits().GetHitZ(lPSD) == PSDXlayer0):
                    npsdX = 0
                if(pev.pEvtPsdHits().GetHitZ(lPSD)== PSDXlayer1):
                    npsdX = 1
                
                if not opts.mc:
                    crossingX = DmpVSvc.gPsdECor.GetPathLengthPosition(pev.pEvtPsdHits().fGlobalBarID[lPSD],track_sel.getDirection(),track_sel.getImpactPoint(), array_lenghtX)

                if crossingX:
                    psdChargeX[npsdX].append(pev.pEvtPsdHits().fEnergy[lPSD]) 
                    psdGIDX[npsdX].append(pev.pEvtPsdHits().fGlobalBarID[lPSD]) 
                    psdPathlengthX[npsdX].append(array_lenghtX[1])
                    psdPositionX[npsdX].append(pev.pEvtPsdHits().GetHitX(lPSD))
            
            elif pev.pEvtPsdHits().IsHitMeasuringY(lPSD):
                crossingY = False
                lenghtY = [-99999.,-99999.]
                array_lenghtY = array('d',lenghtY)

                if(pev.pEvtPsdHits().GetHitZ(lPSD) == PSDYlayer0):
                    npsdY = 0
                if(pev.pEvtPsdHits().GetHitZ(lPSD)== PSDYlayer1):
                    npsdY = 1
                
                if not opts.mc:
                    crossingY = DmpVSvc.gPsdECor.GetPathLengthPosition(pev.pEvtPsdHits().fGlobalBarID[lPSD],track_sel.getDirection(),track_sel.getImpactPoint(), array_lenghtY)

                if crossingY:
                    psdChargeY[npsdY].append(pev.pEvtPsdHits().fEnergy[lPSD]) 
                    psdGIDY[npsdY].append(pev.pEvtPsdHits().fGlobalBarID[lPSD]) 
                    psdPathlengthY[npsdY].append(array_lenghtY[1])
                    psdPositionY[npsdY].append(pev.pEvtPsdHits().GetHitY(lPSD))
        
        '''
        print psdChargeX
        print psdGIDX
        print psdPathlengthX
        print psdPositionX

        print psdChargeY
        print psdGIDY
        print psdPathlengthY
        print psdPositionY
        
        '''

        psdFinalChargeX = [-999,-999]
        psdFinalChargeY = [-999,-999]

        #psdFinalChargeX_corr = [-999,-999]
        #psdFinalChargeY_corr = [-999,-999]

        psdFinalChargeX_proj = [-999,-999]
        psdFinalChargeY_proj = [-999,-999]

        psdX_pathlength = [-999,-999]
        psdY_pathlength = [-999,-999]

        psdX_position = [-999,-999]
        psdY_position = [-999,-999]
         
        PsdEC_tmpX = 0.
        PsdEC_tmpY = 0.

        for ipsd in xrange(0,2):
            
            if(len(psdChargeY[ipsd]) > 0):
                pos_max_len = np.argmax(psdPathlengthY[ipsd])
                lenghtY = [-99999.,-99999.]
                array_lenghtY = array('d',lenghtY)
                test_pos = False 
                if not opts.mc:
                    test_pos = DmpVSvc.gPsdECor.GetPathLengthPosition(psdGIDY[ipsd][pos_max_len],track_sel.getDirection(),track_sel.getImpactPoint(), array_lenghtY)
                 
                '''   
                PsdEC_tmpY = -1.
                if test_pos:
                    PsdEC_tmpY = DmpVSvc.gPsdECor.GetPsdECorSp3(psdGIDY[ipsd][pos_max_len], array_lenghtY[0])
                '''

                psdFinalChargeY[ipsd] = psdChargeY[ipsd][pos_max_len]
                h_psd_ChargeY[ipsd].Fill(psdFinalChargeY[ipsd])
                #psdFinalChargeY_corr[ipsd] = psdChargeY[ipsd][pos_max_len]*PsdEC_tmpY
                psdFinalChargeY_proj[ipsd] = array_lenghtY[0]
                psdY_pathlength[ipsd] = array_lenghtY[1]
                psdY_position[ipsd] =  psdPositionY[ipsd][pos_max_len]   
                


            if(len(psdChargeX[ipsd]) > 0):  
                pos_max_len = np.argmax(psdPathlengthX[ipsd])
                lenghtX = [-99999.,-99999.]
                array_lenghtX = array('d',lenghtX)
                test_pos = False 
                
                if not opts.mc:
                    test_pos = DmpVSvc.gPsdECor.GetPathLengthPosition(psdGIDX[ipsd][pos_max_len],track_sel.getDirection(),track_sel.getImpactPoint(), array_lenghtY)
                '''    
                PsdEC_tmpY = -1.
                if test_pos:
                    PsdEC_tmpX = DmpVSvc.gPsdECor.GetPsdECorSp3(psdGIDX[ipsd][pos_max_len], array_lenghtX[0])
                '''
                psdFinalChargeX[ipsd] = psdChargeX[ipsd][pos_max_len]
                h_psd_ChargeX[ipsd].Fill(psdFinalChargeX[ipsd])
                #psdFinalChargeX_corr[ipsd] = psdChargeX[ipsd][pos_max_len]*PsdEC_tmpX
                psdFinalChargeX_proj[ipsd] = array_lenghtX[0]
                psdX_pathlength[ipsd] = array_lenghtX[1]
                psdX_position[ipsd] =  psdPositionX[ipsd][pos_max_len] 










    ### Writing output files to file

    if opts.data:

        tf_skim = TFile(opts.outputFile,"RECREATE")

        h_energy_all.Write()
        h_energyCut.Write()
        h_energyCut_SAAcut.Write()
        h_energyCut_noTrack.Write()
        h_energyCut_Track.Write()
        h_energyCut_TrackMatch.Write()

        for BGO_idxl in range(14):
            h_energyBGOl[BGO_idxl].Write()
            h_BGOb_maxEnergyFraction[BGO_idxl].Write()
            for BGO_idxb in range(23):
                h_energyBGOb[BGO_idxl][BGO_idxb].Write()
        
        h_thetaBGO.Write()
        h_BGOl_maxEnergyFraction.Write()
        h_terrestrial_lat_vs_long.Write()

        h_STK_nTracks.Write()
        h_STK_trackChi2norm.Write()
        h_STK_nTracksChi2Cut.Write()

        for iLayer in range(6):
            h_stk_cluster_XvsY[iLayer].Write()

        h_ThetaSTK.Write()
        h_deltaTheta.Write()

        h_imapctPointSTK.Write()
        h_resX_STK_BGO.Write()
        h_resY_STK_BGO.Write()

        h_stk_chargeClusterX.Write()
        h_stk_chargeClusterY.Write()

        h_psd_ChargeX[0].Write()
        h_psd_ChargeX[1].Write()

        h_psd_ChargeY[0].Write()
        h_psd_ChargeY[1].Write()

        tf_skim.Close()

    
        
Пример #21
0
def recenergy(name, chivalue):
    outputfile = "KaonEnergyRes_" + 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')

    t = [10, 30, 50, 70, 100, 120, 140, 150]
    t = [100]
    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]
    #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]
    #inputfiles = ["/home/lorenzo/Calo/results/Proton_25_3_2020/"+str(name)+""+"/Proton_"+str(i)+".root" for i in t]
    #inputfiles = ["/home/lorenzo/Calo/results/Neutron_25_3_2020/"+str(name)+""+"/Neutron_"+str(i)+".root" for i in t]
    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)

        #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)

                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()
        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]))

    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()
    '''	
	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()
    def __init__(self,
                 inputfilename="config/configEffPredictor.cfg",
                 debug=False):
        #Set the debug flag
        self.DEBUG = debug

        #HV Points To Perform Calculations for
        self.LIST_HVPTS = []

        #Detector Names
        self.NAME_DET_DUT = "Detector"
        self.NAME_DET_CLUSTQ = "GE11-III-FIT-0001"
        self.NAME_DET_CLUSTSIZE = "GE11-IV-CERN-0001"

        #Declare Detector Container
        self.PARAMS_DET_DUT = PARAMS_DET()

        self.SECTOR_IETA_CLUSTSIZENORM = 5
        self.SECTOR_IETA_QC5 = 4

        self.SECTOR_IPHI_CLUSTSIZENORM = 2
        self.SECTOR_IPHI_QC5 = 2

        self.ANA_UNI_GRANULARITY = 32

        #Declare Gain Containers
        self.PARAMS_GAIN_DET_DUT = PARAMS_GAIN()
        self.PARAMS_GAIN_DET_CLUSTQ = PARAMS_GAIN()
        self.PARAMS_GAIN_DET_CLUSTSIZE = PARAMS_GAIN()

        #File Names
        self.FILE_CLUSTQ_MEAN = ""  #File having ordered triplet of (V_Drift, ClustSize, Mean) data
        self.FILE_CLUSTQ_MPV = ""  #As above but for MPV
        self.FILE_CLUSTQ_SIGMA = ""  #As above but for Sigma

        self.FILE_MAPPING_DUT = ""  #Mapping config file for detector under test
        self.FILE_MAPPING_DUT_VFAT2DET = ""  #Mapping config file for detectur under test which translates VFAT position to (ieta,iphi) coordinate

        self.FILE_MIP_AVG_CLUST_SIZE = ""  #File having a TF1 which is a fit of MIP <ClustSize> vs. Gain

        self.FILE_OUTPUT = ""  #Output filename to be created

        self.FILE_QC5_RESP_UNI = ""  #Framework output file
        self.FILE_SCURVE_DATA = ""  #TFile containing the scurveFitTree TTree with SCurve data

        #TObject Names
        self.TOBJ_NAME_FUNC_AVGCLUSTSIZE = ""

        #Load the input file and set all variables
        list_strLines = []
        with open(inputfilename) as inputFile:
            list_strLines = inputFile.readlines()

        inputFile.close()

        #strip new line character ('\n') from the file
        list_strLines = [x.strip() for x in list_strLines]

        if self.DEBUG:
            print "Field_Name\tValue"

        #Set Variables
        for iPos in range(0, len(list_strLines)):
            #Get this (field_name,value) pair
            strLine = list_strLines[iPos].split("\t")

            #Skip if commented (e.g. first character of first member is "#")
            if strLine[0][0] == "#":
                continue

            #Transform to upper case
            strLine[0] = strLine[0].upper()

            #Print (field_name, value) pair
            if self.DEBUG:
                print "{0}\t{1}".format(strLine[0], strLine[1])

            #Set values
            if strLine[0] == "FILE_FRAMEWORK_OUTPUT":
                #self.ANASUITEGAIN.openInputFile(strLine[1])
                self.FILE_QC5_RESP_UNI = strLine[1]
            elif strLine[0] == "FILE_CLUSTQ_MEAN":
                self.FILE_CLUSTQ_MEAN = strLine[1]
            elif strLine[0] == "FILE_CLUSTQ_MPV":
                self.FILE_CLUSTQ_MPV = strLine[1]
            elif strLine[0] == "FILE_CLUSTQ_SIGMA":
                self.FILE_CLUSTQ_SIGMA = strLine[1]
            elif strLine[0] == "FILE_CLUSTSIZE":
                self.FILE_MIP_AVG_CLUST_SIZE = strLine[1]
            elif strLine[0] == "FILE_OUTPUT":
                #self.FILE_OUTPUT = strLine[1]
                self.FILE_OUTPUT = TFile(strLine[1], "RECREATE", "", 1)
                self.DIR_CHARGE = self.FILE_OUTPUT.mkdir("ChargeData")
                self.DIR_MAP_EFF = self.FILE_OUTPUT.mkdir("EffMaps")
                #self.DIR_MAP_GAIN=self.FILE_OUTPUT.mkdir("GainMaps")
            elif strLine[0] == "FILE_DUT_MAPPING_GEO":
                self.FILE_MAPPING_DUT = strLine[1]
            elif strLine[0] == "FILE_DUT_MAPPING_VFATPOS2IETAIPHI":
                self.FILE_MAPPING_DUT_VFAT2DET = strLine[1]
            elif strLine[0] == "FILE_DUT_SCURVEDATA":
                self.FILE_SCURVE_DATA = strLine[1]
            elif strLine[0] == "DUT_GAIN_P0":
                self.PARAMS_GAIN_DET_DUT.GAIN_CURVE_P0 = float(strLine[1])
            elif strLine[0] == "DUT_GAIN_P0_ERR":
                self.PARAMS_GAIN_DET_DUT.GAIN_CURVE_P0_ERR = float(strLine[1])
            elif strLine[0] == "DUT_GAIN_P1":
                self.PARAMS_GAIN_DET_DUT.GAIN_CURVE_P1 = float(strLine[1])
            elif strLine[0] == "DUT_GAIN_P1_ERR":
                self.PARAMS_GAIN_DET_DUT.GAIN_CURVE_P1_ERR = float(strLine[1])
            elif strLine[0] == "DUT_IETA_CLUST_SIZE_NORM":
                self.SECTOR_IETA_CLUSTSIZENORM = int(strLine[1])
            elif strLine[0] == "DUT_IETA_QC5_GAIN_CAL":
                self.SECTOR_IETA_QC5 = int(strLine[1])
            elif strLine[0] == "DUT_IPHI_CLUST_SIZE_NORM":
                self.SECTOR_IPHI_CLUSTSIZENORM = int(strLine[1])
            elif strLine[0] == "DUT_IPHI_QC5_GAIN_CAL":
                self.SECTOR_IPHI_QC5 = int(strLine[1])
            elif strLine[0] == "DUT_NUM_SIM_PTS_PER_RO":
                self.NUMSIMPTS_PER_RO = int(strLine[1])
            elif strLine[0] == "DUT_QC5_RESP_UNI_HVPT":
                self.PARAMS_DET_DUT.DET_IMON_QC5_RESP_UNI = float(strLine[1])
            elif strLine[0] == "DUT_SERIAL_NUMBER":
                self.NAME_DET_DUT = strLine[1]
            elif strLine[0] == "DUT_SLICE_GRANULARITY":
                self.ANA_UNI_GRANULARITY = int(strLine[1])
            elif strLine[0] == "DET_CLUSTQ_SERIAL_NUMBER":
                self.NAME_DET_CLUSTQ = strLine[1]
            elif strLine[0] == "DET_CLUSTQ_GAIN_P0":
                self.PARAMS_GAIN_DET_CLUSTQ.GAIN_CURVE_P0 = float(strLine[1])
            elif strLine[0] == "DET_CLUSTQ_GAIN_P0_ERR":
                self.PARAMS_GAIN_DET_CLUSTQ.GAIN_CURVE_P0_ERR = float(
                    strLine[1])
            elif strLine[0] == "DET_CLUSTQ_GAIN_P1":
                self.PARAMS_GAIN_DET_CLUSTQ.GAIN_CURVE_P1 = float(strLine[1])
            elif strLine[0] == "DET_CLUSTQ_GAIN_P1_ERR":
                self.PARAMS_GAIN_DET_CLUSTQ.GAIN_CURVE_P1_ERR = float(
                    strLine[1])
            elif strLine[0] == "DET_CLUSTSIZE_SERIAL_NUMBER":
                self.NAME_DET_CLUSTSIZE = strLine[1]
            elif strLine[0] == "DET_CLUSTSIZE_TF1_TNAME":
                self.TOBJ_NAME_FUNC_AVGCLUSTSIZE = strLine[1]
            elif strLine[0] == "EFF_HVPT_LIST":
                self.LIST_HVPTS = strLine[1].split(",")
            else:
                print "Input Field Name:"
                print strLine[0]
                print "Not recognized, please cross-check input file:"
                print inputfilename

        del list_strLines

        #Declare Cluster Charge Analysis Suite
        self.ANASUITECLUSTQ = AnalysisSuiteClusterCharge(
            file_out=self.FILE_OUTPUT,
            params_gain=self.PARAMS_GAIN_DET_CLUSTQ,
            calcGain=True,
            debug=self.DEBUG)

        #Load the Landau Cluster Charge Data
        if self.DEBUG:
            print "Loading Landau Cluster Charge Data"

        if len(self.FILE_CLUSTQ_MEAN) == 0:
            print "Landau Cluster Charge Mean Filename not found, problem!"
        if len(self.FILE_CLUSTQ_MPV) == 0:
            print "Landau Cluster Charge MPV Filename not found, problem!"
        if len(self.FILE_CLUSTQ_SIGMA) == 0:
            print "Landau Cluster Charge Sigma Filename not found, problem!"

        self.ANASUITECLUSTQ.loadData(
            inputfilename_MEAN=self.FILE_CLUSTQ_MEAN,
            inputfilename_MPV=self.FILE_CLUSTQ_MPV,
            inputfilename_SIGMA=self.FILE_CLUSTQ_SIGMA)

        #Interpolate the Landau Cluster Charge Data
        if self.DEBUG:
            print "Interpolating Landau Cluster Charge Data"

        self.ANASUITECLUSTQ.interpolateData()

        #Declare Gain Map Analysis Suite
        self.PARAMS_DET_DUT.DETPOS_IETA = self.SECTOR_IETA_QC5
        self.PARAMS_DET_DUT.DETPOS_IPHI = self.SECTOR_IPHI_QC5

        if self.DEBUG:
            print "Loading Mapping"

        self.PARAMS_DET_DUT.loadMapping(self.FILE_MAPPING_DUT, self.DEBUG)

        self.ANASUITEGAIN = AnalysisSuiteGainMap(
            file_out=self.FILE_OUTPUT,
            inputfilename=self.FILE_QC5_RESP_UNI,
            #outputfilename=self.FILE_OUTPUT,
            #outputfileoption="RECREATE",
            params_gain=self.PARAMS_GAIN_DET_DUT,
            params_det=self.PARAMS_DET_DUT,
            debug=self.DEBUG)

        #Make the dictionary for OBS vs cluster position histograms
        self.DICT_H_CHON_VS_CLUSTPOS = {}
        self.DICT_H_CLUSTQ_VS_CLUSTPOS = {}
        self.DICT_H_NOISEQ_VS_CLUSTPOS = {}
        self.DICT_H_THRESH_VS_CLUSTPOS = {}
        for etaSector in self.PARAMS_DET_DUT.LIST_DET_GEO_PARAMS:
            iNumBinsX = self.ANA_UNI_GRANULARITY * etaSector.NBCONNECT
            xLower = -0.5 * etaSector.SECTSIZE
            xUpper = 0.5 * etaSector.SECTSIZE

            #Channels On vs cluster position histograms
            h_chOn_vs_clustPos = TH2F(
                "h_iEta{0}_chOn_vs_clustPos".format(etaSector.IETA), "",
                iNumBinsX, xLower, xUpper, 125, 0, 1.25)
            h_chOn_vs_clustPos.SetDirectory(gROOT)
            self.DICT_H_CHON_VS_CLUSTPOS[
                etaSector.SECTPOS] = h_chOn_vs_clustPos

            #Cluster charge vs cluster position histograms
            h_clustQ_vs_clustPos = TH2F(
                "h_iEta{0}_clustQ_vs_clustPos".format(etaSector.IETA), "",
                iNumBinsX, xLower, xUpper, 400, 0, 100)
            h_clustQ_vs_clustPos.SetDirectory(gROOT)
            self.DICT_H_CLUSTQ_VS_CLUSTPOS[
                etaSector.SECTPOS] = h_clustQ_vs_clustPos

            #Noise vs cluster position histograms
            h_noiseQ_vs_clustPos = TH2F(
                "h_iEta{0}_noiseQ_vs_clustPos".format(etaSector.IETA), "",
                iNumBinsX, xLower, xUpper, 100, 0, 10)
            h_noiseQ_vs_clustPos.SetDirectory(gROOT)
            self.DICT_H_NOISEQ_VS_CLUSTPOS[
                etaSector.SECTPOS] = h_noiseQ_vs_clustPos

            #Thresh vs cluster position histograms
            h_thresh_vs_clustPos = TH2F(
                "h_iEta{0}_thresh_vs_clustPos".format(etaSector.IETA), "",
                iNumBinsX, xLower, xUpper, 100, 0, 10)
            h_thresh_vs_clustPos.SetDirectory(gROOT)
            self.DICT_H_THRESH_VS_CLUSTPOS[
                etaSector.SECTPOS] = h_thresh_vs_clustPos

        #Load the MIP average cluster size vs. gain formulat
        fileMIPAvgClustSize = TFile(self.FILE_MIP_AVG_CLUST_SIZE, "READ", "",
                                    1)

        if self.DEBUG:
            print "Loading function for MIP <Clust Size> vs. Gain"

        self.FUNC_AVG_MIP_CLUSTSIZE = fileMIPAvgClustSize.Get(
            self.TOBJ_NAME_FUNC_AVGCLUSTSIZE)

        #Initialize the VFAT noise analysis suite
        self.ANASUITENOISE = AnalysisSuiteVFATNoise(
            detector=self.PARAMS_DET_DUT,
            inputMappingFile=self.FILE_MAPPING_DUT_VFAT2DET,
            inputSCurveFile=self.FILE_SCURVE_DATA,
            convert2fC=True,
            debug=self.DEBUG)

        #Make the Dictionary for Efficiency by Readout Sector
        #Here each value is a tuple average, std. dev, num pts
        self.DICT_EFF_READOUT = {
            key: []
            for key in self.ANASUITENOISE.DICT_MAPPING
        }
        #self.DICT_AVGEFF_READOUT = {}

        #Make the Dictionary for Efficiency TGraphErrs by Readout Sector
        self.DICT_G_EFF_VS_HVPTS_RO = {}
        self.DICT_G_ANASLICE_VS_HVPTS_RO = {}
        self.DICT_G_EFF_VS_GAIN_RO = {}
        for key in self.DICT_EFF_READOUT:
            #Avg Eff +/- Std Dev Eff vs. HVPts
            g_Eff_vs_HVPts = TGraphErrors(len(self.LIST_HVPTS))
            g_Eff_vs_HVPts.SetName("g_iEta{0}iPhi{1}_avgEff_vs_HVPts".format(
                int(key[0]), int(key[1])))
            g_Eff_vs_HVPts.SetTitle("")
            g_Eff_vs_HVPts.SetMarkerStyle(21)
            self.DICT_G_EFF_VS_HVPTS_RO[key] = g_Eff_vs_HVPts

            #Avg Eff +/- Std Dev Eff vs. HVPts
            g_Eff_vs_Gain = TGraphErrors(len(self.LIST_HVPTS))
            g_Eff_vs_Gain.SetName("g_iEta{0}iPhi{1}_avgEff_vs_Gain".format(
                int(key[0]), int(key[1])))
            g_Eff_vs_Gain.SetTitle("")
            g_Eff_vs_Gain.SetMarkerStyle(21)
            self.DICT_G_EFF_VS_GAIN_RO[key] = g_Eff_vs_Gain

            #Number of Slices used for analysis (here a slice is counted if the landau charge interpolation was valid)
            g_AnaSlices_vs_HVPts = TGraph(len(self.LIST_HVPTS))
            g_AnaSlices_vs_HVPts.SetName(
                "g_iEta{0}iPhi{1}_anaSlices_vs_HVPts".format(
                    int(key[0]), int(key[1])))
            g_AnaSlices_vs_HVPts.SetTitle("")
            g_AnaSlices_vs_HVPts.SetMarkerStyle(21)
            self.DICT_G_ANASLICE_VS_HVPTS_RO[key] = g_AnaSlices_vs_HVPts

        #Tell user initialization completed successfully
        #if self.DEBUG:
        print "AnalysisSuiteEfficiencyPredictor::init() - Initialization completed successfully"

        return
Пример #23
0
def test():
    setStyle()
    h2 = TH2F('h2', 'h2;Col;Row', 64, -0.5, 63.5, 128, -0.5, 127.5)
    h2.SetLineColor(920)
    h2C = h2.Clone('h2C')
    valid_list = [(i + 32 * k, j, 0, 1) for i in range(24, 32)
                  for j in range(32) for k in range(3, 4)]
    #     valid_list = [(i+32*k,j,0,1) for i in range(7) for j in range(32) for k in range(4)]
    #     for t in [(i+32*k,j,0,1) for i in range(7) for j in range(32) for k in range(4)]:
    for t in valid_list:
        h2C.Fill(t[1], t[0])

    lt = TLatex()
    cav1 = TCanvas('cav1', 'cav1', 800, 700)
    cav1.Divide(2)
    cav1a = cav1.cd(1)
    h2C.Draw('box')
    htx = h2.Clone('htx')
    htx.Draw("colzsame")
    lt0 = lt.DrawLatexNDC(0.2, 0.95, "empty")
    cav1b = cav1.cd(2)
    h2C.Draw('box')
    htC = h2.Clone('htC')
    htC.Draw("colzsame")
    cav1.cd()
    #     waitRootCmdX()
    #
    figI = 0
    with open('../data/xRay/data_xRayTest_Jul27_1.dat', 'r') as fin1:
        started = False
        date0 = parse('2018-07-27 16:05:33.9')
        date1 = parse('2018-09-11 22:52:35.0')
        #         datax = None
        datax = []
        while True:
            line = fin1.readline()
            if len(line) == 0: break
            if line[0:5] == '#2018':
                #                 print line,
                date = parse(line[1:])
                #                 print date
                started = date0 < date < date1
            elif started:
                #                 print [ord(w) for w in line]
                if datax:
                    print '-->', datax
                    print '===', [ord(w) for w in line[:-1]]
                datax += [ord(w) for w in line[:-1]]
                adds, r = getAddressesN(datax, False)
                if r:
                    print '>>>>', datax
                    print '++++', r
                if adds == [] or adds is None:
                    print '---:', date
                    print datax
                    print
                datax = r
                #                 continue
                bc1.show("OKBLUE", str(date))
                #                 print date
                print adds

                if adds:
                    htx.Reset()
                    for x in adds:
                        #                         if x not in valid_list:
                        #                             print [ord(w) for w in line[:-1]]
                        #                             print adds
                        #                             getAddresses(line[:-1],True)
                        #                             print x
                        #                             return 0
                        #                         h2.Fill(x[1],x[0])
                        htx.Fill(x[1], x[0])
                        htC.Fill(x[1], x[0])
                    lt0.SetText(0.2, 0.95, str(date))
                    cav1a.Modified()
                    cav1b.Modified()
                waitRootCmdX(sDir + sTag + str(figI), autoSave)
                figI += 1

    h2.Draw('colzsame')
    waitRootCmdX()
Пример #24
0
def write_1(var, sample):
    for s in attr:
        if sample == 'qcd':
            color1 = 4
        elif sample == 'ttt':
            color1 = 880 + 1  #400+3
        elif sample == 'ct0':
            color1 = 8  #634
        elif sample == 'ct0p05':
            color1 = 3
        elif sample == 'ct1':
            color1 = 2
        elif sample == 'ct100':
            color1 = 6
        elif sample == 'vbfHToBB':
            color1 = 800 + 10
        elif sample == 'vbfct0p':
            color1 = 3
        elif sample == 'vbfct1p':
            color1 = 860
        elif sample == 'vbfct100p':
            color1 = 1
        elif sample == 'vbfct0p60g':
            color1 = 3
        elif sample == 'vbfct100p60g':
            color1 = 3

        elif sample == 'zhct0p40g':
            color1 = 3

        if s == 'pt':
            h_par = [number_of_bin, 0, 300]
        elif s == 'eta':
            h_par = [number_of_bin, -2.5, 2.5]
        elif s == 'phi':
            h_par = [number_of_bin, -math.pi, math.pi]
        elif s == 'CSV':
            h_par = [number_of_bin, 0, 1]
        elif s == 'chf':
            h_par = [number_of_bin, 0, 1]
        elif s == 'nhf':
            h_par = [number_of_bin, 0, 1]
        elif s == 'phf':
            h_par = [number_of_bin, 0, 1]
        elif s == 'elf':
            h_par = [number_of_bin, 0, 1]
        elif s == 'muf':
            h_par = [number_of_bin, 0, 1]
        elif s == 'chm':
            h_par = [number_of_bin, 0, 100]
        elif s == 'chm':
            h_par = [number_of_bin, 0, 100]
        elif s == 'cm':
            h_par = [number_of_bin, 0, 100]
        elif s == 'nm':
            h_par = [number_of_bin, 0, 100]
        elif s == 'dR_q1':
            h_par = [number_of_bin, -1.1, 3 * math.pi]
        elif s == 'dR_q2':
            h_par = [number_of_bin, -1.1, 3 * math.pi]
        elif s == 'dR_q3':
            h_par = [number_of_bin, -1.1, 3 * math.pi]
        elif s == 'dR_q4':
            h_par = [number_of_bin, -1.1, 3 * math.pi]

        elif s == 'nPV':
            h_par = [number_of_bin, 0, 80]

        tree[sample] = file_dict[sample].Get('reconstruction;1').Get(
            'tree')  #.Get('ntuple;1').Get('tree')

        if twoD == 0:
            hist[sample][s] = TH1F(sample + s, '; %s; events' % s, h_par[0],
                                   h_par[1], h_par[2])
            #hist_CHS[sample][s] = TH1F(sample+s + 'CHS', '; %s; events' %s , h_par[0], h_par[1], h_par[2])
        elif twoD == 1:
            hist[sample][s] = TH2F(sample + s, '; %s; events' % s, h_par[0],
                                   h_par[1], h_par[2], number_of_bin, 0, 300)
            #hist_CHS[sample][s] = TH2F(sample+s +'CHS', '; %s; events' %s , h_par[0], h_par[1], h_par[2] , number_of_bin, 0, 300)
        print(tree[sample])
        hist[sample][s].Sumw2()
        #hist_CHS[sample][s].Sumw2()

        if twoD == 0:
            #tree[sample].Project(sample+s, var + '.' + s, cutting )
            tree[sample].Project(sample + s, s, cutting)
            #tree[sample].Project(sample+s+'CHS', 'CHS' + var + '.' + s, cutting_CHS )
        elif twoD == 1:
            #tree[sample].Project(sample+s, var + '.' + s + ':' + var + '.' + 'pt', cutting )
            tree[sample].Project(sample + s, s + ':' + var + '.' + 'pt',
                                 cutting)
            #tree[sample].Project(sample+s+'CHS', 'CHS' + var + '.' + s + ':' + var + '.' + 'pt', cutting_CHS )

        if hist[sample][s].Integral(
        ) != 0:  #and hist_CHS[sample][s].Integral() != 0:
            hist[sample][s].Scale(1 / float(hist[sample][s].Integral()))
            #hist_CHS[sample][s].Scale(1/float(hist_CHS[sample][s].Integral()))
        else:
            print("zero denominator!")
        entr = tree[sample].GetEntries(cutting)
        hist[sample][s].SetLineColor(color1)
        hist[sample][s].SetLineWidth(3)
        hist[sample][s].SetTitle(
            'cut: ' + cutting.replace('(', '_').replace(')', '_').replace(
                '&&', ',').replace('Jet', 'J').replace('GenBquark', 'GBQ') +
            '[entries:' + str(entr) + ']')
        #hist_CHS[sample][s].SetLineColor(color1+44)
        #hist_CHS[sample][s].SetLineWidth(3)

        #hist[sample][s].SetTitleSize(0.4,'t')
        #hist[sample][s].GetYaxis().SetTitleOffset(1.6)
        if s == 'elf':
            hist[sample][s].SetAxisRange(0., 0.02, "Y")
            #hist_CHS[sample][s].SetAxisRange(0., 0.02,"Y")
        elif s == 'muf':
            hist[sample][s].SetAxisRange(0., 0.02, "Y")
            #hist_CHS[sample][s].SetAxisRange(0., 0.02,"Y")
        print(hist[sample][s].GetEntries())
Пример #25
0
# Trick for docker install to run headless
# and never use plt.show() 
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt 

from scipy.optimize import minimize 

from array import array 
from ROOT import (TH1F, TH2F, TH1D, TF1, TFile, TCanvas,
                  gPad, gStyle, TLatex, TGraphErrors, TLine,
                  kGray, kRed, kBlue, kBlack)

default_histo = TH1F('default', '', 100, 0, 1)
default_histo2d = TH2F('default', '', 100, 0, 1, 100, 0, 1)

def load_histos(file):
    ''' Use the ROOT file structure to load a dictionary of histograms. '''
    h = {}
    for k in file.GetListOfKeys():
        h[k.GetName()] = file.Get(k.GetName())
    return h

def numpify(histo):
    """ TH1F to np.arrays. """

    if type(histo) not in [TH1F, TH1D]:
        raise NotImplementedError('Can not numpify type {}'.format(type(histo)))

    nbins = histo.GetNbinsX()
leg.Draw()
c.Print(remainder[0] + ".pdf", "Title:data_1d")

radfracHist_10 = radHist_10.Clone("radfrac_10mrad")
radfracHist_10.SetLineColor(1)
radfracHist_10.SetTitle("Radiative fraction (10mrad)")
radfracHist_10.GetXaxis().SetTitle("pair invariant mass [GeV]")
radfracHist_10.GetYaxis().SetTitle("radiative fraction")
radfracHist_10.Divide(totalHist_10)
radfracHist_10.Draw()
radfracHist_10.GetXaxis().SetRangeUser(0, 0.17)
radfracHist_10.GetYaxis().SetRangeUser(0, 0.5)
radfracHist_10.Fit("pol3", "", "", 0.027, 0.18)
c.Print(remainder[0] + ".pdf", "Title:data_1d")

radFracAt40 = TH2F("radFracAt40", "RadFrac vs. theta cut (40 MeV)", 9, 1, 10,
                   10, 0.065, 0.1)
radFracAt50 = TH2F("radFracAt50", "RadFrac vs. theta cut (50 MeV)", 9, 1, 10,
                   10, 0.065, 0.1)
radFracAt60 = TH2F("radFracAt60", "RadFrac vs. theta cut (60 MeV)", 9, 1, 10,
                   10, 0.065, 0.1)
radFracAt70 = TH2F("radFracAt70", "RadFrac vs. theta cut (70 MeV)", 9, 1, 10,
                   10, 0.065, 0.1)
radFracAt80 = TH2F("radFracAt80", "RadFrac vs. theta cut (80 MeV)", 9, 1, 10,
                   10, 0.065, 0.1)
radFracAt90 = TH2F("radFracAt90", "RadFrac vs. theta cut (90 MeV)", 9, 1, 10,
                   10, 0.065, 0.1)
radFracAt100 = TH2F("radFracAt100", "RadFrac vs. theta cut (100 MeV)", 9, 1,
                    10, 10, 0.065, 0.1)
radFracAt110 = TH2F("radFracAt110", "RadFrac vs. theta cut (110 MeV)", 9, 1,
                    10, 10, 0.065, 0.1)
radFracAt120 = TH2F("radFracAt120", "RadFrac vs. theta cut (120 MeV)", 9, 1,
Пример #27
0
    # -------- Fill dictionaries with function AnalyseThresholdScan() in functions.pyc

    DIC_AnalyseThresholdScan = AnalyseThresholdScan(FileDataThrScan)

    TDAC_value_dic = DIC_AnalyseThresholdScan[0]
    Threshold_value_dic = DIC_AnalyseThresholdScan[1]
    Sigma_value_dic = DIC_AnalyseThresholdScan[2]
    Chi2_value_dic = DIC_AnalyseThresholdScan[3]
    Scurve_plot_dic = DIC_AnalyseThresholdScan[4]
    Data_pointsX_dic = DIC_AnalyseThresholdScan[5]
    Data_pointsY_dic = DIC_AnalyseThresholdScan[6]

    # -------- Set histograms and fitting function

    myfit = TF1("myfit", "[0]+0.5*TMath::Erf([1]*([2]+x))", -1., 3000.)
    TDAC2D = TH2F("TDAC2D", "TDAC 2D plot;#Row;#Column;Threshold [e]", 24, 0,
                  24, 36, 12, 48)
    TDAC1D = TH1F("TDACDist", "TDAC distribution;Threshold [e];nb of pixels",
                  16, 0, 16)
    thresh2D = TH2F("thresh2D", "Threshold 2D plot;#Row;#Column;Threshold [e]",
                    24, 0, 24, 36, 12, 48)
    thresh1D = TH1F("threshDist",
                    "Threshold distribution;Threshold [e];nb of pixels", 300,
                    -.1, 4000)
    sigma2D = TH2F("sigma2D", "Sigma 2D plot;#Row;#Column;Sigma [e]", 24, 0,
                   24, 36, 12, 48)
    sigma1D = TH1F("sigmaDist", "Sigma distribution;Sigma [e];nb of pixels",
                   300, -.1, 500)
    chi2_1D = TH1F("chi2Dist", "Chi2 distribution; ;nb of pixels", 300, 0, 1)
    chi2_2D = TH2F("chi2_2D", "Chi2 2D plot;#Row;#Column;chi2", 24, 0, 24, 36,
                   12, 48)
    correlation = TH2F("correlation", "Threshold vs TDAC;TDAC;Threshold [e]",
inputfile = "/eos/uscms/store/user/cmstestbeam/2019_04_April_CMSTiming/KeySightScope/RecoData/TimingDAQRECO/RecoWithTracks/v6_CACTUSSkim/Completed/Data_CACTUSDigital_TimingOptimized_HighTreshold_16492-16516.root"
#inputfile = "/eos/uscms/store/user/cmstestbeam/2019_04_April_CMSTiming/KeySightScope/RecoData/TimingDAQRECO/RecoWithTracks/v6_CACTUSSkim/Completed/Data_CACTUSDigital_TimingOptimized_LowThreshold_16517-16711.root"

if not os.path.exists(inputfile):
    print "input file " + inputfile + " does not exist"
    exit()

file = TFile(inputfile)
tree = file.Get("pulse")

#c = TCanvas("cv","cv",800,800)

##########################
#2D Efficiency
##########################
den = TH2F("den", ";x;y", 20, 19, 21, 20, 23, 25)
num = TH2F("num", ";x;y", 20, 19, 21, 20, 23, 25)
tree.Draw("y_dut[2]:x_dut[2]>>den",
          "ntracks==1 && y_dut[0] > 0 && npix>0 && nback>0", "colz")
tree.Draw("y_dut[2]:x_dut[2]>>num",
          "ntracks==1 && y_dut[0] > 0 && npix>0 && nback>0 && amp[3] > 200 ",
          "colz")

EfficiencyUtils.Plot2DEfficiency(num, den, "CACTUSEfficiencyVsXY",
                                 "CACTUS Pixel (5,3) Digital", "X [mm]", 19.0,
                                 21.0, "Y [mm]", 23.0, 25.0, -0.001, 0.20)

##########################
#1D Efficiency Vs X
##########################
Пример #29
0
def analysis(
    hadron="Lambda_c",
    collision="pp14p0",
    yrange="absy3p0",
    brmode="central",
    model="Pyhia8mode2",
    use_unnorm=1,
):
    gStyle.SetOptStat(0)
    with open(r"databases/significance.yaml") as filesignificance:
        paramsignificance = yaml.safe_load(filesignificance)
    ymin = paramsignificance[hadron][collision][yrange]["ymin"]
    ymax = paramsignificance[hadron][collision][yrange]["ymax"]
    # bin of the final analysis, has to be the binning of efficiency, bkg histos
    binanal = array("d",
                    paramsignificance[hadron][collision][yrange]["binning"])
    nfileyieldth = paramsignificance[hadron][collision][yrange]["theoryfile"]

    nfileeff = paramsignificance[hadron][collision][yrange]["efffile"]
    nhistoeff = paramsignificance[hadron][collision][yrange]["histoeff"]
    nfilebkg = paramsignificance[hadron][collision][yrange]["bkgfile"]
    nhistobkg = paramsignificance[hadron][collision][yrange]["histobkg"]
    nhistoyieldth = paramsignificance[hadron][collision][yrange]["histoyield"]
    nhistoyieldth_norm = paramsignificance[hadron][collision][yrange][
        "histoyield_norm"]

    with open(r"databases/general.yaml") as fileparamgen:
        paramgen = yaml.safe_load(fileparamgen)
    with open(r"databases/theory_yields.yaml") as fileyields:
        paramyields = yaml.safe_load(fileyields)

    textcollision = paramgen["text_string"][collision]
    textrapid = paramgen["text_string"][yrange]
    textmodel = paramgen["text_string"][model]

    sigma_aa_b = paramgen["statistics"][collision]["sigmaAA_b"]
    lumiaa_monthi_invnb = paramgen["statistics"][collision][
        "lumiAA_monthi_invnb"]
    nevt = sigma_aa_b * lumiaa_monthi_invnb * 1e9
    # nevt = 2.*1e9
    bratio = paramgen["branchingratio"][hadron][brmode]
    decaychannel = paramgen["latexparticle"][hadron]

    if hadron == "Chi_c" and yrange == "absy1p44":
        bratio *= 0.8  # chi_c1 and chi_c2 are measured together: non-weighted average of their BRs
        decaychannel = "#chi_{c} #rightarrow J/#psi #gamma"

    yieldmid = paramyields[model][collision][yrange][hadron]
    text = "%s, N_{ev} = %f 10^{9}" % (textmodel, (float)(nevt) / 1.0e9)
    text_a = "%s, %s, BR=%.2f%%" % (decaychannel, textrapid, bratio * 100)
    text_b = "ALICE3 projection, with IRIS, no PID, %s" % textcollision
    fileeff = TFile(nfileeff)
    histoeff = fileeff.Get(nhistoeff)
    filebkg = TFile(nfilebkg)
    hbkgperevent = filebkg.Get(nhistobkg)

    fileyieldth = TFile(nfileyieldth)
    histoyieldth = None

    if use_unnorm == 1:
        histodndptth = fileyieldth.Get(nhistoyieldth)
        histodndptth.Scale(
            1.0 / 70000.0)  # TEMPORARY this is a fix to account for the
        # conversion from a cross-section in mub
        # to yields, sigma=70000 mub
    else:
        histodndptth = fileyieldth.Get(nhistoyieldth_norm)
        integral = 0
        for ibin in range(histodndptth.GetNbinsX()):
            binwdith = histodndptth.GetBinWidth(ibin + 1)
            integral += histodndptth.GetBinContent(ibin + 1) * binwdith
        histodndptth.Scale(1.0 / integral)
        histodndptth.Scale(yieldmid)
        print("yieldmid = %f\n", yieldmid)
        integral = 0
        for ibin in range(histodndptth.GetNbinsX()):
            binwdith = histodndptth.GetBinWidth(ibin + 1)
            integral += histodndptth.GetBinContent(ibin + 1) * binwdith
        print("yieldmid = %f\n", yieldmid)

    if hadron == "Chi_c" and collision == "pp14p0":
        print("scaling signal yield by 0.1")
        histodndptth.Scale(0.1)  # because pythia8 is wrong by a factor ~10

    if hadron == "Chi_c" and yrange == "absy1p44":
        print("scaling bkg by 2*2, and signal by 3.4")
        hbkgperevent.Scale(
            2
        )  # to take approximately into account the worsening of the sig/bkg in the full
        # rapidity range (PbWO4 and W+Sci)
        hbkgperevent.Scale(
            2
        )  # because in |y| < 1.44 we sum chi_c1 and chi_c2 (states are not resolved)
        histodndptth.Scale(
            3.4
        )  # because in |y| < 1.44 we sum chi_c1 and chi_c2 (states are not resolved).
        # Assuming chi_c2/chi_c1 (!!) from Pythia8

    if hadron == "Chi_c" and yrange == "absy0p33":
        print("scaling signal and bkg by 0.23, from |y| < 1.44 to |y| < 0.33")
        hbkgperevent.Scale(
            0.23
        )  # to take into account the reduction of the statistics from |y| < 1.44 to |y| < 0.33
        # (the input file for chi_c is always |y| < 1.44)
        histodndptth.Scale(
            0.23
        )  # to take into account the reduction of the statistics from |y| < 1.44 to |y| < 0.33
        # (the input file for chi_c is always |y| < 1.44)

    histoyieldth = histodndptth.Clone("histoyieldth")

    for ibin in range(histoyieldth.GetNbinsX()):
        binwdith = histoyieldth.GetBinWidth(ibin + 1)
        yieldperevent = histoyieldth.GetBinContent(ibin +
                                                   1) * binwdith * bratio
        histoyieldth.SetBinContent(ibin + 1, yieldperevent)
        histoyieldth.SetBinError(ibin + 1, 0.0)
    histoyieldth = histoyieldth.Rebin(
        len(binanal) - 1, "histoyieldth", binanal)
    histosignfperevent = histoyieldth.Clone("histosignfperevent")
    histosignf = histoyieldth.Clone("histosignf")
    histosigoverbkg = histoyieldth.Clone("histosigoverbkg")

    canvas = TCanvas("canvas", "A Simple Graph Example", 881, 176, 668, 616)
    gStyle.SetOptStat(0)
    canvas.SetHighLightColor(2)
    canvas.Range(-1.25, -4.625, 11.25, 11.625)
    canvas.SetFillColor(0)
    canvas.SetBorderMode(0)
    canvas.SetBorderSize(2)
    canvas.SetLogy()
    canvas.SetFrameBorderMode(0)
    canvas.SetFrameBorderMode(0)
    canvas.cd()
    gPad.SetLogy()

    hempty = TH2F(
        "hempty",
        ";p_{T} (GeV/c); Significance(3#sigma)",
        100,
        0.0,
        10.0,
        100,
        ymin,
        ymax,
    )
    hempty.GetXaxis().SetTitle("p_{T} (GeV/c)")
    hempty.GetXaxis().SetLabelFont(42)
    hempty.GetXaxis().SetTitleOffset(1)
    hempty.GetXaxis().SetTitleFont(42)
    hempty.GetYaxis().SetLabelFont(42)
    hempty.GetYaxis().SetTitleOffset(1.35)
    hempty.GetYaxis().SetTitleFont(42)
    hempty.GetZaxis().SetLabelFont(42)
    hempty.GetZaxis().SetTitleOffset(1)
    hempty.GetZaxis().SetTitleFont(42)
    hempty.Draw()

    histosignf = histosignfperevent.Clone("histosignf")
    for ibin in range(histoyieldth.GetNbinsX()):
        yieldperevent = histoyieldth.GetBinContent(ibin + 1)
        bkgperevent = hbkgperevent.GetBinContent(ibin + 1)
        eff = histoeff.GetBinContent(ibin + 1)
        signalperevent = eff * yieldperevent
        significanceperevent = 0
        if bkgperevent > 0:
            significanceperevent = signalperevent / sqrt(signalperevent +
                                                         bkgperevent)
        signaloverbkg = 0
        if bkgperevent > 0:
            signaloverbkg = signalperevent / bkgperevent
        histosignfperevent.SetBinContent(ibin + 1, significanceperevent)
        histosignfperevent.SetBinError(ibin + 1, 0.0)
        histosignf.SetBinContent(ibin + 1, significanceperevent * sqrt(nevt))
        histosignf.SetBinError(ibin + 1, 0.0)
        histosigoverbkg.SetBinContent(ibin + 1, signaloverbkg)
        histosigoverbkg.SetBinError(ibin + 1, 0.0)

    histosignfperevent.SetLineColor(1)
    histosignfperevent.SetMarkerColor(1)
    histosignfperevent.SetLineWidth(1)
    histosignf.SetLineColor(1)
    histosignf.SetMarkerColor(1)
    histosignf.SetLineWidth(2)
    histosignf.Draw("same")
    t_b = TLatex()
    t_b.SetNDC()
    t_b.SetTextFont(42)
    t_b.SetTextColor(1)
    t_b.SetTextSize(0.035)
    t_b.SetTextAlign(12)
    t_b.DrawLatex(0.2, 0.85, text_b)
    t_c = TLatex()
    t_c.SetNDC()
    t_c.SetTextFont(42)
    t_c.SetTextColor(1)
    t_c.SetTextSize(0.03)
    t_c.SetTextAlign(12)
    t_c.DrawLatex(0.2, 0.80, text)
    t_a = TLatex()
    t_a.SetNDC()
    t_a.SetTextFont(42)
    t_a.SetTextColor(1)
    t_a.SetTextSize(0.035)
    t_a.SetTextAlign(12)
    t_a.DrawLatex(0.2, 0.75, text_a)
    canvas.SaveAs(hadron + "_" + collision + "_" + yrange + "_results.pdf")
    canvas.SaveAs(hadron + "_" + collision + "_" + yrange + "_results.C")

    foutput = TFile(
        "foutput" + hadron + "_" + collision + "_" + yrange + ".root",
        "recreate")
    foutput.cd()
    histoeff.Write()
    hbkgperevent.Write()
    histosignfperevent.Write()
    histoyieldth.Write()
    histosignf.Write()
    histodndptth.Write()
    histosigoverbkg.Write()
from ROOT import TCanvas, TFile, TProfile, TNtuple, TH1F, TH2F from ROOT import gROOT, gBenchmark, gRandom, gSystem, Double
# Create a new canvas, and customize it.
c1 = TCanvas( 'c1', 'Dynamic Filling Example', 200, 10, 700, 500 ) c1.SetFillColor( 42 ) c1.GetFrame().SetFillColor( 21 ) 
c1.GetFrame().SetBorderSize( 6 ) c1.GetFrame().SetBorderMode( -1 )
# Create a new ROOT binary machine independent file. Note that this file may contain any kind of ROOT objects, histograms, 
# pictures, graphics objects, detector geometries, tracks, events, etc.. This file is now becoming the current directory.
hfile = gROOT.FindObject( 'py-hsimple.root' ) if hfile:
   hfile.Close() hfile = TFile( 'py-hsimple.root', 'RECREATE', 'Demo ROOT file with histograms' )
# Create some histograms, a profile histogram and an ntuple
hpx = TH1F( 'hpx', 'This is the px distribution', 100, -4, 4 ) hpxpy = TH2F( 'hpxpy', 'py vs px', 40, -4, 4, 40, -4, 4 ) hprof = 
TProfile( 'hprof', 'Profile of pz versus px', 100, -4, 4, 0, 20 ) ntuple = TNtuple( 'ntuple', 'Demo ntuple', 'px:py:pz:random:i' )
# Set canvas/frame attributes.
hpx.SetFillColor( 48 ) gBenchmark.Start( 'hsimple' )
# Initialize random number generator.
gRandom.SetSeed() rannor, rndm = gRandom.Rannor, gRandom.Rndm
# For speed, bind and cache the Fill member functions,
histos = [ 'hpx', 'hpxpy', 'hprof', 'ntuple' ] for name in histos:
   exec('%sFill = %s.Fill' % (name,name))
# Fill histograms randomly.
px, py = Double(), Double() kUPDATE = 1000 for i in range( 25000 ):
 # Generate random values.
   rannor( px, py )
   pz = px*px + py*py
   random = rndm(1)
 # Fill histograms.
   hpx.Fill( px )
   hpxpy.Fill( px, py )
   hprof.Fill( px, pz )
   ntuple.Fill( px, py, pz, random, i )
 # Update display every kUPDATE events.
   if i and i%kUPDATE == 0: