##################################################################################################
#                                                                                                #    
#                                      ```...`                                                   #    
#                                   `......-::::.`...---.`                                       #    
#                                  ``     `.-::-.....---:::-`                                    #    
#                                           ..`      `.--:://-                                   #    
#                                     `//:`            .-:::/+:                                  #    
#                                    +m/`sy            `.-:://+`                                 #    
#                              `    :mMmdN/        .::.`.-:://+-                                 #    
#                   ``-//-----------odMMMs`      -yh:/m+.-:///+-                                 #    
#               `..--------/oyy/---::/+sh.      -mNd/omh-:://++.                                 #    
#             `.-------------:------::///:.     yNMMMMNs-:///+:                                  #    
#           `------------------------:::://:`   omNNNmy-:///+:`                                  #    
#          .--------........---------:::::/+/.  `+sys/-::/+++:`                                  #    
#         .---------.---------------:::::///++:..------::://+o+.                                 #    
#        .---------...-------------:::::://++/----------:::///+o-                                #    
#        -------------------------::::::////:---.-------::::///+o.                               #    
#       `:----------------------:::::::///:---..-------:::::///+o/                               #    
#       .:--------------------:::::://///:-------------::::////+o+             `.-               #    
#       `::---------------:::::::://////:------------::::::///+++/            ..-:               #    
#       `::::--------:::::::////////////-----------::::://///++++-           .--:/`  ``..        #    
#        -/:::::::::::://///////////////--------::::://////+++++/`          .--:/+...--/.        #    
#         :///::::://////++++++++++++++/-----::::///////++++++//.         `.---::----:/:         #    
#          :+//////++++++++++++++++++o+/-:::::///////++++++++/:`         `..-------:/+/`````.`   #    
#           ./++++ooooooooooooooooooo/:::::///+++++++++++++//-`         `.---------///-..--:-    #    
#            `-+osssso/+sssssssssso+/::://+++ooooooooo+++/:-`          `----------------://-     #    
#               .:+:.` `-+ossyyyysooo++++oosssssoooo++//+:.            ---------------:/+/.      #    
#                         `-/+osyyyyyysssyysssssoo++++++oso/.----.````.-------------://+/`       #    
#                             `..-://+++osysssssooosyso+ooossydhs+----------------:://++:        #    
#                                       `+ssssssssssyyyo+++++/:--------------::::////////-`      #    
#                   `                  -+osooooooooosshhs/:----..--------::://////++//:----.     #    
#           ..`    ...`               :ssooooossssssyyy+:------------::/++ooooooooooo+/:----.`   #    
#           .--..``-.--`              .oysssssssssshdo:----------::/++ossyhddhhdo....--------`   #    
#     ``    `:-.---:----`             .----------:+mh:------:://++oohhhdddddddddms`              #    
#    `.......-:----------.`          .-...```````..smy++//++ooooooooyddddddddddddmy`             #    
#      `.-------------------.`````..-/:--.....`````.:shhhdddho/::/+oohdddddhhhhhddms             #    
#         `-------....--------------/:-...````````````..----:/.` ``-/+hddddhhhddddmd:            #    
#           `.-----.--..-----------:/:-....````````````````..::``  `.:ommddhdddmmmmms            #    
#             `---------------::://++:--......``````````....--/:`````.:sdddmmmmmdddmh`           #    
#             .--------:://+++++//:-//:--.....................-/-````.-/yydhyyyhhhhdd`           #    
#           `..----:://///:--..``   :+::--------..............-//.```.-:sdhyyyyyhhhhd`           #    
#          ..--::://::-..-://+///:-`.o/::----.................-:+:.``..:+hyyyyyyhhhhs            #    
#         .-::-..`   `:+ooooooooooso/o+:::---------------------:++-....:/yyyyyyyyhhh:            #    
#          `        .syso+++++++oooosso+/::::::-----------::::::+s/-..--:shyyyyyhhys`            #    
#                `.../yysoooooo+oooossyso///::------------::://++yo:---:/ohyyyyhhys.             #    
#                :o+:`.oysoooooooooossyhhoo+:----------:::::://++dh+::::/+dhhhhhys.              #    
#                .ooo:``ohyssoooooosssyhhoooo+:------::::::////++ymo//::/+dhhddh/`               #    
#                 /sso:``ohyyssssssssyyhdysooooo/:::://++///++++shds+////+mddho-                 #    
#                  :sss/.`odhyyyyyyyyyyhdddyssooso///+oysooooosshNhso++//+hyo-                   #    
#                   -syy+-.sdhhhyyyyyyyyyyhhhyyssssoosyyysssyhdmNdysso++/ossso+/-.               #    
#                    `/syo:-sddhhhyyyyysssyyhhhhyyyysosssssossyyhyyssso+ossoo++//-               #    
#                      `+hy/-oddhhyyyyssssyyyhddddhh+  `/oosssssssssoo+ydhho/:-.`                #    
#                       :osso:+ddhhyyyssssyyyhddhhyo.   `/oosssssssssssyhhhhhhhhy+.              #    
#                        -sso+::yddhyyyyyyyyyhho `       `:+osssssssssyhsoshdhhhhddo-`           #    
#                         .oys/--odddhhhhyyhhhs.           .:osyyyyyyhsoooyhdhyssyhds/           #    
#                          `/yy+:-/dmdddhhhhyo.             `yhhhhhysoosyhddhsoosyyds-           #    
#                            .+ys+/+dmdddhy+.               `shyssoosyhdddhysooosyhdo-`          #    
#                              .+so:-/::-.                   `-+oshhhhhhyyssoooosyhd/-           #    
#                                ``                        .:+oooo++oooooooooooosyhh-.           #    
#                                                        `+oooo++++++++++++++ooosyho`            #    
#                                                        +ssooooo++++++++++++oosyhd/.            #    
#                                                       `yyysssoooooooo+++oooosyyhh-.            #    
#                                                        sdhhyyyssssssssssssyyyhhd+-.            #    
#                                                        .hmddddhhhhhhhhhhhhhddddo:-             #    
#                                                         `:ohddmmddddddddddhyso/::              #    
#                                                            -:/++ooooooo++//:--.`               #    
##################################################################################################
#                           ____       _                                                         #
#                          / ___| __ _| | __ _ _ __   __ _  __ _  ___                            #
#                         | |  _ / _` | |/ _` | '_ \ / _` |/ _` |/ _ \                           #
#                         | |_| | (_| | | (_| | |_) | (_| | (_| | (_) |                          # 
#                     _____\____|\__,_|_|\__,_| .__/ \__,_|\__, |\___/ _                         #  
#                    |  ___| __ __ _ _ __ ___ |_|____      |___/  _ __| | _                      #_
#                    | |_ | '__/ _` | '_ ` _ \ / _ \ \ /\ / / _ \| '__| |/ /                     #
#                    |  _|| | | (_| | | | | | |  __/\ V  V / (_) | |  |   <                      # 
#                    |_|  |_|  \__,_|_| |_| |_|\___| \_/\_/ \___/|_|  |_|\_\                     #
#                                                                                                # 
##################################################################################################

import ROOT as r
from   ROOT import gROOT, TCanvas, TFile, TGraphErrors, SetOwnership
import math, sys, optparse, array, copy, os
import gc, inspect

import include.Sample as Sample
import include.helper as helper
import include.Canvas as Canvas

WORKPATH = os.path.abspath('./') + '/'

class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'


def makeValidation(lumi, treeMC, var, name, xlabel, logx, LLlabel = False):

    hSR_MC = treeMC.getLoopTH1F('histMC_SR_'+name, 'SR_' + var, xlabel)
    hCR_MC = treeMC.getLoopTH1F('histMC_CR_'+name, 'CR_' + var, xlabel)

    hSR_MC.SetMarkerStyle(20)
    hSR_MC.SetMarkerSize(0.8)
    hCR_MC.SetMarkerStyle(20)
    hCR_MC.SetMarkerSize(0.8)

    luminosity = lumi

    ### Get maximum
    maxValCR = hCR_MC.GetMaximum()
    maxValSR = hSR_MC.GetMaximum()
    maxVal = max(maxValCR, maxValSR)

    ### Set Maximum
    if not logx:
        hCR_MC.SetMaximum(1.3*maxVal)
        hSR_MC.SetMaximum(1.3*maxVal)
    else:
        hCR_MC.SetMaximum(100.0*maxVal)
        hSR_MC.SetMaximum(100.0*maxVal)
        hCR_MC.SetMinimum(0.1)
        hSR_MC.SetMaximum(0.1)


    ### Canvas object
    plot = Canvas.Canvas('hist_'+name, 'png', 0.7, 0.79, 0.9, 0.87)

    plot.addHisto(hCR_MC, 'P', 'Control region', 'l', r.kBlue, 1, 0)
    plot.addHisto(hSR_MC, 'P, SAME', 'Signal region', 'l', r.kRed, 1, 0)


    ### Dilepton banner
    if LLlabel == 'EE':
        plot.addLatex(0.17, 0.84, 'e^{+}e^{-} channel')
    if LLlabel == 'MM':
        plot.addLatex(0.17, 0.84, '#mu^{+}#mu^{-} channel')

    ### Save it
    #plot.save(1, 0, logx, luminosity, '')
    plot.saveRatio(1, 0, logx, luminosity, hSR_MC, hCR_MC, label="SR/CR", outputDir = 'closurePlots/')


def makeCumulativeValidation(lumi, tree, var, name, xlabel, logx, LLlabel = False):

    hSR = tree.getLoopTH1F('histMC_SR_'+name, 'SR_' + var, xlabel)
    hCR = tree.getLoopTH1F('histMC_CR_'+name, 'CR_' + var, xlabel)

    cumSR = r.TH1F('cumSR', '', hSR.GetNbinsX(), hSR.GetXaxis().GetXmin(), hSR.GetXaxis().GetXmax())
    cumCR = r.TH1F('cumCR', '', hCR.GetNbinsX(), hCR.GetXaxis().GetXmin(), hCR.GetXaxis().GetXmax())

    cumSR.GetXaxis().SetTitle('('+xlabel+')_{min}')
    cumSR.GetYaxis().SetTitle('Number of events with '+xlabel+ ' > ('+xlabel+')_{min}')
    cumCR.GetXaxis().SetTitle('('+xlabel+')_{min}')
    cumCR.GetYaxis().SetTitle('Number of events with '+xlabel+ ' > ('+xlabel+')_{min}')

    for n in range(1, hSR.GetNbinsX() + 1):
        valSR = 0.0
        errSR = 0.0
        valCR = 0.0
        errCR = 0.0
        for j in range(n, hSR.GetNbinsX() + 1):
            valSR = valSR + hSR.GetBinContent(j)
            errSR = errSR + hSR.GetBinError(j)
            valCR = valCR + hCR.GetBinContent(j)
            errCR = errCR + hCR.GetBinError(j)
        cumSR.SetBinContent(n, valSR)
        cumSR.SetBinError(n, errSR)
        cumCR.SetBinContent(n, valCR)
        cumCR.SetBinError(n, errCR)

    

    cumSR.SetMarkerStyle(20)
    cumSR.SetMarkerSize(0.8)
    cumCR.SetMarkerStyle(20)
    cumCR.SetMarkerSize(0.8)

    luminosity = lumi

    ### Get maximum
    maxValCR = cumCR.GetMaximum()
    maxValSR = cumSR.GetMaximum()
    maxVal = max(maxValCR, maxValSR)

    ### Set Maximum
    if not logx:
        cumCR.SetMaximum(1.3*maxVal)
        cumSR.SetMaximum(1.3*maxVal)
    else:
        cumCR.SetMaximum(100.0*maxVal)
        cumSR.SetMaximum(100.0*maxVal)
        cumCR.SetMinimum(0.1)
        cumSR.SetMaximum(0.1)


    ### Canvas object
    plot = Canvas.Canvas('hist_'+name, 'png', 0.7, 0.79, 0.9, 0.87, 1)

    plot.addHisto(cumCR, 'P', 'Control region', 'l', r.kBlue, 1, 0)
    plot.addHisto(cumSR, 'P, SAME', 'Signal region', 'l', r.kRed, 1, 0)


    ### Dilepton banner
    if LLlabel == 'EE':
        plot.addLatex(0.17, 0.84, 'e^{+}e^{-} channel')
    if LLlabel == 'MM':
        plot.addLatex(0.17, 0.84, '#mu^{+}#mu^{-} channel')

    ### Save it
    #plot.save(1, 0, logx, luminosity, '')
    plot.saveRatio(1, 0, logx, luminosity, cumSR, cumCR, label="SR/CR", outputDir = 'closureDATAPlots/')



if __name__ == "__main__":

    print bcolors.HEADER

                                                                                          
    print "                                 ```.....`                              "           
    print "                               `.````.-:::-.-------.                    "           
    print "                              ``      .--.`````.--://-                  "   
    print "                                   `   `        `-::://`                "    
    print "                                `os/y:           .-::/+/                "    
    print "                                yNdod+        ````-:://+`               "    
    print "                 ``-/-..------.-hNMMs`     `oy/sy.-:://+.               "    
    print "              `..------:+ss/--::/+sh.     `dNh/sN/-://+/`               "    
    print "           `.-------------------::///.    /NMMMNm::///+-                "    
    print "         `.---------------------:::://:`  -dmNNh/:///+-                 "    
    print "        `--------.---.----------:::::/+/.``-++/:-://+o+.                "    
    print "       `--------..--------------:::://++/---------:://++:               "    
    print "       .----------------------::::::/++:----------::://+o:              "    
    print "       ---------------------::::::://:---..------:::://++o`             "    
    print "      `:-------------------::::::///:----.------::::://++o.             "    
    print "      `::--------------::::::://///:-----------:::::///+++.             "    
    print "       ::::------:::::::://////////----------:::::////+++/`             "    
    print "       ./:::::::::::///////////////-------:::://////++++/-              "    
    print "        -///////////++++++++++++++/----:::///////++++++/-               "    
    print "         ./+///+++++ooooooooo+ooo+::::::///++++++++++//.                "    
    print "          `-+ooosssooooosssssso+/:::///+++++oooo+++//-`                 "    
    print "            `-+so/-.:+sssyyysso++///+oooooooooo++//-`                   "    
    print "               ``    `.:+osyyyyysssssssssssoo++++oo+:`..```             "    
    print "                         `.-:/+++oooyyysssooosso+ooosoyhyo/-.           "    
    print "                                  ``+sssssssssyyso++++/:------::        "    
    print "                                  -+oooooooooosyhy+:----.-------::      "    
    print '########################################################################' 
    print '                      Starting IFCA-LLP analysis...                     '
    print '########################################################################' + bcolors.ENDC

    parser = optparse.OptionParser(usage='usage: %prog [opts] FilenameWithSamples', version='%prog 1.0')
    parser.add_option('-i', '--input', action='store', type=str, dest='inputFile', default='launchWithGridui/merged.root', help='the input file. default \'merged.root\'')
    (opts, args) = parser.parse_args()


    ############# Set the TDR plot style
    gROOT.ProcessLine('.L include/tdrstyle.C')
    gROOT.SetBatch(1)
    r.setTDRStyle()

    ############# Datasets definition
    MuonData = []
    MuonData.append('DoubleMuon-Run2016B')
    ElectronData = []
    ElectronData.append('DoubleEG-Run2016B')

    lumi = 4.8

    ############# Tree creation
    treeMuonDATA = Sample.Tree(helper.selectSamples(WORKPATH + 'dat/DATA.dat', MuonData, 'DATA'), 'DATA', 1, WORKPATH + opts.inputFile)
    treeElectronDATA = Sample.Tree(helper.selectSamples(WORKPATH + 'dat/DATA.dat', ElectronData, 'DATA'), 'DATA', 1, WORKPATH + opts.inputFile)


    #makeBackgroundValidation(lumi, treeMC, 'EEsel_leadingPt', 'EEsel_leadingPt', 'Leading p_{T} (GeV/c)', 1, 'EE')
    #makeBackgroundValidation(lumi, treeMC, 'EEsel_subleadingPt', 'EEsel_subleadingPt', 'Subleading p_{T} (GeV/c)', 1, 'EE')
    #makeBackgroundValidation(lumi, treeMC, 'EEsel_invMass', 'EEsel_invMass', 'Mass (GeV/c^{2})', 1, 'EE')
    #makeBackgroundValidation(lumi, treeMC, 'EEsel_Chi2', 'EEsel_Chi2', 'Vertex #Chi^{2}', 1, 'EE')
    #makeBackgroundValidation(lumi, treeMC, 'EEsel_dPhi', 'EEsel_dPhi', 'Collinearity |#Delta#Phi|', 1, 'EE')
    makeCumulativeValidation(lumi, treeElectronDATA, 'SiF_EEsel_minIxy', 'SiF_EEsel_minIxy', '|d_{0}|/#sigma_{d}', 1, 'EE')
    
    #makeBackgroundValidation(lumi, treeMC, 'MMsel_leadingPt', 'MMsel_leadingPt', 'Leading p_{T} (GeV/c)', 1, 'MM')
    #makeBackgroundValidation(lumi, treeMC, 'MMsel_subleadingPt', 'MMsel_subleadingPt', 'Subleading p_{T} (GeV/c)', 1, 'MM')
    #makeBackgroundValidation(lumi, treeMC, 'MMsel_invMass', 'MMsel_invMass', 'Mass (GeV/c^{2})', 1, 'MM')
    #makeBackgroundValidation(lumi, treeMC, 'MMsel_Chi2', 'MMsel_Chi2', 'Vertex #Chi^{2}', 1, 'MM')
    #makeBackgroundValidation(lumi, treeMC, 'MMsel_dPhi', 'MMsel_dPhi', 'Collinearity |#Delta#Phi|', 1, 'MM')
    makeCumulativeValidation(lumi, treeMuonDATA, 'SiF_MMsel_minIxy', 'SiF_MMsel_minIxy', '|d_{0}|/#sigma_{d}', 1, 'MM')


