Skip to content
Snippets Groups Projects

First snippet for Joseph

  • Clone with SSH
  • Clone with HTTPS
  • Embed
  • Share
    The snippet can be accessed without any authentication.
    Authored by Felicia Volle

    A plotting script which needs to be adapted.

    Edited
    PlotMyNicePlots.py 8.14 KiB
    #! /usr/bin/python
    
    ################# PlotMyNicePlots.py ############################
    #                                                                   #
    #    Author: Felicia Volle                                          #
    #    Date:   21/06/2025                                             #
    #    Description: For Joseph's Dark Photon internship               #
    #    Usage:  python PlotMyNicePlots.py -f /path/to/my/file.root     #
    #            -t Rho_Tuple_Prompt/DecayTree                          #
    #                                                                   #
    #####################################################################
    
    
    ################# IMPORT ############################################
    
    import os, sys
    from ROOT import TFile, TLatex, TH1F, TPaveText, TCanvas, TLegend, gROOT, gStyle, kBlue, kOrange, TMath
    gROOT.SetBatch(True)
    import argparse
    
    ################# VARIABLES AND DICTIONNARIES #######################
    
    # Example selection requirement, to be adapted for Dark Photons
    VetoDict = {'PhiVeto':'TMath::Abs(Phi_M -1020) > 12',
        }
    
    ################# FUNCTION DEFINITION ###############################
    
    
    def get_args():
        parser = argparse.ArgumentParser(description='Plotting Options')
        parser.add_argument('-f', '--filename', type=str,
                            help='''What is the name of the file ?''',
                            required=True)
        parser.add_argument('-t', '--tree', type=str,
                            help='''What is the name of the tree ?''',
                            required=True)
        parser.add_argument('-p', '--path', type=str, 
                            help='''What is the path to VetoPlots ?''',
                            required=True)
        parser.add_argument('-a', '--angle', type=str,
                            help='''Plot which angle ?''', required=True)
        parser.add_argument('-s', '--selectionFile', type=str,
                            help='''Where is selection file ?''', 
                            required=False, 
                            default='1==1')
        return parser.parse_args()
    
    
    def getCuts(cutsFile):
        """
        Read cuts from a .txt file and return a string
        Cuts on different lines in the file are concatenated
        with an && string.
        :cutsFile: type str
        Name of the file that contains the cuts
        """
        with open(cutsFile, 'r') as f:
            cuts = f.readlines()
            cuts = [c.strip() for c in cuts]
            cut_string = " && ".join(cuts)
        return cut_string
    
    
    def get_correctExpression(x):
        # TLatex label has better quality, but no #ell, 
        # therefore use TMathText for cosTheta_lepton
        AngleDict={'Phi' : ['Phi', '#phi', 40, -TMath.Pi(), TMath.Pi()], 
                   'cosTl':['cosTheta_lepton', '\\cos(\\theta_{\\ell})', 40, -1, 1], 
                   'cosTp':['cosTheta_Lst', 'cos(#theta_{p})', 40, -1, 1]}
        return AngleDict[x]
    
    def get_correctExpression_UCAS(x):
        # TLatex label has better quality, but no #ell, 
        # therefore use TMathText for cosTheta_lepton
        AngleDict={'Phi' : ['phi', '#phi', 40, -TMath.Pi(), TMath.Pi()], 
                   'cosTl':['cos_theta_l', '\\cos(\\theta_{\\ell})', 40, -1, 1], 
                   'cosTp':['cos_theta_Lz', 'cos(#theta_{p})', 40, -1, 1]}
        return AngleDict[x]
    
    
    def drawAngles( a, inputTree, TriggerSel, year, name_of_bin, Path, pK, NicePK, nice_bin_name, qsq_bin_min, qsq_bin_max, mpKMin, mpKMax, GeV2ToMeV2, L1520):
        cName = TCanvas('c', 'c', 0, 0, 600, 450)
        xName, xAxis, xBins, xmin, xmax = get_correctExpression(a)
        x2Name, x2Axis, x2Bins, x2min, x2max = get_correctExpression_UCAS(a)
        BinWidth = (xmax - xmin)/xBins
    
        yAxis = 'Normalized entries / (%.2f)' % (BinWidth)
    
        
        qsq = "Jpsi_M*Jpsi_M"
        q2_cut = "({} >= {} && {} <= {})".format(qsq, qsq_bin_min*GeV2ToMeV2, qsq, qsq_bin_max*GeV2ToMeV2)
    
        MCperBin = 'B_BKGCAT <= 10 && '+q2_cut
        OnlyTrigger = MCperBin + " && " + TriggerSel
        Sel = OnlyTrigger
    
        # Apply JPsi Veto in rare mode
        if (name_of_bin != 'JPsi' and name_of_bin != 'Psi2S'):
            Sel = OnlyTrigger+' && TMath::Abs(LtoK_M - 3097)>35'
    
        pK, NicePK = '', ''
        if L1520 == True:
            Lst_Cut = f"(X_M >= {mpKMin} && X_M <= {mpKMax})" 
            Sel = Sel + " && " + Lst_Cut
    
        h1 = TH1F("h1", "Angle def Orsay", xBins, xmin, xmax)
        inputTree.Project("h1", xName, "( "+Sel+")*PIDweight")
    
        h2 = TH1F("h2", "Angle def UCAS", xBins, xmin, xmax)
        inputTree.Project("h2", x2Name, "( "+Sel+")*PIDweight")
    
        # Draw Normalized 
        h1.Scale(1.0/h1.Integral())
        h2.Scale(1.0/h2.Integral())
    
        h1.GetXaxis().SetTitle( xAxis )
        h1.GetYaxis().SetTitle( yAxis )
        h1.SetTitle("")
    
        maxi = h1.GetBinContent(h1.GetMaximumBin())
        if h2.GetBinContent(h2.GetMaximumBin()) > maxi :
            maxi = h2.GetBinContent(h2.GetMaximumBin())
    
        mini = h1.GetBinContent(h1.GetMinimumBin())
        if h2.GetBinContent(h2.GetMinimumBin()) < mini :
            mini = h2.GetBinContent(h2.GetMinimumBin())
    
    
        h1.SetMaximum(maxi+(maxi-mini)*0.5)
        h1.SetMinimum(mini-(maxi-mini)*0.7)
    
        h1.SetLineColor(kOrange-3)
        h1.SetMarkerColor(kOrange-3)
    
        h2.SetLineColor(kBlue+2)
        h2.SetMarkerColor(kBlue+2)
    
        #h1.Draw("AXIS") 
        h1.DrawCopy("L")
        h2.DrawCopy("L SAME")
    
        # LHCb label
        lhcbName = TPaveText(gStyle.GetPadLeftMargin() + 0.05,
                             0.87 - gStyle.GetPadTopMargin(),
                             gStyle.GetPadLeftMargin() + 0.20,
                             0.95 - gStyle.GetPadTopMargin(),
                             "BRNDC")
        lhcbName.AddText("LHCb unofficial")
        lhcbName.SetFillColor(0)
        lhcbName.SetTextAlign(12)
        lhcbName.SetTextSize(0.06)
        lhcbName.SetBorderSize(0)
        lhcbName.Draw()
     
        lhcbText = TLatex() 
        lhcbText.SetTextFont(132)
        lhcbText.SetTextSize(0.06)
        lhcbText.SetTextAlign(12)
        lhcbText.DrawLatexNDC(0.6, 0.91-gStyle.GetPadTopMargin(), nice_bin_name+NicePK) #0.85
    
        cName.Update()
        
        legend = TLegend(0.55, 0.17, 0.92, 0.35)
    
        legend.AddEntry(h1, "Angle def Orsay", "lep")
        legend.AddEntry(h2, "Angle def UCAS", "lep")
    
        legend.Draw()
        cName.Update()
    
        if not os.path.isdir(Path+'/VetoPlots/AngleComparison'):
            os.mkdir(Path+'/VetoPlots/AngleComparison')
    
        PlotName = Path+'/VetoPlots/AngleComparison/'+a+'_'+year+'_'+pK+'_'+name_of_bin+'.png'
        cName.SaveAs(PlotName)
        
        del h1
        del h2
    
        cName.Close()
        return PlotName
    
    
    def getVariableList(a):
        aName = get_correctExpression(a)[0]
        uName = get_correctExpression_UCAS(a)[0]
        l = ['X_M', 'Jpsi_M', 'B_M']
        l.append(aName)
        l.append(uName)
        return l
    
    
    
    ################# MAIN ##############################################
    
    if __name__ == '__main__':
        args  = get_args()
        fName = args.filename
        tree  = args.tree
        path  = args.path
        a     = args.angle
        sF    = args.selectionFile
    
        year  = fName.split("_")[-2]
        Scale = 1
    
        sys.path.insert(1, p)
        #sys.path.append(path)
        from setup import q2list, q2Dict, getMCcutstring, mpKMax, mpKMin, GeV2ToMeV2
    
        iF = TFile(fName, "READ")
        iT = iF.Get(tree)
        
        BranchList = getVariableList(a)
        for activeBranchName in BranchList:
            iT.SetBranchStatus(activeBranchName, 1)
        
        gROOT.LoadMacro(path+"/lhcbStyle.C")
    
        # Trigger and loose PID selection specified in FinalSelection.txt
        TrigSel = "1==1"
        if sF != 'FinalSelection':
            TrigSel = getCuts(path+sF)
    
        print(" <<< START PLOTTING ANGLE {} >>> ".format(a))
        print(" <<< TRIGGER SEL = {} >>> ".format(TrigSel))
    
        for name_of_bin in q2list: #loop over the bins
            print ('----------------------------------------------')
            qsq_bin_min, qsq_bin_max, nice_bin_name =  q2Dict[name_of_bin]
            print (f'---- qsq_bin_min {qsq_bin_min}  GeV2')
            print (f'---- qsq_bin_max {qsq_bin_max}  GeV2')
    
            tot_cut, pK, NicePK = getMCcutstring(name_of_bin, qsq_bin_min, qsq_bin_max, L1520=False, Truth=False, PID=True)
            # Once around L1520
            #c2 = drawAngles(a, iT, TrigSel, year, name_of_bin, path, pK, NicePK, nice_bin_name, qsq_bin_min, qsq_bin_max, mpKMin, mpKMax, GeV2ToMeV2, L1520=True)
            # Once all pK region
            c1 = drawAngles(a, iT, TrigSel, year, name_of_bin, path, pK, NicePK, nice_bin_name, qsq_bin_min, qsq_bin_max, mpKMin, mpKMax, GeV2ToMeV2, L1520=False)
    
        iF.Close()
    
    #EOF
    lhcbStyle.C 6.29 KiB
    // all users - please change the name of this file to lhcbStyle.C
    // Commits to lhcbdocs svn of .C files are not allowed
    {
    
      // define names for colours
      Int_t black  = 1;
      Int_t red    = 2;
      Int_t green  = 3;
      Int_t blue   = 4;
      Int_t yellow = 5; 
      Int_t magenta= 6;
      Int_t cyan   = 7;
      Int_t purple = 9;
      
    
      ////////////////////////////////////////////////////////////////////
      // PURPOSE:
      //
      // This macro defines a standard style for (black-and-white) 
      // "publication quality" LHCb ROOT plots. 
      //
      // USAGE:
      //
      // Include the lines
      //   gROOT->ProcessLine(".L lhcbstyle.C");
      //   lhcbStyle();
      // at the beginning of your root macro.
      //
      // Example usage is given in myPlot.C
      //
      // COMMENTS:
      //
      // Font:
      // 
      // The font is chosen to be 132, this is Times New Roman (like the text of
      //  your document) with precision 2.
      //
      // "Landscape histograms":
      //
      // The style here is designed for more or less square plots.
      // For longer histograms, or canvas with many pads, adjustements are needed. 
      // For instance, for a canvas with 1x5 histograms:
      //  TCanvas* c1 = new TCanvas("c1", "L0 muons", 600, 800);
      //  c1->Divide(1,5);
      //  Adaptions like the following will be needed:
      //  gStyle->SetTickLength(0.05,"x");
      //  gStyle->SetTickLength(0.01,"y");
      //  gStyle->SetLabelSize(0.15,"x");
      //  gStyle->SetLabelSize(0.1,"y");
      //  gStyle->SetStatW(0.15);
      //  gStyle->SetStatH(0.5);
      //
      // Authors: Thomas Schietinger, Andrew Powell, Chris Parkes, Niels Tuning
      // Maintained by Editorial board member (currently Niels)
      ///////////////////////////////////////////////////////////////////
    
      // Use times new roman, precision 2 
      Int_t lhcbFont        = 132;  // Old LHCb style: 62;
      // Line thickness
      Double_t lhcbWidth    = 2.00; // Old LHCb style: 3.00;
      // Text size
      Double_t lhcbTSize    = 0.055; 
      
      // use plain black on white colors
      gROOT->SetStyle("Plain"); 
      TStyle *lhcbStyle= new TStyle("lhcbStyle","LHCb plots style");
      
      //lhcbStyle->SetErrorX(0); //  don't suppress the error bar along X
    
      lhcbStyle->SetFillColor(1);
      lhcbStyle->SetFillStyle(1001);   // solid
      lhcbStyle->SetFrameFillColor(0);
      lhcbStyle->SetFrameBorderMode(0);
      lhcbStyle->SetPadBorderMode(0);
      lhcbStyle->SetPadColor(0);
      lhcbStyle->SetCanvasBorderMode(0);
      lhcbStyle->SetCanvasColor(0);
      lhcbStyle->SetStatColor(0);
      lhcbStyle->SetLegendBorderSize(0);
      lhcbStyle->SetLegendFont(132);
    
      // If you want the usual gradient palette (blue -> red)
      lhcbStyle->SetPalette(1);
      // If you want colors that correspond to gray scale in black and white:
      int colors[8] = {0,5,7,3,6,2,4,1};
      lhcbStyle->SetPalette(8,colors);
    
      // set the paper & margin sizes
      lhcbStyle->SetPaperSize(20,26);
      lhcbStyle->SetPadTopMargin(0.05);
      lhcbStyle->SetPadRightMargin(0.05); // increase for colz plots
      lhcbStyle->SetPadBottomMargin(0.16);
      lhcbStyle->SetPadLeftMargin(0.14);
      
      // use large fonts
      lhcbStyle->SetTextFont(lhcbFont);
      lhcbStyle->SetTextSize(lhcbTSize);
      lhcbStyle->SetLabelFont(lhcbFont,"x");
      lhcbStyle->SetLabelFont(lhcbFont,"y");
      lhcbStyle->SetLabelFont(lhcbFont,"z");
      lhcbStyle->SetLabelSize(lhcbTSize,"x");
      lhcbStyle->SetLabelSize(lhcbTSize,"y");
      lhcbStyle->SetLabelSize(lhcbTSize,"z");
      lhcbStyle->SetTitleFont(lhcbFont);
      lhcbStyle->SetTitleFont(lhcbFont,"x");
      lhcbStyle->SetTitleFont(lhcbFont,"y");
      lhcbStyle->SetTitleFont(lhcbFont,"z");
      lhcbStyle->SetTitleSize(1.2*lhcbTSize,"x");
      lhcbStyle->SetTitleSize(1.2*lhcbTSize,"y");
      lhcbStyle->SetTitleSize(1.2*lhcbTSize,"z");
    
      // use medium bold lines and thick markers
      lhcbStyle->SetLineWidth(lhcbWidth);
      lhcbStyle->SetFrameLineWidth(lhcbWidth);
      lhcbStyle->SetHistLineWidth(lhcbWidth);
      lhcbStyle->SetFuncWidth(lhcbWidth);
      lhcbStyle->SetGridWidth(lhcbWidth);
      lhcbStyle->SetLineStyleString(2,"[12 12]"); // postscript dashes
      lhcbStyle->SetMarkerStyle(20);
      lhcbStyle->SetMarkerSize(1.0);
    
      // label offsets
      lhcbStyle->SetLabelOffset(0.010,"X");
      lhcbStyle->SetLabelOffset(0.010,"Y");
    
      // by default, do not display histogram decorations:
      lhcbStyle->SetOptStat(0);  
      //lhcbStyle->SetOptStat("emr");  // show only nent -e , mean - m , rms -r
      // full opts at http://root.cern.ch/root/html/TStyle.html#TStyle:SetOptStat
      lhcbStyle->SetStatFormat("6.3g"); // specified as c printf options
      lhcbStyle->SetOptTitle(0);
      lhcbStyle->SetOptFit(0);
      //lhcbStyle->SetOptFit(1011); // order is probability, Chi2, errors, parameters
      //titles
      lhcbStyle->SetTitleOffset(0.95,"X");
      lhcbStyle->SetTitleOffset(0.95,"Y");
      lhcbStyle->SetTitleOffset(1.2,"Z");
      lhcbStyle->SetTitleFillColor(0);
      lhcbStyle->SetTitleStyle(0);
      lhcbStyle->SetTitleBorderSize(0);
      lhcbStyle->SetTitleFont(lhcbFont,"title");
      lhcbStyle->SetTitleX(0.0);
      lhcbStyle->SetTitleY(1.0); 
      lhcbStyle->SetTitleW(1.0);
      lhcbStyle->SetTitleH(0.05);
      
      // look of the statistics box:
      lhcbStyle->SetStatBorderSize(0);
      lhcbStyle->SetStatFont(lhcbFont);
      lhcbStyle->SetStatFontSize(0.05);
      lhcbStyle->SetStatX(0.9);
      lhcbStyle->SetStatY(0.9);
      lhcbStyle->SetStatW(0.25);
      lhcbStyle->SetStatH(0.15);
    
      // put tick marks on top and RHS of plots
      lhcbStyle->SetPadTickX(1);
      lhcbStyle->SetPadTickY(1);
    
      // histogram divisions: only 5 in x to avoid label overlaps
      lhcbStyle->SetNdivisions(505,"x");
      lhcbStyle->SetNdivisions(510,"y");
      
      gROOT->SetStyle("lhcbStyle");
      gROOT->ForceStyle();
    
      // add LHCb label
      TPaveText* lhcbName = new TPaveText(gStyle->GetPadLeftMargin() + 0.05,
                                          0.87 - gStyle->GetPadTopMargin(),
                                          gStyle->GetPadLeftMargin() + 0.20,
                                          0.95 - gStyle->GetPadTopMargin(),
                                          "BRNDC");
      lhcbName->AddText("LHCb");
      lhcbName->SetFillColor(0);
      lhcbName->SetTextAlign(12);
      lhcbName->SetBorderSize(0);
    
      TText *lhcbLabel = new TText();
      lhcbLabel->SetTextFont(lhcbFont);
      lhcbLabel->SetTextColor(1);
      lhcbLabel->SetTextSize(lhcbTSize);
      lhcbLabel->SetTextAlign(12);
    
      TLatex *lhcbLatex = new TLatex();
      lhcbLatex->SetTextFont(lhcbFont);
      lhcbLatex->SetTextColor(1);
      lhcbLatex->SetTextSize(lhcbTSize);
      lhcbLatex->SetTextAlign(12);
    
      cout << "-------------------------" << endl;  
      cout << "Set LHCb Style - Feb 2012" << endl;
      cout << "-------------------------" << endl;  
      
    }
    
    
    0% Loading or .
    You are about to add 0 people to the discussion. Proceed with caution.
    Please register or to comment