Пример #1
0
def calculation(arg):

    mode, cat, w = arg

    if mode == "2016":
        TTG = TTG_16
        lumi_scale = 35.92
    elif mode == "2017":
        TTG = TTG_17
        lumi_scale = 41.53
    elif mode == "2018":
        TTG = TTG_18
        lumi_scale = 59.74

    selCut = args.selection
    selCuts = [cutInterpreter.cutString("-".join([selCut, cat]))]

    filterCutMc = getFilterCut(int(mode),
                               isData=False,
                               skipBadChargedCandidate=True,
                               skipVertexFilter=False)
    tr = TriggerSelector(int(mode))
    triggerCutMc = tr.getSelection()
    #    tr            = TriggerSelector( int(mode), singleLepton=args.selection.count("nLepTight1") )
    #    triggerCutMc  = tr.getSelection( "MC" )

    selCuts += [triggerCutMc]
    selCuts += [filterCutMc]
    selCuts += ["pTStitching==1"]
    #    if overlapcut: selCuts += ["overlapRemoval==1"]

    preSelectionSR = "&&".join(selCuts)
    if not args.useCorrectedIsoVeto:
        preSelectionSR = preSelectionSR.replace("nLeptonVetoIsoCorr",
                                                "nLeptonVeto")

    if not "hoton" in selCut and cat != noCat_sel:
        yields[mode][cat][sel] = -1
        return

#    print TTG.getEventList( preSelectionSR ).GetN()
    yields[mode][cat][w] = TTG.getYieldFromDraw(selectionString=preSelectionSR,
                                                weightString=w.replace(
                                                    "luminosity",
                                                    str(lumi_scale)))['val']
Пример #2
0
        eventNorm = 1. / sample.normalization

from TTGammaEFT.Analysis.regions import preFiringSumJetEta
from TTGammaEFT.Analysis.regions import preFiringSumJetPtLog
from TTGammaEFT.Analysis.Region import texString

allRegions = [\
              ( preFiringSumJetEta, -5, 5 ),
              ( preFiringSumJetPtLog,  30, 1000 ),
             ]

allModes = ['all', 'mumu', 'mue', 'ee', 'SF']

selection = cutInterpreter.cutString(args.selection)
addSelection = "Jet_pt<500&&Jet_pt>30&&Jet_cleanmask&&abs(Jet_eta)<3.5"
metFilter = getFilterCut(2017, isData=True, skipBadChargedCandidate=True)

ptMinVal = 30
ptMaxVal = 1000
etaMinVal = -5
etaMaxVal = 5

variableString = "Jet_pt:Jet_eta"
ptBinning = [
    val0 for region in preFiringSumJetPtLog
    for val0, val1 in region.vals.values()
] + [ptMaxVal]
etaBinning = [
    val0 for region in preFiringSumJetEta
    for val0, val1 in region.vals.values()
] + [etaMaxVal]
Пример #3
0
    event.nHighPTPhotons = len(highPTPhotons)


# add functions to calculate your own variables here
# this is slow, use it only if needed
sequence = []  # sequenceExample ]

# MC samples need to be corrected by certain scale factors to correct e.g. detector effects. Define the "weight" here:
mcWeight = lambda event, sample: event.reweightTrigger * event.reweightL1Prefire * event.reweightPU * event.reweightLeptonTightSF * event.reweightLeptonTrackingTightSF * event.reweightPhotonSF * event.reweightPhotonElectronVetoSF * event.reweightBTag_SF
# a weight for all samples incluuding data is defined here
weight = lambda event, sample: event.weight

# get some additional cuts specific for MC and/or data
# MET Filter cut for data and MC
filterCutData = getFilterCut(args.year,
                             isData=True,
                             skipBadChargedCandidate=True)
filterCutMc = getFilterCut(args.year,
                           isData=False,
                           skipBadChargedCandidate=True)
# Trigger cuts for MC (already applied for Data)

# Sample definition
mc = [
    mc_samples.TTG, mc_samples.Top, mc_samples.DY_LO, mc_samples.WJets,
    mc_samples.WG_NLO, mc_samples.ZG, mc_samples.rest
]

if args.noData:
    # Scale the histograms by the luminosity taken by CMS in each year
    if args.year == 2016: lumi_scale = 35.92
cache_dir = os.path.join(cache_directory, "drawHistos", "all", args.selection, args.mode)
dirDB = MergingDirDB(cache_dir)
if not dirDB: raise

# Sample definition
os.environ["gammaSkim"]="False" #always false for QCD estimat
from TTGammaEFT.Samples.nanoTuples_Run2016_14Dec2018_semilep_postProcessed import *
data2016 = Run2016
from TTGammaEFT.Samples.nanoTuples_Run2017_14Dec2018_semilep_postProcessed import *
data2017 = Run2017
from TTGammaEFT.Samples.nanoTuples_Run2018_14Dec2018_semilep_postProcessed import *
data2018 = Run2018

lumi_scale   = (data2016.lumi + data2017.lumi + data2018.lumi) * 0.001

filterCutData = getFilterCut( 2016, isData=True,  skipBadChargedCandidate=True )
data2016.setSelectionString( [filterCutData, "reweightHEM>0", cutInterpreter.cutString( args.mode )] )
data2016.setWeightString( "weight" )

filterCutData = getFilterCut( 2017, isData=True,  skipBadChargedCandidate=True )
data2017.setSelectionString( [filterCutData, "reweightHEM>0", cutInterpreter.cutString( args.mode )] )
data2017.setWeightString( "weight" )

filterCutData = getFilterCut( 2018, isData=True,  skipBadChargedCandidate=True )
data2018.setSelectionString( [filterCutData, "reweightHEM>0", cutInterpreter.cutString( args.mode )] )
data2018.setWeightString( "weight" )

setup = Setup( year=2016, photonSelection=False, checkOnly=False, runOnLxPlus=False ) #photonselection always false for qcd estimate
setup = setup.sysClone( parameters=allRegions[args.selection]["parameters"] )

selection = setup.selection( "MC", channel="all", **setup.defaultParameters() )["prefix"]
Пример #5
0
def calculation(arg):

    mode, cat, sel = arg

    TTG = TTG_16
    #    if   mode == "2016": TTG = TTG_16
    #    elif mode == "2017": TTG = TTG_17
    #    elif mode == "2018": TTG = TTG_18

    triggercut = False
    filtercut = False
    overlapcut = False

    selCut = sel
    if selCut == "entries":
        weight = "1"
        selCut = "all"
#    elif selCut == "genweight*lumi":
#        weight = "%f*weight"%lumi_scale
#        selCut = "all"
#    elif selCut == "genweight*lumi*SF":
#        weight = weightString
#        selCut = "all"
    else:
        weight = weightString
    if "triggerCut" in selCut:
        selCut = selCut.replace("triggerCut", "")
        triggercut = True
    if "METfilter" in selCut:
        selCut = selCut.replace("METfilter", "")
        filtercut = True
    if "overlapRemoval" in selCut:
        selCut = selCut.replace("overlapRemoval", "")
        overlapcut = True
    selCut = "-".join([cut for cut in selCut.split("-") if cut])

    if not selCut: selCut = "all"
    #print("Calcuating yield for mode %s and category %s and selection %s"%(mode,cat,sel))

    selCuts = [cutInterpreter.cutString("-".join([selCut, cat]))]

    filterCutMc = getFilterCut(int(mode),
                               isData=False,
                               skipBadChargedCandidate=True,
                               skipVertexFilter=False)
    tr = TriggerSelector(int(mode))
    triggerCutMc = tr.getSelection()
    #    tr            = TriggerSelector( int(mode), singleLepton=True )
    #    triggerCutMc  = tr.getSelection( "MC" )

    if triggercut: selCuts += [triggerCutMc]
    if filtercut: selCuts += [filterCutMc]
    if overlapcut: selCuts += ["overlapRemoval==1"]
    selCuts += ["pTStitching==1"]

    preSelectionSR = "&&".join(selCuts)
    #    if not args.useCorrectedIsoVeto: preSelectionSR = preSelectionSR.replace("nLeptonVetoIsoCorr","nLeptonVeto")

    if mode != "2016" or (not "hoton" in selCut and cat != noCat_sel):
        yields[mode][cat][sel] = -1
        return

    print TTG.getEventList(preSelectionSR).GetN()
    yields[mode][cat][sel] = TTG.getEventList(
        selectionString=preSelectionSR
    ).GetN(
    )  #int(round(TTG.getYieldFromDraw( selectionString=preSelectionSR, weightString=weight )['val']))
Пример #6
0
        mode=args.mode,
        isoDiscriminator=args.isoDiscriminator,
        upper=pt_upper,
        lower=pt_lower)

    if eventSelection != "(1)":
        eventSelection += "&&" + pt_str
        selectionName += "-pt{}To{}".format(pt_lower, pt_upper)
    else:
        eventSelection = pt_str
        selectionName = "pt{}To{}".format(pt_lower, pt_upper)

logger.info("selection %s -> %s", selectionName, eventSelection)

data_selectionString = "&&".join([
    getFilterCut(isData=True, year=year), triggerSelection, leptonSelection,
    jetSelection, eventSelection
])
data_sample.setSelectionString(data_selectionString)
mc_selectionString = "&&".join([
    getFilterCut(isData=False, year=year), triggerSelection, leptonSelection,
    jetSelection, eventSelection
])
for s in mc:
    s.setSelectionString(mc_selectionString)

#lumi_scale                 = data_sample.lumi/1000
data_sample.scale = 1.
mc[0].weight = qcd_prescale_x_nvtx_puRW
for sample in mc[1:]:
    sample.weight = ewk_prescale_x_nvtx_puRW
Пример #7
0
tex.SetNDC()
tex.SetTextSize(0.04)
tex.SetTextAlign(11) # align right

# fire up the cache
cache_dir_ = os.path.join(cache_dir, 'fake_pu_cache')
dirDB      = DirDB(cache_dir_)

pu_key = ( triggerSelection, leptonSelection, jetSelection, args.era, args.small)
if dirDB.contains( pu_key ) and not args.overwrite:
    reweight_histo = dirDB.get( pu_key )
    logger.info( "Found PU reweight in cache %s", cache_dir_ )
else:
    logger.info( "Didn't find PU reweight histo %r. Obtaining it now.", pu_key)

    data_selectionString = "&&".join([getFilterCut(isData=True, year=year), triggerSelection, leptonSelection, jetSelection])
    data_nvtx_histo = data_sample.get1DHistoFromDraw( "PV_npvsGood", [100, 0, 100], selectionString=data_selectionString, weightString = "weight" )
    data_nvtx_histo.Scale(1./data_nvtx_histo.Integral())

    mc_selectionString = "&&".join([getFilterCut(isData=False, year=year), triggerSelection, leptonSelection, jetSelection])
    mc_histos  = [ s.get1DHistoFromDraw( "PV_npvsGood", [100, 0, 100], selectionString=mc_selectionString, weightString = "weight*reweightBTag_SF") for s in mc]
    mc_histo     = mc_histos[0]
    for h in mc_histos[1:]:
        mc_histo.Add( h )

    mc_histo.Scale(1./mc_histo.Integral())

    reweight_histo = data_nvtx_histo.Clone()
    reweight_histo.Divide(mc_histo)
    
    dirDB.add( pu_key, reweight_histo ) 
Пример #8
0
else:
    raise Exception("Region not implemented")

lumiString = "(35.92*(year==2016)+41.53*(year==2017)+59.74*(year==2018))"
ws = "(%s*weight*reweightHEM*reweightTrigger*reweightL1Prefire*reweightPU*reweightLeptonTightSF*reweightLeptonTrackingTightSF*reweightPhotonSF*reweightPhotonElectronVetoSF*reweightBTag_SF)" % lumiString
ws16 = "+(%s*(PhotonNoChgIsoNoSieie0_photonCatMagic==2)*(%f-1)*(year==2016))" % (
    ws, misIDSF_val[2016].val)
ws17 = "+(%s*(PhotonNoChgIsoNoSieie0_photonCatMagic==2)*(%f-1)*(year==2017))" % (
    ws, misIDSF_val[2017].val)
ws18 = "+(%s*(PhotonNoChgIsoNoSieie0_photonCatMagic==2)*(%f-1)*(year==2018))" % (
    ws, misIDSF_val[2018].val)

weightString = ws  # ws16 + ws17 +ws18

filterCutMc = getFilterCut(
    args.year, isData=False,
    skipBadChargedCandidate=True)  #, skipVertexFilter=True )

sample0b = copy.deepcopy(sample)
sample1b = copy.deepcopy(sample)
sample2pb = copy.deepcopy(sample)

sample0b.setSelectionString(
    [filterCutMc, "pTStitching==1", "overlapRemoval==1", "nGenBJet==0"])
sample0b.setWeightString(weightString)

sample1b.setSelectionString(
    [filterCutMc, "pTStitching==1", "overlapRemoval==1", "nGenBJet==1"])
sample1b.setWeightString(weightString)

sample2pb.setSelectionString(
Пример #9
0
if args.noData:
    if args.year == 2016:   lumi_scale = 35.92
    elif args.year == 2017: lumi_scale = 41.86
    elif args.year == 2018: lumi_scale = 58.83
    allSamples = mc
else:
    if args.year == 2016:   data_sample = Run2016
    elif args.year == 2017: data_sample = Run2017
    elif args.year == 2018: data_sample = Run2018
    data_sample.texName        = "data (legacy)"
    data_sample.name           = "data"
    data_sample.style          = styles.errorStyle( ROOT.kBlack )
    lumi_scale                 = data_sample.lumi * 0.001
    data_sample.setWeightString("weight")
    data_sample.setSelectionString( [ getFilterCut( args.year, isData=True ), cutInterpreter.cutString( args.selection ) ] )
    allSamples = [data_sample] + mc

w         = WeightInfo( signalSample.reweight_pkl )
w.set_order( int(args.order) )
variables = w.variables

tr = TriggerSelector( args.year, singleLepton=True )

signals = []
# Sample definition
for i, param in enumerate( params ):
    sample                = copy.deepcopy( signalSample )
    sample.params         = param
    if param["legendText"] == "tt#gamma":
        sample.style = styles.fillStyle( ttGammaSample.color )
Пример #10
0
    yield_fid = 0
    yield_fid_reco = 0

    for i_year, year in enumerate(settings.years):
        setup = Setup(year=int(year),
                      photonSelection=False,
                      checkOnly=True,
                      runOnLxPlus=False)
        setup = setup.sysClone(
            parameters=allRegions[settings.reco_selection]["parameters"])
        # reco selection
        reco_selection = setup.selection("MC",
                                         channel="all",
                                         **setup.defaultParameters())

        MET_filter_cut = "(year==%s&&" % year + getFilterCut(
            isData=False, year=int(year), skipBadChargedCandidate=True) + ")"
        reco_selection_str = MET_filter_cut + "&&triggered&&pTStitching==1&&overlapRemoval==1&&" + cutInterpreter.cutString(
            reco_selection['prefix'])

        # fiducial seletion
        fiducial_selection_str = cutInterpreter.cutString(
            settings.fiducial_selection
        ) + "&&pTStitching==1&&overlapRemoval==1"

        ttreeFormulas = {
            'is_fiducial':
            fiducial_selection_str,
            'is_reco':
            reco_selection_str,
            'gen_weight':
            'weight*(35.92*(year==2016)+41.53*(year==2017)+59.74*(year==2018))',
Пример #11
0

for regions, minval, maxval in allRegions:

    Nbins = len(regions)
    rate = {}

    for index, mode in enumerate( allModes ):

        hists = {}
        for sample in allSamples:
            hists[sample.name] = ROOT.TH1F(sample.name+mode,"", Nbins, minval, maxval)

        # Define 2l selections
        leptonSelection = cutInterpreter.cutString( mode )
        totalSelection  = [ getFilterCut( 2017, isData=True, skipBadChargedCandidate=True ),  leptonSelection, selection, addSelection ]
    
        Run2017_noPreFiring.setSelectionString( totalSelection + [ "unPreFirableEvent==1"] )
        Run2017.setSelectionString( totalSelection )

        for i_region, region in enumerate(regions):
            # compute signal yield for this region (this is the final code)

            logger.info( "At region %s", region )
            logger.info( "Using region cut-string %s", region.cutString() )

            rate[region] = {}

            for i_sample, sample in enumerate( allSamples ):
                eventList = sample.getEventList( selectionString=region.cutString() )
                rate[region][sample.name] = eventList.GetN() * eventNorm
Пример #12
0
]

evtList = True

#from TTGammaEFT.Samples.nanoTuples_Sync_semilep_postProcessed      import TTG_sync_16 # as sample
#from TTGammaEFT.Samples.nanoTuples_Sync_semilep_postProcessed      import WJets_sync_16 # as sample
#from TTGammaEFT.Samples.nanoTuples_Sync_semilep_postProcessed      import QCD_e_sync_16 # as sample
#from TTGammaEFT.Samples.nanoTuples_Sync_semilep_postProcessed      import QCD_mu_sync_16 # as sample

#from TTGammaEFT.Samples.nanoTuples_Fall17_private_semilep_postProcessed import QCD_mu80To120, QCD_e80To120
from TTGammaEFT.Samples.nanoTuples_Autumn18_private_semilep_postProcessed import QCD_mu80To120, QCD_e80To120

#allsamples = [QCD_mu_sync_16, QCD_e_sync_16, TTG_sync_16, WJets_sync_16]
allsamples = [QCD_mu80To120]
filterCutMc = getFilterCut(2016,
                           isData=False,
                           skipBadChargedCandidate=True,
                           skipVertexFilter=False)

if not evtList:
    #  for mode in ["e","mu"]:
    for nj in [">=4", "==3", "==2"]:
        lumi = 1

        mode = "mu"
        weightStrings = ["1"]
        #    weightStrings  += ["weight"]
        #    weightStrings  += ["weight*reweightPU"]
        #    weightStrings  += ["weight*reweightPU*reweightLeptonTightSF*reweightLeptonTrackingTightSF"]
        #    weightStrings  += ["weight*reweightPU*reweightLeptonTightSF*reweightLeptonTrackingTightSF*reweightBTag_SF"]
        #    weightStrings  += ["weight*reweightPU*reweightLeptonTightSF*reweightLeptonTrackingTightSF*reweightBTag_SF*reweightL1Prefire"]
Пример #13
0
if args.noData:
    if args.year == 2016: lumi_scale = 35.92
    elif args.year == 2017: lumi_scale = 41.86
    elif args.year == 2018: lumi_scale = 58.83
    allSamples = mc
else:
    if args.year == 2016: data_sample = Run2016
    elif args.year == 2017: data_sample = Run2017
    elif args.year == 2018: data_sample = Run2018
    data_sample.texName = "data (legacy)"
    data_sample.name = "data"
    data_sample.style = styles.errorStyle(ROOT.kBlack)
    lumi_scale = data_sample.lumi * 0.001
    data_sample.setWeightString("weight")
    data_sample.setSelectionString([
        getFilterCut(args.year, isData=True),
        cutInterpreter.cutString(args.selection)
    ])
    allSamples = [data_sample] + mc

tr = TriggerSelector(args.year)

for sample in mc:
    sample.style = styles.fillStyle(sample.color)
    sample.setWeightString(
        "weight*%f*reweightDilepTriggerBackup*reweightPU*reweightLeptonSF*reweightLeptonTrackingSF*reweightPhotonSF*reweightPhotonElectronVetoSF*reweightBTag_SF"
        % lumi_scale)
    sample.setSelectionString([
        getFilterCut(args.year, isData=False),
        tr.getSelection("MC"),
        cutInterpreter.cutString(args.selection)
Пример #14
0
isMC   =  True not in [s.isData for s in samples]

# Check that all samples which are concatenated have the same x-section.
assert isData or len(set([s.xSection for s in samples]))==1, "Not all samples have the same xSection: %s !"%(",".join([s.name for s in samples]))
assert isMC or len(samples)==1, "Don't concatenate data samples"

xSection = samples[0].xSection if isMC else None

L1PW = L1PrefireWeight(options.year)

treeFormulas = {"triggerDecision": {'string':triggerCond} }
logger.info("Sample will have the following trigger skim: %s"%triggerCond)
skimConds.append( triggerCond )

# apply MET filter
skimConds.append( getFilterCut(options.year, isData=isData, ignoreJSON=True, skipWeight=True) )

isr                 = ISRweight()

#Samples: combine if more than one
if len(samples)>1:
    sample_name =  samples[0].name+"_comb"
    logger.info( "Combining samples %s to %s.", ",".join(s.name for s in samples), sample_name )
    sample      = Sample.combine(sample_name, samples, maxN = maxNfiles)
    sampleForPU = Sample.combine(sample_name, samples, maxN = -1)
elif len(samples)==1:
    sample      = samples[0]
    sampleForPU = samples[0]
    if options.small:
        sample.reduceFiles( to = maxNfiles )
else:
Пример #15
0
    def selection(self,
                  dataMC,
                  dileptonic=None,
                  invertLepIso=None,
                  addMisIDSF=None,
                  nJet=None,
                  nBTag=None,
                  nPhoton=None,
                  MET=None,
                  zWindow=None,
                  m3Window=None,
                  leptonEta=None,
                  leptonPt=None,
                  photonIso=None,
                  processCut=None,
                  channel="all"):
        """Define full selection
           dataMC: "Data" or "MC" or "MCptincl
           channel: all, e or mu, eetight, mumutight, SFtight
           zWindow: offZeg, onZeg, onZSFllTight, onZSFllgTight, onZSFlloffZSFllg or all
           m3Window: offM3, onM3 or all
           photonIso: highSieie, highChgIso, highChgIsohighSieie
        """
        if not dileptonic: dileptonic = self.parameters["dileptonic"]
        if not invertLepIso: invertLepIso = self.parameters["invertLepIso"]
        if not addMisIDSF: addMisIDSF = self.parameters["addMisIDSF"]
        if not nJet: nJet = self.parameters["nJet"]
        if not nBTag: nBTag = self.parameters["nBTag"]
        if not nPhoton: nPhoton = self.parameters["nPhoton"]
        if not MET: MET = self.parameters["MET"]
        if not zWindow: zWindow = self.parameters["zWindow"]
        if not leptonEta: leptonEta = self.parameters["leptonEta"]
        if not leptonPt: leptonPt = self.parameters["leptonPt"]
        if not m3Window: m3Window = self.parameters["m3Window"]
        if not photonIso: photonIso = self.parameters["photonIso"]

        #Consistency checks
        assert dataMC in ["Data", "MC", "DataMC", "MCpTincl"
                          ], "dataMC = Data or MC or DataMC, got %r." % dataMC
        assert channel in allChannels, "channel must be one of " + ",".join(
            allChannels) + ". Got %r." % channel
        assert zWindow in [
            "offZeg", "onZeg", "onZSFllTight", "onZSFllgTight",
            "onZSFlloffZSFllg", "all"
        ], "zWindow must be one of onZeg, offZeg, onZSFllTight, onZSFllgTight, all. Got %r" % zWindow
        assert m3Window in [
            "offM3", "onM3", "all"
        ], "m3Window must be one of onM3, offM3, all. Got %r" % m3Window
        assert photonIso in [
            None, "highSieieNoChgIso", "lowSieieNoChgIso", "noSieie",
            "highSieie", "lowChgIsoNoSieie", "highChgIsoNoSieie", "noChgIso",
            "highChgIso", "noChgIsoNoSieie", "highChgIsohighSieie"
        ], "PhotonIso must be one of highSieie, highChgIso, highChgIsohighSieie. Got %r" % photonIso
        assert processCut in [
            None, "cat0", "cat1", "cat2", "cat3", "cat13", "cat02", "cat134",
            "cat4"
        ], "Process specific cut must be one of cat0, cat2, cat13, cat4. Got %r" % processCut
        if self.sys['selectionModifier']:
            assert self.sys[
                'selectionModifier'] in jmeVariations + metVariations + eVariations + muVariations, "Don't know about systematic variation %r, take one of %s" % (
                    self.sys['selectionModifier'],
                    ",".join(jmeVariations + metVariations + eVariations +
                             muVariations))

        res = {"cuts": [], "prefixes": []}

        # default lepton selections
        tightLepton = "nLepTight1"
        vetoLepton = "nLepVeto1"
        #        vetoLepton   = "nLepNoCorrVeto1"
        jetCutVar = "nJetGood"
        jetPrefix = "nJet"
        btagCutVar = "nBTagGood"
        btagPrefix = "nBTag"
        photonCutVar = "nPhotonGood"
        photonPrefix = "nPhoton"
        photonCatVar = "PhotonGood0_photonCatMagic"
        photonCatPrefix = "photoncat"
        photonVetoCutVar = "nPhotonNoChgIsoNoSieie"
        photonVetoPrefix = "nHadPhoton"
        #        photonVetoCutVar = None
        #        photonVetoPrefix = None
        if channel in ["e", "eetight"]:
            leptonEtaCutVar = "abs(LeptonTight0_eta+LeptonTight0_deltaEtaSC)"
            leptonEtaPrefix = "etascl"
        else:
            leptonEtaCutVar = "abs(LeptonTight0_eta)"
            leptonEtaPrefix = "etal"

        leptonPtCutVar = "LeptonTight0_pt"
        leptonPtPrefix = "ptl"

        if dileptonic:
            tightLepton = "nLepTight2-OStight"
            vetoLepton = "nLepVeto2"

        if photonIso:
            zWindow += "SB"

        if invertLepIso:
            # invert leptonIso in lepton cuts
            channel += "Inv"
            zWindow += "Inv"
            tightLepton = "nInvLepTight1"
            vetoLepton = "nLepVeto1"
            #            vetoLepton   = "nLepNoCorrVeto1"
            jetCutVar = "nJetGoodInvLepIso"
            jetPrefix = "nInvLJet"
            btagCutVar = "nBTagGoodInvLepIso"
            btagPrefix = "nInvLBTag"
            photonCutVar = "nPhotonGoodInvLepIso"
            photonPrefix = "nInvLPhoton"
            photonCatVar = "PhotonGoodInvLepIso0_photonCatMagic"
            photonCatPrefix = "invLphotoncat"
            #            photonVetoCutVar = None
            #            photonVetoPrefix = None
            photonVetoCutVar = "nPhotonNoChgIsoNoSieieInvLepIso"
            photonVetoPrefix = "nInvLHadPhoton"
            if channel in ["eInv", "eetightInv"]:
                leptonEtaCutVar = "abs(LeptonTightInvIso0_eta+LeptonTightInvIso0_deltaEtaSC)"
                leptonEtaPrefix = "etainvscl"
            else:
                leptonEtaCutVar = "abs(LeptonTightInvIso0_eta)"
                leptonEtaPrefix = "etainvl"

            leptonPtCutVar = "LeptonTightInvIso0_pt"
            leptonPtPrefix = "ptinvl"

        #photon cut
        photonSel = nPhoton and not (nPhoton[0] == 0 and nPhoton[1] <= 0)

        if photonSel and photonIso:

            if invertLepIso:
                jetCutVar = "nJetGoodNoChgIsoNoSieieInvLepIso"
                jetPrefix = "nInvLNoChgIsoNoSieieJet"
                btagCutVar = "nBTagGoodNoChgIsoNoSieieInvLepIso"
                btagPrefix = "nInvLNoChgIsoNoSieieBTag"
                photonCutVar = "nPhotonNoChgIsoNoSieieInvLepIso"
                photonPrefix = "nInvLHadPhoton"
                photonVetoCutVar = "nPhotonNoChgIsoNoSieieInvLepIso"
                photonVetoPrefix = "nInvLHadPhoton"
                photonCatVar = "PhotonNoChgIsoNoSieieInvLepIso0_photonCatMagic"
                photonCatPrefix = "invLNoChgIsoNoSieiephotoncat"
                photonIso += "InvL"

            else:
                jetCutVar = "nJetGoodNoChgIsoNoSieie"
                jetPrefix = "nNoChgIsoNoSieieJet"
                btagCutVar = "nBTagGoodNoChgIsoNoSieie"
                btagPrefix = "nNoChgIsoNoSieieBTag"
                photonCutVar = "nPhotonNoChgIsoNoSieie"
                photonPrefix = "nHadPhoton"
                photonVetoCutVar = "nPhotonNoChgIsoNoSieie"
                photonVetoPrefix = "nHadPhoton"
                photonCatVar = "PhotonNoChgIsoNoSieie0_photonCatMagic"
                photonCatPrefix = "noChgIsoNoSieiephotoncat"

        if not photonSel and not dileptonic:
            # remove default zwindow cut in qcd estimation for non photon regions
            zWindow = "all"

        #Postfix for variables (only for MC and if we have a jme variation)
        jSysStr = ""
        if (
                dataMC == "MC" or dataMC == "MCpTincl"
        ) and self.sys['selectionModifier'] in jmeVariations + metVariations:
            jSysStr = "_" + self.sys['selectionModifier']
        pSysStr = ""
        lSysStr = ""
        isEVar = False
        isMuVar = False
        if (dataMC == "MC" or dataMC == "MCpTincl"
            ) and self.sys['selectionModifier'] in muVariations:
            lSysStr = "_" + self.sys['selectionModifier']
            #            leptonPtCutVar += "_totalUp" if "up" in self.sys['selectionModifier'].lower() else "_totalDown"
            isMuVar = True
        if (dataMC == "MC" or dataMC == "MCpTincl"
            ) and self.sys['selectionModifier'] in eVariations:
            lSysStr = "_" + self.sys['selectionModifier']
            pSysStr = "_" + self.sys['selectionModifier']
            isEVar = True
#            leptonPtCutVar += "_totalUp" if "up" in self.sys['selectionModifier'].lower() else "_totalDown"

        if photonSel and photonIso:

            res["prefixes"].append(photonIso)
            preselphotonIso = cutInterpreter.cutString(photonIso)
            if dataMC == "MC":
                res["cuts"].append(
                    preselphotonIso.replace("0_", "0" + pSysStr + "_"))
            else:
                res["cuts"].append(preselphotonIso)

        #leptons or inv. iso leptons
        res["prefixes"].append(tightLepton)
        lepSel = cutInterpreter.cutString(tightLepton)
        if lSysStr: lepSel = lepSel.replace("==", "%s==" % lSysStr)
        res["cuts"].append(lepSel)

        #lepton channel or inv. iso lepton channel
        res["prefixes"].append(channel)
        chStr = cutInterpreter.cutString(channel)
        if lSysStr and ((channel in ["e", "eetight"] and isEVar) or
                        (channel in ["mu", "mumutight"] and isMuVar)):
            chStr = chStr.replace("==", "%s==" % lSysStr)
        res["cuts"].append(chStr)

        #lepton veto or no Iso lepton veto
        res["prefixes"].append(vetoLepton)
        chVetoStr = cutInterpreter.cutString(vetoLepton)
        if lSysStr: chVetoStr = chVetoStr.replace("==", "%s==" % lSysStr)
        res["cuts"].append(chVetoStr)

        if nJet and not (nJet[0] == 0 and nJet[1] < 0):
            assert nJet[0] >= 0 and (nJet[1] >= nJet[0] or nJet[1] < 0
                                     ), "Not a good nJet selection: %r" % nJet
            njetsstr = jetCutVar + jSysStr + ">=" + str(nJet[0])
            prefix = jetPrefix + str(nJet[0])
            if nJet[1] >= 0:
                njetsstr += "&&" + jetCutVar + jSysStr + "<=" + str(nJet[1])
                if nJet[1] != nJet[0]: prefix += "To" + str(nJet[1])
            else:
                prefix += "p"
            res["cuts"].append(njetsstr)
            res["prefixes"].append(prefix)

        if nBTag and not (nBTag[0] == 0 and nBTag[1] < 0):
            assert nBTag[0] >= 0 and (
                nBTag[1] >= nBTag[0]
                or nBTag[1] < 0), "Not a good nBTag selection: %r" % nBTag
            if jSysStr: nbtstr = btagCutVar + jSysStr + ">=" + str(nBTag[0])
            else: nbtstr = btagCutVar + jSysStr + ">=" + str(nBTag[0])
            prefix = btagPrefix + str(nBTag[0])
            if nBTag[1] >= 0:
                if jSysStr:
                    nbtstr += "&&" + btagCutVar + jSysStr + "<=" + str(
                        nBTag[1])
                else:
                    nbtstr += "&&" + btagCutVar + jSysStr + "<=" + str(
                        nBTag[1])
                if nBTag[1] != nBTag[0]: prefix += "To" + str(nBTag[1])
            else:
                prefix += "p"
            res["cuts"].append(nbtstr)
            res["prefixes"].append(prefix)

        if photonSel:
            #photon cut
            assert nPhoton[0] >= 0 and (
                nPhoton[1] >= nPhoton[0] or
                nPhoton[1] < 0), "Not a good nPhoton selection: %r" % nPhoton
            nphotonsstr = photonCutVar + pSysStr + ">=" + str(nPhoton[0])
            prefix = photonPrefix + str(nPhoton[0])
            if nPhoton[1] >= 0:
                nphotonsstr += "&&" + photonCutVar + pSysStr + "<=" + str(
                    nPhoton[1])
                if nPhoton[1] != nPhoton[0]: prefix += "To" + str(nPhoton[1])
            else:
                prefix += "p"
            res["cuts"].append(nphotonsstr)
            res["prefixes"].append(prefix)

            if photonVetoCutVar:
                nphotonVetosstr = photonVetoCutVar + pSysStr + ">=" + str(
                    nPhoton[0])
                prefix = photonVetoPrefix + str(nPhoton[0])
                if nPhoton[1] >= 0:
                    nphotonVetosstr += "&&" + photonVetoCutVar + pSysStr + "<=" + str(
                        nPhoton[1])
                    if nPhoton[1] != nPhoton[0]:
                        prefix += "To" + str(nPhoton[1])
                else:
                    prefix += "p"
                res["cuts"].append(nphotonVetosstr)
                res["prefixes"].append(prefix)

        else:
            addMisIDSF = False
            res["cuts"].append(photonCutVar + pSysStr + "==0")
            res["prefixes"].append(photonPrefix + "0")
            if photonVetoCutVar:
                res["cuts"].append(photonVetoCutVar + pSysStr + "==0")
                res["prefixes"].append(photonVetoPrefix + "0")

        #leptonEta cut
        if leptonEta and not (leptonEta[0] == 0 and leptonEta[1] < 0):
            assert leptonEta[0] >= 0 and (
                leptonEta[1] >= leptonEta[0]
                or leptonEta[1] < 0) and leptonEta[1] != leptonEta[
                    0], "Not a good leptonEta selection: %r" % leptonEta
            leptonEtastr = leptonEtaCutVar + ">=" + str(leptonEta[0])
            prefix = leptonEtaPrefix + str(leptonEta[0])
            if leptonEta[1] >= 0:
                leptonEtastr += "&&" + leptonEtaCutVar + "<" + str(
                    leptonEta[1])
                prefix += "To" + str(leptonEta[1])
            res["cuts"].append(leptonEtastr)
            res["prefixes"].append(prefix)

        #leptonPt cut
        if leptonPt and not (leptonPt[0] == 0 and leptonPt[1] < 0):
            assert leptonPt[0] >= 0 and (
                leptonPt[1] >= leptonPt[0]
                or leptonPt[1] < 0) and leptonPt[1] != leptonPt[
                    0], "Not a good leptonPt selection: %r" % leptonPt
            leptonPtstr = leptonPtCutVar + ">=" + str(leptonPt[0])
            prefix = leptonPtPrefix + str(leptonPt[0])
            if leptonPt[1] >= 0:
                leptonPtstr += "&&" + leptonPtCutVar + "<" + str(leptonPt[1])
                prefix += "To" + str(leptonPt[1])
            res["cuts"].append(leptonPtstr)
            res["prefixes"].append(prefix)

        #MET cut
        if MET and not (MET[0] == 0 and MET[1] < 0):
            assert MET[0] >= 0 and (MET[1] >= MET[0] or MET[1] < 0
                                    ), "Not a good MET selection: %r" % MET
            metsstr = "MET_pt" + jSysStr + ">=" + str(MET[0])
            prefix = "met" + str(MET[0])
            if MET[1] >= 0:
                metsstr += "&&" + "MET_pt" + jSysStr + "<" + str(MET[1])
                if MET[1] != MET[0]: prefix += "To" + str(MET[1])
            res["cuts"].append(metsstr)
            res["prefixes"].append(prefix)

        #Z window
        if not "all" in zWindow:
            res["prefixes"].append(zWindow)
            preselZWindow = cutInterpreter.cutString(zWindow)
            if pSysStr:
                for s in systematicReplacements[self.sys['selectionModifier']]:
                    if s in preselZWindow:
                        preselZWindow = preselZWindow.replace(s, s + pSysStr)
            res["cuts"].append(preselZWindow)

        #M3 window
        if m3Window != "all":
            res["prefixes"].append(m3Window)
            preselM3Window = cutInterpreter.cutString(m3Window)
            res["cuts"].append(preselM3Window)

        if processCut:
            catPrefix = photonCatPrefix + processCut.replace("cat", "")
            res["prefixes"].append(catPrefix)
            catCut = cutInterpreter.cutString(catPrefix)
            res["cuts"].append(catCut.replace("0_", "0" + pSysStr + "_"))

        #badEEVeto


#        if self.year == 2017:
#            res["prefixes"].append("BadEEJetVeto")
#            badEEStr = cutInterpreter.cutString( "BadEEJetVeto" )
#            res["cuts"].append( badEEStr )

        if invertLepIso:
            res["cuts"].append("triggeredInvIso==1")
        elif lSysStr:
            res["cuts"].append("triggered" + lSysStr + "==1")
        else:
            res["cuts"].append("triggered==1")

        res["cuts"].append("reweightHEM>0")

        if dataMC == "MC":
            res["cuts"].append("overlapRemoval==1")
            res["cuts"].append("pTStitching==1")

        if dataMC == "MCpTincl":
            res["cuts"].append("overlapRemoval==1")

        if dataMC != "DataMC":
            res["cuts"].append(
                getFilterCut(isData=(dataMC == "Data"),
                             year=self.year,
                             skipBadChargedCandidate=True))
            res["cuts"].extend(self.externalCuts)

        catVar = photonCatVar.split("0")[0] + "0"
        if pSysStr: catVar += pSysStr
        return {
            "cut":
            "&&".join(res["cuts"]),
            "prefix":
            "-".join(res["prefixes"]),
            "weightStr":
            self.weightString(dataMC,
                              photon=catVar if addMisIDSF else None,
                              addMisIDSF=addMisIDSF and self.isPhotonSelection)
        }