示例#1
0
  def fitRatioSlope(self,fitFuncRatio,fitRange):
    self.plots.phiPropRatio.FitSlicesY()
    histRatio=ROOT.gDirectory.Get(self.plots.phiPropRatio.GetName()+'_1')
    histRatio.SetName(self.name+'_RatioMean')
    if self.type==0:
      self.plots.phiBPropRatioUnSc.FitSlicesY()
      histBRatioUnSc=ROOT.gDirectory.Get(self.plots.phiBPropRatioUnSc.GetName()+'_1')
      histBRatioUnSc.SetName(self.name+'_BRatioMean_unSc')

      self.plots.phiBPropRatioSc.FitSlicesY()
      histBRatioSc=ROOT.gDirectory.Get(self.plots.phiBPropRatioSc.GetName()+'_1')
      histBRatioSc.SetName(self.name+'_BRatioMean_sc')

    # Set up fitting functions
    fitRatio=ROOT.TF1(histRatio.GetName(),fitFuncRatio,fitRange[0],fitRange[1])
    if self.type==0:
      fitBRatioUnSc=ROOT.TF1(histBRatioUnSc.GetName(),fitFuncRatio,fitRange[0],fitRange[1])
      fitBRatioSc=ROOT.TF1(histBRatioSc.GetName(),fitFuncRatio,fitRange[0],fitRange[1])

    # Draw ratio fit function
    canvRatio=ROOT.TCanvas(histRatio.GetName()+'_canv')
    canvRatio.cd()
    canvRatio.SetGrid()
    histRatio.Draw()
    histRatio.GetXaxis().SetRangeUser(-1000,1000)
    histRatio.GetXaxis().SetTitle('#phi_{stub}')
    histRatio.GetYaxis().SetRangeUser(-1000,1000)
    histRatio.GetYaxis().SetTitle('#phi_{prop}')
    gStyle.SetOptFit()
    if self.type==0:
      canvBRatioUnSc=ROOT.TCanvas(histBRatioUnSc.GetName()+'_canv')
      canvBRatioUnSc.cd()
      canvBRatioUnSc.SetGrid()
      histBRatioUnSc.Draw()
      histBRatioUnSc.GetXaxis().SetRangeUser(-1000,1000)
      histBRatioUnSc.GetXaxis().SetTitle('#phi_{stub,b}')
      histBRatioUnSc.GetYaxis().SetRangeUser(-1000,1000)
      histBRatioUnSc.GetYaxis().SetTitle('#phi_{prop,b}')
      gStyle.SetOptFit()

      canvBRatioSc=ROOT.TCanvas(histBRatioSc.GetName()+'_canv')
      canvBRatioSc.cd()
      canvBRatioSc.SetGrid()
      histBRatioSc.Draw()
      histBRatioSc.GetXaxis().SetRangeUser(-1000,1000)
      histBRatioSc.GetXaxis().SetTitle('#phi_{stub,b}')
      histBRatioSc.GetYaxis().SetRangeUser(-1000,1000)
      histBRatioSc.GetYaxis().SetTitle('#phi_{prop,b}')
      gStyle.SetOptFit()

    histRatio.Fit(fitRatio,'R')
    if self.type==0:
      histBRatioUnSc.Fit(fitBRatioUnSc,'R')
      histBRatioSc.Fit(fitBRatioSc,'R')

    self.plots.PhiPropRatioMean=copy.deepcopy(histRatio)
    if self.type==0:
      self.plots.PhiBPropRatioMeanUnSc=copy.deepcopy(histBRatioUnSc)
      self.plots.PhiBPropRatioMeanSc=copy.deepcopy(histBRatioSc)
示例#2
0
文件: utils.py 项目: kjvbrt/FCC_tools
def plot(obj, plot_name, plot_notes=[]):
    canvas = TCanvas('canvas' + plot_name, "Canvas", 450, 450)
    gPad.SetLeftMargin(.13)
    gPad.SetTopMargin(.05)

    gStyle.SetOptStat(11)
    gStyle.SetOptFit(1111)

    if 'TH2' in obj.ClassName():
        gPad.SetRightMargin(.13)
        draw_options = 'COLZ'

    if 'profile' in obj.GetName():
        gPad.SetRightMargin(.05)
        draw_options = ''

    if 'graph' in obj.GetName():
        gPad.SetRightMargin(.05)
        draw_options = 'APE'
        obj.SetMarkerSize(.7)
        obj.SetMarkerStyle(21)

    note = TPaveText(.2, .7, .5, .9, "brNDC")
    note.SetFillStyle(0)
    note.SetFillColor(0)
    note.SetBorderSize(0)
    note.SetTextColor(1)
    note.SetTextFont(42)
    note.SetTextAlign(11)
    for note_text in plot_notes:
        note.AddText(note_text)

    obj.Draw(draw_options)
    note.Draw()
    canvas.Print('output/' + plot_name + '.pdf')
示例#3
0
文件: graphUtils.py 项目: namcneal/QY
    def drawFit(self,h,figdir='',SetLogy=False,SetLogx=False,extraName=None):
        '''
        draw histogram with fit parameters
        '''
        name = h.GetName()
        if extraName is not None: name += '_' + extraName
        title = h.GetTitle()
        if SetLogx: name += '_logx'
        if SetLogy: name += '_logy'
        pdf = os.path.join( figdir ,  name + '.pdf' )
        ps  = os.path.join( figdir , name + '.ps' )
        xsize,ysize = 1100,850 # landscape style
        noPopUp = True
        if noPopUp : gROOT.ProcessLine("gROOT->SetBatch()")
        canvas = TCanvas(pdf,title,xsize,ysize)
        
        gStyle.SetOptFit(1111)
        h.Draw()
        if SetLogy: canvas.SetLogy(1)
        if SetLogx: canvas.SetLogx(1)
        
        canvas.Draw()
        canvas.SetGrid(1)
        canvas.SetTicks(1)
        canvas.cd()
        canvas.Modified()
        canvas.Update()
        
        canvas.Print(ps,'Landscape')
        os.system('ps2pdf ' + ps + ' ' + pdf)
        if os.path.exists(pdf): os.system('rm ' + ps)

        return
示例#4
0
def DoCBFit(histo, ZZtree, title, p):
    canv = makeCMSCanvas(str(random.random()),"Fit result ",900,700)

    Z1_fitFunction = TF1('Z1_fitFunction',DoubleCB(),60. ,120., 7)

    Z1_fitFunction.SetParameters(p[0],p[1],p[2],p[3],p[4],p[5],p[6])

    Z1_fitFunction.SetParLimits(0,85.,95.)#mean
    Z1_fitFunction.SetParLimits(1,0.,5.)#width
    Z1_fitFunction.SetParLimits(2,0.,2.)#alpha1
    Z1_fitFunction.SetParLimits(3,0.,100.)#n1
    Z1_fitFunction.SetParLimits(4,0.,2.)#alpha2
    Z1_fitFunction.SetParLimits(5,0.,100.)#n2
    Z1_fitFunction.SetParLimits(6,0.,1000000.)#const

    Z1_fitFunction.SetParName(0,"Mean")#mean
    Z1_fitFunction.SetParName(1,"Sigma")#width
    Z1_fitFunction.SetParName(2,"#alpha_{1}")#alpha1
    Z1_fitFunction.SetParName(3,"n_{1}")#n1
    Z1_fitFunction.SetParName(4,"#alpha_{2}")#alpha2
    Z1_fitFunction.SetParName(5,"n_{2}")#n2
    Z1_fitFunction.SetParName(6,"C")#const

    canv.cd()
    histo.Fit(Z1_fitFunction)
    gStyle.SetOptFit()
    histo.SetTitle("")
    histo.Draw()
    print ("Mass: " +str(Z1_fitFunction.GetParameters()[0]) + " Width: " + str(Z1_fitFunction.GetParameters()[1]))
    printLumiPrelOut(canv)
    canv.SaveAs("DataVsMC/FitResults/"+title+"_fit.pdf")
    canv.SaveAs("DataVsMC/FitResults/"+title+"_fit.png")
    return Z1_fitFunction.GetParameters()[0], Z1_fitFunction.GetParError(0);
示例#5
0
def main():
    fwhm = np.array([], dtype="float")
    da.save_Tree(filepath, win_percent=0.1)
    f = TFile(filepath + "/" + "focus.root", "recreate")
    f.mkdir("distribution_of_amp")
    f.distribution.cd()
    da.hist2(filepath, 1, 0, 1)
    h2 = f.distribution.hist2
    gDirectory.cd("..")
    f.mkfir("projection")
    f.projection.cd()
    z = h2.GetNbinsY()
    for i in range(0, z):
        da.projection(h2, 'x', name="_pz", i, i + 1)
        fwhm_value = calculate_FWHM(f.projection.hist2_pz)
        np.append(fwhm, fwhm_value)
        da.projection(h2, 'x', "_z" + str(i), i, i + 1)

    f2 = TFile(filepath + "/" + "position_and_amp.root")
    z_min = f2.t1.GetMinimum("z")
    z_max = f2.t1.GetMaximum("z")
    z = np.arange(z_min, z_max + 1)
    z = z.astype("float")
    tgr = TGraph(z.size, z, fwhm)
    t1 = TCanva("t1", "focus")
    tgr.GetXaxis().SetTitle("z[um]")
    tgr.GetYaxis().SetTitle("FWHM[um]")
    tgr.Draw("AC*")
    tgr.Fit("pol2")
    gStyle.SetOptFit(1)
    c1.Update()
    c1.SaveAs("./result/focus.pdf")
def TopMassStyle():
    """Set the style plot in order to create fancier plots!"""
    gStyle.SetPadTickX(1);
    gStyle.SetPadTickY(1);
    gStyle.SetHistLineWidth(3);
    gStyle.SetMarkerStyle(1);

    gStyle.SetTextSize(0.065);

    gStyle.SetOptFit(1111);
    gStyle.SetTitleSize(.05,"X");#.055
    gStyle.SetTitleOffset(1.1,"X");#1.2,0.9
    gStyle.SetLabelSize(.05,"X");

    gStyle.SetTitleSize(.05,"Y");#.055
    gStyle.SetTitleOffset(1.1,"Y");
    gStyle.SetLabelSize(.05,"Y");

    gStyle.SetPadLeftMargin(.16);
    gStyle.SetPadBottomMargin(.12);

    gStyle.SetTitleSize(.05,"Z");
    gStyle.SetTitleOffset(1.8,"Z");
    gStyle.SetLabelSize(0.06,"Z");

    gStyle.SetLegendTextSize(0.04);

    gStyle.SetOptStat(112210);

    gStyle.SetPadLeftMargin(.12);
    gStyle.SetPadRightMargin(.02);
    gStyle.SetPadBottomMargin(.12);
    gStyle.SetPadTopMargin(.07);
    gStyle.SetPadGridX(1);
    gStyle.SetPadGridY(1);
示例#7
0
def DoLandauFit(histo, lumi, ZZtree, title):
    #gSystem.Exec("mkdir -p FitResults")
    can = []
    result = []
    for i in range(0,len(histo)):
        canv = makeCMSCanvas(str(random.random())+str(i),"Fit result "+str(i),900,700)
        can.append(canv)
    
    Z1_fitFunction = TF1('Z1_fitFunction',"[0]*TMath::Landau(x,[1],[2])",0,4)
    
    Z1_fitFunction.SetParameters(100,0.1,1.0)
    
    #Z1_fitFunction.SetParLimits(0,85.,95.)
    #Z1_fitFunction.SetParLimits(1,0.,5.)
    #Z1_fitFunction.SetParLimits(2,0.,2.)
    
    Z1_fitFunction.SetParName(0,"Const")#constant
    Z1_fitFunction.SetParName(1,"Position")#position
    Z1_fitFunction.SetParName(2,"Scale")#scale
    
    for i in range(0,len(histo)):
        can[i].cd()
        histo[i].Fit(Z1_fitFunction,"","",0.,2.)
        histo[i].Draw()
        gStyle.SetOptFit()
        position = Z1_fitFunction.GetParameters()[1]
        scale = Z1_fitFunction.GetParameters()[2]
        position_err = Z1_fitFunction.GetParError(1)
        scale_err = Z1_fitFunction.GetParError(2)
        result.append(Result(position,scale,lumi[i],position_err,scale_err))
        print ("Position: " +str(position) + " Scale: " + str(scale))
        printLumiPrelOut(can[i])
        can[i].SaveAs("FitResults/"+title+"_Landfit_"+str(i)+".pdf")
        can[i].SaveAs("FitResults/"+title+"_Landfit_"+str(i)+".png")
    return result;
示例#8
0
def setStyle():
    NRGBs = 5
    NCont = 255

    #gErrorIgnoreLevel

    #Double_t stops[NRGBs] = { 0.00, 0.34, 0.61, 0.84, 1.00 };
    #Double_t red[NRGBs]   = { 0.00, 0.00, 0.87, 1.00, 0.51 };
    #Double_t green[NRGBs] = { 0.00, 0.81, 1.00, 0.20, 0.00 };
    #Double_t blue[NRGBs]  = { 0.51, 1.00, 0.12, 0.00, 0.00 };
    #TColor::CreateGradientColorTable(NRGBs, stops, red, green, blue, NCont);
    #gStyle.SetNumberContours(NCont);

    #  gStyle.SetPadBorderMode(0)
    #  gStyle.SetFrameBorderMode(0)
    gStyle.SetOptStat(0)
    gStyle.SetOptFit(0)

    #  gStyle.SetLabelSize(0.05,"X")
    #  gStyle.SetLabelSize(0.05,"Y")
    # 0.035
    #  gStyle.SetLabelSize(0.035,"XY")
    gStyle.SetTitleSize(AxisLabelSizeX, "X")
    gStyle.SetTitleSize(AxisLabelSizeY, "Y")

    gStyle.SetTitleOffset(kDefaultTitleOffsetX, "X")
    gStyle.SetTitleOffset(kDefaultTitleOffsetY, "Y")

    gStyle.SetOptStat(0)
    gStyle.SetOptTitle(0)
    gStyle.SetTitleSize(0.035, "xy")
示例#9
0
    def set2DStyle(self, opt="BasicRainBow"):

        gStyle.SetPadRightMargin(
            0.2
        )  # Leave more space to the right side of the current Pad to show the histogram scale

        if opt == "FancyRainBow":
            icol = 0
            gStyle.SetFrameBorderMode(icol)
            gStyle.SetFrameFillColor(icol)
            gStyle.SetCanvasBorderMode(icol)
            gStyle.SetCanvasColor(icol)
            gStyle.SetPadBorderMode(icol)
            gStyle.SetPadColor(icol)
            gStyle.SetStatColor(icol)
            gStyle.SetOptTitle(0)
            gStyle.SetOptStat(0)
            gStyle.SetOptFit(0)

            ncontours = 999

            s = array.array('d', [0.00, 0.34, 0.61, 0.84, 1.00])
            r = array.array('d', [0.00, 0.00, 0.87, 1.00, 0.51])
            g = array.array('d', [0.00, 0.81, 1.00, 0.20, 0.00])
            b = array.array('d', [0.51, 1.00, 0.12, 0.00, 0.00])

            npoints = len(s)
            TColor.CreateGradientColorTable(npoints, s, r, g, b, ncontours)
            gStyle.SetNumberContours(ncontours)

        if opt == "BasicRainBow":
            gStyle.SetPalette(
                1
            )  # This resets the color palette to a simple Rainbow Color Map w/ 50 colors. See https://root.cern.ch/doc/master/classTColor.html
示例#10
0
def calceff(run,tdc,strip=71):
  f82=TFile("./histo%d_0.root" % run);
  f82.cd("/run%d/TDC%d/LmAnalysis" % (run,tdc));
  c1=TCanvas();
  gStyle.SetOptFit();

  heff=f82.Get("/run%d/TDC%d/LmAnalysis/Efficiency" % (run,tdc));
  hstrip=f82.Get("/run%d/TDC%d/LmAnalysis/hdts%d" % (run,tdc,strip));
  hstrip.Rebin(2)
  scfit=TF1("scfit","gaus",hstrip.GetMean()-6.*hstrip.GetRMS(),hstrip.GetMean()+6.*hstrip.GetRMS())
  hstrip.GetXaxis().SetRangeUser(hstrip.GetMean()-6.*hstrip.GetRMS(),hstrip.GetMean()+6.*hstrip.GetRMS())
  hstrip.Fit("scfit","Q");
  dtmean=scfit.GetParameter(1)
  dtres=scfit.GetParameter(2)

  ntrg=heff.GetBinContent(2)
  n1=heff.GetBinContent(3)
  n2=heff.GetBinContent(4)
  eff=n1/ntrg
  deff=math.sqrt(eff*(1-eff)/ntrg)
  effp=n2/ntrg
  deffp=math.sqrt(effp*(1-effp)/ntrg)
  
  print("|%d|150|%d|%d|%d|%5.2f|%5.2f|%5.2f|%5.2f|%5.2f|%5.3f|" % (run,int(ntrg),int(n1),int(n2),eff*100,deff*100,effp*100,deffp*100,dtmean,dtres))
  hstrip.Draw()
  c1.Update()
  c1.SaveAs("Run%d_Strip%d_pos.png" % (run,strip));

  val = raw_input()
示例#11
0
def SetStyle():
    gROOT.SetStyle('Plain')
    gROOT.ForceStyle()
    gStyle.SetTextFont(42)

    gStyle.SetOptTitle(0)
    gStyle.SetOptFit(1112)
    gStyle.SetOptStat(1110)

    gStyle.SetPadRightMargin(0.08)
    gStyle.SetPadTopMargin(0.11)
    gStyle.SetPadBottomMargin(0.12)

    gStyle.SetTitleFont(42, 'x')
    gStyle.SetTitleFont(42, 'y')
    gStyle.SetTitleFont(42, 'z')

    gStyle.SetTitleOffset(1.05, 'x')
    gStyle.SetTitleOffset(1.00, 'y')

    gStyle.SetTitleSize(0.05, 'x')
    gStyle.SetTitleSize(0.05, 'y')
    gStyle.SetTitleSize(0.05, 'z')

    gStyle.SetLabelFont(42, 'x')
    gStyle.SetLabelFont(42, 'y')
    gStyle.SetLabelFont(42, 'z')

    gStyle.SetLabelSize(0.05, 'x')
    gStyle.SetLabelSize(0.05, 'y')
    gStyle.SetLabelSize(0.05, 'z')

    TGaxis.SetMaxDigits(3)
    gStyle.SetStatY(0.9)
示例#12
0
def fitProfile(run,sel=92):
  f82=TFile("./histo%d_0.root" % run);
  #f82.cd("/run%d/TDC%d/LmAnalysis/Timing" % (run,tdc));
  f82.cd("/run%d/ChamberAll" % (run));
  c1=TCanvas();
  gStyle.SetOptFit();
  pos0=[]
  pmean0=[]
  pos1=[]
  pmean1=[]
  hall=f82.Get("/run%d/ChamberAll/XY" % (run));
  for i in range(sel,sel+1):
    pos0.append(0)
    pmean0.append(0)
    #hstrip=f82.Get("/run%d/TDC%d/LmAnalysis/Timing/hdtpos%d" % (run,tdc,i+71));
    hstrip=hall.ProjectionY("strip%d" % (i),(i),i+1)
    if (hstrip.GetEntries()<100):
      continue
    scfit=TF1("scfit","gaus",hstrip.GetMean()-2.*hstrip.GetRMS(),hstrip.GetMean()+2.*hstrip.GetRMS())
    hstrip.Fit("scfit","Q","",hstrip.GetMean()-2.*hstrip.GetRMS(),hstrip.GetMean()+2.*hstrip.GetRMS())
    dtmean=scfit.GetParameter(1)
    dtres=scfit.GetParameter(2)
    print(run,i,dtmean,dtres,dtmean*80./8.3,dtres*80/8.3)
    c1.Update()
    #val = raw_input()
    time.sleep(2)
示例#13
0
def fit_distribution(run_num,
                     attr1='FitResult_Energy',
                     attr2='FitResult_XtalNum==0',
                     draw=False):
    """give an output file number from fitter,
    fit peak to find mean and variance with their errors"""
    #in_file = TFile("/home/newg2/Workspace/L1Tests/crunchedFiles/gm2uw_%05i_analysis.root" % run_num)
    in_file = TFile(
        "/Users/kimsiang/Work/UWCENPA/gm2/SLAC2016/Data/gm2uw_run%05i_analysis.root"
        % run_num)
    tree = in_file.Get("slacAnalyzer/eventTree")
    tree.Draw("%s>>h1(200)" % attr1, attr2, "goff")
    hist = gROOT.FindObject("h1")
    mean = hist.GetMean()
    std = hist.GetRMS()
    low = mean - 3 * std
    high = mean + 3 * std
    tree.Draw("%s>>h2(100,%s,%s)" % (attr1, str(low), str(high)), attr2,
              "goff")
    hist = gROOT.FindObject("h2")
    hist.Fit("gaus", "0q")
    func = hist.GetFunction("gaus")
    out = (func.GetParameter(1), func.GetParameter(2), func.GetParError(1),
           func.GetParError(2))
    if draw:
        gStyle.SetOptFit(1)
        hist.Draw()
        hist.GetFunction("gaus").Draw("same")
        raw_input('any key to continue')
    in_file.Close()
    return out
示例#14
0
def doSuperTGraph( data, canvas, obj):
    xmin=-1.8
    xmax=1.8
    gStyle.SetOptFit(0)
    gStyle.SetOptStat(0)
    gROOT.SetBatch(1)

    color=[601,417,920,633,910,433,400,619,1,922]
    mg = TMultiGraph();
    leg = TLegend(0.58,0.75,0.89,0.89);
    i=0
    for ivar in data['var']:

       
        if not os.path.exists(data['fold']+"/"+ivar+"_ll.root"): 
            continue
        print '>>> Opening File :' , data['fold']+"/"+ivar+"_ll.root"
        inFile = TFile.Open ( data['fold']+"/"+ivar+"_ll.root" ," READ ")

        c1 = inFile.Get(canvas);
        gr = c1.GetListOfPrimitives().FindObject(obj)

        xaxis = gr.GetXaxis().GetTitle()
        yaxis = gr.GetYaxis().GetTitle()

        gr.SetLineColor(color[i])
        mg.Add(gr)
        leg.AddEntry(gr,ivar,"l")
        i=i+1
        print i
    

    c = TCanvas()
    c.cd() 
    c.SetGrid()
    mg.Draw("al")
    line1 = TF1("line1","pol0",-100,100)
    line1.FixParameter(0,1.)
    line1.SetLineWidth(2)
    line1.SetLineStyle(2)
    line1.SetLineColor(2)
    line1.Draw("same")
  
    line2 = TF1("line2","pol0",-100,100)
    line2.FixParameter(0,3.84)
    line2.SetLineWidth(2)
    line2.SetLineStyle(2)
    line2.SetLineColor(2)
    line2.Draw("same") 


    mg.SetTitle(";" +xaxis+";" +yaxis)
    mg.GetYaxis().SetRangeUser(0,10)

    leg.SetNColumns(2)
    leg.SetBorderSize(0)
    leg.Draw("same")
    c.SaveAs(data['fold']+"combined10.png")
    c.SaveAs(data['fold']+"combined10.pdf")
    c.SaveAs(data['fold']+"combined10.root")
示例#15
0
 def DefaultPlotStyle(self):
     gStyle.SetPalette(55)  # 55 is kRainBow. 53 is kDarkBodyRadiator
     gStyle.SetOptStat(self.optStat1D)
     gStyle.SetOptFit(11111)
     gStyle.SetStatH(0.12)
     gStyle.SetStatW(0.15)
     gStyle.SetPadBottomMargin(0.15)
     gStyle.SetPadTopMargin(0.15)
示例#16
0
def doSuperTGraphAll( file_list, canvas, obj, output):

    gStyle.SetOptFit(0)
    gStyle.SetOptStat(0)
    gROOT.SetBatch(1)

    mg = TMultiGraph();
    leg = TLegend(0.58,0.75,0.89,0.89);

    for iFile in file_list:
       
        if not os.path.exists(iFile['path']): 
            print '>>> This File does not exist -->  '+iFile['path']+'... check path ... '
            continue
        print '>>> Opening File :' , iFile['path']
        inFile = TFile.Open ( iFile['path'] ," READ ")

        c1 = inFile.Get(canvas);
        gr = c1.GetListOfPrimitives().FindObject(obj)

        xaxis = gr.GetXaxis().GetTitle()
        yaxis = gr.GetYaxis().GetTitle()

        gr.SetLineColor(iFile['color'])
        mg.Add(gr)
        leg.AddEntry(gr,iFile['legend'],"l")
    

    c = TCanvas()
    c.cd() 
    c.SetGrid()
    mg.Draw("al")
    line1 = TF1("line1","pol0",-100,100)
    line1.FixParameter(0,1.)
    line1.SetLineWidth(2)
    line1.SetLineStyle(2)
    line1.SetLineColor(2)
    line1.Draw("same")
  
    line2 = TF1("line2","pol0",-100,100)
    line2.FixParameter(0,3.84)
    line2.SetLineWidth(2)
    line2.SetLineStyle(2)
    line2.SetLineColor(2)
    line2.Draw("same") 
 


    mg.SetTitle(";" +xaxis+";" +yaxis)
    mg.GetYaxis().SetRangeUser(0,10)

    leg.SetNColumns(2)
    leg.SetBorderSize(0)
    leg.Draw("same")
    c.SaveAs(output+"10.png")
    c.SaveAs(output+"10.pdf")
    c.SaveAs(output+"10.root")
示例#17
0
 def _initDefaultStyle(self):
     gROOT.Reset()
     gROOT.SetStyle("Plain")
     gStyle.SetOptStat(0)
     gStyle.SetOptFit(1111)
     gStyle.SetPadLeftMargin(0.12)
     gStyle.SetPadBottomMargin(0.12)
     gStyle.SetMarkerSize(1.)
     gStyle.SetHistLineWidth(1)
示例#18
0
def set_meeting_style():
    from ROOT import gStyle
    gStyle.SetOptDate(0)
    gStyle.SetOptTitle(0)
    gStyle.SetOptStat(1111)
    gStyle.SetStatBorderSize(1)
    gStyle.SetStatColor(10)
    gStyle.SetStatFont(42)
    gStyle.SetStatFontSize(0.03)
    gStyle.SetOptFit(1111)
示例#19
0
    def GaussianFit(self, histo):
        '''
		Fit Histograms for Exercise 3. 
		### FALTA Fit Breit Wigner  
		'''
        self.gHisto = self.Gfile.Get('g_' + histo)
        self.gHisto.Fit("gaus")
        #self.fit1 = self.gHisto.GetFunction("gaus")
        gStyle.SetOptFit()
        self.createCanvas(self.gHisto, 'fit_' + histo)
示例#20
0
    def fit(self, distribution, s_graphs):
        """ Fit Gaussian distribution over TGraphs. """

        graphs = self._get_graphs(s_graphs)

        for idx, graph in enumerate(graphs):
            try:
                numbering = self._numbering[idx]
            except IndexError:
                numbering = -1
            graph.Fit(distribution, 'Q')
            graph.GetFunction(distribution).SetLineColor(4)
            self._fits.append(
                ToolboxFit(graph.GetFunction(distribution), numbering))

        # If there is only one fit, show stats
        if len(graphs) == 1:
            gStyle.SetOptFit(1111111)
        else:
            gStyle.SetOptFit(0000000)
示例#21
0
def fun():
    c1 = TCanvas("c1", "c1", 600, 500)
    t.Draw()
    u.Draw("SAMES")
    v.Draw("SAMES")
    w.Draw("SAMES")
    o.Draw("SAMES")
    v.GetXaxis().SetTitle("Photons in Evt")
    v.GetYaxis().SetTitle("Events")
    v.GetYaxis().SetTitleOffset(1.3)
    u.GetXaxis().SetTitle("Photons in Evt")
    u.GetYaxis().SetTitle("Events")
    u.GetYaxis().SetTitleOffset(1.3)
    t.GetXaxis().SetTitle("Photons in Evt")
    t.GetYaxis().SetTitle("Events")
    t.GetYaxis().SetTitleOffset(1.3)
    w.GetXaxis().SetTitle("Photons in Evt")
    w.GetYaxis().SetTitle("Events")
    w.GetYaxis().SetTitleOffset(1.3)
    o.GetXaxis().SetTitle("Photons in Evt")
    o.GetYaxis().SetTitle("Events")
    o.GetYaxis().SetTitleOffset(1.3)

    #Stats/Fit Options, stat box placement (top/bottom)
    gPad.Update()
    #	su = u.FindObject("stats")
    #	su.SetY1NDC(.1)
    #	su.SetY2NDC(.25)
    #	su.SetTextColor(ROOT.kRed)
    u.Fit(fit_u)
    #	sv = v.FindObject("stats")
    #	sv.SetY1NDC(.25)
    #	sv.SetY2NDC(.4)
    #	sv.SetTextColor(ROOT.kGreen)
    v.Fit(fit_v)
    #	sw = w.FindObject("stats")
    #	sw.SetY1NDC(.4)
    #	sw.SetY2NDC(.55)
    #	sw.SetTextColor(ROOT.kViolet)
    w.Fit(fit_w)
    gStyle.SetOptFit(0)
    gStyle.SetOptStat(0)
    #	st = t.FindObject("stats")
    #	st.SetY1NDC(.55)
    #	st.SetY2NDC(.7)
    #	st.SetTextColor(ROOT.kBlue)
    t.Fit(fit_t)
    #so = o.FindObject("stats")
    #so.SetY1NDC(.7)
    #so.SetY2NDC(.85)
    #so.SetTextColor(ROOT.kCyan)
    o.Fit(fit_o)
    return c1
示例#22
0
def export(info, args, npull=15):
    from ROOT import TFile, gROOT, gStyle, TPad, TCanvas
    from math import ceil
    gROOT.SetStyle("Plain")
    gStyle.SetOptFit(1)
    gStyle.SetOptStat(0)
    gROOT.SetBatch(1)

    # outdir = outdir_base % info.year
    # outvar = '%s/%s/' % (outdir,info.variable)
    # if not os.path.isdir(outvar): os.mkdir(outvar)
    # outsys = '%s/%s' % (outvar,info.sysdir)
    # if not os.path.isdir(outsys): os.mkdir(outsys)

    # outname = 'pulls_%s.pdf' % info.variable
    # output = '%s/%s' % (outsys,outname)
    output = "pulls.pdf"
    pulls = TFile.Open(args.g)
    canvas = pulls.Get("nuisances")
    objlist = canvas.GetListOfPrimitives()
    prefit = objlist.At(0).Clone()
    fit_bg = objlist.At(2).Clone()
    fit_bs = objlist.At(3).Clone()
    legend = objlist.At(6).Clone()

    prefit.GetYaxis().SetRangeUser(-4, 4)

    legend.SetX1(0.76)
    legend.SetX2(0.99)

    npages = int(ceil(float(prefit.GetNbinsX()) / npull))
    for page in range(npages):
        canvas = TCanvas()
        canvas.SetBottomMargin(0.15)
        canvas.SetRightMargin(0.25)
        canvas.SetGridx()
        canvas.Draw()
        xlo = page * npull + 1
        xhi = page * npull + npull
        if xhi > prefit.GetNbinsX(): xhi = prefit.GetNbinsX()
        prefit.GetXaxis().SetRange(xlo, xhi)

        prefit.Draw("E2")
        prefit.Draw("histsame")
        fit_bg.Draw("EPsame")
        fit_bs.Draw("EPsame")
        legend.Draw()

        if page == 0: canvas.SaveAs(output + "(")
        elif page + 1 == npages: canvas.SaveAs(output + ")")
        else: canvas.SaveAs(output)
def makeMassRes(inputDATA,inputMC,output,weights,weights2,trackType,funct,mcIsData,dataIsMC):
	style = setTDRStyle()
	gStyle.SetTitleYOffset(1.45)
	gStyle.SetTitleXOffset(1.45)
	gStyle.SetOptFit(0)
	gStyle.SetStatX(.9)
	gStyle.SetStatY(.9)
	
	(data_B,mc_B,ptdaB,ptmcB) = loadHistos(inputDATA,inputMC,"BB",weights,weights2,trackType,mcIsData,dataIsMC)
	(data_E,mc_E,ptdaE,ptmcE) = loadHistos(inputDATA,inputMC,"BE",weights,weights2,trackType,mcIsData,dataIsMC)
	# ~ (data_E2,mc_E2,ptdaE2,ptmcE2) = loadHistos(inputDATA,inputMC,"BE_neweta",weights,weights2,trackType,mcIsData,dataIsMC)

	drawMassRes(data_B,mc_B,output,"BB",ptdaB,ptmcB,trackType,funct,mcIsData,dataIsMC,inputDATA)
	drawMassRes(data_E,mc_E,output,"BE",ptdaE,ptmcE,trackType,funct,mcIsData,dataIsMC,inputDATA)
示例#24
0
def fitpos(run,tdc):
  f82=TFile("./histo%d_0.root" % run);
  #f82.cd("/run%d/TDC%d/LmAnalysis/Timing" % (run,tdc));
  f82.cd("/run%d/Chamber%d/Timing" % (run,tdc));
  c1=TCanvas();
  gStyle.SetOptFit();
  pos=[]
  pmean=[]
  for i in range(48):
    pos.append(0)
    pmean.append(0)
    #hstrip=f82.Get("/run%d/TDC%d/LmAnalysis/Timing/hdtpos%d" % (run,tdc,i+71));
    hstrip=f82.Get("/run%d/Chamber%d/Timing/All/hdtpos%d" % (run,tdc,i+71));
    if (hstrip == None):
      continue
    hstrip.Rebin(2)
    
    hstrip.Draw()
    c1.Update()

    print("Enter min max")
    #hmin = float(raw_input())
    #hmax = float(raw_input())
    hmin=-20.
    hmax=20.
    print(hmin,hmax)
    #scfit=TF1("scfit","gaus",hstrip.GetMean()-3.*hstrip.GetRMS(),hstrip.GetMean()+3.*hstrip.GetRMS())
    #hstrip.GetXaxis().SetRangeUser(hstrip.GetMean()-3.*hstrip.GetRMS(),hstrip.GetMean()+3.*hstrip.GetRMS())
    
    scfit=TF1("scfit","gaus",hmin,hmax)
    hstrip.GetXaxis().SetRangeUser(hmin,hmax)
    hstrip.Fit("scfit","Q");
    dtmean=scfit.GetParameter(1)
    dtres=scfit.GetParameter(2)
    hstrip.Draw()
    c1.Update()
    #c1.SaveAs("Run%d_Strip_pos.png" % (run));

    val = raw_input()
    pmean[i]=hstrip.GetMean()
    if (dtres>1. and  dtres<4):
      pos[i]=dtmean
    else:
      pos[i]=hstrip.GetMean()
  print(pos)
  print(pmean)
  
  for i in range(12):
    print("fe1_2tr[%d]=%5.3f;" % (i,pos[i]))
示例#25
0
 def initGraphics(self, ndet, nlb):
     "Initialise graphics and setup histogram for status matrix"
     from ROOT import gROOT, TCanvas, TH2F, gStyle
     hist = TH2F(
         "DetectorStatus", "%s tag %s runs %i to %i (%i LBs)" %
         (self.foldername, self.tag, self.runmin, self.runmax, nlb),
         ndet + 1, 0.5, ndet + 1.5, nlb, 0.5, nlb + 0.5)
     hist.Fill(ndet + 1, 1, 49.)
     hist.SetNdivisions(0)
     gROOT.SetStyle("Plain")
     gStyle.SetPalette(0)
     gStyle.SetOptStat(0)
     gStyle.SetOptFit(0)
     canvas = TCanvas(self.foldername, self.foldername, 0, 0, 500, 600)
     return (hist, canvas)
示例#26
0
def set_statbox(x=.95,
                y=.88,
                w=.16,
                entries=3,
                only_fit=False,
                opt=None,
                form=None):
    if only_fit:
        gStyle.SetOptStat(0011)
        gStyle.SetOptFit(1)
    gStyle.SetOptStat(opt) if opt is not None else do_nothing()
    gStyle.SetFitFormat(form) if form is not None else do_nothing()
    gStyle.SetStatX(x)
    gStyle.SetStatY(y)
    gStyle.SetStatW(w)
    gStyle.SetStatH(.04 * entries)
示例#27
0
 def _initDefaultStyle(self):
     gROOT.Reset()
     gROOT.SetStyle("Plain")
     #gStyle.SetOptStat(0)
     gStyle.SetOptFit(1111)
     gStyle.SetPadLeftMargin(0.1)
     gStyle.SetPadBottomMargin(0.1)
     gStyle.SetMarkerSize(1.5)
     gStyle.SetHistLineWidth(1)
     gStyle.SetStatFontSize(0.025)
     gStyle.SetTitleFontSize(0.05)
     gStyle.SetTitle(
         'CMS Preliminary tH, H#to#tau#tau, 19.7 fb^{-1} at 8 TeV')
     gStyle.SetTitleSize(0.06, "XYZ")
     gStyle.SetLabelSize(0.05, "XYZ")
     gStyle.SetNdivisions(510, "XYZ")
示例#28
0
def setStyle():
    gROOT.Reset()
    icol = 0
    # WHITE
    font = 42
    # Helvetica
    tsize = 0.05
    gStyle.SetFrameBorderMode(icol)
    gStyle.SetFrameFillColor(icol)
    gStyle.SetCanvasBorderMode(icol)
    gStyle.SetCanvasColor(icol)
    gStyle.SetPadBorderMode(icol)
    gStyle.SetPadColor(icol)
    gStyle.SetStatColor(icol)
    gStyle.SetPaperSize(20, 26)
    gStyle.SetPadTopMargin(0.05)
    gStyle.SetPadRightMargin(0.08)
    gStyle.SetPadBottomMargin(0.15)
    gStyle.SetPadLeftMargin(0.12)
    gStyle.SetTitleXOffset(1.05)
    gStyle.SetTitleYOffset(0.95)
    gStyle.SetTextFont(font)
    gStyle.SetTextSize(tsize)
    gStyle.SetLabelFont(font, "x")
    gStyle.SetTitleFont(font, "x")
    gStyle.SetLabelFont(font, "y")
    gStyle.SetTitleFont(font, "y")
    gStyle.SetLabelFont(font, "z")
    gStyle.SetTitleFont(font, "z")
    gStyle.SetLabelSize(tsize * 0.85, "x")
    gStyle.SetTitleSize(tsize * 1.10, "x")
    gStyle.SetLabelSize(tsize * 0.85, "y")
    gStyle.SetTitleSize(tsize * 1.10, "y")
    gStyle.SetLabelSize(tsize * 0.85, "z")
    gStyle.SetTitleSize(tsize * 1.10, "z")
    gStyle.SetMarkerStyle(20)
    gStyle.SetMarkerSize(1.)
    gStyle.SetHistLineWidth(2)
    gStyle.SetLineStyleString(2, "[12 12]")
    # postscript dashes
    gStyle.SetEndErrorSize(0.)
    # gStyle.SetOptTitle(0);
    gStyle.SetOptStat(0)
    gStyle.SetOptFit(0)
    gStyle.SetPadTickX(1)
    gStyle.SetPadTickY(1)
    gStyle.SetPaintTextFormat("4.1f")
示例#29
0
def plotPerBxStep(options):
    """Save histograms (per BX and step) to PDF files"""
    name = options['scan'] + '_' + options['name'] + options['extra']
    if 'method' in options:
        name += '_' + options['method']
    f = openRootFileR(name)
    for bx in options['crossings']:
        for step in range(len(O['nominalPos'][options['scan']])):
            histname = plotName(name+'_bx'+str(bx)+'_step'+str(step), \
                                timestamp=False)
            filename = plotName(name+'_bx'+str(bx)+'_step'+str(step), \
                                timestamp=True)
            filepath = plotPath(name+'_bx'+str(bx)+'_step'+str(step), \
                                timestamp=True)
            print '<<< Save plot:', filepath
            hist = f.Get(histname)
            canvas = TCanvas()
            canvas.SetLogx(options['logx'])
            canvas.SetLogy(options['logy'])
            gStyle.SetOptStat(options['optstat'])
            gStyle.SetOptFit(options['optfit'])
            hist.Draw()
            gPad.Update()
            hist.GetXaxis().SetTitle(options['xtitle'])
            hist.GetXaxis().SetRangeUser(options['xmin'], options['xmax'])
            hist.GetYaxis().SetTitle(options['ytitle'])
            hist.GetYaxis().SetTitleOffset(1.2)
            for axis in [hist.GetXaxis(), hist.GetYaxis()]:
                axis.SetTitleFont(133)
                axis.SetTitleSize(16)
                axis.SetLabelFont(133)
                axis.SetLabelSize(12)
                axis.CenterTitle()
            stats = hist.FindObject('stats')
            stats.SetTextFont(133)
            stats.SetTextSize(16)
            drawSignature(filename)
            gPad.Modified()
            gPad.Update()
            if 'custom' in options:
                extragraphs = options['custom'](hist)
            canvas.Print(filepath)
            canvas.Close()
    closeRootFile(f, name)
def main():
    # configure and run
    _MGR = sf2r_manager(DEBUG)
    _MGR.ff_type_detector()
    plots = _MGR.run()
    file = None
    if not os.path.exists('fluka2root.root'):
        file = TFile('fluka2root.root', 'new')
    else:
        file = TFile('fluka2root.root', 'recreate')

    # set for apperance
    c = TCanvas('USRTRACK CARTESIAN REFERENCE FRAME 2D - XY',
                'USRTRACK CARTESIAN REFERENCE FRAME 2D - XY', 670, 400)
    gStyle.SetPalette(1)
    gStyle.SetOptStat(0)
    gStyle.SetOptFit(0)

    # make a test plot and store plots in file
    for plot in plots:
        if plot.get_type() == '1DPLOT':
            if PLOT1D:
                plot.get_histo().Draw()
                plot.get_histo().Write()
        if plot.get_type() == '2DPLOT':
            if PLOT2D:
                #gPad.SetLogz()
                #gPad.SetGridx()
                #gPad.SetGridy()
                #plot.get_histo().Draw('P')
                plot.get_histo().Write()
        if plot.get_type() == '3DPLOT':
            if PLOT3D:
                #gPad.SetLogz();
                #gPad.SetGridx();
                #gPad.SetGridy();
                #plot.get_histo().Draw('P')
                plot.get_histo().Write()

    file.Close()

    print ' --> Press enter to finish... '
    raw_input()