예제 #1
0
    def addSig(self, *args, **kwd):
        if len(args) > 2:
            args = args[0:2] + (allsamples.getmany(args[2]),) + args[3:]
        elif 'samples' in kwd:
            kwd['samples'] = allsamples.getmany(kwd['samples'])

        self.sigGroups.append(GroupSpec(*args, **kwd))
예제 #2
0
파일: plotutil.py 프로젝트: MiT-HEP/MonoX
    def addBkg(self, *args, **kwd):
        if len(args) > 2:
            args = args[0:2] + allsamples.getmany(args[2]) + args[3:]
        elif 'samples' in kwd:
            kwd['samples'] = allsamples.getmany(kwd['samples'])

        if len(args) < 4 and 'region' not in kwd:
            kwd['region'] = self.obs.region

        self.bkgGroups.append(GroupSpec(*args, **kwd))
예제 #3
0
 def addBkg(self, *args, **kwd):
     if len(args) > 2:
         args = args[0:2] + allsamples.getmany(args[2]) + args[3:]
     elif 'samples' in kwd:
         if type(kwd['samples'][0]) == tuple:
             kwd['samples'] = [ allsamples.get(sname) for (sname, _) in kwd['samples'] ]
         else:
             kwd['samples'] = allsamples.getmany(kwd['samples'])
         
     self.bkgGroups.append(GroupSpec(*args, **kwd))
예제 #4
0
파일: plotutil.py 프로젝트: yiiyama/MonoX
 def __init__(self, name, obsSamples = []):
     self.name = name # name serves as the default region selection (e.g. monoph)
     self.baseline = '1'
     self.fullSelection = ''
     self.obs = GroupSpec('data_obs', 'Observed', samples = allsamples.getmany(obsSamples))
     self.prescales = dict([(s, 1) for s in self.obs.samples])
     self.sigGroups = []
     self.signalPoints = []
     self.bkgGroups = []
     self.plots = []
     self.treeMaker = ''
예제 #5
0
파일: ssw2.py 프로젝트: blallen/MitMonoX
def processSampleNames(_inputNames, _selectorKeys, _plotConfig = ''):
    snames = []

    if _plotConfig:
        # if a plot config is specified, use the samples for that
        snames = plotconfig.getConfig(_plotConfig).samples()

    else:
        snames = _inputNames

    # handle special group names
    if 'all' in snames:
        snames.remove('all')
        snames = _selectorKeys
    if 'data16' in snames:
        snames.remove('data16')
        snames += [key for key in _selectorKeys if '16' in key and allsamples[key].data]
    if 'bkgd' in snames:
        snames.remove('bkgd')
        snames += [key for key in _selectorKeys if not allsamples[key].data and not key.startswith('dm') and not key.startswith('add') and not key.endswith('-d')]
    if 'dmfs' in snames:
        snames.remove('dmfs')
        snames += [key for key in _selectorKeys if key.startswith('dm') and key[3:5] == 'fs']
    if 'dm' in snames:
        snames.remove('dm')
        snames += [key for key in _selectorKeys if key.startswith('dm') and not key[3:5] == 'fs']
    if 'add' in snames:
        snames.remove('add')
        snames += [key for key in _selectorKeys if key.startswith('add')]
    if 'fs' in snames:
        snames.remove('fs')
        snames += [key for key in _selectorKeys if 'fs' in key]

    # filter out empty samples
    for name in list(snames):
        if '*' in name: # wild card
            snames.remove(name)
            snames.extend([s.name for s in allsamples.getmany(name)])
        try:
            samp = allsamples[name]
        except KeyError:
            print name, "is not in datasets.csv. Removing it from the list of samples to run over."
            snames.remove(name)
            

    snames = [name for name in snames if allsamples[name].sumw != 0.]

    return snames
예제 #6
0
basedir = os.path.dirname(thisdir)
sys.path.append(basedir)

TEMPLATEONLY = True
FITPSEUDODATA = False

from datasets import allsamples
from plotstyle import SimpleCanvas
import config
import utils

ROOT.RooMsgService.instance().setGlobalKillBelow(ROOT.RooFit.ERROR)
ROOT.gROOT.LoadMacro(basedir + '/../common/MultiDraw.cc+')

#targs = allsamples.getmany(['sph-16b-m', 'sph-16c-m', 'sph-16d-m'])
targs = allsamples.getmany(['sph-16*-m'])
dataLumi = sum(s.lumi for s in targs)

### Canvas
from plotstyle import SimpleCanvas
canvas = SimpleCanvas()
canvas.lumi = dataLumi


### Make templates
# Visualization
def plotHist(hist):
    canvas.addHistogram(hist)
    canvas.xtitle = '#phi\''
    canvas.printWeb('monophoton/halo', hist.GetName(), logy=False)
    canvas.Clear()
예제 #7
0
파일: plot.py 프로젝트: blallen/MitMonoX
        if isSensitive or outFile:
            usedPoints = []

            for sspec in plotConfig.signalPoints:
                usedPoints.append(sspec.name)
                hist = groupHist(sspec.group, vardef, plotConfig, args.skimDir, samples = [sspec.name], name = sspec.name, lumi = lumi, outFile = outFile)

                if vardef.name == 'count' or vardef.name == args.bbb or vardef.name == args.chi2:
                    counters[sspec.name] = hist
                elif plotDir:
                    canvas.addSignal(hist, title = sspec.title, color = sspec.color, drawOpt = drawOpt)

        # write out all signal distributions if asked for
        if args.allSignal:
            for group in plotConfig.sigGroups:
                for sample in allsamples.getmany(group.samples):
                    if sample.name not in usedPoints:
                        usedPoints.append(sample.name)
                        groupHist(group, vardef, plotConfig, args.skimDir, samples = [sample.name], name = sample.name, lumi = lumi, outFile = outFile)

        if args.asimov == '':
            print 'data_obs'
            if args.saveTrees:
                obshist = []
            else:
                obshist = vardef.makeHist('data_obs', outDir = outFile)
    
            for sname in plotConfig.obs.samples:
                if args.saveTrees:
                    obshist += getHist(sname, allsamples[sname], plotConfig, vardef, args.skimDir, prescale = plotConfig.prescales[sname], outDir = sampleDir)
                else:
예제 #8
0
data.Add('/mnt/hadoop/scratch/yiiyama/monophoton/skim/sph-16*-m_tpeg.root')

outputFile.cd()
data.Draw('probes.sieie>>hdata', selection, 'goff')

hmc.Scale(hdata.GetSumOfWeights() / hmc.GetSumOfWeights())

ratio = hdata.Clone('ratio')
ratio.Divide(hmc)

line = ROOT.TF1('line', '[0] + [1] * x', 0.0085, 0.0105)
line.SetParameters(1.5, -100.)
ratio.Fit(line)

outputFile.cd()
hmc.Write()
hdata.Write()
ratio.Write()
line.Write('fit')

# visualize

canvas = DataMCCanvas(lumi=sum(s.lumi
                               for s in allsamples.getmany('sph-16*-m')))
canvas.legend.setPosition(0.7, 0.7, 0.9, 0.9)

canvas.addStacked(hmc, title='MC', color=ROOT.kBlue, style=3003)
canvas.addObs(hdata, title='Data')

canvas.printWeb('purity', 'sieie_ratio', logy=False)
예제 #9
0
파일: SFmerge.py 프로젝트: yiiyama/MonoX
import sys
import os
import math

thisdir = os.path.dirname(os.path.realpath(__file__))
basedir = os.path.dirname(thisdir)
sys.path.append(basedir)

import ROOT
from datasets import allsamples

file1 = ROOT.TFile("../data/muo_muon_idsf_2016_bcdef.root")
file2 = ROOT.TFile("../data/muo_muon_idsf_2016_gh.root")

lumi1 = sum(s.lumi for s in allsamples.getmany("sph-16{b,c,d,e,f}-m"))
lumi2 = sum(s.lumi for s in allsamples.getmany("sph-16{g,h}-m"))

lids = ['Loose', 'Tight']

outfile = ROOT.TFile("../data/muo_muon_idsf_2016.root", "RECREATE")

unc = 0.01

for lid in lids:

    folder = "MC_NUM_" + lid + "ID_DEN_genTracks_PAR_pt_eta"
    axes = "pt_abseta"

    sfhistname = folder + "/" + axes + "_ratio"
    sfhist1 = file1.Get(sfhistname)
    sfhist2 = file2.Get(sfhistname)
예제 #10
0
파일: ModelScan.py 프로젝트: yiiyama/MonoX
    return (obs, exp)


###======================================================================================
### Make Datacards and compute limits
###======================================================================================

classes = {}  # "dmv" : ( [mMed], [mDM] )
modelList = []

if opts.models == []:
    opts.models = ['add', 'dmv', 'dmvfs', 'dma', 'dmafs', 'dmewk', 'zgr']

for model in opts.models:
    samples = allsamples.getmany(model + '-*')
    snames = [s.name for s in samples]
    modelList += snames

    for sname in snames:
        (name, xval, yval) = sname.split('-')
        if not name in classes.keys():
            classes[name] = ([], [])
        if not xval in classes[name][0]:
            classes[name][0].append(xval)
        if not yval in classes[name][1]:
            classes[name][1].append(yval)

LimitToolDir = os.path.join(os.environ['CMSSW_BASE'],
                            'src/HiggsAnalysis/CombinedLimit')
cardDir = os.path.join(LimitToolDir, 'data/monoph')
예제 #11
0
    ('w{m,p}lnuewk', mc_wlnu),
    ('znn{,n}-*', mc_cand),
    ('dyn-50', applyMod(mc_cand + mc_lep + mc_dilep + [tpegLowPt, tpmgLowPt, 'tp2e', 'tp2m'], s.addGenPhotonVeto)),
    ('dyn-50@', applyMod(mc_cand + mc_lep + mc_dilep + [tpegLowPt, tpmgLowPt, 'tp2e', 'tp2m'], s.addGenPhotonVeto, s.genBosonPtTruncator(maximum = 50.))),
    ('dyn-50-*', applyMod(mc_cand + mc_lep + mc_dilep + [tpegLowPt, tpmgLowPt, 'tp2e', 'tp2m'], s.addGenPhotonVeto)),
    ('zewk', applyMod(mc_cand + mc_lep + mc_dilep + [tpegLowPt, tpmgLowPt, 'tp2e', 'tp2m'], s.addGenPhotonVeto)),
    ('qcd-*', mc_cand + mc_qcd + mc_dilep + mc_lep),
    ('add-*', mc_sig),
    ('dm*', mc_sig),
    ('dph*', mc_sig),
    ('hbb-nlo-125', mc_sig)
"""

allSelectors = {}
for pat, sels in allSelectors_byPattern:
    samples = allsamples.getmany(pat)
    for sample in samples:
        if sample in allSelectors:
            raise RuntimeError('Duplicate skim config for ' + sample.name)

        sampleSelectors = {}
        for sel in sels:
            # sel has to be either a selector function name or a tuple of form (region, selector[, modifiers])
            if type(sel) is str:
                sampleSelectors[sel] = getattr(s, sel)
            elif len(sel) == 2:
                sampleSelectors[sel[0]] = sel[1]
            else:
                sampleSelectors[sel[0]] = sel[1:]

        allSelectors[sample] = sampleSelectors
예제 #12
0
import ROOT

mask = collections.defaultdict(set)
if args.mask:
    with open(args.mask) as source:
        for run, ranges in json.load(source).items():
            for begin, end in ranges:
                mask[int(run)] |= set(range(begin, end + 1))

allLumis = collections.defaultdict(set)
sampleRuns = collections.defaultdict(set)

if not args.list:
    print 'Calculating integrated luminosity for', args.snames, 'from', config.ntuplesDir

    for sample in allsamples.getmany(args.snames):
        dname = config.ntuplesDir + '/' + sample.book + '/' + sample.fullname
    
        for fname in os.listdir(dname):
            if not fname.endswith('.root'):
                continue

            path = dname + '/' + fname

            source = ROOT.TFile.Open(path)
            if not source:
                continue
        
            gr = source.Get('ProcessedRunsLumis')
            if gr:
                for iP in range(gr.GetN()):
예제 #13
0
파일: skim.py 프로젝트: blallen/MitMonoX
thisdir = os.path.dirname(os.path.realpath(__file__))
basedir = os.path.dirname(thisdir)
sys.path.append(basedir)
from datasets import allsamples
import config

try:
    os.makedirs(config.histDir + '/trigger')
except OSError:
    pass

obj = sys.argv[1]
snames = sys.argv[2:]

samples = allsamples.getmany(snames)

print 'Skimming samples'
print [s.name for s in samples]

ROOT.gSystem.Load(config.libsimpletree)
ROOT.gSystem.AddIncludePath('-I' + config.dataformats + '/interface')

ROOT.gROOT.LoadMacro(thisdir + '/Skimmer.cc+')

# available object - sample - skim type configurations
configs = {
    'photon': {'sph': ROOT.kDiphoton, 'sel': ROOT.kElectronPhoton, 'smu': ROOT.kMuonPhoton, 'jht': ROOT.kJetHT},
    'muon': {'smu': ROOT.kDimuon},
    'electron': {'sel': ROOT.kDielectron},
    'met': {'sel': ROOT.kElectronMET}
예제 #14
0
파일: ModelScan.py 프로젝트: DylanHsu/MonoX
    return (obs, exp)


###======================================================================================
### Make Datacards and compute limits
###======================================================================================

classes = {} # "dmv" : ( [mMed], [mDM] ) 
modelList = []

if opts.models == []:
    opts.models = ['add', 'dmv', 'dmvfs', 'dma', 'dmafs', 'dmewk', 'zgr']

for model in opts.models:
    samples = allsamples.getmany(model + '-*')
    snames = [s.name for s in samples]
    modelList += snames

    for sname in snames:
        (name, xval, yval) = sname.split('-')
        if not name in classes.keys():
            classes[name] = ( [], [] )
        if not xval in classes[name][0]:
            classes[name][0].append(xval)
        if not yval in classes[name][1]:
            classes[name][1].append(yval)
        
LimitToolDir = os.path.join(os.environ['CMSSW_BASE'], 'src/HiggsAnalysis/CombinedLimit')
cardDir = os.path.join(LimitToolDir, 'data/monoph')
if not os.path.exists(cardDir):
예제 #15
0
import os
import sys
import shutil

thisdir = os.path.dirname(os.path.realpath(__file__))
basedir = os.path.dirname(thisdir)
sys.path.append(basedir)
import config
import utils
from datasets import allsamples

import ROOT

for sample in allsamples.getmany('sph-16*'):
    source = ROOT.TFile.Open(utils.getSkimPath(sample.name, 'offtime'))

    tree = source.Get('events')
    tmpname = '/tmp/' + os.environ[
        'USER'] + '/' + sample.name + '_offtimeIso.root'
    outputFile = ROOT.TFile.Open(tmpname, 'recreate')

    newtree = tree.CopyTree(
        'TMath::Abs(photons.scEta) < 1.4442 && photons.scRawPt > 175 && photons.mipEnergy < 4.9 && photons.time > -15. && photons.time < -10. && (photons.mediumX[][2] || (photons.type == 2 && photons.trackIso < 40.)) && photons.sieie < 0.0104 && photons.hOverE < 0.026 && t1Met.pt > 170. && t1Met.photonDPhi > 0.5 && t1Met.minJetDPhi > 0.5'
    )
    newtree.Write()
    source.Close()
    outputFile.Close()

    shutil.copy(tmpname,
                config.skimDir + '/' + sample.name + '_offtimeIso.root')
    os.remove(tmpname)
예제 #16
0
파일: lumilist.py 프로젝트: kpark1/MonoX
if args.mask:
    with open(args.mask) as source:
        for run, ranges in json.load(source).items():
            for begin, end in ranges:
                mask[int(run)] |= set(range(begin, end + 1))

allLumis = collections.defaultdict(set)
sampleRuns = collections.defaultdict(set)

if not args.list:
    print 'Calculating integrated luminosity for', args.snames

    arun = array.array('I', [0])
    alumi = array.array('I', [0])

    for sample in allsamples.getmany(args.snames):
        print sample.name
        for path in sample.files():
            source = ROOT.TFile.Open(path)

            if not source:
                print 'Cannot open', path
                continue

            tree = source.Get('lumiSummary')
            if not tree:
                print path, 'does not have lumiSummary. Extracting the lumi list from the events tree.'
                tree = source.Get('events')

            tree.SetBranchStatus('*', False)
            tree.SetBranchStatus('runNumber', True)
예제 #17
0
파일: pes.py 프로젝트: sraman2/MonoX
import array

thisdir = os.path.dirname(os.path.realpath(__file__))
basedir = os.path.dirname(thisdir)
sys.path.append(basedir)

from plotstyle import DataMCCanvas
from datasets import allsamples
from main.plotutil import PlotDef
from main.plotconfig import getConfig
import config

import ROOT as r
r.gROOT.SetBatch(True)

lumi = sum([s.lumi for s in allsamples.getmany('sph-16*-m')])
canvas = DataMCCanvas(lumi=lumi)

varDef = PlotDef('phoPt',
                 'E_{T}^{#gamma}',
                 'photons.scRawPt[0]',
                 [175.0, 200., 250., 300., 400., 600., 1000.0],
                 unit='GeV',
                 overflow=True)

gj = ['gj-100', 'gj-200', 'gj-400', 'gj-600']
wlnun = [
    'wlnun-0', 'wlnun-50', 'wlnun-100', 'wlnun-250', 'wlnun-400', 'wlnun-600'
]
top = ['ttg', 'tg']
gg = ['gg-40', 'gg-80']
예제 #18
0
파일: skim.py 프로젝트: blallen/MitMonoX
import ROOT

thisdir = os.path.dirname(os.path.realpath(__file__))
basedir = os.path.dirname(thisdir)
sys.path.append(basedir)
from datasets import allsamples
import config

ROOT.gSystem.Load(config.libsimpletree)
ROOT.gSystem.AddIncludePath('-I' + config.dataformats + '/interface')

skim = sys.argv[1]
snames = sys.argv[2:]

puSource = ROOT.TFile.Open(basedir + '/data/pileup.root')
puweight = puSource.Get('puweight')

ROOT.gROOT.LoadMacro(thisdir + '/monoph.cc+')
ROOT.gROOT.LoadMacro(thisdir + '/dimu.cc+')

for sample in allsamples.getmany(snames):
    source = ROOT.TChain('events')
    source.Add(config.ntuplesDir + '/' + sample.book + '/' + sample.fullname + '/*.root')
    
    outName = config.histDir + '/veto_eff/' + skim +'_' + sample.name + '.root'
    
    if sample.data:
        getattr(ROOT, skim)(source, outName)
    else:
        getattr(ROOT, skim)(source, outName, sample.crosssection / sample.sumw, puweight)
예제 #19
0
파일: direct.py 프로젝트: MiT-HEP/MonoX
    
    # garbage collection
    if subdet == 'barrel':
        template = ROOT.TH1D('template', ';#sigma_{i#etai#eta}', 44, 0.004, 0.015)
    else:
        template = ROOT.TH1D('template', ';#sigma_{i#etai#eta}', 45, 0.015, 0.06)
    ratioTemplate = ROOT.TH1D('ratio', ';I_{CH} (GeV)', 3, array.array('d', [0., chIsoCuts[isub][1], 3.5, 5.]))
    ptTotal = ROOT.TH1D('ptTotal', '', 1, 0., 1.)
    outputFile = ROOT.TFile.Open(outputFileName, 'recreate')
    
    # target and hadron templates
    dataPlotter = ROOT.multidraw.MultiDraw()
    dataPlotter.setWeightBranch('')
    
    lumi = 0.
    for sample in allsamples.getmany(fakeParams.measurementDataset):
        utils.addSkimPaths(dataPlotter, sample.name, fakeParams.measurementSelection)
        lumi += sample.lumi

    if subdet == 'barrel':
        dataPlotter.setFilter('t1Met.pt < 100. && photons.isEB[0]')
    else:
        dataPlotter.setFilter('t1Met.pt < 100. && !photons.isEB[0]')

    mcPlotter = ROOT.multidraw.MultiDraw()
    for sample in allsamples.getmany(fakeParams.measurementMC):
        utils.addSkimPaths(mcPlotter, sample.name, fakeParams.measurementSelection)
    
    if subdet == 'barrel':
        mcPlotter.setFilter('t1Met.pt < 100. && photons.isEB[0]')
    else:
예제 #20
0
파일: plotiso.py 프로젝트: yiiyama/MonoX
def plotiso(loc, pid, pt, met, tune):
    inputKey = tune + '_' + loc + '_' + pid + '_PhotonPt' + pt + '_Met' + met

    try:
        ptSel = s.PhotonPtSels['PhotonPt' + pt]
    except KeyError:
        print 'Inputted pt range', pt, 'not found!'
        print 'Not applying any pt selection!'
        ptSel = '(1)'

    try:
        metSel = s.MetSels['Met' + met]
    except KeyError:
        print 'Inputted met range', met, 'not found!'
        print 'Not applying any met selection!'
        metSel = '(1)'

    var = s.getVariable('chiso', tune, loc)

    versDir = s.versionDir
    WEBDIR = os.environ['HOME'] + '/public_html/cmsplots'
    plotDir = os.path.join(WEBDIR, 'purity', s.Version, inputKey, 'chiso')
    histDir = os.path.join(versDir, inputKey)
    if not os.path.exists(plotDir):
        os.makedirs(plotDir)
    if not os.path.exists(histDir):
        os.makedirs(histDir)

    pids = pid.split('-')
    pid = pids[0]
    extras = pids[1:]

    selections = s.getSelections(tune, loc, pid)

    itune = s.Tunes.index(tune)

    ### Plot I_{CH} from sph data and gjets MC

    # selection on H/E & INH & IPh
    baseSel = ' && '.join([
        ptSel, metSel, selections['fiducial'], selections['hovere'],
        selections['nhiso'], selections['phiso']
    ])
    if 'pixel' in extras:
        baseSel = baseSel + ' && ' + s.Cuts['pixelVeto']
    if 'monoph' in extras:
        baseSel = baseSel + ' && ' + s.Cuts['monophId']
    if 'max' in extras:
        baseSel = baseSel.replace('chIso', 'chIsoMax')
        var = s.Variable('TMath::Max(0., photons.chIsoMaxX[0][%d])' % itune,
                         *var[1:])

    truthSel = '(photons.matchedGenId == -22)'

    # output file
    outName = 'chiso'  #  + inputKey
    print 'plotiso writing to', histDir + '/' + outName + '.root'
    outFile = ROOT.TFile(histDir + '/' + outName + '.root', 'RECREATE')

    # don't use var.binning for binning
    binning = [0., var.cuts[pid]] + [0.1 * x for x in range(20, 111, 5)]

    # make the data iso distribution for reference
    extractor = s.HistExtractor('sphData', s.Samples['sphData'], var)
    print 'setBaseSelection(' + baseSel + ')'
    extractor.plotter.setBaseSelection(baseSel)
    extractor.categories.append(
        ('data', 'I_{CH} Distribution from SinglePhoton Data', ''))
    hist = extractor.extract(binning)[0]
    hist.Scale(1. / hist.GetSumOfWeights())

    formatHist(hist, 'Events')
    printHist([hist], 'HIST', outName + '_data', plotDir, logy=True)

    extractor = s.HistExtractor('gjetsMc', s.Samples['gjetsMc'], var)
    print 'setBaseSelection(' + baseSel + ' && ' + truthSel + ')'
    extractor.plotter.setBaseSelection(baseSel + ' && ' + truthSel)
    extractor.categories.append(
        ('rawmc', 'I_{CH} Distribution from #gamma+jets MC', ''))
    raw = extractor.extract(binning)[0]
    raw.Scale(1. / raw.GetSumOfWeights())

    formatHist(raw, 'Events')

    ### Plot I_{CH} from sph data and dy MC Zee samples

    eSelScratch = ' && '.join([
        'tp.mass > 81 && tp.mass < 101', metSel, selections['fiducial'],
        selections['hovere'], selections['nhiso'], selections['phiso'],
        selections['sieie']
    ])

    eSel = 'weight * (' + eSelScratch.replace("photons", "probes") + ')'
    eExpr = var.expression.replace('photons', 'probes')

    print 'Extracting electron MC distributions'

    mcTree = ROOT.TChain('events')
    for sample in allsamples.getmany('dy-50-*'):
        mcTree.Add(utils.getSkimPath(sample.name, 'tpeg'))

    print 'Draw(' + eExpr + ', ' + eSel + ')'

    mcHist = raw.Clone("emc")
    mcHist.Reset()
    mcTree.Draw(eExpr + ">>emc", eSel, 'goff')
    mcHist.Scale(1. / mcHist.GetSumOfWeights())

    formatHist(mcHist, 'Events')

    print 'Extracting electron data distributions'

    dataTree = ROOT.TChain('events')
    for sample in allsamples.getmany('sph-16*'):
        dataTree.Add(utils.getSkimPath(sample.name, 'tpeg'))

    print 'Draw(' + eExpr + ', ' + eSel + ')'

    dataHist = raw.Clone("edata")
    dataHist.Reset()
    dataTree.Draw(eExpr + ">>edata", eSel, 'goff')
    dataHist.Scale(1. / dataHist.GetSumOfWeights())

    formatHist(dataHist, 'Events')

    printHist([mcHist, dataHist],
              'HIST',
              outName + '_electrons',
              plotDir,
              logy=True)

    scaled = raw.Clone("scaledmc")

    scaleHist = raw.Clone("escale")
    scaleHist.SetTitle("Data/MC Scale Factors from Electrons")
    scaleHist.Reset()
    for iBin in range(1, scaleHist.GetNbinsX() + 1):
        dataValue = dataHist.GetBinContent(iBin)
        dataError = dataHist.GetBinError(iBin)

        mcValue = mcHist.GetBinContent(iBin)
        mcError = mcHist.GetBinError(iBin)

        if mcValue == 0 or dataValue == 0:
            ratio = 1
            error = 0.05
        else:
            ratio = dataValue / mcValue
            error = ratio * ((dataError / dataValue)**2 +
                             (mcError / mcValue)**2)**(0.5)

        scaleHist.SetBinContent(iBin, ratio)
        scaled.SetBinContent(iBin, ratio * scaled.GetBinContent(iBin))
        scaleHist.SetBinError(iBin, error)

    scaled.Scale(1. / scaled.GetSumOfWeights())

    formatHist(scaled, 'Events')
    formatHist(scaleHist, 'Scale Factor', lstyle=ROOT.kSolid)

    printHist([scaleHist], '', outName + '_scale', plotDir, logy=False)
    printHist([raw, scaled], 'HIST', outName + '_photons', plotDir, logy=True)

    outFile.Close()
예제 #21
0
파일: plotutil.py 프로젝트: MiT-HEP/MonoX
 def addObs(self, snames, prescale=1):
     samples = allsamples.getmany(snames)
     for sample in samples:
         self.obs.samples.append(sample)
         self.prescales[sample] = prescale
예제 #22
0
sys.path.append(basedir)
from plotstyle import SimpleCanvas, RatioCanvas
from datasets import allsamples
import purity.selections as selections
import config
import utils

ROOT.gROOT.SetBatch(True)

###########################
# Setup and configuration #
###########################

snames = ['sph-16*-m']

lumi = sum(s.lumi for s in allsamples.getmany(snames))
canvas = SimpleCanvas(lumi=lumi)
rcanvas = RatioCanvas(lumi=lumi)

binning = array.array('d', map(float, selections.photonPtBinning))
pid = 'medium'
tune = 'Spring16'  # 'GJetsCWIso'
extras = 'pixel-chargedpf'  # -monoph'
suffix = '_Spring16'  # '_GJetsCWIso'

itune = selections.Tunes.index(tune)

inputFile = ROOT.TFile.Open(basedir + '/data/impurity_' + tune + '.root')
impurityGraph = inputFile.Get("barrel-" + pid + "-" + extras + "-Met0to60")

outputFile = ROOT.TFile.Open(
예제 #23
0
파일: skim.py 프로젝트: blallen/MitMonoX
    names = ' '.join(sorted(sampleIds.keys()))
    print names
    sys.exit(0)

elif targets[0] == 'all':
    targets = sampleIds.keys()

# if target contains mc / eldata / mudata
for confName in skimConfig:
    if confName in targets:
        targets.remove(confName)
        for sname in skimConfig[targets][0]:
            if sname not in targets:
                targets.append(sname)

samples = allsamples.getmany(targets)

suffix = {'kEG': 'eg', 'kMG': 'mg', 'kMMG': 'mmg'}

puSource = ROOT.TFile.Open(basedir + '/data/pileup.root')
if not puSource:
    print 'NPV reweight absent - run monophoton/ssw2.py'
    sys.exit(1)

reweight = puSource.Get('puweight')
reweight.SetDirectory(ROOT.gROOT)
puSource.Close()

#npvSource = ROOT.TFile.Open('npvreweight.root')
#reweight = npvSource.Get('reweight')
예제 #24
0
파일: eff.py 프로젝트: yiiyama/MonoX
    for omname in omnames:
        oname = omname[0]
        mname = omname[1]
        print oname, mname

        snames, region, basesel, colname = measurements[(oname, mname)]

        outputFile = ROOT.TFile.Open(
            outDir + '/trigger_efficiency_%s_%s.root' % (oname, mname),
            'recreate')

        # fill the histograms
        plotter = ROOT.MultiDraw()
        plotter.setWeightBranch('')

        for sample in allsamples.getmany(snames):
            plotter.addInputPath(utils.getSkimPath(sample.name, region))

        plotter.setBaseSelection(basesel)

        # make an empty histogram for each (trigger, variable) combination
        histograms = []

        for tname, (passdef, commonsel, title,
                    variables) in confs[oname].items():
            if len(omname) > 2 and tname != omname[2]:
                continue

            trigDir = outputFile.mkdir(tname)

            passdef = passdef.format(col=colname)
예제 #25
0
import os
import sys
import shutil
import ROOT

NENTRIES = -1

thisdir = os.path.dirname(os.path.realpath(__file__))
basedir = os.path.dirname(thisdir)
sys.path.append(basedir)

from datasets import allsamples
import config

sphSamples = allsamples.getmany('sph-16*')

tree = ROOT.TChain('skimmedEvents')
for sample in sphSamples:
    tree.Add('/data/t3home000/yiiyama/studies/monophoton/efake_skim/' +
             sample.name + '_eg.root')

rhoBins = [0., 5., 7., 9.] + [10. + x
                              for x in range(8)] + [18., 20., 23., 30., 35.]

outputFile = ROOT.TFile.Open(config.histDir + '/worstIsoEA.root', 'recreate')
graph = ROOT.TGraphErrors(len(rhoBins) - 1)

for iP in range(len(rhoBins) - 1):
    rhoMin = rhoBins[iP]
    rhoMax = rhoBins[iP + 1]