Beispiel #1
0
def main():
    # usage description
    usage = "Example: ./scripts/plotLimits.py -M Asymptotic -l logs -f qq --massrange 1200 7000 100"

    # input parameters
    parser = ArgumentParser(description='Script that plots limits for specified mass points',epilog=usage)
    parser.add_argument('analysis', type=str, help='Analysis name')
    parser.add_argument('model', type=str, help='Model name')

    parser.add_argument("-M", "--method", dest="method", required=True,
                        choices=['ProfileLikelihood', 'HybridNew', 'Asymptotic', 'MarkovChainMC', 'theta', 'HybridNewGrid'],
                        help="Method to calculate upper limits",
                        metavar="METHOD")
    parser.add_argument('--fit_function', type=str, default="f4", help="Name of fit function used for background estimate")
    parser.add_argument('--timesAE', action='store_true', help="Set y-axis to sigma*BR*A*e, instead of sigma*BR")
    parser.add_argument('--fitTrigger', action='store_true', help="Use trigger fit")
    parser.add_argument('--correctTrigger', action='store_true', help="Use trigger correction")
    parser.add_argument('--useMCTrigger', action='store_true', help="Use MC trigger emulation")
    #results_group = parser.add_mutually_exclusive_group(required=True)
    #results_group.add_argument("-l", "--logs_path", dest="logs_path",
    #                           help="Path to log files",
    #                           metavar="LOGS_PATH")
    #results_group.add_argument("-r", "--results_file", dest="results_file",
    #                           help="Path to a file containing results",
    #                           metavar="RESULTS_FILE")

    #parser.add_argument("-f", "--final_state", dest="final_state", required=True,
    #                    help="Final state (e.g. qq, qg, gg)",
    #                    metavar="FINAL_STATE")

    #parser.add_argument("-f2", "--finalstate2", dest="final_state2", required=True, help="hG,lG,hR, or lR", metavar="FINAL_STATE2")
    parser.add_argument("--noSyst", action="store_true", help="Make plots for limits without systematics")
    parser.add_argument("--freezeNuisances", type=str, help="Make plots for limits with frozen nuisance parameters")
    parser.add_argument("--postfix", dest="postfix", default='', help="Postfix for the output plot name (default: %(default)s)")

    parser.add_argument("--fileFormat", dest="fileFormat", default='pdf', help="Format of the output plot (default: %(default)s)")
    parser.add_argument("--saveObjects", type=str, help="Save plot objects")
    parser.add_argument("--extraText", dest="extraText", default='', help="Extra text on the plot (default: %(default)s)")

    parser.add_argument("--lumi_sqrtS", dest="lumi_sqrtS", default='19.7 fb^{-1} (8 TeV)', help="Integrated luminosity and center-of-mass energy (default: %(default)s)")

    parser.add_argument("--printResults", dest="printResults", default=False, action="store_true", help="Print results to the screen")

    mass_group = parser.add_mutually_exclusive_group(required=True)
    mass_group.add_argument("--mass",
                            type=int,
                            nargs = '*',
                            default = 1000,
                            help="Mass can be specified as a single value or a whitespace separated list (default: %(default)i)"
                            )
    mass_group.add_argument("--massrange",
                            type=int,
                            nargs = 3,
                            help="Define a range of masses to be produced. Format: min max step",
                            metavar = ('MIN', 'MAX', 'STEP')
                            )
    mass_group.add_argument("--masslist",
                            help = "List containing mass information"
                            )

    args = parser.parse_args()

    if args.method == 'HybridNew':
        searchmethod = 'Hybrid New'

    # mass points for which resonance shapes will be produced
    input_masses = []

    if args.massrange != None:
        MIN, MAX, STEP = args.massrange
        input_masses = range(MIN, MAX+STEP, STEP)
    elif args.masslist != None:
        # A mass list was provided
        print "Will create mass list according to", args.masslist
        masslist = __import__(args.masslist.replace(".py",""))
        input_masses = masslist.masses
    else:
        input_masses = args.mass
    # sort masses
    input_masses.sort()

    from ROOT import kTRUE, kFALSE, gROOT, gStyle, gPad, TGraph, TCanvas, TLegend, TF1, TFile
    from ROOT import kGreen, kYellow, kWhite

    # Make acc*eff TGraph
    ae_x = array('d',[325, 350, 400, 500, 600, 750, 900, 1200])
    if args.timesAE:
        ae_y = np.ones(len(ae_x))
    else:
        ae_y = array('d', [])
        for mass in ae_x:
            ae_y.append(analysis_config.simulation.get_signal_AE(args.analysis, args.model, int(mass)))
    acceptance_times_efficiency = TGraph(len(ae_x), ae_x, ae_y)
    #xs = array('d',[250,300,400,500,600,750,900,1200])

    #trigger_correctionl = TF1("trigbbl_efficiency", "(1. / (1. + TMath::Exp(-1. * (x - [0]) / [1])))**[2]", 175, 400)
    #trigger_correctionl.SetParameter(0, 1.82469e+02)
    #trigger_correctionl.SetParameter(1,  2.87768e+01)
    #trigger_correctionl.SetParameter(2,  9.11659e-01)

    #trigger_correctionh = TF1("trigbbh_efficiency", "(1. / (1. + TMath::Exp(-1. * (x - [0]) / [1])))**[2]", 300, 600)
    #trigger_correctionh.SetParameter(0, 3.61785e+02)
    #trigger_correctionh.SetParameter(1,  3.16523e+01)
    #trigger_correctionh.SetParameter(2,  4.84357e-01)
    #if args.timesAE:
    #    ys = np.ones(len(xs))
    #else:
    #    if args.analysis == "trigbbh_CSVTM" and args.model == "Hbb":
    #    	#ys = array('d',[188./19751.,1304./19993.,2697./49494.,881./19999.,534./19598.])
    #		ys = array('d',[24./19737.,188./19751.,1171./19984.,1419./19992.,1304./19993.,2697./49494.,881./19999.,534./19598.])
    #		#graphMod = trigger_correctionh
    #    elif args.analysis == "trigbbl_CSVTM" and args.model == "Hbb":
    #		#ys = array('d',[30./2797.,1583./19995.,1295./19996.,999./19996.,528./19999.])
    #		ys = array('d',[574./19737.,763./39502.,651./19984.,583./19992.,984./39986.,1905./98988.,656./39998.,369./39196.])
    #		#graphMod = trigger_correctionh
    #    elif args.analysis == "trigbbh_CSVTM" and args.model == "RSG":
    #		#ys = array('d',[109./19751.,488./19993.,954./49494.,328./19999.,182./19598.])
    #		ys = array('d',[40./19977.,30./2797.,1522./19991.,1640./19396.,1583./19995.,1295./19996.,999./19996.,528./19999.])
    #		#graphMod = trigger_correctionl
    #    elif args.analysis == "trigbbl_CSVTM" and args.model == "RSG":
    #		#ys = array('d',[23./2797.,599./19995.,448./19996.,338./19996.,190./19999.])
    #		ys = array('d',[696./19977.,137./5594.,797./19991.,652./19396.,1206./39990.,891./39992.,675./39992.,379./39998.])
    #		#graphMod = trigger_correctionl

    ##ys = array('d',[1,1,1,1,1,1,1,1,])   

    #acceptance_times_efficiency = TGraph(len(xs),xs,ys)


    # arrays holding results
    masses = array('d')
    xs_obs_limits = array('d')
    xs_exp_limits = array('d')
    masses_exp = array('d')
    xs_exp_limits_1sigma = array('d')
    xs_exp_limits_1sigma_up = array('d')
    xs_exp_limits_2sigma = array('d')
    xs_exp_limits_2sigma_up = array('d')

    for mass in input_masses:
        print ">> Reading results for %s %s resonance with m = %i GeV..."%(args.analysis, args.model, int(mass))
        masses.append(mass)
        masses_exp.append(mass)

        # For masses above 1100, you scaled down the signal by 10 by hand, to help the limit setting.
        #if args.analysis == "trigbbh_CSVTM" and mass >= 1100:
        input_xs = 1./100.
        #else:
        #    input_xs = 1.

        if args.method == "HybridNewGrid":
            found_limit = {"obs":False, "exp0":False, "exp1":False, "exp2":False, "exp-1":False, "exp-2":False}
            for what in found_limit.keys():
                log_file_path = limit_config.get_combine_log_path_grid(args.analysis, args.model, mass, args.fit_function, what, systematics=(not args.noSyst), frozen_nps=args.freezeNuisances, fitTrigger=args.fitTrigger, correctTrigger=args.correctTrigger, useMCTrigger=args.useMCTrigger)
                print "Reading log file from " + log_file_path
                log_file = open(log_file_path, 'r')
                for line in log_file:
                    if re.search("^Limit: r <", line) and re.search("95%", line):
                        found_limit[what] = True
                        this_limit = float(line.split()[3])/acceptance_times_efficiency.Eval(mass)
                        print "Found limit for " + what + " = " + str(this_limit)
                        if what == "obs":
                            xs_obs_limits.append(this_limit * input_xs)
                        elif what == "exp0":
                            xs_exp_limits.append(this_limit * input_xs)
                        elif what == "exp1":
                            xs_exp_limits_1sigma_up.append(this_limit * input_xs)
                        elif what == "exp2":
                            xs_exp_limits_2sigma_up.append(this_limit * input_xs)
                        elif what == "exp-1":
                            xs_exp_limits_1sigma.append(this_limit * input_xs)
                        elif what == "exp-2":
                            xs_exp_limits_2sigma.append(this_limit * input_xs)
            if not found_limit["obs"]:
                xs_obs_limits.append(0)
            if not found_limit["exp0"]:
                xs_exp_limits.append(0)
            if not found_limit["exp1"]:
                xs_exp_limits_1sigma.append(0)
            if not found_limit["exp2"]:
                xs_exp_limits_1sigma_up.append(0)
            if not found_limit["exp-1"]:
                xs_exp_limits_2sigma.append(0)
            if not found_limit["exp-2"]:
                xs_exp_limits_2sigma_up.append(0)
            if len(masses) != len(xs_obs_limits):
                print "** ERROR: ** Could not find observed limit for m =", int(mass), "GeV. Aborting."
                sys.exit(1)
        else:
            print "Reading log file from " + limit_config.get_combine_log_path(args.analysis, args.model, mass, args.fit_function, args.method, systematics=(not args.noSyst), frozen_nps=args.freezeNuisances, fitTrigger=args.fitTrigger, correctTrigger=args.correctTrigger, useMCTrigger=args.useMCTrigger)
            if not os.path.exists((limit_config.get_combine_log_path(args.analysis, args.model, mass, args.fit_function, args.method, systematics=(not args.noSyst), frozen_nps=args.freezeNuisances, fitTrigger=args.fitTrigger, correctTrigger=args.correctTrigger, useMCTrigger=args.useMCTrigger))):
                print "[plot_limits] WARNING : Log file not found! Setting limits to zero and skipping this point."
                print "[plot_limits] WARNING : \t{}".format(limit_config.get_combine_log_path(args.analysis, args.model, mass, args.fit_function, args.method, systematics=(not args.noSyst), frozen_nps=args.freezeNuisances, fitTrigger=args.fitTrigger, correctTrigger=args.correctTrigger, useMCTrigger=args.useMCTrigger))
                xs_obs_limits.append(0)
                xs_exp_limits.append(0)
                xs_exp_limits_1sigma.append(0)
                xs_exp_limits_1sigma_up.append(0)
                xs_exp_limits_2sigma.append(0)
                xs_exp_limits_2sigma_up.append(0)
                continue
            log_file = open(limit_config.get_combine_log_path(args.analysis, args.model, mass, args.fit_function, args.method, systematics=(not args.noSyst), frozen_nps=args.freezeNuisances, fitTrigger=args.fitTrigger, correctTrigger=args.correctTrigger, useMCTrigger=args.useMCTrigger))

            foundMethod = False
            middle = 0
            # read the log file
            found_limit = {"obs":False, "exp":False, "exp+1":False, "exp+2":False, "exp-1":False, "exp-2":False}
            for line in log_file:
                if args.method == 'Asymptotic':
                    if re.search("^Observed Limit: r", line):
                        xs_obs_limits.append(float(line.split()[-1])/acceptance_times_efficiency.Eval(mass) * input_xs)
                        found_limit["obs"] = True
                        if mass == 325 and args.model == "ZPrime":
                            print "[debug] ZPrime 325 GeV limit = {}".format(xs_obs_limits[-1])
                            print "[debug] \tA*e={}, input_xs={}".format(acceptance_times_efficiency.Eval(mass), input_xs)
                    if re.search("^Expected 50.0%: r", line):
                        middle = float(line.split()[-1])
                        found_limit["exp"] = True
                        xs_exp_limits.append(middle/acceptance_times_efficiency.Eval(mass) * input_xs)
                    if re.search("^Expected 16.0%: r", line):
                        xs_exp_limits_1sigma.append((float(line.split()[-1]))/acceptance_times_efficiency.Eval(mass) * input_xs)
                        found_limit["exp-1"] = True
                    if re.search("^Expected 84.0%: r", line):
                        xs_exp_limits_1sigma_up.append(float(line.split()[-1])/acceptance_times_efficiency.Eval(mass) * input_xs)
                        found_limit["exp+1"] = True
                    if re.search("^Expected  2.5%: r", line):
                        xs_exp_limits_2sigma.append(float(line.split()[-1])/acceptance_times_efficiency.Eval(mass) * input_xs)
                        found_limit["exp-2"] = True
                    if re.search("^Expected 97.5%: r", line):
                        xs_exp_limits_2sigma_up.append(float(line.split()[-1])/acceptance_times_efficiency.Eval(mass) * input_xs)
                        found_limit["exp+2"] = True
                elif args.method == 'theta':
                    if re.search('^# x; y; yerror', line):
                        foundMethod = True
                    if line.split()[0] == '0' and foundMethod:
                        xs_obs_limits.append(float(line.split()[1])/acceptance_times_efficiency.Eval(mass) * input_xs)
                else:
                    searchmethod = "Hybrid New"
                    if re.search(' -- ' + searchmethod, line):
                        foundMethod = True
                    if re.search("^Limit: r", line) and foundMethod:
                        xs_obs_limits.append(float(line.split()[3])/acceptance_times_efficiency.Eval(mass) * input_xs)
                        found_limit["obs"] = True
                        print "[debug] Found limit " + str(xs_obs_limits[-1])

            if not found_limit["obs"]:
                xs_obs_limits.append(0)
            if not found_limit["exp"]:
                xs_exp_limits.append(0)
            if not found_limit["exp+1"]:
                xs_exp_limits_1sigma.append(0)
            if not found_limit["exp+2"]:
                xs_exp_limits_1sigma_up.append(0)
            if not found_limit["exp-1"]:
                xs_exp_limits_2sigma.append(0)
            if not found_limit["exp-2"]:
                xs_exp_limits_2sigma_up.append(0)
            if len(masses) != len(xs_obs_limits):
                print "** ERROR: ** Could not find observed limit for m =", int(mass), "GeV. Aborting."
                sys.exit(1)

        if args.method == 'Asymptotic' or args.method == 'HybridNewGrid':
            if len(masses) != len(xs_exp_limits):
                print "** ERROR: ** Could not find expected limit for m =", int(mass), "GeV. Aborting."
                print "masses = ",
                print masses
                print "xs_exp_limits = ",
                print xs_exp_limits
                sys.exit(1)

            if len(masses) != len(xs_exp_limits_1sigma):
                print "** ERROR: ** Could not find expected 1 sigma down limit for m =", int(mass), "GeV. Aborting."
                print "masses = ",
                print masses
                print "xs_exp_limits_1sigma = ",
                print xs_exp_limits_1sigma
                sys.exit(1)

            if len(masses) != len(xs_exp_limits_1sigma_up):
                print "** ERROR: ** Could not find expected 1 sigma up limit for m =", int(mass), "GeV. Aborting."
                print "masses = ",
                print masses
                print "xs_exp_limits_1sigma_up = ",
                print xs_exp_limits_1sigma_up
                sys.exit(1)

            if len(masses) != len(xs_exp_limits_2sigma):
                print "** ERROR: ** Could not find expected 2 sigma down limit for m =", int(mass), "GeV. Aborting."
                sys.exit(1)

            if len(masses) != len(xs_exp_limits_2sigma_up):
                print "** ERROR: ** Could not find expected 2 sigma up limit for m =", int(mass), "GeV. Aborting."
                sys.exit(1)
    if args.method == 'Asymptotic' or args.method == 'HybridNewGrid':
        # complete the expected limit arrays
        for i in range(0,len(masses)):
            masses_exp.append( masses[len(masses)-i-1] )
            xs_exp_limits_1sigma.append( xs_exp_limits_1sigma_up[len(masses)-i-1] )
            xs_exp_limits_2sigma.append( xs_exp_limits_2sigma_up[len(masses)-i-1] )

    if args.printResults:
        print "masses =", masses.tolist()
        print "xs_obs_limits =", xs_obs_limits.tolist()
        print "xs_exp_limits =", xs_exp_limits.tolist()
        print ""
        print "masses_exp =", masses_exp.tolist()
        print "xs_exp_limits_1sigma =", xs_exp_limits_1sigma.tolist()
        print "xs_exp_limits_2sigma =", xs_exp_limits_2sigma.tolist()


    gROOT.SetBatch(kTRUE);
    gStyle.SetOptStat(0)
    gStyle.SetOptTitle(0)
    gStyle.SetTitleFont(42, "XYZ")
    gStyle.SetTitleSize(0.05, "XYZ")
    gStyle.SetLabelFont(42, "XYZ")
    gStyle.SetLabelSize(0.05, "XYZ")
    gStyle.SetCanvasBorderMode(0)
    gStyle.SetFrameBorderMode(0)
    gStyle.SetCanvasColor(kWhite)
    gStyle.SetPadTickX(1)
    gStyle.SetPadTickY(1)
    gStyle.SetPadLeftMargin(0.15)
    gStyle.SetPadRightMargin(0.05)
    gStyle.SetPadTopMargin(0.05)
    gStyle.SetPadBottomMargin(0.15)
    gROOT.ForceStyle()

    # theory curves: gg
    massesS8 = array('d', [1000.0,1100.0,1200.0,1300.0,1400.0,1500.0,1600.0,1700.0,1800.0,1900.0,2000.0,2100.0,2200.0,2300.0,2400.0,2500.0,2600.0,2700.0,2800.0,2900.0,3000.0,3100.0,3200.0,3300.0,3400.0,3500.0,3600.0,3700.0,3800.0,3900.0,4000.0,4100.0,4200.0,4300.0,4400.0,4500.0,4600.0,4700.0,4800.0,4900.0,5000.0,5100.0,5200.0,5300.0,5400.0,5500.0,5600.0,5700.0,5800.0,5900.0,6000.0])
    xsS8 = array('d', [5.46E+02,3.12E+02,1.85E+02,1.12E+02,7.19E+01,4.59E+01,3.02E+01,2.01E+01,1.37E+01,9.46E+00,6.55E+00,4.64E+00,3.27E+00,2.36E+00,1.70E+00,1.24E+00,9.11E-01,6.69E-01,4.97E-01,3.71E-01,2.78E-01,2.07E-01,1.55E-01,1.19E-01,9.26E-02,7.08E-02,5.43E-02,4.15E-02,3.22E-02,2.50E-02,1.92E-02,1.51E-02,1.19E-02,9.25E-03,7.35E-03,5.86E-03,4.53E-03,3.66E-03,2.91E-03,2.33E-03,1.86E-03,1.45E-03,1.12E-03,8.75E-04,6.90E-04,5.55E-04,4.47E-04,3.63E-04,2.92E-04,2.37E-04,1.97E-04])

    graph_xsS8 = TGraph(len(massesS8),massesS8,xsS8)
    graph_xsS8.SetLineWidth(3)
    graph_xsS8.SetLineStyle(8)
    graph_xsS8.SetLineColor(6)

    # theory curves: qg
    massesString = array('d', [1000.0,1100.0,1200.0,1300.0,1400.0,1500.0,1600.0,1700.0,1800.0,1900.0,2000.0,2100.0,2200.0,2300.0,2400.0,2500.0,2600.0,2700.0,2800.0,2900.0,3000.0,3100.0,3200.0,3300.0,3400.0,3500.0,3600.0,3700.0,3800.0,3900.0,4000.0,4100.0,4200.0,4300.0,4400.0,4500.0,4600.0,4700.0,4800.0,4900.0,5000.0,5100.0,5200.0,5300.0,5400.0,5500.0,5600.0,5700.0,5800.0,5900.0,6000.0,6100.0,6200.0,6300.0,6400.0,6500.0,6600.0,6700.0,6800.0,6900.0,7000.0,7100.0,7200.0,7300.0,7400.0,7500.0,7600.0,7700.0,7800.0,7900.0,8000.0,8100.0,8200.0,8300.0,8400.0,8500.0,8600.0,8700.0,8800.0,8900.0,9000.0,9100.,9200.,9300.,9400.,9500.,9600.,9700.,9800.,9900.,10000.])
    xsString = array('d', [8316.184311558545,5312.93137758767,3435.0309937336524,2304.4139502741305,1569.8115447896687,1090.9516635659693,770.901859690924,551.9206062572061,399.69535383507633,293.77957451762086,218.15126842827823,162.87634729465125,123.17685479653694,93.63530805932386,71.53697229809124,55.37491301647483,42.75271508357369,33.36378355470234,26.06619302090876,20.311817606835643,16.1180931789545,12.768644973921226,10.142660425967444,8.057990848043234,6.400465846290908,5.115134438331436,4.132099789492928,3.3193854239538734,2.6581204529344302,2.157554604919995,1.7505176068913348,1.4049155245498584,1.140055677916783,0.9253251132104159,0.7522038169131606,0.6119747371392215,0.49612321727328523,0.40492020959456737,0.33091999402250655,0.27017917021492555,0.2201693919322846,0.17830700070267996,0.14564253802358157,0.11940534430331146,0.09694948234356839,0.0793065371847468,0.06446186373361917,0.05282660618352478,
                           0.0428516302310620888,0.0348997638039910363,0.0283334766442618227,0.0231416918363592127,0.0187417921340763783,0.0153501307395115115,0.0124396534127133717,0.0100542205744949455,0.0081744954858627415,0.0066338099362915941,0.0053365711503318145,0.00430912459914657443,0.00346381039244064343,0.00278602671711227174,0.00225154342228859257,0.0018082930150063248,0.00143929440338502119,0.0011581373956044489,0.00091869589873893118,0.00073410823691329855,0.00058669382997948734,0.0004661568745858897,0.000368716655469570365,0.000293168485206959169,0.000230224535021638668,0.000182317101888465142,0.000143263359883433282,0.000112630538527214965,0.000088189175598406759,0.000068708474367442343,0.000053931726669273556,0.0000416417855733682702,0.0000326529676755488658,0.0000254365480426201587,0.0000198410151166864761,0.0000154034425617473576,0.0000119095554601641413,9.2537574320108232e-6,7.2155417437856749e-6,5.6130924422251982e-6,4.36634755605624901e-6,3.39717456406994868e-6,2.6766018046173896e-6])

    massesQstar = array('d', [1000.0,1100.0,1200.0,1300.0,1400.0,1500.0,1600.0,1700.0,1800.0,1900.0,2000.0,2100.0,2200.0,2300.0,2400.0,2500.0,2600.0,2700.0,2800.0,2900.0,3000.0,3100.0,3200.0,3300.0,3400.0,3500.0,3600.0,3700.0,3800.0,3900.0,4000.0,4100.0,4200.0,4300.0,4400.0,4500.0,4600.0,4700.0,4800.0,4900.0,5000.0,5100.0,5200.0,5300.0,5400.0,5500.0,5600.0,5700.0,5800.0,5900.0,6000.0,6100.0,6200.0,6300.0,6400.0,6500.0,6600.0,6700.0,6800.0,6900.0,7000.0,7100.0,7200.0,7300.0,7400.0,7500.0,7600.0,7700.0,7800.0,7900.0,8000.0,8100.0,8200.0,8300.0,8400.0,8500.0,8600.0,8700.0,8800.0,8900.0,9000.0])
    xsQstar = array('d', [0.4101E+03,0.2620E+03,0.1721E+03,0.1157E+03,0.7934E+02,0.5540E+02,0.3928E+02,0.2823E+02,0.2054E+02,0.1510E+02,0.1121E+02,0.8390E+01,0.6328E+01,0.4807E+01,0.3674E+01,0.2824E+01,0.2182E+01,0.1694E+01,0.1320E+01,0.1033E+01,0.8116E+00,0.6395E+00,0.5054E+00,0.4006E+00,0.3182E+00,0.2534E+00,0.2022E+00,0.1616E+00,0.1294E+00,0.1038E+00,0.8333E-01,0.6700E-01,0.5392E-01,0.4344E-01,0.3503E-01,0.2827E-01,0.2283E-01,0.1844E-01,0.1490E-01,0.1205E-01,0.9743E-02,0.7880E-02,0.6373E-02,0.5155E-02,0.4169E-02,0.3371E-02,0.2725E-02,0.2202E-02,0.1779E-02,0.1437E-02,0.1159E-02,0.9353E-03,0.7541E-03,0.6076E-03,0.4891E-03,0.3935E-03,0.3164E-03,0.2541E-03,0.2039E-03,0.1635E-03,0.1310E-03,0.1049E-03,0.8385E-04,0.6699E-04,0.5347E-04,0.4264E-04,0.3397E-04,0.2704E-04,0.2151E-04,0.1709E-04,0.1357E-04,0.1077E-04,0.8544E-05,0.6773E-05,0.5367E-05,0.4251E-05,0.3367E-05,0.2666E-05,0.2112E-05,0.1673E-05,0.1326E-05])

    graph_xsString = TGraph(len(massesString),massesString,xsString)
    graph_xsString.SetLineWidth(3)
    graph_xsString.SetLineStyle(8)
    graph_xsString.SetLineColor(9)

    graph_xsQstar = TGraph(len(massesQstar),massesQstar,xsQstar)
    graph_xsQstar.SetLineWidth(3)
    graph_xsQstar.SetLineStyle(2)
    graph_xsQstar.SetLineColor(1)

    # theory curves: qq
    massesTh = array('d', [1000.0,1100.0,1200.0,1300.0,1400.0,1500.0,1600.0,1700.0,1800.0,1900.0,2000.0,2100.0,2200.0,2300.0,2400.0,2500.0,2600.0,2700.0,2800.0,2900.0,3000.0,3100.0,3200.0,3300.0,3400.0,3500.0,3600.0,3700.0,3800.0,3900.0,4000.0,4100.0,4200.0,4300.0,4400.0,4500.0,4600.0,4700.0,4800.0,4900.0,5000.0,5100.0,5200.0,5300.0,5400.0,5500.0,5600.0,5700.0,5800.0,5900.0,6000.0,6100.0,6200.0,6300.0,6400.0,6500.0,6600.0,6700.0,6800.0,6900.0,7000.0,7100.0,7200.0,7300.0,7400.0,7500.0,7600.0,7700.0,7800.0,7900.0,8000.0,8100.0,8200.0,8300.0,8400.0,8500.0,8600.0,8700.0,8800.0,8900.0,9000.0])

    xsAxi = array('d', [0.1849E+03,0.1236E+03,0.8473E+02,0.5937E+02,0.4235E+02,0.3069E+02,0.2257E+02,0.1680E+02,0.1263E+02,0.9577E+01,0.7317E+01,0.5641E+01,0.4374E+01,0.3411E+01,0.2672E+01,0.2103E+01,0.1658E+01,0.1312E+01,0.1041E+01,0.8284E+00,0.6610E+00,0.5294E+00,0.4250E+00,0.3417E+00,0.2752E+00,0.2220E+00,0.1792E+00,0.1449E+00,0.1172E+00,0.9487E-01,0.7686E-01,0.6219E-01,0.5033E-01,0.4074E-01,0.3298E-01,0.2671E-01,0.2165E-01,0.1755E-01,0.1422E-01,0.1152E-01,0.9322E-02,0.7539E-02,0.6092E-02,0.4917E-02,0.3965E-02,0.3193E-02,0.2568E-02,0.2062E-02,0.1653E-02,0.1323E-02,0.1057E-02,0.8442E-03,0.6728E-03,0.5349E-03,0.4242E-03,0.3357E-03,0.2644E-03,0.2077E-03,0.1627E-03,0.1271E-03,0.9891E-04,0.7686E-04,0.5951E-04,0.4592E-04,0.3530E-04,0.2704E-04,0.2059E-04,0.1562E-04,0.1180E-04,0.8882E-05,0.6657E-05,0.4968E-05,0.3693E-05,0.2734E-05,0.2016E-05,0.1481E-05,0.1084E-05,0.7903E-06,0.5744E-06,0.4160E-06,0.3007E-06])
    xsDiquark = array('d', [0.5824E+02,0.4250E+02,0.3172E+02,0.2411E+02,0.1862E+02,0.1457E+02,0.1153E+02,0.9211E+01,0.7419E+01,0.6019E+01,0.4912E+01,0.4031E+01,0.3323E+01,0.2750E+01,0.2284E+01,0.1903E+01,0.1590E+01,0.1331E+01,0.1117E+01,0.9386E+00,0.7900E+00,0.6658E+00,0.5618E+00,0.4745E+00,0.4010E+00,0.3391E+00,0.2869E+00,0.2428E+00,0.2055E+00,0.1740E+00,0.1473E+00,0.1246E+00,0.1055E+00,0.8922E-01,0.7544E-01,0.6376E-01,0.5385E-01,0.4546E-01,0.3834E-01,0.3231E-01,0.2720E-01,0.2288E-01,0.1922E-01,0.1613E-01,0.1352E-01,0.1132E-01,0.9463E-02,0.7900E-02,0.6584E-02,0.5479E-02,0.4551E-02,0.3774E-02,0.3124E-02,0.2581E-02,0.2128E-02,0.1750E-02,0.1437E-02,0.1177E-02,0.9612E-03,0.7833E-03,0.6366E-03,0.5160E-03,0.4170E-03,0.3360E-03,0.2700E-03,0.2162E-03,0.1725E-03,0.1372E-03,0.1087E-03,0.8577E-04,0.6742E-04,0.5278E-04,0.4114E-04,0.3192E-04,0.2465E-04,0.1894E-04,0.1448E-04,0.1101E-04,0.8322E-05,0.6253E-05,0.4670E-05])
    xsWprime = array('d', [0.8811E+01,0.6024E+01,0.4216E+01,0.3010E+01,0.2185E+01,0.1610E+01,0.1200E+01,0.9043E+00,0.6875E+00,0.5271E+00,0.4067E+00,0.3158E+00,0.2464E+00,0.1932E+00,0.1521E+00,0.1201E+00,0.9512E-01,0.7554E-01,0.6012E-01,0.4792E-01,0.3827E-01,0.3059E-01,0.2448E-01,0.1960E-01,0.1571E-01,0.1259E-01,0.1009E-01,0.8090E-02,0.6483E-02,0.5193E-02,0.4158E-02,0.3327E-02,0.2660E-02,0.2125E-02,0.1695E-02,0.1351E-02,0.1075E-02,0.8546E-03,0.6781E-03,0.5372E-03,0.4248E-03,0.3353E-03,0.2642E-03,0.2077E-03,0.1629E-03,0.1275E-03,0.9957E-04,0.7757E-04,0.6027E-04,0.4670E-04,0.3610E-04,0.2783E-04,0.2140E-04,0.1641E-04,0.1254E-04,0.9561E-05,0.7269E-05,0.5510E-05,0.4167E-05,0.3143E-05,0.2364E-05,0.1774E-05,0.1329E-05,0.9931E-06,0.7411E-06,0.5523E-06,0.4108E-06,0.3055E-06,0.2271E-06,0.1687E-06,0.1254E-06,0.9327E-07,0.6945E-07,0.5177E-07,0.3863E-07,0.2888E-07,0.2162E-07,0.1622E-07,0.1218E-07,0.9156E-08,0.6893E-08])
    xsZprime = array('d', [0.5027E+01,0.3398E+01,0.2353E+01,0.1663E+01,0.1196E+01,0.8729E+00,0.6450E+00,0.4822E+00,0.3638E+00,0.2769E+00,0.2123E+00,0.1639E+00,0.1272E+00,0.9933E-01,0.7789E-01,0.6134E-01,0.4848E-01,0.3845E-01,0.3059E-01,0.2440E-01,0.1952E-01,0.1564E-01,0.1256E-01,0.1010E-01,0.8142E-02,0.6570E-02,0.5307E-02,0.4292E-02,0.3473E-02,0.2813E-02,0.2280E-02,0.1848E-02,0.1499E-02,0.1216E-02,0.9864E-03,0.8002E-03,0.6490E-03,0.5262E-03,0.4264E-03,0.3453E-03,0.2795E-03,0.2260E-03,0.1826E-03,0.1474E-03,0.1188E-03,0.9566E-04,0.7690E-04,0.6173E-04,0.4947E-04,0.3957E-04,0.3159E-04,0.2516E-04,0.2001E-04,0.1587E-04,0.1255E-04,0.9906E-05,0.7795E-05,0.6116E-05,0.4785E-05,0.3731E-05,0.2900E-05,0.2247E-05,0.1734E-05,0.1334E-05,0.1022E-05,0.7804E-06,0.5932E-06,0.4492E-06,0.3388E-06,0.2544E-06,0.1903E-06,0.1417E-06,0.1051E-06,0.7764E-07,0.5711E-07,0.4186E-07,0.3055E-07,0.2223E-07,0.1612E-07,0.1164E-07,0.8394E-08])

    graph_xsAxi = TGraph(len(massesTh),massesTh,xsAxi)
    graph_xsAxi.SetLineWidth(3)
    graph_xsAxi.SetLineStyle(3)
    graph_xsAxi.SetLineColor(63)

    graph_xsDiquark = TGraph(len(massesTh),massesTh,xsDiquark)
    graph_xsDiquark.SetLineWidth(3)
    graph_xsDiquark.SetLineStyle(9)
    graph_xsDiquark.SetLineColor(8)

    graph_xsWprime = TGraph(len(massesTh),massesTh,xsWprime)
    graph_xsWprime.SetLineWidth(3)
    graph_xsWprime.SetLineStyle(7)
    graph_xsWprime.SetLineColor(46)

    graph_xsZprime = TGraph(len(massesTh),massesTh,xsZprime)
    graph_xsZprime.SetLineWidth(3)
    graph_xsZprime.SetLineStyle(5)
    graph_xsZprime.SetLineColor(38)

    # limits
    if args.method == "Asymptotic" or args.method == "HybridNewGrid":
        graph_exp_2sigma = ( TGraph(len(masses_exp),masses_exp,xs_exp_limits_2sigma) if len(xs_exp_limits_2sigma) > 0 else TGraph(0) )
        graph_exp_2sigma.SetFillColor(kYellow)

        graph_exp_1sigma = ( TGraph(len(masses_exp),masses_exp,xs_exp_limits_1sigma) if len(xs_exp_limits_2sigma) > 0 else TGraph(0) )
        graph_exp_1sigma.SetFillColor(kGreen+1)

        graph_exp = ( TGraph(len(masses),masses,xs_exp_limits) if len(xs_exp_limits_2sigma) > 0 else TGraph(0) )
        #graph_exp.SetMarkerStyle(24)
        graph_exp.SetLineWidth(3)
        graph_exp.SetLineStyle(2)
        graph_exp.SetLineColor(4)

    graph_obs = TGraph(len(masses),masses,xs_obs_limits)
    graph_obs.SetMarkerStyle(20)
    graph_obs.SetLineWidth(3)
    #graph_obs.SetLineStyle(1)
    graph_obs.SetLineColor(1)

    c = TCanvas("c", "",800,800)
    c.cd()

    legend = TLegend(.58,.72,.90,.90)
    legend.SetBorderSize(0)
    legend.SetFillColor(0)
    legend.SetFillStyle(0)
    legend.SetTextFont(42)
    legend.SetTextSize(0.03)
    legend.SetHeader('95% CL upper limits')

    if len(xs_exp_limits_2sigma) > 0 and (args.method == "Asymptotic" or args.method == "HybridNewGrid"):
        frame = graph_exp_2sigma.GetHistogram().Clone()
    else:
        frame = graph_obs.GetHistogram().Clone()
    frame.Reset()
    frame.GetXaxis().SetTitle("Resonance mass [GeV]")
    frame.GetXaxis().SetTitleOffset(1.05)
    if args.timesAE:
        #if args.model == "ZPrime":
        #    frame.GetYaxis().SetTitle("#sigma #times BR(c#bar{c},b#bar{b}) #times #it{A} #times #epsilon [pb]")
        #else:
        frame.GetYaxis().SetTitle("#sigma #times BR(b#bar{b}) #times #it{A} #times #epsilon [pb]")
    else:
        #if args.model == "ZPrime":
        #    frame.GetYaxis().SetTitle("#sigma #times BR(c#bar{c},b#bar{b}) [pb]")
        #else:
        frame.GetYaxis().SetTitle("#sigma #times BR(b#bar{b}) [pb]")
    frame.GetYaxis().SetTitleOffset(1.2)
    if args.timesAE:
        frame.GetYaxis().SetRangeUser(1e-03,1e+01)
    else:
        frame.GetYaxis().SetRangeUser(1e-01,5e+02)
    frame.Draw("axis")

    if len(xs_exp_limits_2sigma) > 0 and (args.method == "Asymptotic" or args.method == "HybridNewGrid"):
        graph_exp_2sigma.GetXaxis().SetTitle("Resonance mass [GeV]")
        graph_exp_2sigma.GetXaxis().SetTitleOffset(1.1)
        graph_exp_2sigma.GetYaxis().SetTitle("#sigma #times #it{B} [pb]")
        graph_exp_2sigma.GetYaxis().SetTitleOffset(1.1)
        #graph_exp_2sigma.GetYaxis().SetRangeUser(1e-03,1e+02)
        #graph_exp_2sigma.GetXaxis().SetNdivisions(1005)

        graph_exp_2sigma.Draw("F")
        graph_exp_1sigma.Draw("F")
        graph_exp.Draw("L")
        graph_obs.Draw("LP")

        legend.AddEntry(graph_obs,"Observed","lp")
        legend.AddEntry(graph_exp,"Expected","lp")
        legend.AddEntry(graph_exp_1sigma,"#pm 1#sigma","F")
        legend.AddEntry(graph_exp_2sigma,"#pm 2#sigma","F")
    else:
        graph_obs.GetXaxis().SetTitle("Resonance mass [GeV]")
        graph_obs.GetYaxis().SetTitle("#sigma #times #it{B} [pb]")
        graph_obs.GetYaxis().SetTitleOffset(1.1)
        graph_obs.GetYaxis().SetRangeUser(1e-02,1e+03)
        #graph_obs.GetXaxis().SetNdivisions(1005)

        graph_obs.Draw("LP")

        legend.AddEntry(graph_obs,"Observed","lp")

        #if args.final_state == 'gg' :
        #    graph_xsS8.Draw("L")
        #elif args.final_state == 'qg' :
        #    graph_xsQstar.Draw("L")
        #    graph_xsString.Draw("L")
        #elif args.final_state == 'qq' :
        #    graph_xsAxi.Draw("L")
        #    graph_xsDiquark.Draw("L")
        #    graph_xsWprime.Draw("L")
        #    graph_xsZprime.Draw("L")
        
    legend.Draw()

    #legendTh = TLegend(.60,.72,.90,.88)
    #legendTh.SetBorderSize(0)
    #legendTh.SetFillColor(0)
    #legendTh.SetFillStyle(0)
    #legendTh.SetTextFont(42)
    #legendTh.SetTextSize(0.03)
    #legendTh.AddEntry(graph_xsAxi,"Axigluon/coloron","l")
    #legendTh.AddEntry(graph_xsDiquark,"Scalar diquark","l")
    #legendTh.AddEntry(graph_xsWprime,"W' SSM","l")
    #legendTh.AddEntry(graph_xsZprime,"Z' SSM","l")
    #legendTh.Draw()

    # draw the lumi text on the canvas
    CMS_lumi.extraText = args.extraText
    CMS_lumi.lumi_sqrtS = args.lumi_sqrtS # used with iPeriod = 0 (free form)
    iPos = 11
    iPeriod = 0

    CMS_lumi.CMS_lumi(c, iPeriod, iPos)

    gPad.RedrawAxis()

    c.SetLogy()
    postfix = ( ('_' + args.postfix) if args.postfix != '' else '' )
    if args.noSyst:
        postfix += "_noSyst"
    if args.freezeNuisances:
        postfix += "_" + args.freezeNuisances.replace(",", "_")
    if args.fitTrigger:
        postfix += "_fitTrigger"
    elif args.correctTrigger:
        postfix += "_correctTrigger"
    if args.useMCTrigger:
        postfix += "_useMCTrigger"
    fileName = limit_config.paths["limit_plots"] + '/xs_limit_%s_%s_%s_%s.%s'%(args.method,args.analysis, args.model + postfix, args.fit_function, args.fileFormat.lower())
    if args.timesAE:
        fileName = fileName.replace("xs_limit", "xsAE_limit")
    c.SaveAs(fileName)
    print "Plot saved to '%s'"%(fileName)

    graph_obs.Print("all")
    if args.saveObjects:
        output_file = args.saveObjects
        if args.timesAE:
            output_file = output_file.replace(".root", "_timesAE.root")
        f = TFile(output_file, "RECREATE")
        if args.method == "Asymptotic" or args.method == "HybridNewGrid":
            graph_exp_2sigma.SetName("graph_exp_2sigma")
            graph_exp_2sigma.Write()
            graph_exp_1sigma.SetName("graph_exp_1sigma")
            graph_exp_1sigma.Write()
            graph_exp.SetName("graph_exp")
            graph_exp.Write()
        graph_obs.SetName("graph_obs")
        graph_obs.Write()
        f.Close()
Beispiel #2
0
def plotPart(events,
             inHisto,
             nBinsX,
             minX,
             maxX,
             nBinsY,
             minY,
             maxY,
             outfile,
             canvas,
             XaxisTitle="",
             plotTitle="",
             cut="",
             stats=0,
             logY=0):
    events.Draw(
        "{0}>>histoEleBad({1},{2},{3})".format("eleBad" + inHisto, nBinsX,
                                               minX, maxX), cut)
    histoEleBad = ROOT.gROOT.FindObject("histoEleBad")
    events.Draw(
        "{0}>>histoEleTruth({1},{2},{3})".format("eleTruth" + inHisto, nBinsX,
                                                 minX, maxX), cut)
    histoEleTruth = ROOT.gROOT.FindObject("histoEleTruth")
    events.Draw(
        "{0}>>histoPosBad({1},{2},{3})".format("posBad" + inHisto, nBinsX,
                                               minX, maxX), cut)
    histoPosBad = ROOT.gROOT.FindObject("histoPosBad")
    events.Draw(
        "{0}>>histoPosTruth({1},{2},{3})".format("posTruth" + inHisto, nBinsX,
                                                 minX, maxX), cut)
    histoPosTruth = ROOT.gROOT.FindObject("histoPosTruth")
    #histoEleBad = getHisto(events,"eleBad"+inHisto,nBinsX,minX,maxX,cut)
    #histoEleTruth = getHisto(events,"eleTruth"+inHisto,nBinsX,minX,maxX,cut)
    #histoPosBad = getHisto(events,"posBad"+inHisto,nBinsX,minX,maxX,cut)
    #histoPosTruth = getHisto(events,"posTruth"+inHisto,nBinsX,minX,maxX,cut)
    maximumEle = histoEleBad.GetMaximum()
    if (histoEleTruth.GetMaximum() > maximumEle):
        maximumEle = histoEleTruth.GetMaximum()
    maximumPos = histoPosBad.GetMaximum()
    if (histoPosTruth.GetMaximum() > maximumPos):
        maximumPos = histoPosTruth.GetMaximum()
    histoEleBad.SetTitle("Ele " + plotTitle)
    histoEleBad.GetXaxis().SetTitle(XaxisTitle)
    histoEleBad.SetStats(stats)
    histoEleBad.GetYaxis().SetRangeUser(0, 1.2 * maximumEle)
    histoEleBad.Draw()
    canvas.SetLogy(logY)
    histoEleTruth.SetLineColor(2)
    histoEleTruth.Draw("same")
    legend = TLegend(.68, .66, .92, .87)
    legend.SetBorderSize(0)
    legend.SetFillColor(0)
    legend.SetFillStyle(0)
    legend.SetTextFont(42)
    legend.SetTextSize(0.035)
    legend.AddEntry(histoEleBad, "Bad Fit", "LP")
    legend.AddEntry(histoEleTruth, "Truth Fit", "LP")
    legend.Draw()
    canvas.Print(outfile + ".pdf")
    histoPosBad.SetTitle("Pos " + plotTitle)
    histoPosBad.GetXaxis().SetTitle(XaxisTitle)
    histoPosBad.SetStats(stats)
    histoPosBad.GetYaxis().SetRangeUser(0, 1.2 * maximumPos)
    histoPosBad.Draw()
    canvas.SetLogy(logY)
    histoPosTruth.SetLineColor(2)
    histoPosTruth.Draw("same")
    legend.Draw()
    canvas.Print(outfile + ".pdf")
    saveTuplePlot2D(events, "eleBad" + inHisto, "BaduncVZ", nBinsX, minX, maxX,
                    nBinsY, minY, maxY, outfile, canvas,
                    "Bad Ele " + XaxisTitle, "Bad uncVZ [mm]", plotTitle, cut)
    saveTuplePlot2D(events, "eleBad" + inHisto, "TruthuncVZ", nBinsX, minX,
                    maxX, nBinsY, minY, maxY, outfile, canvas,
                    "Bad Ele " + XaxisTitle, "Truth uncVZ [mm]", plotTitle,
                    cut)
    saveTuplePlot2D(events, "eleTruth" + inHisto, "BaduncVZ", nBinsX, minX,
                    maxX, nBinsY, minY, maxY, outfile, canvas,
                    "Truth Ele " + XaxisTitle, "Bad uncVZ [mm]", plotTitle,
                    cut)
    saveTuplePlot2D(events, "eleTruth" + inHisto, "TruthuncVZ", nBinsX, minX,
                    maxX, nBinsY, minY, maxY, outfile, canvas,
                    "Truth Ele " + XaxisTitle, "Truth uncVZ [mm]", plotTitle,
                    cut)
    saveTuplePlot2D(events, "posBad" + inHisto, "BaduncVZ", nBinsX, minX, maxX,
                    nBinsY, minY, maxY, outfile, canvas,
                    "Bad Pos " + XaxisTitle, "Bad uncVZ [mm]", plotTitle, cut)
    saveTuplePlot2D(events, "posBad" + inHisto, "TruthuncVZ", nBinsX, minX,
                    maxX, nBinsY, minY, maxY, outfile, canvas,
                    "Bad Pos " + XaxisTitle, "Truth uncVZ [mm]", plotTitle,
                    cut)
    saveTuplePlot2D(events, "posTruth" + inHisto, "BaduncVZ", nBinsX, minX,
                    maxX, nBinsY, minY, maxY, outfile, canvas,
                    "Truth Pos " + XaxisTitle, "Bad uncVZ [mm]", plotTitle,
                    cut)
    saveTuplePlot2D(events, "posTruth" + inHisto, "TruthuncVZ", nBinsX, minX,
                    maxX, nBinsY, minY, maxY, outfile, canvas,
                    "Truth Pos " + XaxisTitle, "Truth uncVZ [mm]", plotTitle,
                    cut)
    del histoEleBad
    del histoEleTruth
    del histoPosBad
    del histoPosTruth
    del legend
Beispiel #3
0
h_GGH.SetMarkerColor(kRed)
h_GGH.SetMarkerSize(1.2)
#h_GGH.Scale(1./(h_GGH.Integral()))
h_GGH.Draw("hist p")

h_GGH_w.SetMarkerStyle(47)
h_GGH_w.SetMarkerColor(kBlue)
h_GGH_w.SetMarkerSize(1.2)
#h_GGH_w.Scale(1./(h_GGH_w.Integral()))
h_GGH_w.Draw("hist p SAME")

leg1 = TLegend(.65, .75, .87, .85)
leg1.SetBorderSize(0)
leg1.SetFillColor(0)
leg1.SetFillStyle(0)
leg1.SetTextFont(42)
leg1.SetTextSize(0.04)
leg1.AddEntry(h_GGH, "ggH125", "p")
leg1.AddEntry(h_GGH_w, "ggH125_pref", "p")
leg1.Draw()

c_GGH.Update()

#lower plot pad
c_GGH.cd()
pad2_GGH = TPad("pad2_GGH", "pad2_GGH", 0, 0.05, 1, 0.3)
pad2_GGH.SetGridy()
pad2_GGH.Draw()
pad2_GGH.cd()  #pad2 becomes the current pad

#define ratio plot
# BDT
h1 = norm_hists(h_train[2])
h1.GetXaxis().SetTitle("BDT Regression m_{t#bar{t}} [GeV]")
h1.GetYaxis().SetTitle("A.U.")
h1.Draw()
h2 = norm_hists(h_test[2])
h2.SetLineColor(2)
h2.SetMarkerColor(2)
h2.Draw("same")

# Draw legends
lIy = 0.92
lg = TLegend(0.60, lIy - 0.25, 0.85, lIy)
lg.SetBorderSize(0)
lg.SetFillStyle(0)
lg.SetTextFont(42)
lg.SetTextSize(0.04)
lg.AddEntry(h1, "Training", "l")
lg.AddEntry(h2, "Testing", "l")
lg.Draw()

myc.Draw()
myc.SaveAs("TMVA_tutorial_reg_test_1.png")

# BDTG
h1 = norm_hists(h_train[3])
h1.GetXaxis().SetTitle("BDTG Regression m_{t#bar{t}} [GeV]")
h1.GetYaxis().SetTitle("A.U.")
h1.Draw()
h2 = norm_hists(h_test[3])
h2.SetLineColor(2)
def plot():

  myfile = TFile(args.inputFile)

  mytree = gDirectory.Get("physics")
  mytree_weight = mytree.GetWeight()/1e3

  trig_dec  = "( passHLT == 1 )"
  lep_tag_trigmatch = "( lep_tag_isTrigMatched[0] == 1 && ( ( lep_tag_flavour[0] == 11 && lep_tag_pt[0] > 25e3 ) || ( lep_tag_flavour[0] == 13 && lep_tag_pt[0] > 22e3 ) ) )"
  lep_probe_trigmatch = "( lep_probe_isTrigMatched[0] == 1 && ( ( lep_probe_flavour[0] == 11 && lep_probe_pt[0] > 25e3 ) || ( lep_probe_flavour[0] == 13 && lep_probe_pt[0] > 22e3 ) ) )"
  el_tag_eta   = "( TMath::Abs(el_tag_eta[0]) < 1.37 )"
  nbjets       = "( njets_mv2c20_Fix77 > 0 )"
  njets        = "( njets > 0 && njets < 4 )"
  nleptons     = "( nlep == 2 && ( lep_pt[0] > 20e3 && lep_pt[1] > 20e3 ) )"
  same_sign    = "( isSS01 == 1 )"
  # veto charge flips
  #
  ch_flip_veto = "( 1 )"
  if args.doChFlipVeto:
     ch_flip_veto = "( lep_isChFlip[0] == 0 && lep_isChFlip[1] == 0 )"
  # require at least 1 !prompt lepton
  #
  non_prompt   = "( ( lep_truthType[0] != 6 && lep_truthType[0] != 2 ) || ( lep_truthType[1] != 6 && lep_truthType[1] != 2 ) )"
  # require at least one T lepton in the event
  #
  is_tight_event = "1" #"( isNonTightEvent == 0 )"
  # require tag lepton to be T
  #
  tight_tag   = "( lep_tag_isTightSelected[0] == 1 )"

  hist_list_probe_MUPROBEEVT = {}
  hist_list_tag_MUPROBEEVT = {}
  hist_list_probe_ELPROBEEVT = {}
  hist_list_tag_ELPROBEEVT = {}

  # -----------------------------------------------------

  dirname = "OutputPlots_TRUTH"
  if args.outdirname:
     dirname += ( "_" + args.outdirname )

  try:
      os.makedirs(dirname)
  except:
      pass

  # -----------------------------------------------------

  # ----------------
  #    Muon probe
  # ----------------

  sel_FAKE_MUPROBEEVT_T = None
  sel_FAKE_MUPROBEEVT_L = None

  # look only at OF region
  if args.channel == "OF":
    sel_FAKE_MUPROBEEVT_T = "(" + trig_dec + " && " + lep_tag_trigmatch + " && " + lep_probe_trigmatch + " && " + nleptons + " && " + same_sign + " && " +  is_tight_event + " && " + tight_tag + " && " + "( (nmuon == 1 && nel == 1) && ( isProbeMuEvent == 1 ) && ( muon_probe_isTightSelected[0] == 1 ) )" + " && " + el_tag_eta + " && " + nbjets + " && " + njets  + " && " + ch_flip_veto + " && " + non_prompt + ")"
    sel_FAKE_MUPROBEEVT_L = "(" + trig_dec + " && " + lep_tag_trigmatch + " && " + lep_probe_trigmatch + " && " + nleptons + " && " + same_sign + " && " +  is_tight_event + " && " + tight_tag + " && " + "( (nmuon == 1 && nel == 1) && ( isProbeMuEvent == 1 ) && ( muon_probe_isTightSelected[0] == 0 ) )" + " && " + el_tag_eta + " && " + nbjets + " && " + njets + " && " + ch_flip_veto + " && " + non_prompt + ")"
  # look only at SF region
  elif args.channel == "SF":
    sel_FAKE_MUPROBEEVT_T = "(" + trig_dec + " && " + lep_tag_trigmatch + " && " + lep_probe_trigmatch + " && " + nleptons + " && " + same_sign + " && " +  is_tight_event + " && " + tight_tag + " && " + "( ( nmuon == 2 ) && ( isProbeMuEvent == 1 ) && ( muon_probe_isTightSelected[0] == 1 ) )" + " && " + nbjets + " && " + njets + " && " + ch_flip_veto + " && " + non_prompt + ")"
    sel_FAKE_MUPROBEEVT_L = "(" + trig_dec + " && " + lep_tag_trigmatch + " && " + lep_probe_trigmatch + " && " + nleptons + " && " + same_sign + " && " +  is_tight_event + " && " + tight_tag + " && " + "( ( nmuon == 2 ) && ( isProbeMuEvent == 1 ) && ( muon_probe_isTightSelected[0] == 0 ) )" + " && " + nbjets + " && " + njets + " && "  + ch_flip_veto + " && " + non_prompt + ")"

  print "sel_FAKE_MUPROBEEVT_T: \n", sel_FAKE_MUPROBEEVT_T
  print "sel_FAKE_MUPROBEEVT_L: \n", sel_FAKE_MUPROBEEVT_L

  # histograms for probe passing T
  #
  h_probelep_FAKE_MUPROBEEVT_T_pt = TH1D("probelep_FAKE_MUPROBEEVT_T_pt", "probelep_FAKE_MUPROBEEVT_T_pt", 30, 20.0, 200.0)
  hist_list_probe_MUPROBEEVT[h_probelep_FAKE_MUPROBEEVT_T_pt] = ["T","pt"]
  h_probelep_FAKE_MUPROBEEVT_T_ptvarcone30_over_pt = TH1D("probelep_FAKE_MUPROBEEVT_T_ptvarcone30_over_pt", "probelep_FAKE_MUPROBEEVT_T_ptvarcone30_over_pt", 20, 0.0, 0.1)
  hist_list_probe_MUPROBEEVT[h_probelep_FAKE_MUPROBEEVT_T_ptvarcone30_over_pt] = ["T","ptvarcone30_over_pt"]
#  h_probelep_FAKE_MUPROBEEVT_T_ptvarcone20_over_pt = TH1D("probelep_FAKE_MUPROBEEVT_T_ptvarcone20_over_pt", "probelep_FAKE_MUPROBEEVT_T_ptvarcone20_over_pt", 20, 0.0, 0.1)
#  hist_list_probe_MUPROBEEVT[h_probelep_FAKE_MUPROBEEVT_T_ptvarcone20_over_pt] = ["T","ptvarcone20_over_pt"]
  h_probelep_FAKE_MUPROBEEVT_T_topoetcone20_over_pt = TH1D("probelep_FAKE_MUPROBEEVT_T_topoetcone20_over_pt", "probelep_FAKE_MUPROBEEVT_T_topoetcone20_over_pt", 70, -0.2, 0.5)
  hist_list_probe_MUPROBEEVT[h_probelep_FAKE_MUPROBEEVT_T_topoetcone20_over_pt] = ["T","topoetcone20_over_pt"]

  h_probelep_FAKE_MUPROBEEVT_T_pt.GetXaxis().SetTitle("pT [GeV]")
  h_probelep_FAKE_MUPROBEEVT_T_ptvarcone30_over_pt.GetXaxis().SetTitle("ptvarcone30/pT")
#  h_probelep_FAKE_MUPROBEEVT_T_ptvarcone20_over_pt.GetXaxis().SetTitle("ptvarcone20/pT")
  h_probelep_FAKE_MUPROBEEVT_T_topoetcone20_over_pt.GetXaxis().SetTitle("topoetcone20/pT")

  # histograms for probe passing L!T
  #
  h_probelep_FAKE_MUPROBEEVT_L_pt = TH1D("probelep_FAKE_MUPROBEEVT_L_pt", "probelep_FAKE_MUPROBEEVT_L_pt", 30, 20.0, 200.0)
  hist_list_probe_MUPROBEEVT[h_probelep_FAKE_MUPROBEEVT_L_pt]  = ["L","pt"]
  h_probelep_FAKE_MUPROBEEVT_L_ptvarcone30_over_pt = TH1D("probelep_FAKE_MUPROBEEVT_L_ptvarcone30_over_pt", "probelep_FAKE_MUPROBEEVT_L_ptvarcone30_over_pt", 20, 0.0, 0.1)
  hist_list_probe_MUPROBEEVT[h_probelep_FAKE_MUPROBEEVT_L_ptvarcone30_over_pt] = ["L","ptvarcone30_over_pt"]
#  h_probelep_FAKE_MUPROBEEVT_L_ptvarcone20_over_pt = TH1D("probelep_FAKE_MUPROBEEVT_L_ptvarcone20_over_pt", "probelep_FAKE_MUPROBEEVT_L_ptvarcone20_over_pt", 20, 0.0, 0.1)
#  hist_list_probe_MUPROBEEVT[h_probelep_FAKE_MUPROBEEVT_L_ptvarcone20_over_pt] = ["L","ptvarcone20_over_pt"]
  h_probelep_FAKE_MUPROBEEVT_L_topoetcone20_over_pt = TH1D("probelep_FAKE_MUPROBEEVT_L_topoetcone20_over_pt", "probelep_FAKE_MUPROBEEVT_L_topoetcone20_over_pt", 70, -0.2, 0.5)
  hist_list_probe_MUPROBEEVT[h_probelep_FAKE_MUPROBEEVT_L_topoetcone20_over_pt] = ["L","topoetcone20_over_pt"]

  h_probelep_FAKE_MUPROBEEVT_L_pt.GetXaxis().SetTitle("pT [GeV]")
  h_probelep_FAKE_MUPROBEEVT_L_ptvarcone30_over_pt.GetXaxis().SetTitle("ptvarcone30/pT")
#  h_probelep_FAKE_MUPROBEEVT_L_ptvarcone20_over_pt.GetXaxis().SetTitle("ptvarcone20/pT")
  h_probelep_FAKE_MUPROBEEVT_L_topoetcone20_over_pt.GetXaxis().SetTitle("topoetcone20/pT")

  # histograms for tag (passing T: default)
  #
  h_taglep_FAKE_MUPROBEEVT_T_pt = TH1D("taglep_FAKE_MUPROBEEVT_T_pt", "taglep_FAKE_MUPROBEEVT_T_pt", 30, 20.0, 200.0)
  hist_list_tag_MUPROBEEVT[h_taglep_FAKE_MUPROBEEVT_T_pt] = ["T","pt"]
  h_taglep_FAKE_MUPROBEEVT_T_ptvarcone30_over_pt = TH1D("taglep_FAKE_MUPROBEEVT_T_ptvarcone30_over_pt", "taglep_FAKE_MUPROBEEVT_T_ptvarcone30_over_pt", 20, 0.0, 0.1)
  hist_list_tag_MUPROBEEVT[h_taglep_FAKE_MUPROBEEVT_T_ptvarcone30_over_pt] = ["T","ptvarcone30_over_pt"]
  h_taglep_FAKE_MUPROBEEVT_T_ptvarcone20_over_pt = TH1D("taglep_FAKE_MUPROBEEVT_T_ptvarcone20_over_pt", "taglep_FAKE_MUPROBEEVT_T_ptvarcone20_over_pt", 20, 0.0, 0.1)
  hist_list_tag_MUPROBEEVT[h_taglep_FAKE_MUPROBEEVT_T_ptvarcone20_over_pt] = ["T","ptvarcone20_over_pt"]
  h_taglep_FAKE_MUPROBEEVT_T_topoetcone20_over_pt = TH1D("taglep_FAKE_MUPROBEEVT_T_topoetcone20_over_pt", "taglep_FAKE_MUPROBEEVT_T_topoetcone20_over_pt", 70, -0.2, 0.5)
  hist_list_tag_MUPROBEEVT[h_taglep_FAKE_MUPROBEEVT_T_topoetcone20_over_pt] = ["T","topoetcone20_over_pt"]

  h_taglep_FAKE_MUPROBEEVT_T_pt.GetXaxis().SetTitle("pT [GeV]")
  h_taglep_FAKE_MUPROBEEVT_T_ptvarcone30_over_pt.GetXaxis().SetTitle("ptvarcone30/pT")
  h_taglep_FAKE_MUPROBEEVT_T_topoetcone20_over_pt.GetXaxis().SetTitle("topoetcone20/pT")

  mytree.Project("probelep_FAKE_MUPROBEEVT_T_pt", "muon_probe_pt[0]/1e3", "%s * (%s)" %(mytree_weight, sel_FAKE_MUPROBEEVT_T), "" )
  mytree.Project("probelep_FAKE_MUPROBEEVT_L_pt", "muon_probe_pt[0]/1e3", "%s * (%s)" %(mytree_weight, sel_FAKE_MUPROBEEVT_L), "" )
  mytree.Project("probelep_FAKE_MUPROBEEVT_T_ptvarcone30_over_pt", "muon_probe_ptvarcone30[0]/muon_probe_pt[0]", "%s * (%s)" %(mytree_weight, sel_FAKE_MUPROBEEVT_T), "" )
  mytree.Project("probelep_FAKE_MUPROBEEVT_L_ptvarcone30_over_pt", "muon_probe_ptvarcone30[0]/muon_probe_pt[0]", "%s * (%s)" %(mytree_weight, sel_FAKE_MUPROBEEVT_L), "" )
#  mytree.Project("probelep_FAKE_MUPROBEEVT_T_ptvarcone20_over_pt", "muon_probe_ptvarcone20[0]/muon_probe_pt[0]", "%s * (%s)" %(mytree_weight, sel_FAKE_MUPROBEEVT_T), "" )
#  mytree.Project("probelep_FAKE_MUPROBEEVT_L_ptvarcone20_over_pt", "muon_probe_ptvarcone20[0]/muon_probe_pt[0]", "%s * (%s)" %(mytree_weight, sel_FAKE_MUPROBEEVT_L), "" )
  mytree.Project("probelep_FAKE_MUPROBEEVT_T_topoetcone20_over_pt", "muon_probe_topoetcone20[0]/muon_probe_pt[0]", "%s * (%s)" %(mytree_weight, sel_FAKE_MUPROBEEVT_T), "" )
  mytree.Project("probelep_FAKE_MUPROBEEVT_L_topoetcone20_over_pt", "muon_probe_topoetcone20[0]/muon_probe_pt[0]", "%s * (%s)" %(mytree_weight, sel_FAKE_MUPROBEEVT_L), "" )

  if args.channel == "OF":
     # probe is muon, tag is electron
     #
     mytree.Project("taglep_FAKE_MUPROBEEVT_T_pt", "el_tag_pt[0]/1e3", "%s * (%s)" %(mytree_weight, sel_FAKE_MUPROBEEVT_T), "" )
     mytree.Project("taglep_FAKE_MUPROBEEVT_T_ptvarcone30_over_pt", "el_tag_ptvarcone30[0]/el_tag_pt[0]", "%s * (%s)" %(mytree_weight, sel_FAKE_MUPROBEEVT_T), "" )
     mytree.Project("taglep_FAKE_MUPROBEEVT_T_ptvarcone20_over_pt", "el_tag_ptvarcone20[0]/el_tag_pt[0]", "%s * (%s)" %(mytree_weight, sel_FAKE_MUPROBEEVT_T), "" )
     mytree.Project("taglep_FAKE_MUPROBEEVT_T_topoetcone20_over_pt", "el_tag_topoetcone20[0]/el_tag_pt[0]", "%s * (%s)" %(mytree_weight, sel_FAKE_MUPROBEEVT_T), "" )
  elif args.channel == "SF":
     # probe is muon, tag is muon
     #
     mytree.Project("taglep_FAKE_MUPROBEEVT_T_pt", "muon_tag_pt[0]/1e3", "%s * (%s)" %(mytree_weight, sel_FAKE_MUPROBEEVT_T), "" )
     mytree.Project("taglep_FAKE_MUPROBEEVT_T_ptvarcone30_over_pt", "muon_tag_ptvarcone30[0]/muon_tag_pt[0]", "%s * (%s)" %(mytree_weight, sel_FAKE_MUPROBEEVT_T), "" )
#     mytree.Project("taglep_FAKE_MUPROBEEVT_T_ptvarcone20_over_pt", "muon_tag_ptvarcone20[0]/muon_tag_pt[0]", "%s * (%s)" %(mytree_weight, sel_FAKE_MUPROBEEVT_T), "" )
     mytree.Project("taglep_FAKE_MUPROBEEVT_T_topoetcone20_over_pt", "muon_tag_topoetcone20[0]/muon_tag_pt[0]", "%s * (%s)" %(mytree_weight, sel_FAKE_MUPROBEEVT_T), "" )


  # Normalise to unity
  if args.doNorm:
     for hist in hist_list_probe_MUPROBEEVT.keys():
	if hist.Integral() == 0:
	  continue
	hist.Scale(1/hist.Integral())
	hist.GetYaxis().SetTitle("Norm. events")
	#hist.GetYaxis().SetRangeUser(0,1)
     for hist in hist_list_tag_MUPROBEEVT.keys():
	if hist.Integral() == 0:
	  continue
        hist.Scale(1/hist.Integral())
	hist.GetYaxis().SetTitle("Norm. events")
        #hist.GetYaxis().SetRangeUser(0,1)

  # now plot
  #
  print "\tLooking at events where the PROBE is: {0} and the channel is {1}\n".format("MUON", args.channel)
  for  hist_tag in hist_list_tag_MUPROBEEVT.keys():

     c = TCanvas("c","Temp",50,50,700,900)
     c.Divide(1,2)

     c.cd(1)
     legend_T = TLegend(0.6,0.8,0.8,0.85); # (x1,y1 (--> bottom left corner), x2, y2 (--> top right corner) )
     legend_T.SetHeader("2 Lep SS Fake CR - T probe")
     legend_T.SetBorderSize(0)  # no border
     legend_T.SetFillColor(0) # Legend background should be white
     legend_T.SetTextSize(0.04) # Increase entry font size!
     legend_T.SetTextFont(42) # Helvetica

     c.cd(2)
     legend_L = TLegend(0.6,0.8,0.8,0.85); # (x1,y1 (--> bottom left corner), x2, y2 (--> top right corner) )
     legend_L.SetHeader("2 Lep SS Fake CR - L!T probe")
     legend_L.SetBorderSize(0)  # no border
     legend_L.SetFillColor(0) # legend_L background should be white
     legend_L.SetTextSize(0.04) # Increase entry font size!
     legend_L.SetTextFont(42) # Helvetica

     var_tag    = hist_list_tag_MUPROBEEVT[hist_tag][1]
     type_tag   = hist_list_tag_MUPROBEEVT[hist_tag][0]

     hist_tag.SetLineColor(1)
     hist_tag.SetLineWidth(2)

     print "\tPlotting variable: {0}\n".format(var_tag)

     print "\ttag histogram name: {0}\n".format(hist_tag.GetName())

     draw_pad1 = False
     draw_pad2 = False

     for hist_probe in hist_list_probe_MUPROBEEVT.keys():

       print "\t\tprobe histogram name: {0}".format(hist_probe.GetName())

       hist_probe.SetLineColor(2)
       hist_probe.SetLineWidth(2)

       var_probe  = hist_list_probe_MUPROBEEVT[hist_probe][1]
       type_probe = hist_list_probe_MUPROBEEVT[hist_probe][0]

       # must be looking at the same variable!
       #
       if  var_probe != var_tag:
         continue

       print "\t\tfound a match in variable! {0} = {1}\n".format(var_tag,var_probe)

       if type_probe == "T":
          print "\t\t  probe is of type: {0}".format(type_probe)
          print "\n\t\t  --> drawing: \t {0} \t {1} \t on pad(1) of the same canvas\n".format(hist_tag.GetName(),hist_probe.GetName())
          c.cd(1)
          legend_T.AddEntry(None, "", "")
          legend_T.AddEntry(hist_tag, "REAL lepton", "L")
	  legend_T.AddEntry(None, "", "")
          legend_T.AddEntry(hist_probe, "FAKE lepton", "L")
          hist_tag.Draw("HIST")
          hist_probe.Draw("HIST SAME")
          draw_pad1 = True

       elif type_probe == "L":
          print "\t\t  probe is of type: {0}".format(type_probe)
          print "\n\t\t  --> drawing: \t {0} \t {1} \t on pad(2) of the same canvas\n".format(hist_tag.GetName(),hist_probe.GetName())
          c.cd(2)
          legend_L.AddEntry(None, "", "")
	  legend_L.AddEntry(hist_tag, "REAL lepton", "L")
	  legend_L.AddEntry(None, "", "")
          legend_L.AddEntry(hist_probe, "FAKE lepton", "L")
          hist_tag.Draw("HIST")
          hist_probe.Draw("HIST SAME")
          draw_pad2 = True

       if ( draw_pad1 and draw_pad2 ):
	 c.cd(1)
         legend_T.Draw()
	 c.cd(2)
	 legend_L.Draw()
         plotname = dirname + "/FAKE_MUPROBEEVT_" + var_probe
         c.SaveAs(plotname+".png")

     del c

  # -----------------------------------------------------

  # ---------------------
  #    Electron probe
  # ---------------------

  sel_FAKE_ELPROBEEVT_T = None
  sel_FAKE_ELPROBEEVT_L = None

  # look only at OF region
  if args.channel == "OF":
    sel_FAKE_ELPROBEEVT_T = "(" + trig_dec + " && " + lep_tag_trigmatch + " && " + lep_probe_trigmatch + " && " + nleptons + " && " + same_sign + " && " +  is_tight_event + " && " + tight_tag + " && " + "( (nmuon == 1 && nel == 1) && ( isProbeElEvent == 1 ) && ( el_probe_isTightSelected[0] == 1 ) )" + " && " + nbjets + " && " + njets + " && "  + ch_flip_veto + " && " + non_prompt + ")"
    sel_FAKE_ELPROBEEVT_L = "(" + trig_dec + " && " + lep_tag_trigmatch + " && " + lep_probe_trigmatch + " && " + nleptons + " && " + same_sign + " && " +  is_tight_event + " && " + tight_tag + " && " + "( (nmuon == 1 && nel == 1) && ( isProbeElEvent == 1 ) && ( el_probe_isTightSelected[0] == 0 ) )" + " && " + nbjets + " && " + njets + " && " + ch_flip_veto + " && " + non_prompt + ")"



  # look only at SF region
  elif args.channel == "SF":
    sel_FAKE_ELPROBEEVT_T = "(" + trig_dec + " && " + lep_tag_trigmatch + " && " + lep_probe_trigmatch + " && " + nleptons + " && " + same_sign + " && " +  is_tight_event + " && " + tight_tag + " && " + "( ( nel == 2 ) && ( isProbeElEvent == 1 ) && ( el_probe_isTightSelected[0] == 1 ) )" + " && " + el_tag_eta + " && " + nbjets + " && " + njets + " && "  + ch_flip_veto + " && " + non_prompt + ")"
    sel_FAKE_ELPROBEEVT_L = "(" + trig_dec + " && " + lep_tag_trigmatch + " && " + lep_probe_trigmatch + " && " + nleptons + " && " + same_sign + " && " +  is_tight_event + " && " + tight_tag + " && " + "( ( nel == 2 ) && ( isProbeElEvent == 1 ) && ( el_probe_isTightSelected[0] == 0 ) )" + " && " + el_tag_eta + " && " + nbjets + " && " + njets + " && " + ch_flip_veto + " && " + non_prompt + ")"

  print "sel_FAKE_ELPROBEEVT_T: \n", sel_FAKE_ELPROBEEVT_T
  print "sel_FAKE_ELPROBEEVT_L: \n", sel_FAKE_ELPROBEEVT_L

  # histograms for probe passing T
  #
  h_probelep_FAKE_ELPROBEEVT_T_pt = TH1D("probelep_FAKE_ELPROBEEVT_T_pt", "probelep_FAKE_ELPROBEEVT_T_pt", 30, 20.0, 200.0)
  hist_list_probe_ELPROBEEVT[h_probelep_FAKE_ELPROBEEVT_T_pt] = ["T","pt"]
#  h_probelep_FAKE_ELPROBEEVT_T_ptvarcone30_over_pt = TH1D("probelep_FAKE_ELPROBEEVT_T_ptvarcone30_over_pt", "probelep_FAKE_ELPROBEEVT_T_ptvarcone30_over_pt", 20, 0.0, 0.1)
#  hist_list_probe_ELPROBEEVT[h_probelep_FAKE_ELPROBEEVT_T_ptvarcone30_over_pt] = ["T","ptvarcone30_over_pt"]
  h_probelep_FAKE_ELPROBEEVT_T_ptvarcone20_over_pt = TH1D("probelep_FAKE_ELPROBEEVT_T_ptvarcone20_over_pt", "probelep_FAKE_ELPROBEEVT_T_ptvarcone20_over_pt", 20, 0.0, 0.1)
  hist_list_probe_ELPROBEEVT[h_probelep_FAKE_ELPROBEEVT_T_ptvarcone20_over_pt] = ["T","ptvarcone20_over_pt"]
  h_probelep_FAKE_ELPROBEEVT_T_topoetcone20_over_pt = TH1D("probelep_FAKE_ELPROBEEVT_T_topoetcone20_over_pt", "probelep_FAKE_ELPROBEEVT_T_topoetcone20_over_pt", 70, -0.2, 0.5)
  hist_list_probe_ELPROBEEVT[h_probelep_FAKE_ELPROBEEVT_T_topoetcone20_over_pt] = ["T","topoetcone20_over_pt"]

  h_probelep_FAKE_ELPROBEEVT_T_pt.GetXaxis().SetTitle("pT [GeV]")
#  h_probelep_FAKE_ELPROBEEVT_T_ptvarcone30_over_pt.GetXaxis().SetTitle("ptvarcone30/pT")
  h_probelep_FAKE_ELPROBEEVT_T_ptvarcone20_over_pt.GetXaxis().SetTitle("ptvarcone20/pT")
  h_probelep_FAKE_ELPROBEEVT_T_topoetcone20_over_pt.GetXaxis().SetTitle("topoetcone20/pT")

  # histograms for probe passing L!T
  #
  h_probelep_FAKE_ELPROBEEVT_L_pt = TH1D("probelep_FAKE_ELPROBEEVT_L_pt", "probelep_FAKE_ELPROBEEVT_L_pt", 30, 20.0, 200.0)
  hist_list_probe_ELPROBEEVT[h_probelep_FAKE_ELPROBEEVT_L_pt]  = ["L","pt"]
#  h_probelep_FAKE_ELPROBEEVT_L_ptvarcone30_over_pt = TH1D("probelep_FAKE_ELPROBEEVT_L_ptvarcone30_over_pt", "probelep_FAKE_ELPROBEEVT_L_ptvarcone30_over_pt", 20, 0.0, 0.1)
#  hist_list_probe_ELPROBEEVT[h_probelep_FAKE_ELPROBEEVT_L_ptvarcone30_over_pt] = ["L","ptvarcone30_over_pt"]
  h_probelep_FAKE_ELPROBEEVT_L_ptvarcone20_over_pt = TH1D("probelep_FAKE_ELPROBEEVT_L_ptvarcone20_over_pt", "probelep_FAKE_ELPROBEEVT_L_ptvarcone20_over_pt", 20, 0.0, 0.1)
  hist_list_probe_ELPROBEEVT[h_probelep_FAKE_ELPROBEEVT_L_ptvarcone20_over_pt] = ["L","ptvarcone20_over_pt"]
  h_probelep_FAKE_ELPROBEEVT_L_topoetcone20_over_pt = TH1D("probelep_FAKE_ELPROBEEVT_L_topoetcone20_over_pt", "probelep_FAKE_ELPROBEEVT_L_topoetcone20_over_pt", 70, -0.2, 0.5)
  hist_list_probe_ELPROBEEVT[h_probelep_FAKE_ELPROBEEVT_L_topoetcone20_over_pt] = ["L","topoetcone20_over_pt"]

  h_probelep_FAKE_ELPROBEEVT_L_pt.GetXaxis().SetTitle("pT [GeV]")
#  h_probelep_FAKE_ELPROBEEVT_L_ptvarcone30_over_pt.GetXaxis().SetTitle("ptvarcone30/pT")
  h_probelep_FAKE_ELPROBEEVT_L_ptvarcone20_over_pt.GetXaxis().SetTitle("ptvarcone20/pT")
  h_probelep_FAKE_ELPROBEEVT_L_topoetcone20_over_pt.GetXaxis().SetTitle("topoetcone20/pT")

  # histograms for tag (passing T: default)
  #
  h_taglep_FAKE_ELPROBEEVT_T_pt = TH1D("taglep_FAKE_ELPROBEEVT_T_pt", "taglep_FAKE_ELPROBEEVT_T_pt", 30, 20.0, 200.0)
  hist_list_tag_ELPROBEEVT[h_taglep_FAKE_ELPROBEEVT_T_pt] = ["T","pt"]
  h_taglep_FAKE_ELPROBEEVT_T_ptvarcone30_over_pt = TH1D("taglep_FAKE_ELPROBEEVT_T_ptvarcone30_over_pt", "taglep_FAKE_ELPROBEEVT_T_ptvarcone30_over_pt", 20, 0.0, 0.1)
  hist_list_tag_ELPROBEEVT[h_taglep_FAKE_ELPROBEEVT_T_ptvarcone30_over_pt] = ["T","ptvarcone30_over_pt"]
  h_taglep_FAKE_ELPROBEEVT_T_ptvarcone20_over_pt = TH1D("taglep_FAKE_ELPROBEEVT_T_ptvarcone20_over_pt", "taglep_FAKE_ELPROBEEVT_T_ptvarcone20_over_pt", 20, 0.0, 0.1)
  hist_list_tag_ELPROBEEVT[h_taglep_FAKE_ELPROBEEVT_T_ptvarcone20_over_pt] = ["T","ptvarcone20_over_pt"]
  h_taglep_FAKE_ELPROBEEVT_T_topoetcone20_over_pt = TH1D("taglep_FAKE_ELPROBEEVT_T_topoetcone20_over_pt", "taglep_FAKE_ELPROBEEVT_T_topoetcone20_over_pt", 70, -0.2, 0.5)
  hist_list_tag_ELPROBEEVT[h_taglep_FAKE_ELPROBEEVT_T_topoetcone20_over_pt] = ["T","topoetcone20_over_pt"]

  h_taglep_FAKE_ELPROBEEVT_T_pt.GetXaxis().SetTitle("pT [GeV]")
  h_taglep_FAKE_ELPROBEEVT_T_ptvarcone30_over_pt.GetXaxis().SetTitle("ptvarcone30/pT")
  h_taglep_FAKE_ELPROBEEVT_T_ptvarcone20_over_pt.GetXaxis().SetTitle("ptvarcone20/pT")
  h_taglep_FAKE_ELPROBEEVT_T_topoetcone20_over_pt.GetXaxis().SetTitle("topoetcone20/pT")

  mytree.Project("probelep_FAKE_ELPROBEEVT_T_pt", "el_probe_pt[0]/1e3", "%s * (%s)" %(mytree_weight, sel_FAKE_ELPROBEEVT_T), "" )
  mytree.Project("probelep_FAKE_ELPROBEEVT_L_pt", "el_probe_pt[0]/1e3", "%s * (%s)" %(mytree_weight, sel_FAKE_ELPROBEEVT_L), "" )
#  mytree.Project("probelep_FAKE_ELPROBEEVT_T_ptvarcone30_over_pt", "el_probe_ptvarcone30[0]/el_probe_pt[0]", "%s * (%s)" %(mytree_weight, sel_FAKE_ELPROBEEVT_T), "" )
#  mytree.Project("probelep_FAKE_ELPROBEEVT_L_ptvarcone30_over_pt", "el_probe_ptvarcone30[0]/el_probe_pt[0]", "%s * (%s)" %(mytree_weight, sel_FAKE_ELPROBEEVT_L), "" )
  mytree.Project("probelep_FAKE_ELPROBEEVT_T_ptvarcone20_over_pt", "el_probe_ptvarcone20[0]/el_probe_pt[0]", "%s * (%s)" %(mytree_weight, sel_FAKE_ELPROBEEVT_T), "" )
  mytree.Project("probelep_FAKE_ELPROBEEVT_L_ptvarcone20_over_pt", "el_probe_ptvarcone20[0]/el_probe_pt[0]", "%s * (%s)" %(mytree_weight, sel_FAKE_ELPROBEEVT_L), "" )
  mytree.Project("probelep_FAKE_ELPROBEEVT_T_topoetcone20_over_pt", "el_probe_topoetcone20[0]/el_probe_pt[0]", "%s * (%s)" %(mytree_weight, sel_FAKE_ELPROBEEVT_T), "" )
  mytree.Project("probelep_FAKE_ELPROBEEVT_L_topoetcone20_over_pt", "el_probe_topoetcone20[0]/el_probe_pt[0]", "%s * (%s)" %(mytree_weight, sel_FAKE_ELPROBEEVT_L), "" )

  if args.channel == "OF":
     # probe is electron, tag is muon
     #
     mytree.Project("taglep_FAKE_ELPROBEEVT_T_pt", "muon_tag_pt[0]/1e3", "%s * (%s)" %(mytree_weight, sel_FAKE_ELPROBEEVT_T), "" )
     mytree.Project("taglep_FAKE_ELPROBEEVT_T_ptvarcone30_over_pt", "muon_tag_ptvarcone30[0]/muon_tag_pt[0]", "%s * (%s)" %(mytree_weight, sel_FAKE_ELPROBEEVT_T), "" )
     mytree.Project("taglep_FAKE_ELPROBEEVT_T_ptvarcone20_over_pt", "muon_tag_ptvarcone20[0]/muon_tag_pt[0]", "%s * (%s)" %(mytree_weight, sel_FAKE_ELPROBEEVT_T), "" )
     mytree.Project("taglep_FAKE_ELPROBEEVT_T_topoetcone20_over_pt", "muon_tag_topoetcone20[0]/muon_tag_pt[0]", "%s * (%s)" %(mytree_weight, sel_FAKE_ELPROBEEVT_T), "" )
  elif args.channel == "SF":
     # probe is electron, tag is electron
     #
     mytree.Project("taglep_FAKE_ELPROBEEVT_T_pt", "el_tag_pt[0]/1e3", "%s * (%s)" %(mytree_weight, sel_FAKE_ELPROBEEVT_T), "" )
#     mytree.Project("taglep_FAKE_ELPROBEEVT_T_ptvarcone30_over_pt", "el_tag_ptvarcone30[0]/el_tag_pt[0]", "%s * (%s)" %(mytree_weight, sel_FAKE_ELPROBEEVT_T), "" )
     mytree.Project("taglep_FAKE_ELPROBEEVT_T_ptvarcone20_over_pt", "el_tag_ptvarcone20[0]/el_tag_pt[0]", "%s * (%s)" %(mytree_weight, sel_FAKE_ELPROBEEVT_T), "" )
     mytree.Project("taglep_FAKE_ELPROBEEVT_T_topoetcone20_over_pt", "el_tag_topoetcone20[0]/el_tag_pt[0]", "%s * (%s)" %(mytree_weight, sel_FAKE_ELPROBEEVT_T), "" )


  # Normalise to unity
  if args.doNorm:
     for hist in hist_list_probe_ELPROBEEVT.keys():
	if hist.Integral() == 0:
	  continue
        hist.Scale(1/hist.Integral())
	hist.GetYaxis().SetTitle("Norm. events")
	#hist.GetYaxis().SetRangeUser(0,1)
     for hist in hist_list_tag_ELPROBEEVT.keys():
	if hist.Integral() == 0:
	  continue
        hist.Scale(1/hist.Integral())
	hist.GetYaxis().SetTitle("Norm. events")
	#hist.GetYaxis().SetRangeUser(0,1)

  # now plot
  #
  print "\tLooking at events where the PROBE is: {0} and the channel is {1}\n".format("ELECTRON", args.channel)
  for  hist_tag in hist_list_tag_ELPROBEEVT.keys():

     c = TCanvas("c","Temp",50,50,700,900)
     c.Divide(1,2)

     c.cd(1)
     legend_T = TLegend(0.6,0.8,0.8,0.85); # (x1,y1 (--> bottom left corner), x2, y2 (--> top right corner) )
     legend_T.SetHeader("2 Lep SS Fake CR - T probe")
     legend_T.SetBorderSize(0)  # no border
     legend_T.SetFillColor(0) # Legend background should be white
     legend_T.SetTextSize(0.04) # Increase entry font size!
     legend_T.SetTextFont(42) # Helvetica

     c.cd(2)
     legend_L = TLegend(0.6,0.8,0.8,0.85); # (x1,y1 (--> bottom left corner), x2, y2 (--> top right corner) )
     legend_L.SetHeader("2 Lep SS Fake CR - L!T probe")
     legend_L.SetBorderSize(0)  # no border
     legend_L.SetFillColor(0) # legend_L background should be white
     legend_L.SetTextSize(0.04) # Increase entry font size!
     legend_L.SetTextFont(42) # Helvetica

     var_tag    = hist_list_tag_ELPROBEEVT[hist_tag][1]
     type_tag   = hist_list_tag_ELPROBEEVT[hist_tag][0]

     hist_tag.SetLineColor(1)
     hist_tag.SetLineWidth(2)

     print "\tPlotting variable: {0}\n".format(var_tag)

     print "\ttag histogram name: {0}\n".format(hist_tag.GetName())

     draw_pad1 = False
     draw_pad2 = False

     for hist_probe in hist_list_probe_ELPROBEEVT.keys():

       print "\t\tprobe histogram name: {0}".format(hist_probe.GetName())

       hist_probe.SetLineColor(2)
       hist_probe.SetLineWidth(2)

       var_probe  = hist_list_probe_ELPROBEEVT[hist_probe][1]
       type_probe = hist_list_probe_ELPROBEEVT[hist_probe][0]

       # must be looking at the same variable!
       #
       if  var_probe != var_tag:
         continue

       print "\t\tfound a match in variable! {0} = {1}\n".format(var_tag,var_probe)

       if type_probe == "T":
          print "\t\t  probe is of type: {0}".format(type_probe)
          print "\n\t\t  --> drawing: \t {0} \t {1} \t on pad(1) of the same canvas\n".format(hist_tag.GetName(),hist_probe.GetName())
          c.cd(1)
	  legend_T.AddEntry(None, "", "")
          legend_T.AddEntry(hist_tag, "REAL lepton", "L")
	  legend_T.AddEntry(None, "", "")
          legend_T.AddEntry(hist_probe, "FAKE lepton", "L")
          hist_tag.Draw("HIST")
          hist_probe.Draw("HIST SAME")
          draw_pad1 = True

       elif type_probe == "L":
          print "\t\t  probe is of type: {0}".format(type_probe)
          print "\n\t\t  --> drawing: \t {0} \t {1} \t on pad(2) of the same canvas\n".format(hist_tag.GetName(),hist_probe.GetName())
          c.cd(2)
	  legend_L.AddEntry(None, "", "")
	  legend_L.AddEntry(hist_tag, "REAL lepton", "L")
	  legend_L.AddEntry(None, "", "")
          legend_L.AddEntry(hist_probe, "FAKE lepton", "L")
          hist_tag.Draw("HIST")
          hist_probe.Draw("HIST SAME")
          draw_pad2 = True

       if ( draw_pad1 and draw_pad2 ):
	 c.cd(1)
         legend_T.Draw()
	 c.cd(2)
	 legend_L.Draw()
         plotname = dirname + "/FAKE_ELPROBEEVT_" + var_probe
         c.SaveAs(plotname+".png")

     del c
Beispiel #6
0
def main():
   import configurations as config
   import csv
   from ModelParser import ModelKey, GroupXsecLimit
   from ROOT import gStyle
   from Styles import marker
   
   gStyle.SetPadTopMargin(0.05)
   gStyle.SetPadRightMargin(0.05)

   from optparse import OptionParser
   parser = OptionParser()
   parser.add_option("-i", "--inputfile", dest="inputfile")
   (options, args) = parser.parse_args()

   models = []
   with open(config.bh_list, 'rb') as f:
      reader = csv.reader(f)
      for r in reader:
         models.append(ModelKey(r[0]))

   from ROOT import TFile, TMultiGraph, TGraph, TLegend, TCanvas
   infile_xsec = TFile(config.bh_xsec, "READ")
   infile_CL = TFile(options.inputfile, "READ")

   from OptimizationTools import Bisection
   from Styles import formatXsecCL, formatExcludedMass

   store = []
   mg = TMultiGraph()
   legend1 = TLegend(0.3241611,0.49,0.746644,0.69)
   legend1.SetHeader("Observed Cross Section Limits")
   legend1.SetTextSize(0.037)
   legend1.SetTextFont(42)
   legend1.SetFillColor(0)
   legend1.SetLineColor(0)

   legend2 = TLegend(0.3241611,0.68,0.746644,0.88)
   legend2.SetHeader("Theoretical Cross Section")
   legend2.SetTextSize(0.037)
   legend2.SetTextFont(42)
   legend2.SetFillColor(0)
   legend2.SetLineColor(0)
   
   legend3 = TLegend(0.3241611,0.8806993,0.886644,0.9273427)
   legend3.SetHeader("String Ball (BlackMax)")
   legend3.SetTextSize(0.037)
   legend3.SetTextFont(42)
   legend3.SetFillColor(0)
   legend3.SetLineColor(0)
   
   iColor = 0
   iStyle = 2
   #for key, group in ModelLimitGroup(models).items():
   for key, group in GroupXsecLimit(models).items():
      if not "SB" in key:
         continue
         
      name = ModelKey(key).name
      gXsec = infile_xsec.Get(key)
      formatXsecCL(gXsec, iColor, iStyle)
      mg.Add(gXsec, "c")
      legend2.AddEntry(gXsec, config.model_description[name], "l")

      gCL95 = infile_CL.Get("%s-CL95" % key)
      formatXsecCL(gCL95, iColor, 1)
      mg.Add(gCL95, "pl")
      legend1.AddEntry(gCL95, config.model_description[name], "pl")

      iColor += 1
      iStyle += 2

   c = TCanvas("SB_BM", "SB_BM", 500, 500)
   c.SetLogy()
   mg.Draw("A")
   mg.GetXaxis().SetTitle("M^{ min} (TeV)")
   mg.GetXaxis().SetRangeUser(3.9,7.1)
   mg.GetYaxis().SetRangeUser(1e-4,50)
   mg.GetYaxis().SetTitle("#sigma (pb)")
   mg.GetYaxis().SetTitleOffset(1.05)
   mg.GetYaxis().SetTitleSize(0.045)
   mg.GetYaxis().SetLabelSize(0.045)
   mg.GetXaxis().SetTitleSize(0.045)
   mg.GetXaxis().SetLabelSize(0.045)
   
   legend1.Draw("plain")
   legend2.Draw("plain")
   legend3.Draw("plain")
   c.Update()

   from ROOT import TPaveText
   cmslabel = TPaveText(0.45,0.96,0.60,0.99,"brNDC")
   cmslabel.AddText(config.cmsTitle)
   cmslabel.SetTextSize(0.041)
   #cmslabel.AddText(config.cmsSubtitle)
   cmslabel.SetFillColor(0)
   cmslabel.Draw("plain")

   raw_input("Press Enter to continue...")
#================================
yarray_4K_1_gr.GetYaxis().SetTitleSize(0.04)
yarray_4K_1_gr.GetXaxis().SetTitleSize(0.04)
yarray_4K_1_gr.GetXaxis().SetLabelSize(0.04)
yarray_4K_1_gr.GetYaxis().SetLabelSize(0.04)
yarray_4K_1_gr.GetXaxis().SetLabelFont(22)
yarray_4K_1_gr.GetYaxis().SetLabelFont(22)
yarray_4K_1_gr.GetXaxis().SetTitleColor(1)
yarray_4K_1_gr.GetYaxis().SetTitleColor(1)

leg1 = TLegend(0.5, 0.6, 0.7, 0.9)
leg1.SetFillColor(0)
leg1.SetFillStyle(0)
leg1.SetTextSize(0.05)
leg1.SetBorderSize(0)
leg1.SetTextFont(22)
leg1.AddEntry("", "GeIA group", "")
leg1.AddEntry(yarray_4K_1_gr, "4K-1V/cm", "lp")
leg1.AddEntry(yarray_4K_2_gr, "4K-10V/cm", "lp")
leg1.AddEntry(yarray_4K_3_gr, "4K-80V/cm(Min)", "lp")
leg1.AddEntry(yarray_77K_1_gr, "77K-20V/cm", "lp")
leg1.AddEntry(yarray_77K_2_gr, "77K-200V/cm", "lp")
leg1.AddEntry(yarray_77K_3_gr, "77K-500V/cm(Min)", "lp")

c.Draw()
yarray_4K_1_gr.Draw("ALP")
yarray_4K_2_gr.Draw("LPsame")
yarray_4K_3_gr.Draw("LPsame")
yarray_77K_1_gr.Draw("LPsame")
yarray_77K_2_gr.Draw("LPsame")
yarray_77K_3_gr.Draw("LPsame")
Beispiel #8
0
def compareUpperLimits(labels, masses, filelabels, **kwargs):
    print color("compareUpperLimits()", color="magenta", prepend=">>>\n>>> ")

    # SIGNAL strength & mass
    extralabel = kwargs.get('extralabel', "")
    plotlabel = kwargs.get('plotlabel', "")

    # LOOP over LABELS
    for label in labels:
        print color("plotUpperLimits - %s" % (label),
                    color="grey",
                    prepend="\n>>> ")

        ymax = -99999
        ymin = 99999
        medians = []

        for filelabel, title in filelabels:
            N = len(masses)
            median = TGraph(N)  # median line
            median.SetTitle(title)
            medians.append(median)
            for i, mass in enumerate(masses):
                filename = getOutputFilename(label, mass, extralabel=filelabel)
                limits = getLimits(filename)
                median.SetPoint(i, mass, limits[2])  # median
                if limits[2] > ymax: ymax = limits[2]
                if limits[2] < ymin: ymin = limits[2]

        median0 = medians[0]
        doLog = ymin and ymax / ymin > 6
        ymax = ymax * 1.40
        xtitle = "m_{X} [GeV]"
        ytitle = "95% upper limit on #sigma#timesBR(X #rightarrow #tau#tau) [pb]"
        if "bbA" in filelabels[0][0]:
            xtitle = "m_{A} [GeV]"
            ytitle = "95% upper limit on #sigma#timesBR(A #rightarrow #tau#tau) [pb]"

        W, H = 800, 800
        T, B = 0.10 * H, 0.16 * H
        L, R = 0.12 * W, 0.04 * W

        # MAIN plot
        canvas = TCanvas("canvas", "canvas", 100, 100, W, H)
        canvas.Divide(2)
        canvas.cd(1)
        gPad.SetPad("pad1", "pad1", 0, 0.37, 1, 1, 0, -1, 0)
        gPad.SetTopMargin(T / H)
        gPad.SetBottomMargin(0.01)
        gPad.SetLeftMargin(L / W)
        gPad.SetRightMargin(R / W)
        gPad.SetTickx(0)
        gPad.SetTicky(0)
        gPad.SetGrid()
        if doLog:
            ymin = 10**(floor(log(ymin, 10)))
            ymax = 10**(ceil(log(ymax, 10)))
            gPad.SetLogy()
        else:
            ymin *= 0 if ymin > 0 else 1.20

        width = 0.25
        height = 0.05 + len(medians) * 0.05
        #x1 = 0.16; x2 = x1 + width # Left
        x2 = 0.70
        x1 = x2 - width  # Right
        x2 = x1 + width
        y1 = 0.86
        y2 = y1 - height
        legend = TLegend(x1, y1, x2, y2)

        frame = gPad.DrawFrame(min(masses), ymin, max(masses), ymax)
        frame.GetYaxis().CenterTitle()
        frame.GetYaxis().SetTitleSize(0.055)
        frame.GetXaxis().SetTitleSize(0.058)
        frame.GetXaxis().SetLabelSize(0.050 * 0)
        frame.GetYaxis().SetLabelSize(0.053)
        frame.GetXaxis().SetLabelOffset(0.012)
        frame.GetXaxis().SetTitleOffset(1.02)
        frame.GetYaxis().SetTitleOffset(1.08)
        frame.GetXaxis().SetNdivisions(508)
        frame.GetYaxis().CenterTitle(True)
        frame.GetYaxis().SetTitle(ytitle)
        frame.GetXaxis().SetTitle(xtitle)

        option = 'L'
        for i, median in enumerate(medians):
            median.SetLineColor(colors[i % len(colors)])
            median.SetLineStyle(styles[i % len(styles)])
            median.SetLineWidth(2 if styles[i % len(styles)] != kDotted else 3)
            median.Draw('L')
            legend.AddEntry(median, median.GetTitle(), 'L')
            if i == 0: option += ' SAME'

        CMS_lumi.CMS_lumi(gPad, 13, 0)
        gPad.SetTicks(1, 1)
        gPad.Modified()
        frame.Draw('sameaxis')

        legend.SetFillStyle(0)
        legend.SetBorderSize(0)
        legend.SetTextSize(0.041)
        legend.SetTextFont(62)
        legend.SetHeader("%s" % (label_dict[label + extralabel]))
        legend.SetTextFont(42)
        legend.Draw()

        # RATIO plot
        canvas.cd(2)
        gPad.SetPad("pad2", "pad2", 0, 0, 1, 0.36, 0, -1, 0)
        gPad.SetTopMargin(0.05)
        gPad.SetBottomMargin(0.24)
        gPad.SetLeftMargin(L / W)
        gPad.SetRightMargin(R / W)

        frame_ratio = gPad.DrawFrame(min(masses), 0.36, max(masses), 1.20)
        frame_ratio.GetYaxis().CenterTitle()
        frame_ratio.GetYaxis().SetTitleSize(0.055 * 1.79)
        frame_ratio.GetXaxis().SetTitleSize(0.058 * 1.79)
        frame_ratio.GetXaxis().SetLabelSize(0.052 * 1.79)
        frame_ratio.GetYaxis().SetLabelSize(0.050 * 1.79)
        frame_ratio.GetXaxis().SetLabelOffset(0.012)
        frame_ratio.GetXaxis().SetTitleOffset(1.00)
        frame_ratio.GetYaxis().SetTitleOffset(0.63)
        frame_ratio.GetXaxis().SetNdivisions(508)
        frame_ratio.GetYaxis().CenterTitle(True)
        frame_ratio.GetYaxis().SetTitle("ratio")
        frame_ratio.GetXaxis().SetTitle(xtitle)
        frame_ratio.GetYaxis().SetNdivisions(5)

        option = 'L'
        ratios = []
        for i, median in enumerate(medians):
            ratio = makeRatioTGraphs(median, median0)
            ratio.SetLineColor(median.GetLineColor())
            ratio.SetLineStyle(median.GetLineStyle())
            ratio.SetLineWidth(median.GetLineWidth())
            ratio.Draw('L')
            ratios.append(ratio)
            if i == 1: option += ' SAME'

        gPad.SetTicks(1, 1)
        gPad.Modified()
        frame_ratio.Draw('sameaxis')

        print " "
        canvas.SaveAs("%s/upperLimit-%s%s_compare.png" %
                      (PLOTS_DIR, label, plotlabel))
        canvas.SaveAs("%s/upperLimit-%s%s_compare.pdf" %
                      (PLOTS_DIR, label, plotlabel))
        canvas.Close()
Beispiel #9
0
ratio_nominal_eleP = ratio(nominal_truth_h, nominal_eleP)
ratio_nominal_iso = ratio(nominal_truth_h, nominal_Iso)
ratio_nominal_matchChi2 = ratio(nominal_truth_h, nominal_MatchChi2)
ratio_nominal_oppo = ratio(nominal_truth_h, nominal_Oppo)
ratio_nominal_posD0 = ratio(nominal_truth_h, nominal_PosD0)
ratio_nominal_trkChi2 = ratio(nominal_truth_h, nominal_TrkChi2)
ratio_nominal_uncP = ratio(nominal_truth_h, nominal_uncP)
ratio_nominal_L1L1 = ratio(nominal_truth_h, nominal_L1L1)
ratio_nominal_L1L2 = ratio(nominal_truth_h, nominal_L1L2)
ratio_nominal_L2L2 = ratio(nominal_truth_h, nominal_L2L2)

legend = TLegend(.68, .66, .92, .87)
legend.SetBorderSize(0)
legend.SetFillColor(0)
legend.SetFillStyle(0)
legend.SetTextFont(42)
legend.SetTextSize(0.035)
legend.AddEntry(ratio_L0_assym, "L0", "LP")
legend.AddEntry(ratio_nominal_assym, "nominal", "LP")

c.Print(outfile + ".pdf[")


def plot(histo1, histo2, outfile, legend):
    histo1.Draw("")
    histo1.SetTitle(str(histo1))
    histo2.Draw("same")
    histo2.SetLineColor(1)
    legend.Draw("same")
    c.Print(outfile + ".pdf", "Title:plot")
Beispiel #10
0
def plotUpperLimits(labels, values):
    # see CMS plot guidelines: https://ghm.web.cern.ch/ghm/plots/

    N = len(labels)
    yellow = TGraph(2 * N)  # yellow band
    green = TGraph(2 * N)  # green band
    median = TGraph(N)  # median line

    up2s = []
    for i in range(N):
        # file_name = "higgsCombine"+labels[i]+"AsymptoticLimits.mH125.root"
        file_name = "higgsCombine.AsymptoticLimits.mH125." + labels[i] + ".root"
        limit = getLimits(file_name)
        # print'limit = ',limit
        # print'values[i] = ',values[i]
        up2s.append(limit[4])
        yellow.SetPoint(i, values[i], limit[4])  # + 2 sigma
        green.SetPoint(i, values[i], limit[3])  # + 1 sigma
        median.SetPoint(i, values[i], limit[2])  # median
        green.SetPoint(2 * N - 1 - i, values[i], limit[1])  # - 1 sigma
        yellow.SetPoint(2 * N - 1 - i, values[i], limit[0])  # - 2 sigma

    W = 800
    H = 600
    T = 0.08 * H
    B = 0.12 * H
    L = 0.12 * W
    R = 0.04 * W
    c = TCanvas("c", "c", 100, 100, W, H)
    c.SetFillColor(0)
    c.SetBorderMode(0)
    c.SetFrameFillStyle(0)
    c.SetFrameBorderMode(0)
    c.SetLeftMargin(L / W)
    c.SetRightMargin(R / W)
    c.SetTopMargin(T / H)
    c.SetBottomMargin(B / H)
    c.SetTickx(0)
    c.SetTicky(0)
    c.SetGrid()
    # c.SetLogy()
    # gPad.SetLogy()
    c.cd()
    # ROOT.gPad.SetLogy()
    # c.SetLogy()
    frame = c.DrawFrame(1.4, 0.001, 4.1, 10)
    frame.GetYaxis().CenterTitle()
    frame.GetYaxis().SetTitleSize(0.05)
    frame.GetXaxis().SetTitleSize(0.05)
    frame.GetXaxis().SetLabelSize(0.04)
    frame.GetYaxis().SetLabelSize(0.04)
    frame.GetYaxis().SetTitleOffset(0.9)
    frame.GetXaxis().SetNdivisions(508)
    frame.GetYaxis().CenterTitle(True)
    # frame.GetYaxis().SetTitle("95% upper limit on #sigma / #sigma_{SM}")

    if (args.atlas_compare):
        frame.GetYaxis().SetTitle(
            "95% CL limits on #sigma(gg#rightarrow X)#times B(X#rightarrow HH) [pb]"
        )
    elif (args.CMS_compare):
        frame.GetYaxis().SetTitle(
            "95% CL limit on #sigma(gg#rightarrow X#rightarrow HH) (fb)")
#    frame.GetYaxis().SetTitle("95% upper limit on #sigma #times BR / (#sigma #times BR)_{SM}")
# frame.GetXaxis().SetTitle("background systematic uncertainty [%]")
#if(args.SM_Radion): frame.GetXaxis.SetTitle("Standard Model")
#else: frame.GetXaxis().SetTitle("Radion Mass (GeV)")
# frame.SetMinimum(0)
# frame.SetMinimum(1) # need Minimum > 0 for log scale
    frame.SetMinimum(1.000001)  # need Minimum > 0 for log scale
    # frame.SetMaximum(max(up2s)*1.05)
    # frame.SetMaximum(max(up2s)*2)
    # frame.SetMaximum(1000.)

    if (args.atlas_compare):
        frame.SetMaximum(7 * 1e2)  # ATLAS
    elif (args.CMS_compare):
        frame.SetMaximum(8 * 1e4)  # CMS HH
    #frame.GetXaxis().SetLimits(min(values),max(values))
    # frame.SetLogy()
    frame.GetXaxis().SetLimits(min(values) - 10, max(values) + 10)

    yellow.SetFillColor(ROOT.kOrange)
    yellow.SetLineColor(ROOT.kOrange)
    yellow.SetFillStyle(1001)
    yellow.Draw('F')

    green.SetFillColor(ROOT.kGreen + 1)
    green.SetLineColor(ROOT.kGreen + 1)
    green.SetFillStyle(1001)
    green.Draw('Fsame')

    median.SetLineColor(1)
    median.SetLineWidth(2)
    median.SetLineStyle(2)
    median.Draw('Lsame')

    CMS_lumi.CMS_lumi(c, 4, 11)
    ROOT.gPad.SetTicks(1, 1)
    frame.Draw('sameaxis')

    # yboost = 0.075
    yboost = -0.2

    x1 = 0.15
    x2 = x1 + 0.24
    y2 = 0.76 + yboost
    y1 = 0.60 + yboost
    legend = TLegend(x1, y1, x2, y2)
    legend.SetFillStyle(0)
    legend.SetBorderSize(0)
    legend.SetTextSize(0.041)
    legend.SetTextFont(42)
    legend.AddEntry(median, "AsymptoticLimits CL_{s} expected", 'L')
    legend.AddEntry(green, "#pm 1 std. deviation", 'f')
    #    legend.AddEntry(green, "AsymptoticLimits CL_{s} #pm 1 std. deviation",'f')
    legend.AddEntry(yellow, "#pm 2 std. deviation", 'f')
    # legend.AddEntry("","STAT Only","")
    #    legend.AddEntry(green, "AsymptoticLimits CL_{s} #pm 2 std. deviation",'f')
    legend.Draw()

    label = TLatex()
    label.SetNDC()
    label.SetTextAngle(0)
    label.SetTextColor(kBlack)
    label.SetTextFont(42)
    label.SetTextSize(0.045)
    label.SetLineWidth(2)
    label.DrawLatex(0.7, 0.7 + yboost, "STAT only")
    print " "
    # c.SaveAs("UpperLimit.png")

    outFile = ''
    if (args.CMS_compare):
        outFile += "CMS_Compare_"
    if (args.atlas_compare):
        outFile += "atlas_Compare_"

    if args.SM_Radion: outFile += "SM_"

    c.SaveAs(outFile + "UpperLimit.pdf")
    c.SaveAs(outFile + "UpperLimit.C")
    c.Close()
Beispiel #11
0
def plotDataMC(args, plot_mu, plot_el):

    hCanvas = TCanvas("hCanvas", "Distribution", 800, 800)
    if args.ratio:
        plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0.5, 1, 1)
        ratioPad = ROOT.TPad("ratioPad", "ratioPad", 0, 0., 1, 0.5)
        setTDRStyle()
        plotPad.UseCurrentStyle()
        ratioPad.UseCurrentStyle()
        plotPad.Draw()
        ratioPad.Draw()
        plotPad.cd()
    else:
        plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0, 1, 1)
        setTDRStyle()
        plotPad.UseCurrentStyle()
        plotPad.Draw()
        plotPad.cd()

    # Data load processes
    colors = createMyColors()
    if args.use2016:
        data_mu = Process(Data2016, normalized=True)
        data_el = Process(Data2016, normalized=True)
    elif args.use2018:
        data_mu = Process(Data2018, normalized=True)
        data_el = Process(Data2018, normalized=True)
    elif args.useall:
        data_all = [
            Process(Data2016, normalized=True),
            Process(Data, normalized=True),
            Process(Data2018, normalized=True)
        ]
    else:
        data_mu = Process(Data, normalized=True)
        data_el = Process(Data, normalized=True)

    eventCounts_mu = totalNumberOfGeneratedEvents(path,
                                                  plot_mu["default"].muon)
    eventCounts_el = totalNumberOfGeneratedEvents(path,
                                                  plot_el["default"].muon)
    negWeights_mu = negWeightFractions(path, plot_mu["default"].muon)
    negWeights_el = negWeightFractions(path, plot_el["default"].muon)

    # Background load processes
    backgrounds = copy(args.backgrounds)
    if plot_mu["default"].useJets:
        if "Wjets" in backgrounds:
            backgrounds.remove("Wjets")
        backgrounds.insert(0, "Jets")

    processes_mu = []
    processes_el = []
    processes_mu2016 = []
    processes_mu2017 = []
    processes_mu2018 = []
    processes_el2016 = []
    processes_el2017 = []
    processes_el2018 = []
    for background in backgrounds:
        if args.use2016:
            if background == "Jets":
                processes_mu.append(
                    Process(getattr(Backgrounds2016, background),
                            eventCounts_mu,
                            negWeights_mu,
                            normalized=True))
                processes_el.append(
                    Process(getattr(Backgrounds2016, background),
                            eventCounts_el,
                            negWeights_el,
                            normalized=True))
            else:
                processes_mu.append(
                    Process(getattr(Backgrounds2016, background),
                            eventCounts_mu, negWeights_mu))
                if background == "Other":
                    processes_el.append(
                        Process(getattr(Backgrounds2016, "OtherEle"),
                                eventCounts_el, negWeights_el))
                else:
                    processes_el.append(
                        Process(getattr(Backgrounds2016, background),
                                eventCounts_el, negWeights_el))
        elif args.use2018:
            if background == "Jets":
                processes_mu.append(
                    Process(getattr(Backgrounds2018, background),
                            eventCounts_mu,
                            negWeights_mu,
                            normalized=True))
                processes_el.append(
                    Process(getattr(Backgrounds2018, background),
                            eventCounts_el,
                            negWeights_el,
                            normalized=True))
            else:
                processes_mu.append(
                    Process(getattr(Backgrounds2018, background),
                            eventCounts_mu, negWeights_mu))
                processes_el.append(
                    Process(getattr(Backgrounds2018, background),
                            eventCounts_el, negWeights_el))
        elif args.useall:
            if background == "Jets":
                processes_mu2016.append(
                    Process(getattr(Backgrounds2016, background),
                            eventCounts_mu,
                            negWeights_mu,
                            normalized=True))
                processes_el2016.append(
                    Process(getattr(Backgrounds2016, background),
                            eventCounts_el,
                            negWeights_el,
                            normalized=True))
                processes_mu2017.append(
                    Process(getattr(Backgrounds, background),
                            eventCounts_mu,
                            negWeights_mu,
                            normalized=True))
                processes_el2017.append(
                    Process(getattr(Backgrounds, background),
                            eventCounts_el,
                            negWeights_el,
                            normalized=True))
                processes_mu2018.append(
                    Process(getattr(Backgrounds2018, background),
                            eventCounts_mu,
                            negWeights_mu,
                            normalized=True))
                processes_el2018.append(
                    Process(getattr(Backgrounds2018, background),
                            eventCounts_el,
                            negWeights_el,
                            normalized=True))
                processes_mu = [
                    processes_mu2016, processes_mu2017, processes_mu2018
                ]
                processes_el = [
                    processes_mu2016, processes_mu2017, processes_mu2018
                ]
            else:
                processes_mu2016.append(
                    Process(getattr(Backgrounds2016, background),
                            eventCounts_mu, negWeights_mu))
                processes_el2016.append(
                    Process(getattr(Backgrounds2016, background),
                            eventCounts_el, negWeights_el))
                processes_mu2017.append(
                    Process(getattr(Backgrounds, background), eventCounts_mu,
                            negWeights_mu))
                processes_el2017.append(
                    Process(getattr(Backgrounds, background), eventCounts_el,
                            negWeights_el))
                processes_mu2018.append(
                    Process(getattr(Backgrounds2018, background),
                            eventCounts_mu, negWeights_mu))
                processes_el2018.append(
                    Process(getattr(Backgrounds2018, background),
                            eventCounts_el, negWeights_el))
                processes_mu = [
                    processes_mu2016, processes_mu2017, processes_mu2018
                ]
                processes_el = [
                    processes_mu2016, processes_mu2017, processes_mu2018
                ]
        else:
            if background == "Jets":
                processes_mu.append(
                    Process(getattr(Backgrounds, background),
                            eventCounts_mu,
                            negWeights_mu,
                            normalized=True))
                processes_el.append(
                    Process(getattr(Backgrounds, background),
                            eventCounts_el,
                            negWeights_el,
                            normalized=True))
            else:
                processes_mu.append(
                    Process(getattr(Backgrounds, background), eventCounts_mu,
                            negWeights_mu))
                processes_el.append(
                    Process(getattr(Backgrounds, background), eventCounts_el,
                            negWeights_el))

    legend = TLegend(0.55, 0.75, 0.925, 0.925)
    legend.SetFillStyle(0)
    legend.SetBorderSize(0)
    legend.SetTextFont(42)

    latex = ROOT.TLatex()
    latex.SetTextFont(42)
    latex.SetTextAlign(31)
    latex.SetTextSize(0.04)
    latex.SetNDC(True)
    latexCMS = ROOT.TLatex()
    latexCMS.SetTextFont(61)
    latexCMS.SetTextSize(0.06)
    latexCMS.SetNDC(True)
    latexCMSExtra = ROOT.TLatex()
    latexCMSExtra.SetTextFont(52)
    latexCMSExtra.SetTextSize(0.045)
    latexCMSExtra.SetNDC(True)
    legendHists = []

    # Modify legend information
    legendHistData_mu = ROOT.TH1F()
    legendHistData_el = ROOT.TH1F()
    dy_mu = ROOT.TH1F()
    dy_el = ROOT.TH1F()
    if args.data:
        legendHistData_mu.SetMarkerColor(ROOT.kViolet)
        legendHistData_el.SetMarkerColor(ROOT.kOrange)
        dy_mu.SetLineColor(ROOT.kBlue - 3)
        dy_el.SetLineColor(ROOT.kRed - 3)
        legend.AddEntry(legendHistData_mu, "Data #rightarrow #mu^{+}#mu^{-}",
                        "pe")
        legend.AddEntry(legendHistData_el, "Data #rightarrow e^{+}e^{-}", "pe")
        legend.AddEntry(dy_mu, "MC Inclusive #rightarrow #mu^{+}#mu^{-}", "l")
        legend.AddEntry(dy_el, "MC Inclusive #rightarrow e^{+}e^{-}", "l")

    if args.useall:
        for i in range(3):
            for process in reversed(processes_mu[i]):
                if not plot_mu[
                        "default"].muon and "#mu^{+}#mu^{-}" in process.label:
                    process.label = process.label.replace(
                        "#mu^{+}#mu^{-}", "e^{+}e^{-}")
                process.theColor = ROOT.kBlue
                process.theLineColor = ROOT.kBlue
                temphist = ROOT.TH1F()
                temphist.SetFillColor(process.theColor)

            for process in reversed(processes_el[i]):
                if not plot_el[
                        "default"].muon and "#mu^{+}#mu^{-}" in process.label:
                    process.label = process.label.replace(
                        "#mu^{+}#mu^{-}", "e^{+}e^{-}")
                process.theColor = ROOT.kRed
                process.theLineColor = ROOT.kRed
                temphist = ROOT.TH1F()
                temphist.SetFillColor(process.theColor)
    else:
        for process in reversed(processes_mu):
            if not plot_mu[
                    "default"].muon and "#mu^{+}#mu^{-}" in process.label:
                process.label = process.label.replace("#mu^{+}#mu^{-}",
                                                      "e^{+}e^{-}")
            process.theColor = ROOT.kBlue
            process.theLineColor = ROOT.kBlue
            temphist = ROOT.TH1F()
            temphist.SetFillColor(process.theColor)

        for process in reversed(processes_el):
            if not plot_el[
                    "default"].muon and "#mu^{+}#mu^{-}" in process.label:
                process.label = process.label.replace("#mu^{+}#mu^{-}",
                                                      "e^{+}e^{-}")
            process.theColor = ROOT.kRed
            process.theLineColor = ROOT.kRed
            temphist = ROOT.TH1F()
            temphist.SetFillColor(process.theColor)

    # Modify plot pad information
    nEvents = -1

    ROOT.gStyle.SetOptStat(0)

    intlumi = ROOT.TLatex()
    intlumi.SetTextAlign(12)
    intlumi.SetTextSize(0.045)
    intlumi.SetNDC(True)
    intlumi2 = ROOT.TLatex()
    intlumi2.SetTextAlign(12)
    intlumi2.SetTextSize(0.07)
    intlumi2.SetNDC(True)
    scalelabel = ROOT.TLatex()
    scalelabel.SetTextAlign(12)
    scalelabel.SetTextSize(0.03)
    scalelabel.SetNDC(True)
    metDiffLabel = ROOT.TLatex()
    metDiffLabel.SetTextAlign(12)
    metDiffLabel.SetTextSize(0.03)
    metDiffLabel.SetNDC(True)
    chi2Label = ROOT.TLatex()
    chi2Label.SetTextAlign(12)
    chi2Label.SetTextSize(0.03)
    chi2Label.SetNDC(True)
    hCanvas.SetLogy()

    # Luminosity information
    plotPad.cd()
    plotPad.SetLogy(0)
    logScale = plot_mu["default"].log

    if logScale == True:
        plotPad.SetLogy()

    if args.use2016:
        lumi_el = 35.9 * 1000
        lumi_mu = 36.3 * 1000
    elif args.use2018:
        lumi_el = 59.97 * 1000
        lumi_mu = 61.608 * 1000
    elif args.useall:
        lumi_el = [35.9 * 1000, 41.529 * 1000, 59.97 * 1000]
        lumi_mu = [36.3 * 1000, 42.135 * 1000, 61.608 * 1000]
    else:
        lumi_el = 41.529 * 1000
        lumi_mu = 42.135 * 1000
    if args.use2016:
        zScaleFac_mu = zScale2016["muons"]
        if "BBBE" in plot_el["default"].fileName:
            zScaleFac_el = zScale2016["electrons"][0]
        elif "BB" in plot_el["default"].fileName:
            zScaleFac_el = zScale2016["electrons"][1]
        elif "BE" in plot_el["default"].fileName:
            zScaleFac_el = zScale2016["electrons"][2]
        else:
            zScaleFac_el = zScale2016["electrons"][0]
    elif args.use2018:
        zScaleFac_mu = zScale2018["muons"]
        if "BBBE" in plot_el["default"].fileName:
            zScaleFac_el = zScale2018["electrons"][0]
        elif "BB" in plot_el["default"].fileName:
            zScaleFac_el = zScale2018["electrons"][1]
        elif "BE" in plot_el["default"].fileName:
            zScaleFac_el = zScale2018["electrons"][2]
        else:
            zScaleFac_el = zScale2018["electrons"][0]

    elif args.useall:
        zScaleFac_mu = [
            zScale2016["muons"], zScale["muons"], zScale2018["muons"]
        ]
        if "BBBE" in plot_el["default"].fileName:
            zScaleFac_el = [
                zScale2016["electrons"][0], zScale["electrons"][0],
                zScale2018["electrons"][0]
            ]
        elif "BB" in plot_el["default"].fileName:
            zScaleFac_el = [
                zScale2016["electrons"][1], zScale["electrons"][1],
                zScale2018["electrons"][1]
            ]
        elif "BE" in plot_el["default"].fileName:
            zScaleFac_el = [
                zScale2016["electrons"][2], zScale["electrons"][2],
                zScale2018["electrons"][2]
            ]
        else:
            zScaleFac_el = [
                zScale2016["electrons"][0], zScale["electrons"][0],
                zScale2018["electrons"][0]
            ]
    else:
        zScaleFac_mu = zScale["muons"]
        if "BBBE" in plot_el["default"].fileName:
            zScaleFac_el = zScale["electrons"][0]
        elif "BB" in plot_el["default"].fileName:
            zScaleFac_el = zScale["electrons"][1]
        elif "BE" in plot_el["default"].fileName:
            zScaleFac_el = zScale["electrons"][2]
        else:
            zScaleFac_el = zScale["electrons"][0]

    # Data and background loading
    if args.useall:
        datamu = []
        datael = []
        for i in range(3):
            datamu.append(data_all[i].loadHistogram(plot_mu["default"],
                                                    lumi_mu[i],
                                                    zScaleFac_mu[i]))
            datael.append(data_all[i].loadHistogram(plot_el["default"],
                                                    lumi_el[i],
                                                    zScaleFac_el[i]))
        stackmu = Stacks(processes_mu, lumi_mu, plot_mu["default"],
                         zScaleFac_mu)
        mu_scaleup = Stacks(processes_mu, lumi_mu, plot_mu["scale_up"],
                            zScaleFac_mu)
        mu_scaledown = Stacks(processes_mu, lumi_mu, plot_mu["scale_down"],
                              zScaleFac_mu)
        mu_ID = Stacks(processes_mu, lumi_mu, plot_mu["ID"], zScaleFac_mu)
        mu_reso = Stacks(processes_mu, lumi_mu, plot_mu["reso"], zScaleFac_mu)
        stackel = Stacks(processes_el, lumi_el, plot_el["default"],
                         zScaleFac_el)
        el_scaleup = Stacks(processes_el, lumi_el, plot_el["scale_up"],
                            zScaleFac_el)
        el_scaledown = Stacks(processes_el, lumi_el, plot_el["scale_down"],
                              zScaleFac_el)
        el_PUup = Stacks(processes_el, lumi_el, plot_el["PU_up"], zScaleFac_el)
        el_PUdown = Stacks(processes_el, lumi_el, plot_el["PU_down"],
                           zScaleFac_el)
    else:
        datamu = data_mu.loadHistogram(plot_mu["default"], lumi_mu,
                                       zScaleFac_mu)
        datael = data_el.loadHistogram(plot_el["default"], lumi_el,
                                       zScaleFac_el)
        stackmu = TheStack(processes_mu, lumi_mu, plot_mu["default"],
                           zScaleFac_mu)
        mu_scaleup = TheStack(processes_mu, lumi_mu, plot_mu["scale_up"],
                              zScaleFac_mu)
        mu_scaledown = TheStack(processes_mu, lumi_mu, plot_mu["scale_down"],
                                zScaleFac_mu)
        mu_ID = TheStack(processes_mu, lumi_mu, plot_mu["ID"], zScaleFac_mu)
        mu_reso = TheStack(processes_mu, lumi_mu, plot_mu["reso"],
                           zScaleFac_mu)

        stackel = TheStack(processes_el, lumi_el, plot_el["default"],
                           zScaleFac_el)
        print(stackel.theHistogram.Integral())
        el_scaleup = TheStack(processes_el, lumi_el, plot_el["scale_up"],
                              zScaleFac_el)
        el_scaledown = TheStack(processes_el, lumi_el, plot_el["scale_down"],
                                zScaleFac_el)
        el_PUup = TheStack(processes_el, lumi_el, plot_el["PU_up"],
                           zScaleFac_el)
        el_PUdown = TheStack(processes_el, lumi_el, plot_el["PU_down"],
                             zScaleFac_el)

    if args.znorm:
        muheight = stackmu.theHistogram.FindBin(90)
        print("Z height of mu: %d +- %d" %
              (stackmu.theHistogram.GetBinCenter(muheight),
               stackmu.theHistogram.GetBinWidth(muheight)))
        print("Z height of mu mc&data: %d, %d" %
              (stackmu.theHistogram.GetBinContent(muheight),
               datamu.GetBinContent(muheight)))
        elheight = stackel.theHistogram.FindBin(90)
        print("Z height of el: %d +- %d" %
              (stackel.theHistogram.GetBinCenter(elheight),
               stackel.theHistogram.GetBinWidth(elheight)))
        print("Z height of el mc&data: %d, %d" %
              (stackel.theHistogram.GetBinContent(elheight),
               datael.GetBinContent(elheight)))
        znum = stackmu.theHistogram.GetBinContent(muheight)
        for h in stackmu.theStack.GetHists():
            print("Z height of each hist in mu")
            print(h.GetBinContent(muheight))
            h.Scale(1. / znum)
        for h in stackel.theStack.GetHists():
            print("Z height of each hist in ee")
            print(h.GetBinContent(elheight))
            h.Scale(1. / znum)
        stackmu.theHistogram.Scale(1. / znum)
        stackel.theHistogram.Scale(1. / znum)

        datamu.Scale(1. / znum)
        datael.Scale(1. / znum)

    if args.ae:
        if args.useall:
            i = 0
            for year in range(2016, 2019):
                for h in stackmu[i].theStack.GetHists():
                    inverseAE(h, plot_mu["default"], year)
                for h in stackel[i].theStack.GetHists():
                    inverseAE(h, plot_el["default"], year)
                inverseAE(stackmu[i].theHistogram, plot_mu["default"], year)
                inverseAE(stackel[i].theHistogram, plot_el["default"], year)
                inverseAE(mu_scaleup[i].theHistogram, plot_mu["scale_up"],
                          year)
                inverseAE(mu_scaledown[i].theHistogram, plot_mu["scale_down"],
                          year)
                inverseAE(mu_ID[i].theHistogram, plot_mu["ID"], year)
                inverseAE(mu_reso[i].theHistogram, plot_mu["reso"], year)
                inverseAE(el_scaleup[i].theHistogram, plot_el["scale_up"],
                          year)
                inverseAE(el_scaledown[i].theHistogram, plot_el["scale_down"],
                          year)
                inverseAE(el_PUup[i].theHistogram, plot_el["PU_up"], year)
                inverseAE(el_PUdown[i].theHistogram, plot_el["PU_down"], year)
                inverseAE(datamu[i], plot_mu["default"], year)
                inverseAE(datael[i], plot_el["default"], year)
        else:
            if args.use2016: year = 2016
            elif args.use2018: year = 2018
            else: year = 2017
            for h in stackmu.theStack.GetHists():
                inverseAE(h, plot_mu["default"], year)
            for h in stackel.theStack.GetHists():
                inverseAE(h, plot_el["default"], year)
            inverseAE(stackmu.theHistogram, plot_mu["default"], year)
            inverseAE(stackel.theHistogram, plot_el["default"], year)
            inverseAE(mu_scaleup.theHistogram, plot_mu["scale_up"], year)
            inverseAE(mu_scaledown.theHistogram, plot_mu["scale_down"], year)
            inverseAE(mu_ID.theHistogram, plot_mu["ID"], year)
            inverseAE(mu_reso.theHistogram, plot_mu["reso"], year)
            inverseAE(el_scaleup.theHistogram, plot_el["scale_up"], year)
            inverseAE(el_scaledown.theHistogram, plot_el["scale_down"], year)
            inverseAE(el_PUup.theHistogram, plot_el["PU_up"], year)
            inverseAE(el_PUdown.theHistogram, plot_el["PU_down"], year)
            inverseAE(datamu, plot_mu["default"], year)
            inverseAE(datael, plot_el["default"], year)

    if args.useall:
        i = 0
        Errs_mu = []
        Errs_el = []
        for year in range(2016, 2019):
            lis_mu = [[
                mu_scaleup[i].theHistogram, mu_scaledown[i].theHistogram
            ], mu_ID[i].theHistogram, mu_reso[i].theHistogram]
            lis_el = [[
                el_scaleup[i].theHistogram, el_scaledown[i].theHistogram
            ], [el_PUup[i].theHistogram, el_PUdown[i].theHistogram]]
            Errs_mu.append(getErrors(stackmu[i].theHistogram, lis_mu))
            Errs_el.append(getErrors(stackel[i].theHistogram, lis_el))
            i += 1
        errmu = Errs_mu[0] + Errs_mu[1] + Errs_mu[2]
        errel = Errs_el[0] + Errs_el[1] + Errs_el[2]
        stackmu = Addstack(stackmu)
        stackel = Addstack(stackel)
        mu_scaleup = Addstack(mu_scaleup)
        mu_scaledown = Addstack(mu_scaledown)
        mu_ID = Addstack(mu_ID)
        mu_reso = Addstack(mu_reso)
        el_scaleup = Addstack(el_scaleup)
        el_scaledown = Addstack(el_scaledown)
        el_PUup = Addstack(el_PUup)
        el_PUdown = Addstack(el_PUdown)
        datamu = Addhist(datamu)
        datael = Addhist(datael)
    else:
        lis_mu = [[mu_scaleup.theHistogram, mu_scaledown.theHistogram],
                  mu_ID.theHistogram, mu_reso.theHistogram]
        lis_el = [[el_scaleup.theHistogram, el_scaledown.theHistogram],
                  [el_PUup.theHistogram, el_PUdown.theHistogram]]
        errmu = getErrors(stackmu.theHistogram, lis_mu)

        errel = getErrors(stackel.theHistogram, lis_el)
    if args.data:
        yMax = datamu.GetBinContent(datamu.GetMaximumBin())
        if "Mass" in plot_mu["default"].fileName:
            yMin = 0.00001
        else:
            yMin = 0.01
        xMax = datamu.GetXaxis().GetXmax()
        xMin = datael.GetXaxis().GetXmin()
    else:
        yMax = stackmu.theHistogram.GetBinContent(datahist.GetMaximumBin())
        yMin = 0.01
        xMax = stackmu.theHistogram.GetXaxis().GetXmax()
        xMin = stackmu.theHistogram.GetXaxis().GetXmin()
    if plot_mu["default"].yMax == None:
        if logScale:
            yMax = yMax * 10000
        else:
            yMax = yMax * 1.5
    else:
        yMax = plot_mu["default"].yMax

    if "Mass" in plot_mu["default"].fileName:
        yMax = 20000000

    if not plot_mu["default"].yMin == None:
        yMin = plot_mu.yMin
    if not plot_mu["default"].xMin == None:
        xMin = plot_mu["default"].xMin
    if not plot_mu["default"].xMax == None:
        xMax = plot_mu["default"].xMax

    xMin = 200
    xMax = 2000
    yMin = 1e-3
    yMax = 1e4

    if args.ae:
        yMin = 0.00001 / 40
        yMax = 200000000.0 / 40
        xMin = 200
        xMax = 2000
        yMin *= 10000
        yMax /= 10
    if args.ae:
        # ~ vh = plotPad.DrawFrame(xMin,yMin,xMax,yMax,"; %s ; %s" %("m(l^{+}l^{-}) [GeV]","3 years data"))
        vh = plotPad.DrawFrame(
            xMin, yMin, xMax, yMax, "; %s ; %s" %
            ("m(l^{+}l^{-}) [GeV]", "Events / GeV * 1/(acc. x eff)"))
    else:
        # ~ vh = plotPad.DrawFrame(xMin,yMin,xMax,yMax,"; %s ; %s" %("m(l^{+}l^{-}) [GeV]","Lumi #times d#sigma(pp#rightarrow ll)"))
        vh = plotPad.DrawFrame(
            xMin, yMin, xMax, yMax,
            "; %s ; %s" % ("m(l^{+}l^{-}) [GeV]", "Events / GeV"))
    vh.GetXaxis().SetMoreLogLabels()

    drawStack_mu = stackmu
    drawStack_el = stackel

    # Draw background from stack
    drawStack_mu.theHistogram.SetLineColor(ROOT.kBlue - 3)
    drawStack_el.theHistogram.SetLineColor(ROOT.kRed - 3)
    drawStack_mu.theHistogram.SetFillStyle(0)
    drawStack_el.theHistogram.SetFillStyle(0)
    drawStack_mu.theHistogram.Draw("same hist")
    drawStack_el.theHistogram.Draw("same hist")

    # Draw data
    datamu.SetMinimum(0.0001)
    if args.data:
        datamu.SetMarkerColor(ROOT.kViolet)
        datael.SetMarkerColor(ROOT.kOrange)
        datamu.Draw("samep")
        datael.Draw("samep")

    # Draw legend
    if "Eta" in plot_mu["default"].fileName or "CosTheta" in plot_mu[
            "default"].fileName:
        legendEta.Draw()
    else:
        legend.Draw()

    plotPad.SetLogx(plot_mu["default"].logX)
    if args.useall:
        latex.DrawLatex(0.95, 0.96, "three years data")
    else:
        latex.DrawLatex(
            0.95, 0.96,
            "%.1f fb^{-1} (13 TeV, #mu#mu), %.1f fb^{-1} (13 TeV, ee)" %
            (lumi_mu * 0.001, lumi_el * 0.001))
    yLabelPos = 0.85
    cmsExtra = "Private Work"
    if not args.data:
        cmsExtra = "#splitline{Private Work}{Simulation}"
        yLabelPos = 0.82
    latexCMS.DrawLatex(0.19, 0.89, "CMS")
    latexCMSExtra.DrawLatex(0.19, yLabelPos, "%s" % (cmsExtra))

    if args.ratio:
        ratioPad.cd()
        ratioPad.SetLogx(plot_mu["default"].logX)

        hhmu = drawStack_mu.theHistogram
        hhel = drawStack_el.theHistogram
        h_mu_scaleup = mu_scaleup.theHistogram
        h_mu_scaledown = mu_scaledown.theHistogram
        h_mu_ID = mu_ID.theHistogram
        h_mu_reso = mu_reso.theHistogram
        h_el_scaleup = el_scaleup.theHistogram
        h_el_scaledown = el_scaledown.theHistogram
        h_el_PUup = el_PUup.theHistogram
        h_el_PUdown = el_PUdown.theHistogram
        ratioGraphs = ROOT.TGraphAsymmErrors(hhmu.GetSize() - 2)
        chann = True if "BB" in plot_mu["default"].fileName else False
        #print(errel)
        #print(errmu)
        for i in range(1, hhmu.GetSize() - 1):
            xval = hhmu.GetBinCenter(i)
            xerr = hhmu.GetBinWidth(i) / 2
            if hhel.GetBinContent(i) == 0: continue
            if hhmu.GetBinContent(i) == 0: continue
            #print(math.sqrt(errmu[i-1])/hhmu.GetBinContent(i))
            yval = hhmu.GetBinContent(i) * 1.0 / hhel.GetBinContent(i)
            yerr = yval * math.sqrt(
                (errel[i - 1]**0.5 / hhel.GetBinContent(i))**2 +
                (errmu[i - 1]**0.5 / hhmu.GetBinContent(i))**2 +
                (hhmu.GetBinError(i) / hhmu.GetBinContent(i))**2 +
                (hhel.GetBinError(i) / hhel.GetBinContent(i))**2)
            ratioGraphs.SetPoint(i, xval, yval)
            ratioGraphs.SetPointError(i, xerr, xerr, yerr, yerr)
            print("M = %f, r+-e = %f +- %f" % (xval, yval, yerr / yval))
        ratioData = ROOT.TGraphAsymmErrors(datamu.GetSize() - 2)
        for i in range(1, datamu.GetSize() - 1):
            xval = datamu.GetBinCenter(i)
            xerr = datamu.GetBinWidth(i) / 2
            if datael.GetBinContent(i) == 0: continue
            if datamu.GetBinContent(i) == 0: continue
            #print(datael.GetBinContent(i))
            #print(datael.GetBinError(i))
            yval = datamu.GetBinContent(i) * 1.0 / datael.GetBinContent(i)
            yerr = yval * math.sqrt(
                (datamu.GetBinError(i) / datamu.GetBinContent(i))**2 +
                (datael.GetBinError(i) / datael.GetBinContent(i))**2)
            ratioData.SetPoint(i, xval, yval)
            ratioData.SetPointError(i, xerr, xerr, yerr, yerr)
            print("M = %f, r+-e = %f +- %f" % (xval, yval, yerr / yval))
        nBinsX = 20
        nBinsY = 10
        if args.ae:
            hAxis = ROOT.TH2F("hAxis", "", nBinsX, xMin, xMax, nBinsY, 0.5,
                              2.5)
        else:
            hAxis = ROOT.TH2F("hAxis", "", nBinsX, xMin, xMax, nBinsY, 0.5, 5)
        hAxis.Draw("AXIS")

        hAxis.GetYaxis().SetNdivisions(408)
        hAxis.SetTitleOffset(0.4, "Y")
        hAxis.SetTitleSize(0.09, "Y")
        hAxis.SetTitleSize(0.06, "X")
        hAxis.SetYTitle("R_{#mu#mu/ee}")
        hAxis.SetXTitle("m(l^{+}l^{-}) [GeV]")
        hAxis.GetXaxis().SetLabelSize(0.048)
        hAxis.GetYaxis().SetLabelSize(0.048)
        #hAxis.GetXaxis().SetTicks("+")
        #hAxis.SetTitleSize(0.15, "Y")
        hAxis.GetXaxis().SetMoreLogLabels()
        oneLine = ROOT.TLine(xMin, 1.0, xMax, 1.0)
        oneLine.SetLineStyle(2)
        oneLine.Draw()

        ratioGraphs.SetFillColor(ROOT.kBlue - 3)
        ratioGraphs.SetMarkerColor(ROOT.kBlue - 3)
        ratioGraphs.GetXaxis().SetLabelSize(0.0)
        ratioGraphs.SetFillStyle(3002)
        ratioGraphs.Draw("SAME p")
        ratioData.SetMarkerColor(ROOT.kViolet)
        ratioData.Draw("same p")

        rlegend = TLegend(0.2, 0.65, 0.5, 0.925)
        rlegend.SetFillStyle(0)
        rlegend.SetBorderSize(1)
        rlegend.SetTextFont(42)
        rlegend.AddEntry(ratioGraphs, "e/mu in MC inclusive", "pe")
        rlegend.AddEntry(ratioData, "e/mu in data", "pe")
        rlegend.Draw("same")

        ratioPad.Update()

    ROOT.gPad.RedrawAxis()
    plotPad.RedrawAxis()
    if args.ratio:
        ratioPad.RedrawAxis()
    if not os.path.exists("lepFlavor"):
        os.makedirs("lepFlavor")

    if args.use2016: year = "2016"
    elif args.useall: year = "2016_to_2018"
    elif args.use2018: year = "2018"
    else: year = "2017"

    if args.ae: year += "_inverseAE"
    if args.znorm: year += "_znorm"

    hCanvas.Print("lepFlavor/%s_%s_datamc.pdf" %
                  (plot_mu["default"].fileName, year))
Beispiel #12
0
def plotDataMC(mainConfig, dilepton):
    import gc
    gc.enable()

    from ROOT import TCanvas, TPad, TH1F, TH1I, THStack, TLegend, TMath, gROOT, TFile, TH2F
    import ratios
    from defs import Backgrounds
    from defs import Backgrounds2011
    from defs import Signals
    from defs import defineMyColors
    from defs import myColors
    from defs import Region
    from defs import Regions
    from defs import Plot
    from corrections import triggerEffs, rSFOFTrig
    from setTDRStyle import setTDRStyle
    gROOT.SetBatch(True)
    from helpers import *
    import math

    ### file to normalize signal MC
    signalDenominatorFile = TFile(
        "../SignalScan/T6bbllsleptonDenominatorHisto4.root")
    signalDenominatorHisto = TH2F(signalDenominatorFile.Get("massScan"))

    if mainConfig.forPAS:
        hCanvas = TCanvas("hCanvas", "Distribution", 600, 800)
    else:
        hCanvas = TCanvas("hCanvas", "Distribution", 800, 800)
    if mainConfig.plotRatio:
        plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0.3, 1, 1)
        ratioPad = ROOT.TPad("ratioPad", "ratioPad", 0, 0., 1, 0.3)
        setTDRStyle()
        plotPad.UseCurrentStyle()
        ratioPad.UseCurrentStyle()
        plotPad.Draw()
        ratioPad.Draw()
        plotPad.cd()
    else:
        plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0, 1, 1)
        setTDRStyle()
        plotPad.UseCurrentStyle()
        plotPad.Draw()
        plotPad.cd()

    colors = createMyColors()

    eventCounts = totalNumberOfGeneratedEvents(mainConfig.dataSetPath)
    processes = []
    for background in mainConfig.backgrounds:
        processes.append(Process(getattr(Backgrounds, background),
                                 eventCounts))

    ### get the signal if any is to be plotted
    signalEventCounts = {}
    signals = []
    signalNameLabel = ""
    for signal in mainConfig.signals:
        m_b = int(signal.split("_")[2])
        m_n_2 = int(signal.split("_")[4])
        signalEventCounts[signal] = signalDenominatorHisto.GetBinContent(
            signalDenominatorHisto.GetXaxis().FindBin(m_b),
            signalDenominatorHisto.GetYaxis().FindBin(m_n_2))
        signals.append(Process(getattr(Signals, signal), signalEventCounts))
        if signalNameLabel == "":
            signalNameLabel = "Signal"
        signalNameLabel += "_m_b_%s_m_n_%s" % (signal.split("_")[2],
                                               signal.split("_")[4])

    #~ legend = TLegend(0.45, 0.6, 0.925, 0.925)
    legend = TLegend(0.55, 0.6, 0.925, 0.925)
    legend.SetFillStyle(0)
    legend.SetBorderSize(0)
    legend.SetTextFont(42)
    #~ legend.SetNColumns(2)
    legendEta = TLegend(0.15, 0.75, 0.7, 0.9)
    legendEta.SetFillStyle(0)
    legendEta.SetBorderSize(0)
    legendEta.SetTextFont(42)

    latex = ROOT.TLatex()
    latex.SetTextFont(42)
    latex.SetTextAlign(31)
    latex.SetTextSize(0.04)
    latex.SetNDC(True)
    latexCMS = ROOT.TLatex()
    latexCMS.SetTextFont(61)
    latexCMS.SetTextSize(0.06)
    latexCMS.SetNDC(True)
    latexCMSExtra = ROOT.TLatex()
    latexCMSExtra.SetTextFont(52)
    latexCMSExtra.SetTextSize(0.045)
    latexCMSExtra.SetNDC(True)
    legendHists = []

    legendHistData = ROOT.TH1F()
    if mainConfig.plotData:
        legend.AddEntry(legendHistData, "Data", "pe")
        legendEta.AddEntry(legendHistData, "Data", "pe")

    ### loop over the background processes, add them in iverse order to the legend
    if mainConfig.plotMC:
        for process in reversed(processes):
            temphist = ROOT.TH1F()
            temphist.SetFillColor(process.theColor)
            ### Do not add a seperate legend entry for DY to tautau if new legend scheme is used
            if not process.label == "DY+jets non resonant":
                legendHists.append(temphist.Clone)
                legend.AddEntry(temphist, process.label, "f")
                legendEta.AddEntry(temphist, process.label, "f")
    if mainConfig.plotRatio:
        temphist = ROOT.TH1F()
        temphist.SetFillColor(myColors["MyGreen"])
        legendHists.append(temphist.Clone)
        #~ legend.AddEntry(temphist,"Syst. uncert.","f")
        temphist2 = ROOT.TH1F()
        temphist2.SetFillColor(myColors["DarkRed"], )
        temphist2.SetFillStyle(3002)
        legendHists.append(temphist2.Clone)

    if mainConfig.plotSignal:
        for Signal in signals:
            temphist = ROOT.TH1F()
            temphist.SetFillColor(Signal.theColor)
            temphist.SetLineColor(Signal.theLineColor)
            legendHists.append(temphist.Clone)
            legend.AddEntry(temphist, Signal.label, "l")
            legendEta.AddEntry(temphist, Signal.label, "l")

    nEvents = -1

    ROOT.gStyle.SetOptStat(0)

    intlumi = ROOT.TLatex()
    intlumi.SetTextAlign(12)
    intlumi.SetTextSize(0.03)
    intlumi.SetNDC(True)
    intlumi2 = ROOT.TLatex()
    intlumi2.SetTextAlign(12)
    intlumi2.SetTextSize(0.07)
    intlumi2.SetNDC(True)
    scalelabel = ROOT.TLatex()
    scalelabel.SetTextAlign(12)
    scalelabel.SetTextSize(0.03)
    scalelabel.SetNDC(True)
    metDiffLabel = ROOT.TLatex()
    metDiffLabel.SetTextAlign(12)
    metDiffLabel.SetTextSize(0.03)
    metDiffLabel.SetNDC(True)
    chi2Label = ROOT.TLatex()
    chi2Label.SetTextAlign(12)
    chi2Label.SetTextSize(0.03)
    chi2Label.SetNDC(True)
    hCanvas.SetLogy()

    treeEE = readTrees(mainConfig.dataSetPath, "EE")
    treeMuMu = readTrees(mainConfig.dataSetPath, "MuMu")
    treeEMu = readTrees(mainConfig.dataSetPath, "EMu")

    mainConfig.plot.addDilepton(dilepton)

    plotPad.cd()
    plotPad.SetLogy(0)
    logScale = mainConfig.plot.log
    #~ logScale = True
    if mainConfig.plot.variable == "met" or mainConfig.plot.variable == "type1Met" or mainConfig.plot.variable == "tcMet" or mainConfig.plot.variable == "caloMet" or mainConfig.plot.variable == "mht":
        logScale = True

    if logScale == True:
        plotPad.SetLogy()

    scaleTree1 = 1.0
    scaleTree2 = 1.0
    if mainConfig.plot.tree1 == "EE":
        tree1 = treeEE
        if mainConfig.useDataTrigEff:
            scaleTree1 = getattr(triggerEffs, mainConfig.etaRegion).effEE.val
            #~ scaleTree1 = getattr(triggerEffs,mainConfig.etaRegion).effEE.val**2
            print "ee trigger Eff:"
            print scaleTree1
        #~ elif mainConfig.useTriggerEmulation:
        #~ scaleTree1 = getattr(triggerEffs,mainConfig.etaRegion).effEE.val/getattr(triggerEffs,mainConfig.etaRegion).effEE.valMC
    elif mainConfig.plot.tree1 == "MuMu":
        tree1 = treeMuMu
        if mainConfig.useDataTrigEff:
            scaleTree1 = getattr(triggerEffs, mainConfig.etaRegion).effMM.val
            #~ scaleTree1 = getattr(triggerEffs,mainConfig.etaRegion).effMM.val**2
            print "mumu trigger Eff:"
            print scaleTree1
        #~ elif mainConfig.useTriggerEmulation:
        #~ scaleTree1 = getattr(triggerEffs,mainConfig.etaRegion).effMM.val/getattr(triggerEffs,mainConfig.etaRegion).effMM.valMC
    elif mainConfig.plot.tree1 == "EMu":
        tree1 = treeEMu
        if mainConfig.useDataTrigEff:
            scaleTree1 = getattr(triggerEffs, mainConfig.etaRegion).effEM.val
            print "emu trigger Eff:"
            print scaleTree1
        #~ elif mainConfig.useTriggerEmulation:
        #~ scaleTree1 = getattr(triggerEffs,mainConfig.etaRegion).effEM.val/getattr(triggerEffs,mainConfig.etaRegion).effEM.valMC
    else:
        print "Unknown Dilepton combination! %s not created!" % (
            mainConfig.plot.filename, )
        return

    if mainConfig.plot.tree2 != "None":
        if mainConfig.plot.tree2 == "EE":
            tree2 = treeEE
            if mainConfig.useDataTrigEff:
                #~ scaleTree2 = mainConfig.selection.trigEffs.effEE.val
                scaleTree2 = mainConfig.selection.trigEffs.effEE.val**2
                print "ee trigger Eff:"
                print scaleTree2
            #~ elif mainConfig.useTriggerEmulation:
            #~ scaleTree2 = getattr(triggerEffs,mainConfig.etaRegion).effEE.val/getattr(triggerEffs,mainConfig.etaRegion).effEE.valMC
        elif mainConfig.plot.tree2 == "MuMu":
            tree2 = treeMuMu
            if mainConfig.useDataTrigEff:
                #~ scaleTree2 = mainConfig.selection.trigEffs.effMM.val
                scaleTree2 = mainConfig.selection.trigEffs.effMM.val**2
                print "mumu trigger Eff:"
                print scaleTree2
            #~ elif mainConfig.useTriggerEmulation:
            #~ scaleTree2 = getattr(triggerEffs,mainConfig.etaRegion).effMM.val/getattr(triggerEffs,mainConfig.etaRegion).effMM.valMC

        elif mainConfig.plot.tree2 == "EMu":
            tree2 = treeEMu
            if mainConfig.useDataTrigEff:
                scaleTree2 = mainConfig.selection.trigEffs.effEM.val
                print "emu trigger Eff:"
                print scaleTree2
            #~ elif mainConfig.useTriggerEmulation:
            #~ scaleTree2 = getattr(triggerEffs,mainConfig.etaRegion).effEM.val/getattr(triggerEffs,mainConfig.etaRegion).effEM.valMC
        else:
            print "Unknown Dilepton combination! %s not created!" % (
                mainConfig.plot.filename, )
            return
    else:
        tree2 = "None"

    if mainConfig.normalizeToData:
        pickleName = mainConfig.plot.filename % (
            "_normalizedToData_" + mainConfig.runRange.label + "_" + dilepton)
    elif mainConfig.useTriggerEmulation:
        pickleName = mainConfig.plot.filename % (
            "_TriggerEmulation_" + mainConfig.runRange.label + "_" + dilepton)
    elif mainConfig.DontScaleTrig:
        pickleName = mainConfig.plot.filename % (
            "_NoTriggerScaling_" + mainConfig.runRange.label + "_" + dilepton)
    elif mainConfig.useDataTrigEff:
        pickleName = mainConfig.plot.filename % (
            "_dataTriggerEffs_" + mainConfig.runRange.label + "_" + dilepton)
    else:
        pickleName = mainConfig.plot.filename % (
            "_" + mainConfig.runRange.label + "_" + dilepton)

    counts = {}
    import pickle
    print mainConfig.plot.cuts
    if mainConfig.plotData:
        datahist = getDataHist(
            mainConfig.plot,
            tree1,
            tree2,
            normalizeToBinWidth=mainConfig.normalizeToBinWidth)
        counts["Data"] = {
            "val": datahist.Integral(0,
                                     datahist.GetNbinsX() + 1),
            "err": math.sqrt(datahist.Integral(0,
                                               datahist.GetNbinsX() + 1))
        }
        print datahist.GetEntries()

    if mainConfig.plotMC:
        #~ stack = TheStack(processes,mainConfig.runRange.lumi,mainConfig.plot,tree1,tree2,1.0,scaleTree1,scaleTree2,saveIntegrals=True,counts=counts,doTopReweighting=mainConfig.doTopReweighting,theoUncert=mainConfig.theoUncert,doPUWeights=mainConfig.doPUWeights,normalizeToBinWidth=mainConfig.normalizeToBinWidth)
        stack = TheStack(processes,
                         mainConfig.runRange.lumi,
                         mainConfig.plot,
                         tree1,
                         tree2,
                         1.0,
                         scaleTree1,
                         scaleTree2,
                         saveIntegrals=True,
                         counts=counts,
                         doTopReweighting=mainConfig.doTopReweighting,
                         doPUWeights=mainConfig.doPUWeights,
                         normalizeToBinWidth=mainConfig.normalizeToBinWidth,
                         useTriggerEmulation=mainConfig.useTriggerEmulation)

        ### get the number of MC events and the uncertainty
        errIntMC = ROOT.Double()
        intMC = stack.theHistogram.IntegralAndError(
            0,
            stack.theHistogram.GetNbinsX() + 1, errIntMC)

        val = float(intMC)
        err = float(errIntMC)

        counts["Total Background"] = {"val": val, "err": err}

        ### scale the stack if MC is to be normalzed to data
        if mainConfig.normalizeToData:
            scalefac = datahist.Integral(
                datahist.FindBin(mainConfig.plot.firstBin),
                datahist.FindBin(
                    mainConfig.plot.lastBin)) / stack.theHistogram.Integral(
                        stack.theHistogram.FindBin(mainConfig.plot.firstBin),
                        stack.theHistogram.FindBin(mainConfig.plot.lastBin))

            drawStack = TheStack(
                processes,
                mainConfig.runRange.lumi,
                mainConfig.plot,
                tree1,
                tree2,
                1.0,
                scalefac * scaleTree1,
                scalefac * scaleTree2,
                doPUWeights=mainConfig.doPUWeights,
                normalizeToBinWidth=mainConfig.normalizeToBinWidth,
                useTriggerEmulation=mainConfig.useTriggerEmulation)
            stackJESUp = TheStack(
                processes,
                mainConfig.runRange.lumi,
                mainConfig.plot,
                tree1,
                tree2,
                0.955,
                scalefac * scaleTree1,
                scalefac * scaleTree2,
                doPUWeights=mainConfig.doPUWeights,
                normalizeToBinWidth=mainConfig.normalizeToBinWidth,
                useTriggerEmulation=mainConfig.useTriggerEmulation)
            stackJESDown = TheStack(
                processes,
                mainConfig.runRange.lumi,
                mainConfig.plot,
                tree1,
                tree2,
                1.045,
                scalefac * scaleTree1,
                scalefac * scaleTree2,
                doPUWeights=mainConfig.doPUWeights,
                normalizeToBinWidth=mainConfig.normalizeToBinWidth,
                useTriggerEmulation=mainConfig.useTriggerEmulation)

        else:
            drawStack = stack

            if mainConfig.plotSyst:

                mainConfig.plot.cuts = mainConfig.plot.cuts.replace(
                    "met ", "metJESUp ")
                mainConfig.plot.cuts = mainConfig.plot.cuts.replace(
                    " ht", " htJESUp")
                mainConfig.plot.cuts = mainConfig.plot.cuts.replace(
                    " nJets ", " nShiftedJetsJESUp ")
                mainConfig.plot.cuts = mainConfig.plot.cuts.replace(
                    "(nJets ", "(nShiftedJetsJESUp ")
                stackJESUp = TheStack(
                    processes,
                    mainConfig.runRange.lumi,
                    mainConfig.plot,
                    tree1,
                    tree2,
                    1.0,
                    scaleTree1,
                    scaleTree2,
                    JESUp=True,
                    saveIntegrals=True,
                    counts=counts,
                    doPUWeights=mainConfig.doPUWeights,
                    normalizeToBinWidth=mainConfig.normalizeToBinWidth,
                    useTriggerEmulation=mainConfig.useTriggerEmulation)
                mainConfig.plot.cuts = mainConfig.plot.cuts.replace(
                    "metJESUp", "metJESDown")
                mainConfig.plot.cuts = mainConfig.plot.cuts.replace(
                    "htJESUp", "htJESDown")
                mainConfig.plot.cuts = mainConfig.plot.cuts.replace(
                    "nShiftedJetsJESUp", "nShiftedJetsJESDown")
                stackJESDown = TheStack(
                    processes,
                    mainConfig.runRange.lumi,
                    mainConfig.plot,
                    tree1,
                    tree2,
                    1.0,
                    scaleTree1,
                    scaleTree2,
                    JESDown=True,
                    saveIntegrals=True,
                    counts=counts,
                    doPUWeights=mainConfig.doPUWeights,
                    normalizeToBinWidth=mainConfig.normalizeToBinWidth,
                    useTriggerEmulation=mainConfig.useTriggerEmulation)
                mainConfig.plot.cuts = mainConfig.plot.cuts.replace(
                    "metJESDown", "met")
                mainConfig.plot.cuts = mainConfig.plot.cuts.replace(
                    "htJESDown", "ht")
                mainConfig.plot.cuts = mainConfig.plot.cuts.replace(
                    "nShiftedJetsJESDown", "nJets")
                mainConfig.plot.cuts = mainConfig.plot.cuts.replace(
                    "*(", "Up*(")
                stackPileUpUp = TheStack(
                    processes,
                    mainConfig.runRange.lumi,
                    mainConfig.plot,
                    tree1,
                    tree2,
                    1.0,
                    scaleTree1,
                    scaleTree2,
                    saveIntegrals=True,
                    PileUpUp=True,
                    counts=counts,
                    doPUWeights=mainConfig.doPUWeights,
                    normalizeToBinWidth=mainConfig.normalizeToBinWidth,
                    useTriggerEmulation=mainConfig.useTriggerEmulation)
                mainConfig.plot.cuts = mainConfig.plot.cuts.replace(
                    "Up*(", "Down*(")
                stackPileUpDown = TheStack(
                    processes,
                    mainConfig.runRange.lumi,
                    mainConfig.plot,
                    tree1,
                    tree2,
                    1.0,
                    scaleTree1,
                    scaleTree2,
                    saveIntegrals=True,
                    PileUpDown=True,
                    counts=counts,
                    doPUWeights=mainConfig.doPUWeights,
                    normalizeToBinWidth=mainConfig.normalizeToBinWidth,
                    useTriggerEmulation=mainConfig.useTriggerEmulation)
                mainConfig.plot.cuts = mainConfig.plot.cuts.replace(
                    "Down*(", "*(")

                errIntMC = ROOT.Double()
                intMCPileUpUp = stackPileUpUp.theHistogram.IntegralAndError(
                    0,
                    stack.theHistogram.GetNbinsX() + 1, errIntMC)
                errIntMC = ROOT.Double()
                intMCPileUpDown = stackPileUpDown.theHistogram.IntegralAndError(
                    0,
                    stack.theHistogram.GetNbinsX() + 1, errIntMC)

                valPileUpUp = float(intMCPileUpUp)
                valPileUpDown = float(intMCPileUpDown)
                pileUpUp = abs(counts["Total Background"]["val"] - valPileUpUp)
                pileUpDown = abs(counts["Total Background"]["val"] -
                                 valPileUpDown)
                counts["Total Background"]["pileUpDown"] = pileUpDown
                counts["Total Background"]["pileUpUp"] = pileUpUp

                if mainConfig.doTopReweighting:
                    stackReweightDown = TheStack(
                        processes,
                        mainConfig.runRange.lumi,
                        mainConfig.plot,
                        tree1,
                        tree2,
                        1.0,
                        scaleTree1,
                        scaleTree2,
                        TopWeightDown=True,
                        saveIntegrals=True,
                        counts=counts,
                        doPUWeights=mainConfig.doPUWeights,
                        normalizeToBinWidth=mainConfig.normalizeToBinWidth,
                        useTriggerEmulation=mainConfig.useTriggerEmulation)
                    stackReweightUp = TheStack(
                        processes,
                        mainConfig.runRange.lumi,
                        mainConfig.plot,
                        tree1,
                        tree2,
                        1.0,
                        scaleTree1,
                        scaleTree2,
                        TopWeightUp=True,
                        saveIntegrals=True,
                        counts=counts,
                        doPUWeights=mainConfig.doPUWeights,
                        normalizeToBinWidth=mainConfig.normalizeToBinWidth,
                        useTriggerEmulation=mainConfig.useTriggerEmulation)

                    errIntMC = ROOT.Double()
                    intMCTopWeightUp = stackReweightUp.theHistogram.IntegralAndError(
                        0,
                        stack.theHistogram.GetNbinsX() + 1, errIntMC)
                    errIntMC = ROOT.Double()
                    intMCTopWeightDown = stackReweightDown.theHistogram.IntegralAndError(
                        0,
                        stack.theHistogram.GetNbinsX() + 1, errIntMC)

                    valTopWeightUp = float(intMCTopWeightUp)
                    valTopWeightDown = float(intMCTopWeightDown)
                    topWeightUp = abs(counts["Total Background"]["val"] -
                                      valTopWeightUp)
                    topWeightDown = abs(counts["Total Background"]["val"] -
                                        valTopWeightDown)
                    counts["Total Background"]["topWeightDown"] = topWeightDown
                    counts["Total Background"]["topWeightUp"] = topWeightUp

                errIntMC = ROOT.Double()
                intMCJESUp = stackJESUp.theHistogram.IntegralAndError(
                    0,
                    stack.theHistogram.GetNbinsX() + 1, errIntMC)
                errIntMC = ROOT.Double()
                intMCJESDown = stackJESDown.theHistogram.IntegralAndError(
                    0,
                    stack.theHistogram.GetNbinsX() + 1, errIntMC)

                valJESUp = float(intMCJESUp)
                valJESDown = float(intMCJESDown)
                jesUp = abs(counts["Total Background"]["val"] - valJESUp)
                jesDown = abs(counts["Total Background"]["val"] - valJESDown)
                counts["Total Background"]["jesDown"] = jesDown
                counts["Total Background"]["jesUp"] = jesUp

        xSec = abs(
            stack.theHistogramXsecUp.Integral(
                0,
                stack.theHistogram.GetNbinsX() + 1) -
            counts["Total Background"]["val"])
        counts["Total Background"]["xSec"] = xSec
        #~ theoUncert = abs(stack.theHistogramTheoUp.Integral(0,stack.theHistogram.GetNbinsX()+1)-counts["Total Background"]["val"])
        #~ counts["Total Background"]["theo"]=theoUncert

    outFilePkl = open("shelves/%s.pkl" % (pickleName), "w")
    pickle.dump(counts, outFilePkl)
    outFilePkl.close()

    if mainConfig.plotSignal:
        signalhists = []
        signalLabels = []
        ymaxSignal = 0
        for Signal in signals:
            signalhist = Signal.createCombinedHistogram(
                mainConfig.runRange.lumi, mainConfig.plot, tree1, tree2)
            signalhist.SetLineWidth(2)
            if mainConfig.stackSignal:
                signalhist.Add(drawStack.theHistogram)
            signalhist.SetMinimum(0.1)
            signalhists.append(signalhist)
            signalLabels.append(Signal.label)
            tmpYmaxSignal = signalhist.GetBinContent(
                signalhist.GetMaximumBin())
            if tmpYmaxSignal > ymaxSignal:
                ymaxSignal = tmpYmaxSignal

    ### set the maximum of the y-axis
    yMax = 0
    yMin = 0
    if mainConfig.plotData:
        yMax = datahist.GetBinContent(datahist.GetMaximumBin())
    if (mainConfig.plotMC and yMax < drawStack.theHistogram.GetBinContent(
            drawStack.theHistogram.GetMaximumBin())):
        yMax = drawStack.theHistogram.GetBinContent(
            drawStack.theHistogram.GetMaximumBin())
    if (mainConfig.plotSignal and yMax < ymaxSignal):
        yMax = ymaxSignal
    if mainConfig.plot.yMax == 0:
        if logScale:
            yMax = yMax * 200
            if datahist.GetBinContent(datahist.GetMinimumBin()) > 0:
                yMin = datahist.GetBinContent(datahist.GetMinimumBin()) / 5.
            else:
                yMin = 0.1
                #~ yMin = 0.5
                #~ yMin = 5
        else:
            yMax = yMax * 1.5

    else:
        yMax = plot.yMax

    #~ yMax = 1200
    #~ yMax = 130

    plotPad.DrawFrame(
        mainConfig.plot.firstBin, yMin, mainConfig.plot.lastBin, yMax,
        "; %s ; %s" % (mainConfig.plot.xaxis, mainConfig.plot.yaxis))

    ### draw the stack
    if mainConfig.plotMC:
        drawStack.theStack.Draw("samehist")
        lineHistogram = drawStack.theHistogram
        lineHistogram.Draw("same l")

    ### Draw signal
    if mainConfig.plotSignal:
        for signalhist in signalhists:
            signalhist.Draw("samehist")

    dileptonLabel = ""
    if dilepton == "SF":
        dileptonLabel = "ee + #mu#mu"
    if dilepton == "OF":
        dileptonLabel = "e#mu"
    if dilepton == "EE":
        dileptonLabel = "ee"
    if dilepton == "MuMu":
        dileptonLabel = "#mu#mu"

    if mainConfig.plotData:
        #~ datahist.SetMinimum(0.1)
        datahist.Draw("samep")

    if mainConfig.normalizeToData:
        scalelabel.DrawLatex(0.6, 0.4,
                             "Background scaled by %.2f" % (scalefac))

    if mainConfig.plot.variable == "eta1" or mainConfig.plot.variable == "eta2":
        legendEta.SetNColumns(2)
        legendEta.Draw()
        intlumi.DrawLatex(
            0.2, 0.7, "#splitline{" + mainConfig.plot.label + " " +
            dileptonLabel + "}{#splitline{" + mainConfig.plot.label2 + "}{" +
            mainConfig.plot.label3 + "}}")
    else:
        legend.Draw()
        intlumi.DrawLatex(
            0.4, 0.55,
            "#splitline{%s}{%s}" % (mainConfig.plot.label2, dileptonLabel))

    latex.DrawLatex(0.95, 0.96,
                    "%s fb^{-1} (13 TeV)" % (mainConfig.runRange.printval, ))
    yLabelPos = 0.85
    #~ yLabelPos = 0.88
    cmsExtra = ""
    if mainConfig.personalWork:
        cmsExtra = "Private Work"
        if not mainConfig.plotData:
            cmsExtra = "#splitline{Private Work}{Simulation}"
            yLabelPos = 0.82
            #~ yLabelPos = 0.85
    elif not mainConfig.plotData:
        cmsExtra = "Simulation"
    elif mainConfig.preliminary:
        cmsExtra = "Preliminary"
    elif mainConfig.forTWIKI:
        cmsExtra = "Unpublished"
    if mainConfig.forPAS:
        latexCMS.DrawLatex(0.15, 0.955, "CMS")
        latexCMSExtra.DrawLatex(0.26, 0.955, "%s" % (cmsExtra))

    else:
        latexCMS.DrawLatex(0.19, 0.89, "CMS")
        latexCMSExtra.DrawLatex(0.19, yLabelPos, "%s" % (cmsExtra))

    if mainConfig.plotRatio:
        ratioPad.cd()
        ratioGraphs = ratios.RatioGraph(datahist,
                                        drawStack.theHistogram,
                                        xMin=mainConfig.plot.firstBin,
                                        xMax=mainConfig.plot.lastBin,
                                        title="Data / MC",
                                        yMin=0.0,
                                        yMax=2,
                                        ndivisions=10,
                                        color=ROOT.kBlack,
                                        adaptiveBinning=0.25)
        if mainConfig.plotSyst:
            ratioGraphs.addErrorByHistograms("Pileup",
                                             stackPileUpUp.theHistogram,
                                             stackPileUpDown.theHistogram,
                                             color=myColors["MyGreen"])
            ratioGraphs.addErrorByHistograms("JES",
                                             stackJESUp.theHistogram,
                                             stackJESDown.theHistogram,
                                             color=myColors["MyGreen"])
            if mainConfig.doTopReweighting:
                ratioGraphs.addErrorByHistograms(
                    "TopWeight",
                    stackReweightUp.theHistogram,
                    stackReweightDown.theHistogram,
                    color=myColors["MyGreen"])
            ratioGraphs.addErrorBySize("Effs",
                                       getattr(rSFOFTrig,
                                               mainConfig.etaRegion).err,
                                       color=myColors["MyGreen"],
                                       add=True)
            ratioGraphs.addErrorByHistograms("Xsecs",
                                             drawStack.theHistogramXsecUp,
                                             drawStack.theHistogramXsecDown,
                                             color=myColors["MyGreen"],
                                             add=True)
            #~ ratioGraphs.addErrorByHistograms( "Theo", drawStack.theHistogramTheoUp, drawStack.theHistogramTheoDown,color=myColors["MyGreen"],add=True)
        ratioGraphs.draw(ROOT.gPad, True, False, True, chi2Pos=0.8)
        if mainConfig.plotSignal and mainConfig.stackSignal:
            signalRatios = []

            legendRatio = TLegend(0.175, 0.725, 0.65, 0.95)
            legendRatio.SetFillStyle(0)
            legendRatio.SetBorderSize(0)
            legendRatio.SetTextFont(42)
            backgroundHist = ROOT.TH1F()
            legendRatio.AddEntry(backgroundHist, "Data / background", "pe")
            temphist = ROOT.TH1F()
            temphist.SetFillColor(myColors["MyGreen"])
            if mainConfig.plotSyst:
                legendRatio.AddEntry(temphist, "Syst. uncert.", "f")
                legendRatio.SetNColumns(2)
            for index, signalhist in enumerate(signalhists):
                signalRatios.append(
                    ratios.RatioGraph(datahist,
                                      signalhist,
                                      xMin=mainConfig.plot.firstBin,
                                      xMax=mainConfig.plot.lastBin,
                                      title="Data / MC",
                                      yMin=0.0,
                                      yMax=2,
                                      ndivisions=10,
                                      color=signalhist.GetLineColor(),
                                      adaptiveBinning=0.25))
                signalRatios[index].draw(ROOT.gPad,
                                         False,
                                         False,
                                         True,
                                         chi2Pos=0.7 - index * 0.1)
                signalhist.SetMarkerColor(signalhist.GetLineColor())
                legendRatio.AddEntry(
                    signalhist,
                    "Data / Background + Signal (%s)" % signalLabels[index],
                    "p")
            legendRatio.Draw("same")

    ROOT.gPad.RedrawAxis()
    plotPad.RedrawAxis()
    if mainConfig.plotRatio:

        ratioPad.RedrawAxis()

    nameModifier = mainConfig.runRange.label + "_" + dilepton
    if mainConfig.doTopReweighting:
        nameModifier += "_TopReweighted"
    if mainConfig.plotData == False:
        nameModifier += "_MCOnly"
    if mainConfig.plotMC == False:
        nameModifier += "_NoBkgMC"

    if mainConfig.plotSignal:
        nameModifier += "_" + signalNameLabel
        if mainConfig.stackSignal:
            nameModifier += "_stackedSignal"

    if mainConfig.normalizeToData:
        hCanvas.Print(
            "fig/DataMC/" + mainConfig.plot.filename %
            ("_scaled_" + nameModifier), )
    elif mainConfig.useTriggerEmulation:
        hCanvas.Print(
            "fig/DataMC/" + mainConfig.plot.filename %
            ("_TriggerEmulation_" + nameModifier), )
    elif mainConfig.DontScaleTrig:
        hCanvas.Print(
            "fig/DataMC/" + mainConfig.plot.filename %
            ("_NoTriggerScaling_" + nameModifier), )
    else:
        hCanvas.Print(
            "fig/DataMC/" + mainConfig.plot.filename % ("_" + nameModifier), )
Beispiel #13
0
    def makeLeptonOriginFracPlots(self, histID=None):

        # Fake lepton origin fraction wrt. X

        # Trick to make sure also the input histograms w/ variable bin size are handled correctly
        binsY = []
        for biny in range(1, self.__hist.GetNbinsY() + 2):
            lowedge = self.__hist.GetYaxis().GetBinLowEdge(biny)
            binsY.append(lowedge)
        arr_binsY = array.array("d", binsY)

        print "hist N binsY: ", self.__hist.GetNbinsY()
        print "Y axis bin lims: ", binsY, " - N bins: ", len(binsY) - 1

        histfakes_BF = TH1D("histfakes_BF" + "_" + histID, "histfakes_BF",
                            self.__hist.GetNbinsY(),
                            arr_binsY)  # B-hadrons in jets (mesons/baryons)
        histfakes_CF = TH1D("histfakes_CF" + "_" + histID, "histfakes_CF",
                            self.__hist.GetNbinsY(),
                            arr_binsY)  # C-hadrons in jets (mesons/baryons)
        histfakes_HFRes = TH1D("histfakes_HFRes" + "_" + histID,
                               "histfakes_HFRes", self.__hist.GetNbinsY(),
                               arr_binsY)  # B,C resonances (J/psi, Upsilon...)
        histfakes_LF = TH1D("histfakes_LF" + "_" + histID, "histfakes_LF",
                            self.__hist.GetNbinsY(),
                            arr_binsY)  # Light hadrons in jets
        histfakes_PhConv = TH1D("histfakes_PhConv" + "_" + histID,
                                "histfakes_PhConv", self.__hist.GetNbinsY(),
                                arr_binsY)  # Photon conversions
        histfakes_Other = TH1D(
            "histfakes_Other" + "_" + histID, "histfakes_Other",
            self.__hist.GetNbinsY(), arr_binsY
        )  # Other fakes (mis-id jets, leptons from generic pi/K...)
        histfakes_Unknown = TH1D(
            "histfakes_Unknown" + "_" + histID, "histfakes_Unknown",
            self.__hist.GetNbinsY(),
            arr_binsY)  # Unknown fakes (failure of MCTruthClassifier)

        stacklegend = TLegend(0.23, 0.25, 0.43, 0.55)
        stacklegend.SetBorderSize(1)
        stacklegend.SetFillColor(kWhite)
        stacklegend.SetTextSize(0.03)
        stacklegend.SetTextFont(42)

        histfakes_list = [(histfakes_BF, kRed), (histfakes_CF, kRed - 9),
                          (histfakes_HFRes, kPink - 2),
                          (histfakes_LF, kOrange + 1),
                          (histfakes_PhConv, kYellow),
                          (histfakes_Other, kPink + 1),
                          (histfakes_Unknown, kAzure + 1)]

        for h in histfakes_list:
            h[0].SetLineWidth(2)
            h[0].SetLineStyle(1)
            h[0].SetLineColor(1)
            h[0].SetFillColor(h[1])

        # Loop over var Y bins of the 2D hist

        for biny in range(1, self.__hist.GetNbinsY() + 2):

            offset = 1  # (to account for underflow bin, which has idx=0)

            # Get the tot. fakes for *this* Y

            fakes_TOT_biny = self.__hist.Integral(0,
                                                  self.__hist.GetNbinsX() + 1,
                                                  biny, biny)

            # Get the HF fakes for *this* Y

            fakes_BF_biny = self.__hist.Integral(
                26 + offset, 26 + offset, biny, biny) + self.__hist.Integral(
                    33 + offset, 33 + offset, biny, biny)
            fakes_CF_biny = self.__hist.Integral(
                25 + offset, 25 + offset, biny, biny) + self.__hist.Integral(
                    32 + offset, 32 + offset, biny, biny)
            fakes_HFRes_biny = self.__hist.Integral(27 + offset, 29 + offset,
                                                    biny, biny)

            # Get the LF fakes for *this* Y

            fakes_LF_biny = self.__hist.Integral(
                23 + offset, 24 + offset, biny, biny) + self.__hist.Integral(
                    30 + offset, 31 + offset, biny, biny)

            # Get the photon conversion fakes for *this* Y

            fakes_PhConv_biny = self.__hist.Integral(5 + offset, 5 + offset,
                                                     biny, biny)

            # Get the "Unknown" fakes for *this* Y

            fakes_Unknown_biny = self.__hist.Integral(0 + offset, 0 + offset,
                                                      biny, biny)

            # Get the other fakes for *this* Y

            fakes_Other_biny = fakes_TOT_biny - (
                fakes_BF_biny + fakes_CF_biny + fakes_HFRes_biny +
                fakes_LF_biny + fakes_PhConv_biny + fakes_Unknown_biny)

            # Set the bin content for the fake lepton origin fraction hists for *this* Y bin

            if fakes_TOT_biny:
                fakes_BF_frac_biny = fakes_BF_biny / fakes_TOT_biny
                fakes_CF_frac_biny = fakes_CF_biny / fakes_TOT_biny
                fakes_HFRes_frac_biny = fakes_HFRes_biny / fakes_TOT_biny
                fakes_LF_frac_biny = fakes_LF_biny / fakes_TOT_biny
                fakes_PhConv_frac_biny = fakes_PhConv_biny / fakes_TOT_biny
                fakes_Unknown_frac_biny = fakes_Unknown_biny / fakes_TOT_biny
                fakes_Other_frac_biny = fakes_Other_biny / fakes_TOT_biny
            else:
                fakes_BF_frac_biny = fakes_CF_frac_biny = fakes_HFRes_frac_biny = fakes_LF_frac_biny = fakes_PhConv_frac_biny = fakes_Unknown_frac_biny = fakes_Other_frac_biny = 0

            if False:
                print("varY - bin[{0}]".format(biny))
                print("\ttot fakes = {0}".format(fakes_TOT_biny))
                print("\t-) BF fakes = {0} ({1:.2f})".format(
                    fakes_BF_biny, fakes_BF_frac_biny))
                print("\t-) CF fakes = {0} ({1:.2f})".format(
                    fakes_CF_biny, fakes_CF_frac_biny))
                print("\t-) HFRes fakes = {0} ({1:.2f})".format(
                    fakes_HFRes_biny, fakes_HFRes_frac_biny))
                print("\t-) LF fakes = {0} ({1:.2f})".format(
                    fakes_LF_biny, fakes_LF_frac_biny))
                print("\t-) PhConv fakes = {0} ({1:.2f})".format(
                    fakes_PhConv_biny, fakes_PhConv_frac_biny))
                print("\t-) Unknown fakes = {0} ({1:.2f})".format(
                    fakes_Unknown_biny, fakes_Unknown_frac_biny))
                print("\t-) Other fakes = {0} ({1:.2f})".format(
                    fakes_Other_biny, fakes_Other_frac_biny))

            histfakes_BF.SetBinContent(biny, fakes_BF_frac_biny)
            histfakes_CF.SetBinContent(biny, fakes_CF_frac_biny)
            histfakes_HFRes.SetBinContent(biny, fakes_HFRes_frac_biny)
            histfakes_LF.SetBinContent(biny, fakes_LF_frac_biny)
            histfakes_PhConv.SetBinContent(biny, fakes_PhConv_frac_biny)
            histfakes_Unknown.SetBinContent(biny, fakes_Unknown_frac_biny)
            histfakes_Other.SetBinContent(biny, fakes_Other_frac_biny)

            self.conversion_frac_VS_Y.append(
                (biny, round(fakes_PhConv_frac_biny, 3)))

        # Add histograms w/ fake origin fractions into a stack plot

        stacklegend.AddEntry(histfakes_BF, "B-Had Fakes", "F")
        stacklegend.AddEntry(histfakes_CF, "C-Had Fakes", "F")
        stacklegend.AddEntry(histfakes_HFRes, "J/#psi,#Upsilon Fakes", "F")
        stacklegend.AddEntry(histfakes_LF, "L-Had Fakes", "F")
        stacklegend.AddEntry(histfakes_PhConv, "#gamma conversion", "F")
        stacklegend.AddEntry(histfakes_Other, "Other Fakes", "F")
        stacklegend.AddEntry(histfakes_Unknown, "Unknown", "F")

        stack = THStack("LepOriginFrac_VS_Y_STACK", "LepOriginFrac_VS_Y_STACK")
        stack.Add(histfakes_BF)
        stack.Add(histfakes_CF)
        stack.Add(histfakes_HFRes)
        stack.Add(histfakes_LF)
        stack.Add(histfakes_PhConv)
        stack.Add(histfakes_Other)
        stack.Add(histfakes_Unknown)

        return stack, stacklegend
def DrawOverlap(fileVec, histVec, titleVec,legendtext,pngname,logstatus=[0,0],xRange=[-99999,99999,1]):

    gStyle.SetOptTitle(0)
    gStyle.SetOptStat(0)
    gStyle.SetTitleOffset(1.1,"Y");
    #gStyle.SetTitleOffset(1.9,"X");
    gStyle.SetLineWidth(3)
    gStyle.SetFrameLineWidth(3); 

    i=0

    histList_=[]
    histList=[]
    histList1=[]
    maximum=[]
    
    ## Legend    
    leg = TLegend(0.1, 0.70, 0.89, 0.89)#,NULL,"brNDC");
    leg.SetBorderSize(0)
    leg.SetNColumns(3)
    leg.SetLineColor(1)
    leg.SetLineStyle(1)
    leg.SetLineWidth(1)
    leg.SetFillColor(0)
    leg.SetFillStyle(0)
    leg.SetTextFont(42)
    leg.SetTextSize(0.05)
     
    c = TCanvas("c1", "c1",0,0,500,500)
    c.SetBottomMargin(0.15)
    c.SetLogy(logstatus[1])
    c.SetLogx(logstatus[0])
    print ("you have provided "+str(len(fileVec))+" files and "+str(len(histVec))+" histograms to make a overlapping plot" )
    print "opening rootfiles"
    c.cd()
    
    ii=0    
    inputfile={}
    print str(fileVec[(len(fileVec)-1)])

    for ifile_ in range(len(fileVec)):
        print ("opening file  "+fileVec[ifile_])
        inputfile[ifile_] = TFile( fileVec[ifile_] )
        print "fetching histograms"
        for ihisto_ in range(len(histVec)):
            print ("printing histo "+str(histVec[ihisto_]))
            histo = inputfile[ifile_].Get(histVec[ihisto_])
            #status_ = type(histo) is TGraphAsymmErrors
            histList.append(histo)
            # for ratio plot as they should nt be normalize 
            histList1.append(histo)
            #print histList[ii].Integral()
            #histList[ii].Rebin(xRange[2])
            #histList[ii].Scale(1.0/histList[ii].Integral())
            maximum.append(histList[ii].GetMaximum())
            maximum.sort()
            ii=ii+1

    print histList
    for ih in range(len(histList)):
        tt = type(histList[ih])
        if logstatus[1] is 1 :
            histList[ih].SetMaximum(100) #1.4 for log
            histList[ih].SetMinimum(0.1) #1.4 for log
        if logstatus[1] is 0 :
            histList[ih].SetMaximum(1.4) #1.4 for log
            histList[ih].SetMinimum(0.001) #1.4 for log
#        print "graph_status =" ,(tt is TGraphAsymmErrors)
#        print "hist status =", (tt is TH1D) or (tt is TH1F)
        if ih == 0 :      
            if tt is TGraphAsymmErrors : 
                histList[ih].Draw("APL")
            if (tt is TH1D) or (tt is TH1F) or (tt is TH1) or (tt is TH1I) :
                histList[ih].Draw("hist")   
        if ih > 0 :
            #histList[ih].SetLineWidth(2)
            if tt is TGraphAsymmErrors : 
                histList[ih].Draw("PL same")
            if (tt is TH1D) or (tt is TH1F) or (tt is TH1) or (tt is TH1I) :
                histList[ih].Draw("hist same")   

        if tt is TGraphAsymmErrors :
            histList[ih].SetMaximum(100) 
            histList[ih].SetMarkerColor(colors[ih])
            histList[ih].SetLineColor(colors[ih])
            histList[ih].SetLineWidth(2)
            histList[ih].SetMarkerStyle(markerStyle[ih])
            histList[ih].SetMarkerSize(1)
            leg.AddEntry(histList[ih],legendtext[ih],"PL")
        if (tt is TH1D) or (tt is TH1F) or (tt is TH1) or (tt is TH1I) :
            histList[ih].SetLineStyle(linestyle[ih])
            histList[ih].SetLineColor(colors[ih])
            histList[ih].SetLineWidth(3)
            leg.AddEntry(histList[ih],legendtext[ih],"L")
        histList[ih].GetYaxis().SetTitle(titleVec[1])
        histList[ih].GetYaxis().SetTitleSize(0.052)
        histList[ih].GetYaxis().SetTitleOffset(0.98)
        histList[ih].GetYaxis().SetTitleFont(42)
        histList[ih].GetYaxis().SetLabelFont(42)
        histList[ih].GetYaxis().SetLabelSize(.052)
        histList[ih].GetXaxis().SetRangeUser(xRange[0],xRange[1])
        #     histList[ih].GetXaxis().SetLabelSize(0.0000);
        
        histList[ih].GetXaxis().SetTitle(titleVec[0])
        histList[ih].GetXaxis().SetLabelSize(0.052)
        histList[ih].GetXaxis().SetTitleSize(0.052)
        #histList[ih].GetXaxis().SetTitleOffset(1.14)
        histList[ih].GetXaxis().SetTitleFont(42)

        histList[ih].GetXaxis().SetLabelFont(42)
        histList[ih].GetYaxis().SetLabelFont(42) 
        histList[ih].GetXaxis().SetNdivisions(507)
        #histList[ih].GetXaxis().SetMoreLogLabels(); 
        #histList[ih].GetXaxis().SetNoExponent();
        #histList[ih].GetTGaxis().SetMaxDigits(3);

        i=i+1
    pt = TPaveText(0.01,0.92,0.95,0.96,"brNDC")
    pt.SetBorderSize(0)
    pt.SetTextAlign(12)
    pt.SetFillStyle(0)
    pt.SetTextFont(42)
    pt.SetTextSize(0.046)
    text = pt.AddText(0.12,0.35,"CMS Internal                     41.5 fb^{-1} (2017) ")
    #text = pt.AddText(0.12,0.35,"CMS Internal                     59.6 fb^{-1} (2018) ")
    #text = pt.AddText(0.6,0.5,"41.5 fb^{-1} (2017) ")
    pt.Draw()
   
    

    leg.Draw()
    outputdirname = 'plots_limit/limitcomp//'
    histname=outputdirname+pngname 
    c.SaveAs(histname+'.png')
    c.SaveAs(histname+'.pdf')
    outputname = 'cp  -r '+ outputdirname+'/*' +' /afs/cern.ch/work/k/khurana/public/AnalysisStuff/monoH/LimitModelPlots/plots_limit/limitcomp/'
def train_and_apply():

    np.random.seed(1)
    ROOT.gROOT.SetBatch()

    #Extract data from root file
    tree = uproot.open("out_all.root")["outA/Tevts"]
    branch_mc = [
        "MC_B_P", "MC_B_eta", "MC_B_phi", "MC_B_pt", "MC_D0_P", "MC_D0_eta",
        "MC_D0_phi", "MC_D0_pt", "MC_Dst_P", "MC_Dst_eta", "MC_Dst_phi",
        "MC_Dst_pt", "MC_Est_mu", "MC_M2_miss", "MC_mu_P", "MC_mu_eta",
        "MC_mu_phi", "MC_mu_pt", "MC_pis_P", "MC_pis_eta", "MC_pis_phi",
        "MC_pis_pt", "MC_q2"
    ]
    branch_rec = [
        "B_P", "B_eta", "B_phi", "B_pt", "D0_P", "D0_eta", "D0_phi", "D0_pt",
        "Dst_P", "Dst_eta", "Dst_phi", "Dst_pt", "Est_mu", "M2_miss", "mu_P",
        "mu_eta", "mu_phi", "mu_pt", "pis_P", "pis_eta", "pis_phi", "pis_pt",
        "q2"
    ]
    nvariable = len(branch_mc)
    x_train = tree.array(branch_mc[0], entrystop=options.maxevents)
    for i in range(1, nvariable):
        x_train = np.vstack(
            (x_train, tree.array(branch_mc[i], entrystop=options.maxevents)))
    x_test = tree.array(branch_rec[0], entrystop=options.maxevents)
    for i in range(1, nvariable):
        x_test = np.vstack(
            (x_test, tree.array(branch_rec[i], entrystop=options.maxevents)))
    x_train = x_train.T
    x_test = x_test.T
    x_test = array2D_float(x_test)
    #Different type of reconstruction variables

    #BN normalization
    gamma = 0
    beta = 0.2

    ar = np.array(x_train)
    a = K.constant(ar[:, 0])
    mean = K.mean(a)
    var = K.var(a)
    x_train = K.eval(K.batch_normalization(a, mean, var, gamma, beta))
    for i in range(1, nvariable):
        a = K.constant(ar[:, i])
        mean = K.mean(a)
        var = K.var(a)
        a = K.eval(K.batch_normalization(a, mean, var, gamma, beta))
        x_train = np.vstack((x_train, a))
    x_train = x_train.T

    ar = np.array(x_test)
    a = K.constant(ar[:, 0])
    mean = K.mean(a)
    var = K.var(a)
    x_test = K.eval(K.batch_normalization(a, mean, var, gamma, beta))
    for i in range(1, nvariable):
        a = K.constant(ar[:, i])
        mean = K.mean(a)
        var = K.var(a)
        a = K.eval(K.batch_normalization(a, mean, var, gamma, beta))
        x_test = np.vstack((x_test, a))
    x_test = x_test.T

    #Add noise, remain to be improved
    noise = np.random.normal(loc=0.0, scale=0.01, size=x_train.shape)
    x_train_noisy = x_train + noise
    noise = np.random.normal(loc=0.0, scale=0.01, size=x_test.shape)
    x_test_noisy = x_test + noise
    x_train = np.clip(x_train, -1., 1.)
    x_test = np.clip(x_test, -1., 1.)
    x_train_noisy = np.clip(x_train_noisy, -1., 1.)
    x_test_noisy = np.clip(x_test_noisy, -1., 1.)

    # Network parameters
    input_shape = (x_train.shape[1], )
    batch_size = 128
    latent_dim = 2

    # Build the Autoencoder Model
    # First build the Encoder Model
    inputs = Input(shape=input_shape, name='encoder_input')
    x = inputs

    # Shape info needed to build Decoder Model
    shape = K.int_shape(x)

    # Generate the latent vector
    latent = Dense(latent_dim, name='latent_vector')(x)

    # Instantiate Encoder Model
    encoder = Model(inputs, latent, name='encoder')
    encoder.summary()

    # Build the Decoder Model
    latent_inputs = Input(shape=(latent_dim, ), name='decoder_input')
    x = Dense(shape[1])(latent_inputs)
    x = Reshape((shape[1], ))(x)
    outputs = Activation('tanh', name='decoder_output')(x)

    # Instantiate Decoder Model
    decoder = Model(latent_inputs, outputs, name='decoder')
    decoder.summary()

    # Autoencoder = Encoder + Decoder
    # Instantiate Autoencoder Model
    autoencoder = Model(inputs, decoder(encoder(inputs)), name='autoencoder')
    autoencoder.summary()

    autoencoder.compile(loss='mse', optimizer='adam')

    # Train the autoencoder
    autoencoder.fit(x_train_noisy,
                    x_train,
                    validation_data=(x_test_noisy, x_test),
                    epochs=options.epochs,
                    batch_size=batch_size)

    # Predict the Autoencoder output from corrupted test imformation
    x_decoded = autoencoder.predict(x_test_noisy)

    # Draw Comparision Plots
    c = TCanvas("c", "c", 700, 700)
    fPads1 = TPad("pad1", "Run2", 0.0, 0.29, 1.00, 1.00)
    fPads2 = TPad("pad2", "", 0.00, 0.00, 1.00, 0.29)
    fPads1.SetBottomMargin(0.007)
    fPads1.SetLeftMargin(0.10)
    fPads1.SetRightMargin(0.03)
    fPads2.SetLeftMargin(0.10)
    fPads2.SetRightMargin(0.03)
    fPads2.SetBottomMargin(0.25)
    fPads1.Draw()
    fPads2.Draw()
    fPads1.cd()
    nbin = 50
    min = -1.
    max = 1.
    variable = "P^{B}"
    lbin = (max - min) / nbin
    lbin = str(float((max - min) / nbin))
    xtitle = branch_rec[options.branch - 1]
    ytitle = "Events/" + lbin + "GeV"
    h_rec = TH1D("h_rec", "" + ";%s;%s" % (xtitle, ytitle), nbin, min, max)
    h_rec.Sumw2()
    h_pre = TH1D("h_pre", "" + ";%s;%s" % (xtitle, ytitle), nbin, min, max)
    h_pre.Sumw2()
    for i in range(x_test_noisy.shape[0]):
        h_rec.Fill(x_test_noisy[i][options.branch - 1])
        h_pre.Fill(x_decoded[i][options.branch - 1])
    h_rec = UnderOverFlow1D(h_rec)
    h_pre = UnderOverFlow1D(h_pre)
    maxY = TMath.Max(h_rec.GetMaximum(), h_pre.GetMaximum())
    h_rec.SetLineColor(2)
    h_rec.SetFillStyle(0)
    h_rec.SetLineWidth(2)
    h_rec.SetLineStyle(1)
    h_pre.SetLineColor(3)
    h_pre.SetFillStyle(0)
    h_pre.SetLineWidth(2)
    h_pre.SetLineStyle(1)
    h_rec.SetStats(0)
    h_pre.SetStats(0)
    h_rec.GetYaxis().SetRangeUser(0, maxY * 1.1)
    h_rec.Draw("HIST")
    h_pre.Draw("same HIST")
    h_rec.GetYaxis().SetTitleSize(0.06)
    h_rec.GetYaxis().SetTitleOffset(0.78)
    theLeg = TLegend(0.5, 0.45, 0.95, 0.82, "", "NDC")
    theLeg.SetName("theLegend")
    theLeg.SetBorderSize(0)
    theLeg.SetLineColor(0)
    theLeg.SetFillColor(0)
    theLeg.SetFillStyle(0)
    theLeg.SetLineWidth(0)
    theLeg.SetLineStyle(0)
    theLeg.SetTextFont(42)
    theLeg.SetTextSize(.05)
    theLeg.AddEntry(h_rec, "Reconstruction", "L")
    theLeg.AddEntry(h_pre, "Prediction", "L")
    theLeg.SetY1NDC(0.9 - 0.05 * 6 - 0.005)
    theLeg.SetY1(theLeg.GetY1NDC())
    fPads1.cd()
    theLeg.Draw()
    title = TLatex(
        0.91, 0.93, "AE prediction compare with reconstruction, epochs=" +
        str(options.epochs))
    title.SetNDC()
    title.SetTextSize(0.05)
    title.SetTextFont(42)
    title.SetTextAlign(31)
    title.SetLineWidth(2)
    title.Draw()
    fPads2.cd()
    h_Ratio = h_pre.Clone("h_Ratio")
    h_Ratio.Divide(h_rec)
    h_Ratio.SetLineColor(1)
    h_Ratio.SetLineWidth(2)
    h_Ratio.SetMarkerStyle(8)
    h_Ratio.SetMarkerSize(0.7)
    h_Ratio.GetYaxis().SetRangeUser(0, 2)
    h_Ratio.GetYaxis().SetNdivisions(504, 0)
    h_Ratio.GetYaxis().SetTitle("Pre/Rec")
    h_Ratio.GetYaxis().SetTitleOffset(0.35)
    h_Ratio.GetYaxis().SetTitleSize(0.13)
    h_Ratio.GetYaxis().SetTitleSize(0.13)
    h_Ratio.GetYaxis().SetLabelSize(0.11)
    h_Ratio.GetXaxis().SetLabelSize(0.1)
    h_Ratio.GetXaxis().SetTitleOffset(0.8)
    h_Ratio.GetXaxis().SetTitleSize(0.14)
    h_Ratio.SetStats(0)
    axis1 = TGaxis(min, 1, max, 1, 0, 0, 0, "L")
    axis1.SetLineColor(1)
    axis1.SetLineWidth(1)
    for i in range(1, h_Ratio.GetNbinsX() + 1, 1):
        D = h_rec.GetBinContent(i)
        eD = h_rec.GetBinError(i)
        if D == 0: eD = 0.92
        B = h_pre.GetBinContent(i)
        eB = h_pre.GetBinError(i)
        if B < 0.1 and eB >= B:
            eB = 0.92
            Err = 0.
        if B != 0.:
            Err = TMath.Sqrt((eD * eD) / (B * B) + (D * D * eB * eB) /
                             (B * B * B * B))
            h_Ratio.SetBinContent(i, D / B)
            h_Ratio.SetBinError(i, Err)
        if B == 0.:
            Err = TMath.Sqrt((eD * eD) / (eB * eB) + (D * D * eB * eB) /
                             (eB * eB * eB * eB))
            h_Ratio.SetBinContent(i, D / 0.92)
            h_Ratio.SetBinError(i, Err)
        if D == 0 and B == 0:
            h_Ratio.SetBinContent(i, -1)
            h_Ratio.SetBinError(i, 0)
        h_Ratio.Draw("e0")
        axis1.Draw()

    c.SaveAs(branch_rec[options.branch - 1] + "_comparision.png")
Beispiel #16
0
def plotUpperLimits(labels, masses, **kwargs):
    print color("plotUpperLimits()", color="magenta", prepend=">>>\n>>> ")
    # https://raw.githubusercontent.com/nucleosynthesis/HiggsAnalysis-CombinedLimit/combine_tutorial_SWAN/combine_tutorials_2016/combine_intro/plotPvalue.py

    # SIGNAL strength & mass
    extralabel = kwargs.get('extralabel', "")

    # LOOP over LABELS
    for label in labels:
        print color("plotUpperLimits - %s" % (label),
                    color="grey",
                    prepend="\n>>> ")

        N = len(masses)
        yellow = TGraph(2 * N)  # yellow band
        green = TGraph(2 * N)  # green band
        median = TGraph(N)  # median line

        up2s = []
        down2s = []
        for i, mass in enumerate(masses):
            filename = getOutputFilename(label, mass, extralabel=extralabel)
            limits = getLimits(filename)
            yellow.SetPoint(i, mass, limits[4])  # + 2 sigma
            green.SetPoint(i, mass, limits[3])  # + 1 sigma
            median.SetPoint(i, mass, limits[2])  # median
            green.SetPoint(2 * N - 1 - i, mass, limits[1])  # - 1 sigma
            yellow.SetPoint(2 * N - 1 - i, mass, limits[0])  # - 2 sigma
            down2s.append(limits[0])
            up2s.append(limits[4])

        ymax = max(up2s) * 1.20
        ymin = min(down2s)
        doLog = ymin and ymax / min(down2s) > 4
        xtitle = "m_{X} [GeV]"
        ytitle = "95% upper limit on #sigma#timesBR(X #rightarrow #tau#tau) [pb]"
        if "bbA" in extralabel:
            xtitle = "m_{A} [GeV]"
            ytitle = "95% upper limit on #sigma#timesBR(A #rightarrow #tau#tau) [pb]"

        W, H = 800, 600
        T, B = 0.08 * H, 0.12 * H
        L, R = 0.12 * W, 0.04 * W
        canvas = TCanvas("canvas", "canvas", 100, 100, W, H)
        canvas.SetFillColor(0)
        canvas.SetBorderMode(0)
        canvas.SetFrameFillStyle(0)
        canvas.SetFrameBorderMode(0)
        canvas.SetTopMargin(T / H)
        canvas.SetBottomMargin(B / H)
        canvas.SetLeftMargin(L / W)
        canvas.SetRightMargin(R / W)
        canvas.SetTickx(0)
        canvas.SetTicky(0)
        canvas.SetGrid()
        canvas.cd()
        if doLog:
            ymin = 0.1  #10**(floor(log(ymin,10))-1)
            ymax = 1000  #10**(ceil(log(ymax,10))+1)
            #ymin, ymax = 0.1, 1000
            canvas.SetLogy()
        else:
            ymin *= 0 if ymin > 0 else 1.20

        frame = canvas.DrawFrame(min(masses), ymin, max(masses), ymax)
        frame.GetYaxis().SetTitleSize(0.055)
        frame.GetXaxis().SetTitleSize(0.055)
        frame.GetXaxis().SetLabelSize(0.044)
        frame.GetYaxis().SetLabelSize(0.044)
        frame.GetXaxis().SetLabelOffset(0.010)
        frame.GetXaxis().SetTitleOffset(1.04)
        frame.GetYaxis().SetTitleOffset(1.08)
        frame.GetXaxis().SetNdivisions(508)
        frame.GetYaxis().CenterTitle(True)
        frame.GetYaxis().SetTitle(ytitle)
        frame.GetXaxis().SetTitle(xtitle)

        yellow.SetFillColor(kOrange)
        yellow.SetLineColor(kOrange)
        yellow.SetFillStyle(1001)
        yellow.Draw('F')

        green.SetFillColor(kGreen + 1)
        green.SetLineColor(kGreen + 1)
        green.SetFillStyle(1001)
        green.Draw('Fsame')

        median.SetLineColor(1)
        median.SetLineWidth(2)
        median.SetLineStyle(2)
        median.Draw('Lsame')

        CMS_lumi.CMS_lumi(canvas, 13, 0)
        gPad.SetTicks(1, 1)
        gPad.Modified()
        frame.Draw('sameaxis')

        width = 0.28
        height = 0.20
        #x1 = 0.16; x2 = x1 + width # Left
        x2 = 0.80
        x1 = x2 - width  # Right
        x2 = x1 + width

        y1 = 0.68
        y2 = y1 + height
        legend = TLegend(x1, y1, x2, y2)
        legend.SetFillStyle(0)
        legend.SetBorderSize(0)
        legend.SetTextSize(0.040)
        legend.SetTextFont(62)
        legend.SetHeader("%s" % (label_dict[label + extralabel]))
        legend.SetTextFont(42)
        legend.AddEntry(median, "Asymptotic CL_{s} expected", 'L')
        legend.AddEntry(green, "#pm 1 std. deviation", 'f')
        #legend.AddEntry(green, "Asymptotic CL_{s} #pm 1 std. deviation",'f')
        legend.AddEntry(yellow, "#pm 2 std. deviation", 'f')
        #legend.AddEntry(green, "Asymptotic CL_{s} #pm 2 std. deviation",'f')
        legend.Draw()

        print " "
        canvas.SaveAs("%s/upperLimit-%s%s.png" %
                      (PLOTS_DIR, label, extralabel))
        canvas.SaveAs("%s/upperLimit-%s%s%s.pdf" %
                      (PLOTS_DIR, label, extralabel))
        canvas.Close()
def drawHistsWithRatio(hists, name, **kwargs):
    """Draw histograms with ratios."""

    title = kwargs.get('title', "")
    xtitle = kwargs.get('xtitle', "")
    ytitle = kwargs.get('ytitle', "")
    rtitle = kwargs.get('rtitle', "Ratio")
    xmin = kwargs.get('xmin', hists[0].GetXaxis().GetXmin())
    xmax = kwargs.get('xmax', hists[0].GetXaxis().GetXmax())
    ymin = kwargs.get('ymin', None)
    ymax = kwargs.get('ymax', None)
    rmin = kwargs.get('rmin', 0.45)
    rmax = kwargs.get('rmax', 1.55)
    logx = kwargs.get('logx', False)
    logy = kwargs.get('logy', False)
    denom = kwargs.get('denom', 1) - 1  # denominator for ratio
    textsize = kwargs.get('textsize', 0.045)
    texts = kwargs.get('text', [])
    width = kwargs.get('width', 0.26)
    #textheight = kwargs.get('textheight',   1.09                 )
    #ctext      = kwargs.get('ctext',        [ ]                  ) # corner text
    #cposition  = kwargs.get('cposition',    'topleft'            ).lower() # cornertext
    #ctextsize  = kwargs.get('ctextsize',    1.4*legendtextsize   )
    colors = kwargs.get('colors', linecolors)
    if not isinstance(texts, list) or isinstance(texts, tuple):
        texts = [texts]
    if ymax == None:
        ymax = 1.12 * max(h.GetMaximum() for h in hists)

    # MAIN plot
    canvas = TCanvas('canvas', 'canvas', 100, 100, 800, 800)
    canvas.SetFillColor(0)
    canvas.SetBorderMode(0)
    canvas.SetFrameBorderMode(0)
    canvas.Divide(2)
    canvas.SetMargin(0.0, 0.0, 0.0, 0.0)
    canvas.cd(1)
    gPad.SetPad('pad1', 'pad1', 0, 0.33, 1, 1)
    gPad.SetMargin(0.12, 0.04, 0.02, 0.08)
    gPad.SetFillColor(0)
    gPad.SetBorderMode(0)
    gPad.SetTickx(0)
    gPad.SetTicky(0)
    gPad.SetGrid()
    gPad.Draw()
    canvas.cd(2)
    gPad.SetPad('pad2', 'pad2', 0, 0, 1, 0.33)
    gPad.SetMargin(0.12, 0.04, 0.30, 0.03)
    gPad.SetFillColor(0)
    gPad.SetFillStyle(4000)
    gPad.SetFrameFillStyle(0)
    gPad.SetBorderMode(0)
    gPad.Draw()

    # MAIN plot
    canvas.cd(1)
    for i, hist in enumerate(hists):
        color = colors[i % len(colors)]
        hist.SetLineColor(color)
        hist.SetLineWidth(2)
        hist.Draw('HIST SAME')
    frame = hists[0]
    frame.GetYaxis().SetTitleSize(0.060)
    frame.GetXaxis().SetTitleSize(0)
    frame.GetXaxis().SetLabelSize(0)
    frame.GetYaxis().SetLabelSize(0.052)
    frame.GetXaxis().SetLabelOffset(0.010)
    frame.GetXaxis().SetTitleOffset(0.98)
    frame.GetYaxis().SetTitleOffset(1.05)
    frame.GetXaxis().SetNdivisions(508)
    frame.GetYaxis().SetTitle(ytitle)
    frame.GetXaxis().SetTitle(xtitle)
    if logx:
        gPad.Update()
        gPad.SetLogx()
    if logy:
        gPad.Update()
        gPad.SetLogy()
    if ymin: frame.SetMinimum(ymin)
    if ymax: frame.SetMaximum(ymax)

    height = 1.1 * textsize * len([l for l in texts + hists if l])
    x1, y1 = 0.90, 0.88
    x2, y2 = x1 - width, y1 - height
    legend = TLegend(x1, y1, x2, y2)
    legend.SetTextSize(textsize)
    legend.SetBorderSize(0)
    legend.SetFillStyle(0)
    legend.SetFillColor(0)
    legend.SetMargin(0.05 / width)
    if title:
        legend.SetTextFont(62)
        legend.SetHeader(title)
    legend.SetTextFont(42)
    for hist in hists:
        legend.AddEntry(hist, hist.GetTitle(), 'l')
    for text in texts:
        legend.AddEntry(0, text, '')
    legend.Draw()

    gPad.SetTicks(1, 1)
    gPad.Modified()
    frame.Draw('AXIS SAME')
    CMS_style.CMS_lumi(gPad, 13, 0)

    # RATIO plot
    canvas.cd(2)
    ratios = []
    for i, hist in enumerate(hists):
        if i == denom: continue
        ratio = hist.Clone(hist.GetName() + "_ratio")
        ratio.Divide(hists[denom])
        for ibin in xrange(1, hist.GetXaxis().GetNbins() + 1):
            if hists[denom].GetBinContent(ibin) == 0:
                if hist.GetBinContent(ibin) == 0:
                    ratio.SetBinContent(ibin, 1)
                else:
                    ratio.SetBinContent(ibin, rmax + 1e5)
        ratio.Draw('HIST SAME')
        ratios.append(ratio)
    frame_ratio = ratios[0]
    frame_ratio.GetYaxis().SetRangeUser(rmin, rmax)
    frame_ratio.GetYaxis().CenterTitle()
    frame_ratio.GetYaxis().SetTitleSize(0.13)
    frame_ratio.GetXaxis().SetTitleSize(0.13)
    frame_ratio.GetXaxis().SetLabelSize(0.12)
    frame_ratio.GetYaxis().SetLabelSize(0.11)
    frame_ratio.GetXaxis().SetLabelOffset(0.012)
    frame_ratio.GetXaxis().SetTitleOffset(1.02)
    frame_ratio.GetYaxis().SetTitleOffset(0.48)
    frame_ratio.GetXaxis().SetNdivisions(508)
    frame_ratio.GetYaxis().CenterTitle(True)
    frame_ratio.GetYaxis().SetTitle(rtitle)
    frame_ratio.GetXaxis().SetTitle(xtitle)
    frame_ratio.GetYaxis().SetNdivisions(505)
    if logx:
        gPad.Update()
        gPad.SetLogx()
    line = TLine(xmin, 1., xmax, 1.)
    line.SetLineColor(hists[denom].GetLineColor())
    line.SetLineWidth(hists[denom].GetLineWidth())
    line.SetLineStyle(1)
    line.Draw('SAME')
    gPad.SetTicks(1, 1)
    gPad.Update()
    gPad.SetGrid()
    gPad.Modified()
    frame_ratio.Draw('SAME AXIS')

    canvas.SaveAs(name + ".png")
    canvas.SaveAs(name + ".pdf")
    canvas.Close()
Beispiel #18
0
def plotPValues(labels, masses0, **kwargs):
    print color("plotPValues()", color="magenta", prepend=">>>\n>>> ")

    # SIGNAL strength & mass
    bins = kwargs.get('bins', [])
    ymin = 0.00005

    # LOOP over LABELS
    for label in labels:
        print color("plotPValues - %s" % (label),
                    color="grey",
                    prepend="\n>>> ")

        masses = array('d', [])
        zeros = array('d', [])
        limitObs = array('d', [])
        limitExps = []

        up2s = []
        for i, mass in enumerate(masses0):
            bin = -1
            if bins: bin = bins[i]
            filename = getOutputFilename(label,
                                         mass,
                                         method="ProfileLikelihood",
                                         bin=bin,
                                         extralabel=".SignifObs")
            limitObs.append(getLimits(filename, brazilian=False))
            masses.append(mass)
            zeros.append(0.0)

        v_masses = TVectorD(len(masses), masses)
        v_zeros = TVectorD(len(zeros), zeros)
        v_limitObs = TVectorD(len(limitObs), limitObs)
        v_limitExps = []
        for limitExp in limitExps:
            v_limitExps.append(TVectorD(len(limitExp), limitExp))

        W = 800
        H = 600
        T = 0.08 * H
        B = 0.12 * H
        L = 0.12 * W
        R = 0.04 * W
        canvas = TCanvas("canvas", "canvas", 100, 100, W, H)
        canvas.SetFillColor(0)
        canvas.SetBorderMode(0)
        canvas.SetFrameFillStyle(0)
        canvas.SetFrameBorderMode(0)
        canvas.SetLeftMargin(L / W)
        canvas.SetRightMargin(R / W)
        canvas.SetTopMargin(T / H)
        canvas.SetBottomMargin(B / H)
        canvas.SetTickx(0)
        canvas.SetTicky(0)
        canvas.SetGrid()
        canvas.SetLogy()  # log
        canvas.cd()

        frame = canvas.DrawFrame(1.4, 0.001, 4.1, 10)
        frame.GetYaxis().CenterTitle()
        frame.GetYaxis().SetTitleSize(0.05)
        frame.GetXaxis().SetTitleSize(0.05)
        frame.GetXaxis().SetLabelSize(0.04)
        frame.GetYaxis().SetLabelSize(0.04)
        frame.GetYaxis().SetTitleOffset(1.14)
        frame.GetXaxis().SetNdivisions(508)
        frame.GetYaxis().CenterTitle(False)
        frame.GetYaxis().SetTitle("local p-value")
        #frame.GetYaxis().SetTitle("95% upper limit on #sigma / #sigma_{SM}")
        frame.GetXaxis().SetTitle("X#rightarrow#tau#tau mass [GeV]")
        frame.SetMinimum(ymin)
        frame.SetMaximum(1.5)
        frame.GetXaxis().SetLimits(min(masses), max(masses))

        latex = TLatex()
        latex.SetTextSize(0.4 * canvas.GetTopMargin())
        latex.SetTextColor(2)
        f1 = TF1("f1", "0.15866", min(masses), max(masses))
        f1.SetLineColor(2)
        f1.SetLineWidth(2)
        f1.Draw("lsame")
        latex.DrawLatex(min(masses) + 1, 0.15866 * 1.1, "1#sigma")
        f2 = TF1("f2", "0.02275", min(masses), max(masses))
        f2.SetLineColor(2)
        f2.SetLineWidth(2)
        f2.Draw("lsame")
        latex.DrawLatex(min(masses) + 1, 0.02275 * 1.1, "2#sigma")
        f3 = TF1("f3", "0.0013499", min(masses), max(masses))
        f3.SetLineColor(2)
        f3.SetLineWidth(2)
        f3.Draw("lsame")
        latex.DrawLatex(min(masses) + 1, 0.0013499 * 1.1, "3#sigma")

        graph_limitExps = []
        colors = [4, 2, 3, 6, 7, 8]
        for i, v_limitExp in enumerate(v_limitExps):
            graph_limitExps.append(
                TGraphAsymmErrors(v_masses, v_limitExp, v_zeros, v_zeros,
                                  v_zeros, v_zeros))
            graph_limitExps[-1].SetLineColor(colors[i])
            graph_limitExps[-1].SetLineWidth(2)
            graph_limitExps[-1].SetLineStyle(2)
            graph_limitExps[-1].Draw("Lsame")

        graph_limitObs = TGraphAsymmErrors(v_masses, v_limitObs, v_zeros,
                                           v_zeros, v_zeros, v_zeros)
        graph_limitObs.SetLineColor(1)
        graph_limitObs.SetLineWidth(2)
        graph_limitObs.Draw("Csame")

        CMS_lumi.CMS_lumi(canvas, 13, 0)
        gPad.SetTicks(1, 1)
        frame.Draw('sameaxis')

        x1 = 0.62
        x2 = x1 + 0.24
        y1 = 0.15
        y2 = y1 + 0.20
        legend = TLegend(x1, y1, x2, y2)
        legend.SetFillStyle(0)
        legend.SetBorderSize(0)
        legend.SetTextSize(0.041)
        legend.SetTextFont(42)
        legend.SetHeader("%s" % (label_dict[label]))
        legend.AddEntry(graph_limitObs, "observed", 'L')  #p-value
        legend.Draw("same")
        gPad.RedrawAxis()

        print " "
        canvas.SaveAs("%s/p-value-local-%s.png" % (PLOTS_DIR, label))
        canvas.SaveAs("%s/p-value-local-%s.pdf" % (PLOTS_DIR, label))
        canvas.Close()
def plot_2D():

  myfile = TFile(args.inputFile)

  mytree = gDirectory.Get("physics")
  mytree_weight = mytree.GetWeight()/1e3

  trig_dec  = "( passHLT == 1 )"
  lep_tag_trigmatch = "( lep_tag_isTrigMatched[0] == 1 && ( ( lep_tag_flavour[0] == 11 && lep_tag_pt[0] > 25e3 ) || ( lep_tag_flavour[0] == 13 && lep_tag_pt[0] > 22e3 ) ) )"
  lep_probe_trigmatch = "( lep_probe_isTrigMatched[0] == 1 && ( ( lep_probe_flavour[0] == 11 && lep_probe_pt[0] > 25e3 ) || ( lep_probe_flavour[0] == 13 && lep_probe_pt[0] > 22e3 ) ) )"
  el_tag_eta   = "( TMath::Abs(el_tag_eta[0]) < 1.37 )"
  nbjets       = "( njets_mv2c20_Fix77 > 0 )"
  njets        = "( njets > 0 && njets < 4 )"
  nleptons     = "( nlep == 2 && ( lep_pt[0] > 20e3 && lep_pt[1] > 20e3 ) )"
  same_sign    = "( isSS01 == 1 )"
  # veto charge flips
  #
  ch_flip_veto = "( 1 )"
  if args.doChFlipVeto:
     ch_flip_veto = "( lep_isChFlip[0] == 0 && lep_isChFlip[1] == 0 )"
  # require at least 1 !prompt lepton
  #
  non_prompt   = "( ( lep_truthType[0] != 6 && lep_truthType[0] != 2 ) || ( lep_truthType[1] != 6 && lep_truthType[1] != 2 ) )"
  # require at least one T lepton in the event
  #
  is_tight_event = "1" #"( isNonTightEvent == 0 )"
  # require tag lepton to be T
  #
  tight_tag   = "( lep_tag_isTightSelected[0] == 1 )"

  hist_list_tag_MUPROBEEVT = {}
  hist_list_tag_ELPROBEEVT = {}

  set_fancy_2D_style()

  gStyle.SetPaintTextFormat("2.1f")

  # -----------------------------------------------------

  dirname = "OutputPlots_TRUTH"
  if args.outdirname:
     dirname += ( "_" + args.outdirname )

  try:
      os.makedirs(dirname)
  except:
      pass

  # -----------------------------------------------------

  # ----------------
  #    Muon probe
  # ----------------

  sel_FAKE_MUPROBEEVT_T = None

  # look only at OF region
  if args.channel == "OF":
    sel_FAKE_MUPROBEEVT_T = "(" + trig_dec + " && " + lep_tag_trigmatch + " && " + lep_probe_trigmatch + " && " + nleptons + " && " + same_sign + " && " +  is_tight_event + " && " + tight_tag + " && " + "( (nmuon == 1 && nel == 1) && ( isProbeMuEvent == 1 ) && ( muon_probe_isTightSelected[0] == 1 ) )" + " && " + el_tag_eta + " && " + nbjets + " && " + njets  + " && " + ch_flip_veto + " && " + non_prompt + ")"
  # look only at SF region
  elif args.channel == "SF":
    sel_FAKE_MUPROBEEVT_T = "(" + trig_dec + " && " + lep_tag_trigmatch + " && " + lep_probe_trigmatch + " && " + nleptons + " && " + same_sign + " && " +  is_tight_event + " && " + tight_tag + " && " + "( ( nmuon == 2 ) && ( isProbeMuEvent == 1 ) && ( muon_probe_isTightSelected[0] == 1 ) )" + " && " + nbjets + " && " + njets + " && " + ch_flip_veto + " && " + non_prompt + ")"

  print "sel_FAKE_MUPROBEEVT_T: \n", sel_FAKE_MUPROBEEVT_T

  # histograms for tag (passing T: default)
  #
  h_taglep_FAKE_MUPROBEEVT_T_pt = TH2D("taglep_FAKE_MUPROBEEVT_T_pt", "taglep_FAKE_MUPROBEEVT_T_pt", 30, 20.0, 200.0, 30, 20.0, 200.0)
  hist_list_tag_MUPROBEEVT[h_taglep_FAKE_MUPROBEEVT_T_pt] = ["T","pt"]
  h_taglep_FAKE_MUPROBEEVT_T_ptvarcone30_over_pt = TH2D("taglep_FAKE_MUPROBEEVT_T_ptvarcone30_over_pt", "taglep_FAKE_MUPROBEEVT_T_ptvarcone30_over_pt", 20, 0.0, 0.1, 20, 0.0, 0.1)
  hist_list_tag_MUPROBEEVT[h_taglep_FAKE_MUPROBEEVT_T_ptvarcone30_over_pt] = ["T","ptvarcone30_over_pt"]
  h_taglep_FAKE_MUPROBEEVT_T_ptvarcone20_over_pt = TH2D("taglep_FAKE_MUPROBEEVT_T_ptvarcone20_over_pt", "taglep_FAKE_MUPROBEEVT_T_ptvarcone20_over_pt", 20, 0.0, 0.1, 20, 0.0, 0.1)
  hist_list_tag_MUPROBEEVT[h_taglep_FAKE_MUPROBEEVT_T_ptvarcone20_over_pt] = ["T","ptvarcone20_over_pt"]
  h_taglep_FAKE_MUPROBEEVT_T_topoetcone20_over_pt = TH2D("taglep_FAKE_MUPROBEEVT_T_topoetcone20_over_pt", "taglep_FAKE_MUPROBEEVT_T_topoetcone20_over_pt", 20, -0.1, 0.1, 20, -0.1, 0.1)
  hist_list_tag_MUPROBEEVT[h_taglep_FAKE_MUPROBEEVT_T_topoetcone20_over_pt] = ["T","topoetcone20_over_pt"]

  h_taglep_FAKE_MUPROBEEVT_T_pt.GetXaxis().SetTitle("REAL pT [GeV]")
  h_taglep_FAKE_MUPROBEEVT_T_ptvarcone30_over_pt.GetXaxis().SetTitle("REAL ptvarcone30/pT")
  h_taglep_FAKE_MUPROBEEVT_T_topoetcone20_over_pt.GetXaxis().SetTitle("REAL topoetcone20/pT")
  h_taglep_FAKE_MUPROBEEVT_T_pt.GetYaxis().SetTitle("FAKE pT [GeV]")
  h_taglep_FAKE_MUPROBEEVT_T_ptvarcone30_over_pt.GetYaxis().SetTitle("FAKE ptvarcone30/pT")
  h_taglep_FAKE_MUPROBEEVT_T_topoetcone20_over_pt.GetYaxis().SetTitle("FAKE topoetcone20/pT")

  if args.channel == "OF":
     # probe is muon, tag is electron
     #
     mytree.Project("taglep_FAKE_MUPROBEEVT_T_pt", "muon_probe_pt[0]/1e3:el_tag_pt[0]/1e3", "%s * (%s)" %(mytree_weight, sel_FAKE_MUPROBEEVT_T), "" )
     mytree.Project("taglep_FAKE_MUPROBEEVT_T_ptvarcone30_over_pt", "muon_probe_ptvarcone30[0]/muon_probe_pt[0]:el_tag_ptvarcone30[0]/el_tag_pt[0]", "%s * (%s)" %(mytree_weight, sel_FAKE_MUPROBEEVT_T), "" )
     mytree.Project("taglep_FAKE_MUPROBEEVT_T_ptvarcone20_over_pt", "muon_probe_ptvarcone20[0]/muon_probe_pt[0]:el_tag_ptvarcone20[0]/el_tag_pt[0]", "%s * (%s)" %(mytree_weight, sel_FAKE_MUPROBEEVT_T), "" )
     mytree.Project("taglep_FAKE_MUPROBEEVT_T_topoetcone20_over_pt", "muon_probe_topoetcone20[0]/muon_probe_pt[0]:el_tag_topoetcone20[0]/el_tag_pt[0]", "%s * (%s)" %(mytree_weight, sel_FAKE_MUPROBEEVT_T), "" )
  elif args.channel == "SF":
     # probe is muon, tag is muon
     #
     mytree.Project("taglep_FAKE_MUPROBEEVT_T_pt", "muon_probe_pt[0]/1e3:muon_tag_pt[0]/1e3", "%s * (%s)" %(mytree_weight, sel_FAKE_MUPROBEEVT_T), "" )
     mytree.Project("taglep_FAKE_MUPROBEEVT_T_ptvarcone30_over_pt", "muon_probe_ptvarcone30[0]/muon_probe_pt[0]:muon_tag_ptvarcone30[0]/muon_tag_pt[0]", "%s * (%s)" %(mytree_weight, sel_FAKE_MUPROBEEVT_T), "" )
#     mytree.Project("taglep_FAKE_MUPROBEEVT_T_ptvarcone20_over_pt", "muon_probe_ptvarcone20[0]/muon_probe_pt[0]:muon_tag_ptvarcone20[0]/muon_tag_pt[0]", "%s * (%s)" %(mytree_weight, sel_FAKE_MUPROBEEVT_T), "" )
     mytree.Project("taglep_FAKE_MUPROBEEVT_T_topoetcone20_over_pt", "muon_probe_topoetcone20[0]/muon_probe_pt[0]:muon_tag_topoetcone20[0]/muon_tag_pt[0]", "%s * (%s)" %(mytree_weight, sel_FAKE_MUPROBEEVT_T), "" )


  # Normalise to unity
  if args.doNorm:
     for hist in hist_list_tag_MUPROBEEVT.keys():
	if hist.Integral() == 0:
	  continue
        hist.Scale(1/hist.Integral())

  # now plot
  #
  print "\tLooking at events where the PROBE is: {0} and the channel is {1}\n".format("MUON", args.channel)
  for  hist_tag in hist_list_tag_MUPROBEEVT.keys():

     c = TCanvas("c","Temp",50,50,900,900)

     legend_T = TLegend(0.4,0.8,0.6,0.85); # (x1,y1 (--> bottom left corner), x2, y2 (--> top right corner) )
     legend_T.SetHeader("2 Lep SS Fake CR - T probe")
     legend_T.SetBorderSize(0)  # no border
     legend_T.SetFillColor(0) # Legend background should be white
     legend_T.SetTextSize(0.04) # Increase entry font size!
     legend_T.SetTextFont(42) # Helvetica

     var_tag    = hist_list_tag_MUPROBEEVT[hist_tag][1]
     type_tag   = hist_list_tag_MUPROBEEVT[hist_tag][0]

     print "\tPlotting variable: {0}\n".format(var_tag)

     print "\ttag histogram name: {0}\n".format(hist_tag.GetName())

     hist_tag.Draw("colz")

     legend_T.Draw()
     plotname = dirname + "/FAKE_MUPROBEEVT_" + var_tag
     c.SaveAs(plotname+".png")

     del c

  # -----------------------------------------------------

  # ---------------------
  #    Electron probe
  # ---------------------

  sel_FAKE_ELPROBEEVT_T = None

  # look only at OF region
  if args.channel == "OF":
    sel_FAKE_ELPROBEEVT_T = "(" + trig_dec + " && " + lep_tag_trigmatch + " && " + lep_probe_trigmatch + " && " + nleptons + " && " + same_sign + " && " +  is_tight_event + " && " + tight_tag + " && " + "( (nmuon == 1 && nel == 1) && ( isProbeElEvent == 1 ) && ( el_probe_isTightSelected[0] == 1 ) )" + " && " + nbjets + " && " + njets + " && "  + ch_flip_veto + " && " + non_prompt + ")"
  # look only at SF region
  elif args.channel == "SF":
    sel_FAKE_ELPROBEEVT_T = "(" + trig_dec + " && " + lep_tag_trigmatch + " && " + lep_probe_trigmatch + " && " + nleptons + " && " + same_sign + " && " +  is_tight_event + " && " + tight_tag + " && " + "( ( nel == 2 ) && ( isProbeElEvent == 1 ) && ( el_probe_isTightSelected[0] == 1 ) )" + " && " + el_tag_eta + " && " + nbjets + " && " + njets + " && "  + ch_flip_veto + " && " + non_prompt + ")"

  print "sel_FAKE_ELPROBEEVT_T: \n", sel_FAKE_ELPROBEEVT_T

  # histograms for tag (passing T: default)
  #
  h_taglep_FAKE_ELPROBEEVT_T_pt = TH2D("taglep_FAKE_ELPROBEEVT_T_pt", "taglep_FAKE_ELPROBEEVT_T_pt", 30, 20.0, 200.0, 30, 20.0, 200.0)
  hist_list_tag_ELPROBEEVT[h_taglep_FAKE_ELPROBEEVT_T_pt] = ["T","pt"]
  h_taglep_FAKE_ELPROBEEVT_T_ptvarcone30_over_pt = TH2D("taglep_FAKE_ELPROBEEVT_T_ptvarcone30_over_pt", "taglep_FAKE_ELPROBEEVT_T_ptvarcone30_over_pt", 20, 0.0, 0.1, 20, 0.0, 0.1)
  hist_list_tag_ELPROBEEVT[h_taglep_FAKE_ELPROBEEVT_T_ptvarcone30_over_pt] = ["T","ptvarcone30_over_pt"]
  h_taglep_FAKE_ELPROBEEVT_T_ptvarcone20_over_pt = TH2D("taglep_FAKE_ELPROBEEVT_T_ptvarcone20_over_pt", "taglep_FAKE_ELPROBEEVT_T_ptvarcone20_over_pt", 20, 0.0, 0.1, 20, 0.0, 0.1)
  hist_list_tag_ELPROBEEVT[h_taglep_FAKE_ELPROBEEVT_T_ptvarcone20_over_pt] = ["T","ptvarcone20_over_pt"]
  h_taglep_FAKE_ELPROBEEVT_T_topoetcone20_over_pt = TH2D("taglep_FAKE_ELPROBEEVT_T_topoetcone20_over_pt", "taglep_FAKE_ELPROBEEVT_T_topoetcone20_over_pt", 20, -0.1, 0.1, 20, -0.1, 0.1)
  hist_list_tag_ELPROBEEVT[h_taglep_FAKE_ELPROBEEVT_T_topoetcone20_over_pt] = ["T","topoetcone20_over_pt"]

  h_taglep_FAKE_ELPROBEEVT_T_pt.GetXaxis().SetTitle("REAL pT [GeV]")
  h_taglep_FAKE_ELPROBEEVT_T_ptvarcone20_over_pt.GetXaxis().SetTitle("REAL ptvarcone20/pT")
  h_taglep_FAKE_ELPROBEEVT_T_topoetcone20_over_pt.GetXaxis().SetTitle("REAL topoetcone20/pT")
  h_taglep_FAKE_ELPROBEEVT_T_pt.GetYaxis().SetTitle("FAKE pT [GeV]")
  h_taglep_FAKE_ELPROBEEVT_T_ptvarcone20_over_pt.GetYaxis().SetTitle("FAKE ptvarcone20/pT")
  h_taglep_FAKE_ELPROBEEVT_T_topoetcone20_over_pt.GetYaxis().SetTitle("FAKE topoetcone20/pT")

  if args.channel == "OF":
     # probe is el, tag is muon
     #
     mytree.Project("taglep_FAKE_ELPROBEEVT_T_pt", "el_probe_pt[0]/1e3:muon_tag_pt[0]/1e3", "%s * (%s)" %(mytree_weight, sel_FAKE_ELPROBEEVT_T), "" )
     mytree.Project("taglep_FAKE_ELPROBEEVT_T_ptvarcone30_over_pt", "el_probe_ptvarcone30[0]/el_probe_pt[0]:muon_tag_ptvarcone30[0]/muon_tag_pt[0]", "%s * (%s)" %(mytree_weight, sel_FAKE_ELPROBEEVT_T), "" )
     mytree.Project("taglep_FAKE_ELPROBEEVT_T_ptvarcone20_over_pt", "el_probe_ptvarcone20[0]/el_probe_pt[0]:muon_tag_ptvarcone20[0]/muon_tag_pt[0]", "%s * (%s)" %(mytree_weight, sel_FAKE_ELPROBEEVT_T), "" )
     mytree.Project("taglep_FAKE_ELPROBEEVT_T_topoetcone20_over_pt", "el_probe_topoetcone20[0]/el_probe_pt[0]:muon_tag_topoetcone20[0]/muon_tag_pt[0]", "%s * (%s)" %(mytree_weight, sel_FAKE_ELPROBEEVT_T), "" )
  elif args.channel == "SF":
     # probe is el, tag is el
     #
     mytree.Project("taglep_FAKE_ELPROBEEVT_T_pt", "el_probe_pt[0]/1e3:el_tag_pt[0]/1e3", "%s * (%s)" %(mytree_weight, sel_FAKE_ELPROBEEVT_T), "" )
     #mytree.Project("taglep_FAKE_ELPROBEEVT_T_ptvarcone30_over_pt", "el_probe_ptvarcone30[0]/el_probe_pt[0]:el_tag_ptvarcone30[0]/el_tag_pt[0]", "%s * (%s)" %(mytree_weight, sel_FAKE_ELPROBEEVT_T), "" )
     mytree.Project("taglep_FAKE_ELPROBEEVT_T_ptvarcone20_over_pt", "el_probe_ptvarcone20[0]/el_probe_pt[0]:el_tag_ptvarcone20[0]/el_tag_pt[0]", "%s * (%s)" %(mytree_weight, sel_FAKE_ELPROBEEVT_T), "" )
     mytree.Project("taglep_FAKE_ELPROBEEVT_T_topoetcone20_over_pt", "el_probe_topoetcone20[0]/el_probe_pt[0]:el_tag_topoetcone20[0]/el_tag_pt[0]", "%s * (%s)" %(mytree_weight, sel_FAKE_ELPROBEEVT_T), "" )


  # Normalise to unity
  if args.doNorm:
     for hist in hist_list_tag_ELPROBEEVT.keys():
	if hist.Integral() == 0:
	  continue
        hist.Scale(1/hist.Integral())

  # now plot
  #
  print "\tLooking at events where the PROBE is: {0} and the channel is {1}\n".format("ELECTRON", args.channel)
  for  hist_tag in hist_list_tag_ELPROBEEVT.keys():

     c = TCanvas("c","Temp",50,50,900,900)

     legend_T = TLegend(0.4,0.8,0.6,0.85); # (x1,y1 (--> bottom left corner), x2, y2 (--> top right corner) )
     legend_T.SetHeader("2 Lep SS Fake CR - T probe")
     legend_T.SetBorderSize(0)  # no border
     legend_T.SetFillColor(0) # Legend background should be white
     legend_T.SetTextSize(0.04) # Increase entry font size!
     legend_T.SetTextFont(42) # Helvetica

     var_tag    = hist_list_tag_ELPROBEEVT[hist_tag][1]
     type_tag   = hist_list_tag_ELPROBEEVT[hist_tag][0]

     print "\tPlotting variable: {0}\n".format(var_tag)

     print "\ttag histogram name: {0}\n".format(hist_tag.GetName())

     hist_tag.Draw("colz")

     legend_T.Draw()
     plotname = dirname + "/FAKE_ELPROBEEVT_" + var_tag
     c.SaveAs(plotname+".png")

     del c