Beispiel #1
0
 def secondaryVarPlot(self,var,range):
     gr = ROOT.TGraphErrors(len(_xpos)-1 if "amplitude" in var else len(_xpos))
     gr.SetTitle("")
     point=0
     for run,xpos in _xpos.iteritems():
         if run==206 and "amplitude" in var: continue # saturation: too close to cathode
         cut = "nPeaks==2 && run==%d" % run
         if ROOT.gROOT.FindObject("h_dt") != None: ROOT.gROOT.FindObject("h_dt").Delete()
         self.tree.Draw('{var}>>h_dt(100,{min},{max})'.format(var=var,min=range[0],max=range[1]),cut)
         h_dt=ROOT.gROOT.FindObject("h_dt")
         mean,rms = h_dt.GetMean(),h_dt.GetMeanError()
         gr.SetPoint(point,xpos,mean)
         gr.SetPointError(point,0,rms)
         point +=1
     customROOTstyle()
     c1 = ROOT.TCanvas("dist_canvas","dist",600,600)
     ROOT.gStyle.SetOptFit(11111)
     gr.SetMarkerStyle(21)
     gr.SetMarkerSize(0.4)
     gr.Draw("APE")
     gr.GetXaxis().SetTitle("x position [cm]")
     gr.GetYaxis().SetTitle(range[2])
     gr.Fit("pol1")
     gr.Draw("APE")
     for ext in self.options.printPlots.split(','):
         plotname=var.replace("[",""); plotname=plotname.replace("]","")
         plotname=plotname.replace("(",""); plotname=plotname.replace(")","");
         plotname=plotname.replace("/","_over_")
         c1.Print('%s.%s'%(plotname,ext))
    def do2dDiff(self,doEB):
        part = 'eb' if doEB else 'ee'
        customROOTstyle()
        refData = self.parseDic(self._allData["ref"])
        newData = self.parseDic(self._allData["current"])
        histos = {}
        if doEB: histos['eb'] = []
        else: 
            histos['eeplus'] = []
            histos['eeminus'] = []
        for s in range(12): 
            if doEB:
                h = rt.TProfile2D(('%s_diff_2d_sample%d' % (part,s)),"",360,1,360,170,-85,85)
                h.GetXaxis().SetTitle('i#phi')
                h.GetYaxis().SetTitle('i#eta')
                h.SetTitle('sample_{%d}^{new}-sample_{%d}^{ref}' % (s,s))
                h.GetZaxis().SetRangeUser(-0.01,0.01)
                histos['eb'].append(h)
            else: 
                hplus = rt.TProfile2D(('%s_plus_diff_2d_sample%d' % (part,s)),"",100,1,100,100,1,100)
                hplus.GetXaxis().SetTitle('ix')
                hplus.GetYaxis().SetTitle('iy')
                hplus.SetTitle('sample_{%d}^{new}-sample_{%d}^{ref}' % (s,s))
                hplus.GetZaxis().SetRangeUser(-0.01,0.01)
                histos['eeplus'].append(hplus)
                hminus = hplus.Clone('%s_minus_diff_2d_sample%d' % (part,s))
                histos['eeminus'].append(hminus)

        detids = EcalDetId('/afs/cern.ch/work/e/emanuele/public/ecal/pulseshapes_db/detids_ECAL.txt')

        for (partition,detid),samples in refData.iteritems():
            key = (partition,detid)
            (x,y,z) = detids.xyz(detid)

            if key not in newData: continue
            if ((doEB and int(partition)==0) or (not doEB and int(partition)==1)): continue
            if z==-999: continue
            if z==0: htofill = histos['eb']
            elif z==1: htofill = histos['eeplus']
            else: htofill = histos['eeminus']
            (ix,iy) = (y,x) if doEB else (x+1,y+1)
            for s in range(12):
                htofill[s].Fill(ix,iy,float((newData[key])[s])-float((refData[key])[s]))

        xsize = 1200
        ysize = int(xsize*170/360+0.1*xsize) if doEB else int(xsize*0.9)
        canv = rt.TCanvas("c","",xsize,ysize)

        for k,v in histos.iteritems():
            for s in range(12):
                #(histos[k])[s].Draw("colz")
                #canv.SaveAs('%s_diff_2d_sample%d.pdf' % (k,s))
                self.printOnePlot( (histos[k])[s], canv, '%s_diff_2d_sample%d' % (k,s) )
    def do2dDiff(self,doEB):
        part = 'eb' if doEB else 'ee'
        customROOTstyle()
        refData = self.parseDic(self._allData["ref"])
        newData = self.parseDic(self._allData["current"])
        histos = {}
        if doEB: histos['eb'] = []
        else: 
            histos['eeplus'] = []
            histos['eeminus'] = []
        for s in range(12): 
            if doEB: 
                h = rt.TProfile2D(('%s_diff_2d_sample%d' % (part,s)),"",360,1,360,170,-85,85)
                h.GetXaxis().SetTitle('i#phi')
                h.GetYaxis().SetTitle('i#eta')
                h.SetTitle('sample_{%d}^{new}-sample_{%d}^{ref}' % (s,s))
                h.GetZaxis().SetRangeUser(-0.03,0.03)
                histos['eb'].append(h)
            else: 
                hplus = rt.TProfile2D(('%s_plus_diff_2d_sample%d' % (part,s)),"",100,1,100,100,1,100)
                hplus.GetXaxis().SetTitle('ix')
                hplus.GetYaxis().SetTitle('iy')
                hplus.SetTitle('sample_{%d}^{new}-sample_{%d}^{ref}' % (s,s))
                hplus.GetZaxis().SetRangeUser(-0.03,0.03)
                histos['eeplus'].append(hplus)
                hminus = hplus.Clone('%s_minus_diff_2d_sample%d' % (part,s))
                histos['eeminus'].append(hminus)

        detids = EcalDetId('/afs/cern.ch/work/e/emanuele/public/ecal/pulseshapes_db/detids_ECAL.txt')

        for (partition,detid),samples in refData.iteritems():
            key = (partition,detid)
            (x,y,z) = detids.xyz(detid)

            if key not in newData: continue
            if ((doEB and int(partition)==0) or (not doEB and int(partition)==1)): continue
            if z==-999: continue
            if z==0: htofill = histos['eb']
            elif z==1: htofill = histos['eeplus']
            else: htofill = histos['eeminus']
            (ix,iy) = (y,x) if doEB else (x,y)
            for s in range(12):
                htofill[s].Fill(ix,iy,float((newData[key])[s])-float((refData[key])[s]))

        xsize = 1200
        ysize = int(xsize*170/360+0.1*xsize) if doEB else int(xsize*0.9)
        canv = rt.TCanvas("c","",xsize,ysize)
        for k,v in histos.iteritems():
            for s in range(12):
                #(histos[k])[s].Draw("colz")
                #canv.SaveAs('%s_diff_2d_sample%d.pdf' % (k,s))
                self.printOnePlot( (histos[k])[s], canv, '%s_diff_2d_sample%d' % (k,s) )
Beispiel #4
0
    def compareIC2D(self,data2,partition,zwidth=0.07,outdirname=''):
        #rt.gStyle.SetOptStat(0)
        customROOTstyle()
        plots = []

        if partition=='EcalBarrel': 
            h = rt.TProfile2D(('%s_%s_icratio_2d' % (self.name,partition)), '',360,1,360,170,-85,85)
            h.GetXaxis().SetTitle('i#phi')
            h.GetYaxis().SetTitle('i#eta')
        else: 
            h = rt.TProfile2D(('%s_%s_icratio_2d' % (self.name,partition)), '',100,1,100,100,1,100)
            h.GetXaxis().SetTitle('ix')
            h.GetYaxis().SetTitle('iy')

        zmin=1-zwidth; zmax=1+zwidth
        if partition=='EcalBarrel': 
            h1d = rt.TH1D(str(h.GetName()).replace('icratio_2d','icratio_1d'),'',200,zmin,zmax)
        else: 
            h1d = rt.TH1D(str(h.GetName()).replace('icratio_2d','icratio_1d'),'',200,zmin,zmax)
            
        h1d.GetXaxis().SetTitle('IC ratio')
        h1d.SetLineColor(rt.kRed)

        for k,v in self.data.iteritems():
            if k.subdet() != partition: continue
            if k not in data2: continue
            icref = data2[k]
            if(v.staterr < 999): 
                h.Fill(k.y,k.x,max(zmin,min(zmax,v.val/icref.val)))
                h1d.Fill(v.val/icref.val)
            
        h.GetZaxis().SetRangeUser(zmin,zmax)
        
        plots.append(h)

        for p in plots:
            xsize = ysize = 1200
            if p.GetDimension()==2: ysize = int(xsize*170/360+0.1*xsize) if 'EcalBarrel' in h.GetName() else int(xsize*0.9)
            canv = rt.TCanvas("c","",xsize,ysize)
            if p.GetDimension()==2: p.Draw("colz")
            else: p.Draw()
            if outdirname == '':
                canv.SaveAs('%s.pdf' % p.GetName())
                canv.SaveAs('%s.png' % p.GetName())
            else:
                canv.SaveAs('%s/%s.pdf' % (outdirname, p.GetName()))
                canv.SaveAs('%s/%s.png' % (outdirname, p.GetName()))
 def plot(self,saveName,doWide=False,extensions="pdf"):
     plotformat = (1200,600) if doWide else (600,600)
     sf = 20./plotformat[0]
     height=plotformat[1]
     ROOT.gStyle.SetPadLeftMargin(600.*0.18/plotformat[0])
     ROOT.gStyle.SetPaperSize(20.,sf*plotformat[1])
     customROOTstyle()
     c1 = ROOT.TCanvas(saveName+"_canvas",saveName,plotformat[0],height)
     g = self.getPulse(self.options.ngroup)
     colors = {"calorimeter":ROOT.kRed, "PMT":ROOT.kBlue} 
     g.SetLineColor(colors[self.channel])
     g.Draw("AL")
     g.GetXaxis().SetTitle("time (ns)")
     g.GetYaxis().SetTitle("Amplitude %s (V)" % self.channel)
     g.Draw("L")
     for ext in extensions.split(","):
         c1.Print("%s_%s.%s"%(saveName,self.channel,ext))
Beispiel #6
0
    def compareIC2D(self,data2,partition,zwidth=0.07):
        #rt.gStyle.SetOptStat(0)
        customROOTstyle()
        plots = []

        if partition=='EcalBarrel': 
            h = rt.TProfile2D(('%s_%s_icratio_2d' % (self.name,partition)), '',360,1,360,170,-85,85)
            h.GetXaxis().SetTitle('i#phi')
            h.GetYaxis().SetTitle('i#eta')
        else: 
            h = rt.TProfile2D(('%s_%s_icratio_2d' % (self.name,partition)), '',100,1,100,100,1,100)
            h.GetXaxis().SetTitle('ix')
            h.GetYaxis().SetTitle('iy')

        zmin=1-zwidth; zmax=1+zwidth
        if partition=='EcalBarrel': 
            h1d = rt.TH1D(str(h.GetName()).replace('icratio_2d','icratio_1d'),'',200,zmin,zmax)
        else: 
            h1d = rt.TH1D(str(h.GetName()).replace('icratio_2d','icratio_1d'),'',200,zmin,zmax)
            
        h1d.GetXaxis().SetTitle('IC ratio')
        h1d.SetLineColor(rt.kRed)

        for k,v in self.data.iteritems():
            if k.subdet() != partition: continue
            if k not in data2: continue
            icref = data2[k]
            if(v.staterr < 999): 
                h.Fill(k.y,k.x,max(zmin,min(zmax,v.val/icref.val)))
                h1d.Fill(v.val/icref.val)
            
        h.GetZaxis().SetRangeUser(zmin,zmax)
        
        plots.append(h)

        for p in plots:
            xsize = ysize = 1200
            if p.GetDimension()==2: ysize = int(xsize*170/360+0.1*xsize) if 'EcalBarrel' in h.GetName() else int(xsize*0.9)
            canv = rt.TCanvas("c","",xsize,ysize)
            if p.GetDimension()==2: p.Draw("colz")
            else: p.Draw()
            canv.SaveAs('%s.pdf' % p.GetName())
            canv.SaveAs('%s.png' % p.GetName())
 def pulseComp(self,detid,pulse,pulseRef):
     customROOTstyle()
     hpulse = rt.TH1F("hpulse","",15,0,15)
     hpulseref = hpulse.Clone("hpulseref")
     # fill the template and fit it
     for s in range(3):  
         hpulse.SetBinContent(s+1,0)
         hpulseref.SetBinContent(s+1,0)
     for s in range(12): 
         hpulse.SetBinContent(s+4,float(pulse[s]))
         hpulseref.SetBinContent(s+4,float(pulseRef[s]))
     canvas = rt.TCanvas("c","",600,600)
     hpulseref.SetLineColor(rt.kBlue+2)
     hpulse.SetMarkerStyle(rt.kFullCircle)
     hpulseref.GetXaxis().SetTitle("sample")
     hpulseref.GetYaxis().SetTitle("a.u.")
     hpulseref.Draw("hist")
     hpulse.Draw("same p")
     fdir = self._options.printDir
     plots = [hpulse,hpulseref]; labels=['new','ref']; styles=['p','l']
     leg = doLegend(plots,labels,styles)
     leg.Draw()
     for ext in self._options.printPlots.split(","):
         canvas.Print("%s/pulse_id%s.%s" % (fdir,detid,ext))
        rt.gPad.SaveAs("time1d_iz%d.pdf" % k)

        pfy = p.ProfileY()
        axtitle = 'i#eta' if k==0 else 'iy'
        pfy.GetXaxis().SetTitle(axtitle)
        pfx.GetYaxis().SetTitle("Time (ns)")
        #pfx.GetYaxis().SetRangeUser(0,0.5)
        pfy.Draw()
        rt.gPad.SaveAs("time_vsiy_iz%d.pdf" % k)

if __name__ == "__main__":
    from optparse import OptionParser
    parser = OptionParser(usage="%prog [options] filewithhists.root")
    parser.add_option("--iz", dest="iz",  type="string", default="", help="iz to plot (0,-1,1)")
    (options, args) = parser.parse_args()

    customROOTstyle()
    rt.gROOT.SetBatch(True)
    filename = args[0]

    prof2D = {}

    if options.iz:
        iz=int(options.iz)
        prof2D[iz] = plotTimingMaps(filename,iz)
    else:
        for iz in range(-1,2): prof2D[iz] = plotTimingMaps(filename,iz)

    plotProjection(prof2D)
    def do2dTime(self,currentTimeIC,doEB,newTimeIC=''):
        part = 'EB' if doEB else 'EE'
        customROOTstyle()
        refData = self.parseDic(self._allData["ref"])
        newData = self.parseDic(self._allData["current"])
        of = rt.TFile.Open('%s_timeVals.root' % part,'recreate')
        histos = []
        histosDiff = []
        if doEB: 
            h = rt.TProfile2D(('%s_time' % part),"",360,1,360,170,-85,85)
            h.GetXaxis().SetTitle('i#phi')
            h.GetYaxis().SetTitle('i#eta')
            h.SetTitle('Time (ns)')
            h.GetZaxis().SetRangeUser(-1,1)
            histos.append(h)
            histosDiff.append(h.Clone(('%s_time_diff' % part)))
        else: 
            hplus = rt.TProfile2D(('%splus_time' % part),"",100,1,100,100,1,100)
            hplus.GetXaxis().SetTitle('ix')
            hplus.GetYaxis().SetTitle('iy')
            hplus.SetTitle('Time (ns)')
            hplus.GetZaxis().SetRangeUser(-1,1)
            histos.append(hplus)
            histosDiff.append(hplus.Clone(('%splus_time_diff' % part)))
            hminus = hplus.Clone('%sminus_time' % part)
            histos.append(hminus)
            histosDiff.append(hminus.Clone(('%sminus_time_diff' % part)))

        detids = EcalDetId('/afs/cern.ch/work/e/emanuele/public/ecal/pulseshapes_db/detids_ECAL.txt')

        # load the current time ICs (dump of the tag)
        self.timeICs = self.loadTimeICs(currentTimeIC)
        if len(newTimeIC)>0: newTimeICs = self.loadTimeICs(newTimeIC)

        histo = rt.TH1F("histo","",15,0,15)
        fitter = AlphaBetaFitter( rt.TF1("alphabeta",alphabeta,0,10,5), doEB)
        cryfit = 0
        for (partition,detid),samples in newData.iteritems():
            key = (partition,detid)
            (x,y,z) = detids.xyz(detid)

            if detid not in self.timeICs: continue
            if ((doEB and int(partition)==0) or (not doEB and int(partition)==1)): continue
            if z==0 or z==1: 
                htofill = histos[0]
                hdifftofill = histosDiff[0]
            else: 
                htofill = histos[1]
                hdifftofill = histosDiff[1]
            (ix,iy) = (y,x) if doEB else (x,y)

            # fill the template and fit it
            for s in range(3):  histo.SetBinContent(s+1,0)
            for s in range(12): histo.SetBinContent(s+4,float((newData[key])[s]))
            # results = fitter.fit(histo,doEB,('pulse_%d_%d_%d.png' % (x,y,z)))
            results = fitter.fit(histo,doEB)
            currentCorr = float(self.timeICs[detid]) + self.timeOffsets[part]
            time = 25.*((results['pars'])[2]-5.5)
            correctedTime = time + currentCorr
            # print "detid = ",key," has time from fit [IC] = ",time, " [",currentCorr,"]"
            htofill.Fill(ix,iy,correctedTime)

            if len(newTimeIC)>0: 
                if detid not in newTimeICs: continue
                newCorr = float(newTimeICs[detid])
                # print '    correctedTime = ',correctedTime,"   newCorr = ",newCorr,"  diff = ", correctedTime - newCorr
                hdifftofill.Fill(ix,iy,correctedTime - newCorr)

            if cryfit % 1000 == 0: print 'fitted ',cryfit,' templates'
            cryfit += 1

        xsize = 1200
        ysize = int(xsize*170/360+0.1*xsize) if doEB else int(xsize*0.9)
        of.cd()
        canv = rt.TCanvas("c","",xsize,ysize)
        for h in histos:
            #h.Draw("colz")
            #canv.SaveAs(h.GetName()+'.pdf')
            self.printOnePlot(h,canv,h.GetName())
            h.Write()
        for h in histosDiff:
            h.Write()
        of.Close()
Beispiel #10
0
    def plotIC2D(self,partition,zhwidth=0.07,errwidth=0.005,outdirname='', norm_etaring=False):
        #rt.gStyle.SetOptStat(0)
        customROOTstyle()
        plots2D = []
        profiles = {}

        if partition=='EcalBarrel': 
            h = rt.TProfile2D(('%s_%s_ic_2d' % (self.name,partition)), '',360,1,360,171,-85.5,85.5)
            h.GetXaxis().SetTitle('i#phi')
            h.GetYaxis().SetTitle('i#eta')
        else: 
            h = rt.TProfile2D(('%s_%s_ic_2d' % (self.name,partition)), '',100,1,100,100,1,100)
            h.GetXaxis().SetTitle('ix')
            h.GetYaxis().SetTitle('iy')

        if partition=='EcalBarrel': 
            hsterr = rt.TProfile(str(h.GetName()).replace('ic_2d','icsterr_1d'),'',85,0.5,85.5)
        else: 
            hsterr = rt.TProfile(str(h.GetName()).replace('ic_2d','icsterr_1d'),'',38,0.5,38.5)
            
        hsterr.GetXaxis().SetTitle('#eta ring')
        hsterr.GetYaxis().SetRangeUser(0,errwidth)
        hsterr.SetMarkerStyle(rt.kFullCircle)
        hsterr.SetMarkerColor(rt.kRed)
        hsterr.SetLineColor(rt.kRed)
        hsyerr = hsterr.Clone(str(h.GetName()).replace('ic_2d','icsyerr_1d'))
        hsyerr.SetMarkerStyle(rt.kFullTriangleUp)
        hsyerr.SetMarkerColor(rt.kGreen+2)
        hsyerr.SetLineColor(rt.kGreen+2)
        htoterr = hsterr.Clone(str(h.GetName()).replace('ic_2d','ictoterr_1d'))
        htoterr.SetMarkerStyle(rt.kFullSquare)
        htoterr.SetMarkerColor(rt.kBlack)
        htoterr.SetLineColor(rt.kBlack)
        htoterr.SetMarkerSize(1.5)
        profiles['errors'] = [hsterr,hsyerr,htoterr]

        ering = EtaRings('InputFile/Endc_x_y_ring.txt')

        zmin=1-zhwidth; zmax=1+zhwidth
        for k,v in self.data.iteritems():
            if k.subdet() != partition: continue
            if(v.staterr < 999): 
                # for EB, the file as ieta in x, but in the histogram ieta is in the y axis
                if k.subdet() == "EcalBarrel":
                    h.Fill(k.y,k.x,max(zmin,min(zmax,v.val)))
                else:
                    h.Fill(k.x,k.y,max(zmin,min(zmax,v.val)))
                hsterr.Fill(ering.etaring(k),v.staterr)
                hsyerr.Fill(ering.etaring(k),v.systerr)
                htoterr.Fill(ering.etaring(k),v.toterr)
            
        h.GetZaxis().SetRangeUser(zmin,zmax)
        
        hnorm1 = h.Clone(str(h.GetName()).replace('ic_2d','ic_2d_norm1etaring'))
    
        if norm_etaring:
            if partition=='EcalBarrel':
                hnorm1 = h.Clone(str(h.GetName()).replace('ic_2d','ic_2d_norm1etaring'))
                for ieta in range (1,172): # range excludes last value, so we have 171 values, but ieta = 0 doesn't exist, so we have 170 eta rings in EB
                    if ieta == 86: 
                        continue
                    ICsum_etaring = 0.0
                    xtalsInEtaRing = 0.0
                    # if xtal is dead, bin content is 0, do not count it in the average
                    for iphi in range (1,361):
                        if h.GetBinContent(iphi,ieta) > 0.00001:
                            ICsum_etaring += h.GetBinContent(iphi,ieta)
                            xtalsInEtaRing += 1.0
                        #print "iphi, ieta, ICsum_etaring = %s %s %s" % (str(iphi), str(ieta), str(ICsum_etaring))
                    ICsum_etaring = ICsum_etaring / xtalsInEtaRing

                    average = 0.0
                    for iphi in range (1,h.GetNbinsX()+1):
                        hnorm1.Fill(iphi,ieta-86,h.GetBinContent(iphi,ieta)/ICsum_etaring)
                        average += h.GetBinContent(iphi,ieta)/(xtalsInEtaRing * ICsum_etaring)
                    #print "etaring %s: average %s" % (str(ieta-86),str(average))

                plots2D.append(hnorm1)
            else:
                hnorm1 = h.Clone(str(h.GetName()).replace('ic_2d','ic_2d_norm1etaring'))
                f_ietaring = rt.TFile("/afs/cern.ch/user/m/mciprian/public/ECALproTools/EE_xyzToEtaRing/eerings_modified.root")
                h_ietaring = f_ietaring.Get("hEEm") if "Minus" in partition else f_ietaring.Get("hEEp")              
                for ietaring in range (0,39):
                    ICsum_etaring = 0.0
                    xtalsInEtaRing = 0.0
                    for ix in range (1,101):
                        for iy in range (1,101):
                            if h_ietaring.GetBinContent(ix,iy) == ietaring:
                                ICsum_etaring += h.GetBinContent(ix,iy)
                                xtalsInEtaRing += 1.0
                    ICsum_etaring = ICsum_etaring / xtalsInEtaRing
                                
                    average = 0.0
                    for ix in range (1,101):
                        for iy in range (1,101):
                            if h_ietaring.GetBinContent(ix,iy) == ietaring:
                                hnorm1.Fill(ix,iy,h.GetBinContent(ix,iy)/ICsum_etaring)
                                average += h.GetBinContent(ix,iy)/(xtalsInEtaRing * ICsum_etaring)                       
                    #print "etaring %s: average %s" % (str(ietaring),str(average))

                plots2D.append(hnorm1)
        else:
            plots2D.append(h)

        leg = rt.TLegend(0.2,0.7,0.5,0.85)
        leg.SetFillColor(0)
        leg.SetShadowColor(0)
        leg.SetLineColor(0)
        leg.SetTextFont(42)
        leg.SetTextSize(0.03)

        for k,p in profiles.iteritems():
            canv = rt.TCanvas("c","",1200,1200)
            canv.cd();
            canv.SetTickx(1);
            canv.SetTicky(1);
            canv.cd();
            #canv.SetBottomMargin(0.1);
            canv.SetRightMargin(0.06);
            canv.SetLeftMargin(0.18);
            p[2].Draw("p")
            p[1].Draw("p same")
            p[0].Draw("p same")
            leg.AddEntry(p[0], 'Stat. error', 'LP')
            leg.AddEntry(p[1], 'Syst. error', 'LP')
            leg.AddEntry(p[2], 'Tot. error', 'LP')
            leg.Draw()
            if outdirname == '':
                canv.SaveAs('%s.pdf' % p[2].GetName())
                canv.SaveAs('%s.png' % p[2].GetName())
            else:
                canv.SaveAs('%s/%s.pdf' % (outdirname, p[2].GetName()))
                canv.SaveAs('%s/%s.png' % (outdirname, p[2].GetName()))

        for p in plots2D:
            xsize = 1200
            ysize = int(xsize*170/360+0.1*xsize) if 'EcalBarrel' in h.GetName() else int(xsize*0.9)
            canv = rt.TCanvas("c","",xsize,ysize)
            if p.GetDimension()==2: p.Draw("colz")
            else: p.Draw()
            if outdirname == '':
                canv.SaveAs('%s.pdf' % p.GetName())
                canv.SaveAs('%s.png' % p.GetName())
            else:
                canv.SaveAs('%s/%s.pdf' % (outdirname, p.GetName()))
                canv.SaveAs('%s/%s.png' % (outdirname, p.GetName()))
Beispiel #11
0
    def plotIC2D(self,partition,zhwidth=0.07,errwidth=0.005):
        #rt.gStyle.SetOptStat(0)
        customROOTstyle()
        plots2D = []
        profiles = {}

        if partition=='EcalBarrel': 
            h = rt.TProfile2D(('%s_%s_ic_2d' % (self.name,partition)), '',360,1,360,170,-85,85)
            h.GetXaxis().SetTitle('i#phi')
            h.GetYaxis().SetTitle('i#eta')
        else: 
            h = rt.TProfile2D(('%s_%s_ic_2d' % (self.name,partition)), '',100,1,100,100,1,100)
            h.GetXaxis().SetTitle('ix')
            h.GetYaxis().SetTitle('iy')

        if partition=='EcalBarrel': 
            hsterr = rt.TProfile(str(h.GetName()).replace('ic_2d','icsterr_1d'),'',85,0,84)
        else: 
            hsterr = rt.TProfile(str(h.GetName()).replace('ic_2d','icsterr_1d'),'',38,0,37)
            
        hsterr.GetXaxis().SetTitle('#eta ring')
        hsterr.GetYaxis().SetRangeUser(0,errwidth)
        hsterr.SetMarkerStyle(rt.kFullCircle)
        hsterr.SetMarkerColor(rt.kRed)
        hsterr.SetLineColor(rt.kRed)
        hsyerr = hsterr.Clone(str(h.GetName()).replace('ic_2d','icsyerr_1d'))
        hsyerr.SetMarkerStyle(rt.kFullTriangleUp)
        hsyerr.SetMarkerColor(rt.kGreen+2)
        hsyerr.SetLineColor(rt.kGreen+2)
        htoterr = hsterr.Clone(str(h.GetName()).replace('ic_2d','ictoterr_1d'))
        htoterr.SetMarkerStyle(rt.kFullSquare)
        htoterr.SetMarkerColor(rt.kBlack)
        htoterr.SetLineColor(rt.kBlack)
        htoterr.SetMarkerSize(1.5)
        profiles['errors'] = [hsterr,hsyerr,htoterr]

        ering = EtaRings('InputFile/Endc_x_y_ring.txt')

        zmin=1-zhwidth; zmax=1+zhwidth
        for k,v in self.data.iteritems():
            if k.subdet() != partition: continue
            if(v.staterr < 999): 
                h.Fill(k.y,k.x,max(zmin,min(zmax,v.val)))
                hsterr.Fill(ering.etaring(k),v.staterr)
                hsyerr.Fill(ering.etaring(k),v.systerr)
                htoterr.Fill(ering.etaring(k),v.toterr)
            
        h.GetZaxis().SetRangeUser(zmin,zmax)
        
        plots2D.append(h)

        leg = rt.TLegend(0.2,0.7,0.5,0.85)
        leg.SetFillColor(0)
        leg.SetShadowColor(0)
        leg.SetLineColor(0)
        leg.SetTextFont(42)
        leg.SetTextSize(0.03)

        for k,p in profiles.iteritems():
            canv = rt.TCanvas("c","",1200,1200)
            p[2].Draw("p")
            p[1].Draw("p same")
            p[0].Draw("p same")
            leg.AddEntry(p[0], 'Stat. error', 'LP')
            leg.AddEntry(p[1], 'Syst. error', 'LP')
            leg.AddEntry(p[2], 'Tot. error', 'LP')
            leg.Draw()
            canv.SaveAs('%s.pdf' % p[2].GetName())
            canv.SaveAs('%s.png' % p[2].GetName())
            

        for p in plots2D:
            xsize = 1200
            ysize = int(xsize*170/360+0.1*xsize) if 'EcalBarrel' in h.GetName() else int(xsize*0.9)
            canv = rt.TCanvas("c","",xsize,ysize)
            if p.GetDimension()==2: p.Draw("colz")
            else: p.Draw()
            canv.SaveAs('%s.pdf' % p.GetName())
            canv.SaveAs('%s.png' % p.GetName())
    def do2dShapeDiff(self,doEB,absoluteShape=False):
        part = 'EB' if doEB else 'EE'
        customROOTstyle()
        refData = self.parseDic(self._allData["ref"])
        newData = self.parseDic(self._allData["current"])
        of = rt.TFile.Open('%s_timeVals.root' % part,'recreate')
        histos = {}
        for ip,par in enumerate(['alpha','beta','T0']):
            (zmin,zmax) = (-0.03,0.03) if par!="T0" else (-1,1) # ns
            if par=="T0" and absoluteShape: (zmin,zmax) = (-5,5) # ns
            if doEB:
                h = rt.TProfile2D(('%s_%s' % (part,par)),"",360,1,360,170,-85,85)
                h.GetXaxis().SetTitle('i#phi')
                h.GetYaxis().SetTitle('i#eta')
                h.SetTitle('Time (ns)' if par=="T0" else '#Delta #{par}/#{par}'.format(par=par))
                h.GetZaxis().SetRangeUser(zmin,zmax)
                histos[par] = [h]
            else: 
                hz = []
                hplus = rt.TProfile2D(('%splus_%s' % (part,par)),"",100,1,100,100,1,100)
                hplus.GetXaxis().SetTitle('ix')
                hplus.GetYaxis().SetTitle('iy')
                hplus.SetTitle('Time (ns)' if par=="T0" else '#Delta #{par}/#{par}'.format(par=par))
                hplus.GetZaxis().SetRangeUser(zmin,zmax)
                hz.append(hplus)
                hminus = hplus.Clone('%sminus_%s' % (part,par))
                hz.append(hminus)
                histos[par] = hz

        detids = EcalDetId('/afs/cern.ch/work/e/emanuele/public/ecal/pulseshapes_db/detids_ECAL.txt')

        cryfit = 0
        for (partition,detid),samples in newData.iteritems():
            key = (partition,detid)
            (x,y,z) = detids.xyz(detid)

            if not absoluteShape and key not in refData: continue
            if ((doEB and int(partition)==0) or (not doEB and int(partition)==1)): continue
            if z==-999: continue

            (ix,iy) = (y,x) if doEB else (x+1,y+1)

            (val,err) = self.timeFit(newData[key],self.abfitter,doEB)
            (valRef,errRef) = self.timeFit(refData[key],self.abfitter,doEB) if not absoluteShape else ({},{})

            for ip,par in enumerate(['alpha','beta','T0']):
                if z==0 or z==1: 
                    htofill = (histos[par])[0]
                else: 
                    htofill = (histos[par])[1]
                value = val[par]-valRef[par] if not absoluteShape else val[par]
                if par!="T0": value = value/valRef[par] if not absoluteShape else value
                #print "par = ",par," val1,2 = ",val[par]," ",valRef[par]," norm value = ",value
                #print "err1,2 = ",err[par]," ",errRef[par]
                htofill.Fill(ix,iy,value)

            if cryfit % 1000 == 0: print 'fitted ',cryfit,' templates'
            cryfit += 1

        xsize = 1200
        ysize = int(xsize*170/360+0.1*xsize) if doEB else int(xsize*0.9)
        of.cd()
        canv = rt.TCanvas("c","",xsize,ysize)
        for k,hvect in histos.iteritems():
            for h in hvect:
                h.Write()
                self.printOnePlot(h,canv,'{name}{absolute}'.format(name=h.GetName(),absolute='_absolute' if absoluteShape else ''),"",True)
        of.Close()
    def do2dTime(self,currentTimeIC,doEB,newTimeIC=''):
        part = 'EB' if doEB else 'EE'
        customROOTstyle()
        refData = self.parseDic(self._allData["ref"])
        newData = self.parseDic(self._allData["current"])
        of = rt.TFile.Open('%s_timeVals.root' % part,'recreate')
        histos = []
        histosDiff = []
        if doEB: 
            h = rt.TProfile2D(('%s_time' % part),"",360,1,360,170,-85,85)
            h.GetXaxis().SetTitle('i#phi')
            h.GetYaxis().SetTitle('i#eta')
            h.SetTitle('Time (ns)')
            h.GetZaxis().SetRangeUser(-1,1)
            histos.append(h)
            histosDiff.append(h.Clone(('%s_time_diff' % part)))
        else: 
            hplus = rt.TProfile2D(('%splus_time' % part),"",100,1,100,100,1,100)
            hplus.GetXaxis().SetTitle('ix')
            hplus.GetYaxis().SetTitle('iy')
            hplus.SetTitle('Time (ns)')
            hplus.GetZaxis().SetRangeUser(-1,1)
            histos.append(hplus)
            histosDiff.append(hplus.Clone(('%splus_time_diff' % part)))
            hminus = hplus.Clone('%sminus_time' % part)
            histos.append(hminus)
            histosDiff.append(hminus.Clone(('%sminus_time_diff' % part)))

        detids = EcalDetId('/afs/cern.ch/work/e/emanuele/public/ecal/pulseshapes_db/detids_ECAL.txt')

        # load the current time ICs (dump of the tag)
        self.timeICs = self.loadTimeICs(currentTimeIC)
        if len(newTimeIC)>0: newTimeICs = self.loadTimeICs(newTimeIC)

        histo = rt.TH1F("histo","",15,0,15)
        cryfit = 0
        for (partition,detid),samples in newData.iteritems():
            key = (partition,detid)
            (x,y,z) = detids.xyz(detid)

            if detid not in self.timeICs: continue
            if ((doEB and int(partition)==0) or (not doEB and int(partition)==1)): continue
            if z==0 or z==1: 
                htofill = histos[0]
                hdifftofill = histosDiff[0]
            else: 
                htofill = histos[1]
                hdifftofill = histosDiff[1]
            (ix,iy) = (y,x) if doEB else (x,y)

            # fill the template and fit it
            for s in range(3):  histo.SetBinContent(s+1,0)
            for s in range(12): histo.SetBinContent(s+4,float((newData[key])[s]))
            self.abfitter.fit(histo,doEB)
            results = {'pars': abfitter.getPars(), 'errs': abfitter.getErrs()}
            currentCorr = float(self.timeICs[detid]) + self.timeOffsets[part]
            time = 25.*((results['pars'])[2]-5.5)
            correctedTime = time + currentCorr
            # print "detid = ",key," has time from fit [IC] = ",time, " [",currentCorr,"]"
            htofill.Fill(ix,iy,correctedTime)

            if len(newTimeIC)>0: 
                if detid not in newTimeICs: continue
                newCorr = float(newTimeICs[detid])
                # print '    correctedTime = ',correctedTime,"   newCorr = ",newCorr,"  diff = ", correctedTime - newCorr
                hdifftofill.Fill(ix,iy,correctedTime - newCorr)

            if cryfit % 1000 == 0: print 'fitted ',cryfit,' templates'
            cryfit += 1

        xsize = 1200
        ysize = int(xsize*170/360+0.1*xsize) if doEB else int(xsize*0.9)
        of.cd()
        canv = rt.TCanvas("c","",xsize,ysize)
        for h in histos:
            #h.Draw("colz")
            #canv.SaveAs(h.GetName()+'.pdf')
            self.printOnePlot(h,canv,h.GetName())
            h.Write()
        for h in histosDiff:
            h.Write()
        of.Close()