Beispiel #1
0
except ImportError as e:
    print "no pyroot_logon.py file to customize ROOT defaults"

from DataFormats.FWLite import Events, Handle
from ROOT import *
from array import array
from math import sqrt
import os

files = []
if len(args) > 0:
    files = args
print 'len(files)', len(files), 'first:', files[0]
events = Events(files)

simHitHandle = Handle('vector<PCaloHit>')
horecoHandle = Handle(
    'edm::SortedCollection<HORecHit,edm::StrictWeakOrdering<HORecHit> >')
simDigiHandle = Handle(
    'edm::SortedCollection<HODataFrame,edm::StrictWeakOrdering<HODataFrame> >')

simHitLabel = ('g4SimHits', 'HcalHits')
horecoLabel = ('horeco')
simDigiLabel = ('simHcalUnsuppressedDigis')

EvtN = 0

outFile = TFile(opts.outputFile, 'recreate')
HOSimHitSum = TH1F("HOSimHitSum", 'Sum HO Sim Hits', 40, 0., 0.02)
EnergyVsEta = TH2F("EnergyVsEta", "Energy vs Eta", 31, -15.5, 15.5, 50, 0.,
                   0.05)
#! /usr/bin/env python

from __future__ import print_function
from DataFormats.FWLite import Events, Handle
import optparse

print("starting python test")

files = ['empty_a.root', 'good_a.root', 'empty_a.root', 'good_b.root']
events = Events(files)

thingHandle = Handle('std::vector<edmtest::Thing>')
indicies = events.fileIndicies()
for event in events:
    newIndicies = event.fileIndicies()
    if indicies != newIndicies:
        print("new file")
    indicies = newIndicies
    event.getByLabel('Thing', thingHandle)
    thing = thingHandle.product()
    for loop in range(thing.size()):
        print(thing.at(loop).a)

events.toBegin()

for event in events:
    pass

events.toBegin()

for event in events:
Beispiel #3
0
argv = []

## _____________      __.____    .__  __             _________ __          _____  _____
## \_   _____/  \    /  \    |   |__|/  |_  ____    /   _____//  |_ __ ___/ ____\/ ____\
##  |    __) \   \/\/   /    |   |  \   __\/ __ \   \_____  \\   __\  |  \   __\\   __\
##  |     \   \        /|    |___|  ||  | \  ___/   /        \|  | |  |  /|  |   |  |
##  \___  /    \__/\  / |_______ \__||__|  \___  > /_______  /|__| |____/ |__|   |__|
##      \/          \/          \/             \/          \/

import ROOT
import sys
import copy
from array import array
from DataFormats.FWLite import Events, Handle
ROOT.gROOT.Macro("rootlogon.C")
jethandle0 = Handle("std::vector<pat::Jet>")
jetlabel0 = ("slimmedJets")
jethandle1 = Handle("std::vector<pat::Jet>")
jetlabel1 = ("slimmedJetsAK8")

rhoHandle = Handle("double")
rhoLabel = ("fixedGridRhoAll")

pvHandle = Handle("std::vector<reco::Vertex>")
pvLabel = ("offlineSlimmedPrimaryVertices")

if options.smearJets and options.isData:
    print 'Misconfiguration. I cannot access generator-level jets on data. Not smearing jets.'
    options.smearJets = False

if options.correctJets:
Beispiel #4
0
    def __init__(self, useMC, outfile, mistagFile, collectionLabelSuffix,
                 useGenWeight, triggerFile, modMassFile, triggerWeight,
                 readGenInfo, pdfWeight):

        self.outfile = outfile
        self.mistagFileStr = mistagFile
        self.triggerFileStr = triggerFile
        self.modMassFileStr = modMassFile
        self.useMC = useMC
        self.useGenWeight = useGenWeight
        self.readGenInfo = readGenInfo
        self.pdfWeight = "nominal"  #pdfWeight
        self.triggerWeight = triggerWeight

        label = 'ttbsmAna' + collectionLabelSuffix

        self.allTopTagHandle = Handle(
            "vector<ROOT::Math::LorentzVector<ROOT::Math::PtEtaPhiM4D<double> > >"
        )
        self.allTopTagLabel = (label, "topTagP4")
        self.allca8Handle = Handle(
            "vector<ROOT::Math::LorentzVector<ROOT::Math::PtEtaPhiM4D<double> > >"
        )
        self.allca8Label = (label, "ca8JetP4")
        self.allwTagHandle = Handle(
            "vector<ROOT::Math::LorentzVector<ROOT::Math::PtEtaPhiM4D<double> > >"
        )
        self.allwTagLabel = (label, "wTagP4")
        self.allTopTagSubjetsHandle = Handle(
            "vector<ROOT::Math::LorentzVector<ROOT::Math::PtEtaPhiM4D<double> > >"
        )
        self.allTopTagSubjetsLabel = (label, "topTagSubjet1P4")

        self.allTopTagTopMassHandle = Handle("std::vector<double>")
        self.allTopTagTopMassLabel = (label, "topTagTopMass")
        self.allTopTagMinMassHandle = Handle("std::vector<double>")
        self.allTopTagMinMassLabel = (label, "topTagMinMass")
        self.allTopTagNSubjetsHandle = Handle("std::vector<double>")
        self.allTopTagNSubjetsLabel = (label, "topTagNSubjets")

        self.allTopTagPartonHandle = Handle("std::vector<int>")
        self.allTopTagPartonLabel = (label, "topTagPartonFlavour")

        self.allgenTopP4Handle = Handle(
            "vector<ROOT::Math::LorentzVector<ROOT::Math::PtEtaPhiM4D<double> > >"
        )
        self.allgenTopP4Label = (label, "genTopP4")

        self.allwTagBdiscHandle = Handle("std::vector<double>")
        self.allwTagBdiscLabel = (label, "wTagBDisc")

        self.allwTagMuHandle = Handle("std::vector<double>")
        self.allwTagMuLabel = (label, "wTagMu")

        self.allNsub1Handle = Handle("std::vector<double>")
        self.allNsub2Handle = Handle("std::vector<double>")
        self.allNsub3Handle = Handle("std::vector<double>")
        self.allNsub4Handle = Handle("std::vector<double>")
        self.allNsub1Label = (label, "tau1")
        self.allNsub2Label = (label, "tau2")
        self.allNsub3Label = (label, "tau3")
        self.allNsub4Label = (label, "tau4")

        self.allNPVHandle = Handle("unsigned int")
        self.allNPVLabel = (label, "npv")

        self.allTopTagSubjetBDiscHandle = Handle("std::vector<double>")
        self.allTopTagSubjetBDiscLabel = (label, "topTagSubjetBDisc")

        self.allTopTagSubjetJetIDHandle = Handle("std::vector<int>")
        self.allTopTagSubjetJetIDLabel = (label, "topTagSubjetJetID")

        self.allTopTagBDiscHandle = Handle("std::vector<double>")
        self.allTopTagBDiscLabel = (label, "topTagBDisc")

        self.h_met = Handle(
            "vector<ROOT::Math::LorentzVector<ROOT::Math::PtEtaPhiM4D<double> > >"
        )
        self.metLabel = (label, "pfMET")
        self.weightsHandle = Handle("double")
        self.weightsLabel = (label, "weight")
        self.pdfHandle = Handle("std::vector<double>")
        self.pdfLabel = (label, "pdfWeights")

        self.__book__()
Beispiel #5
0
def main():
    vhdl_dict = VHDLConstantsParser.parse_vhdl_file("data/ugmt_constants.vhd")

    opts = parse_options()
    fname_dict = discover_emu_files(opts.emudirectory)
    # rankLUT = l1t.MicroGMTRankPtQualLUT()

    for pattern, fnames in fname_dict.iteritems():
        print "+" * 30, pattern, "+" * 30
        events = Events(fnames['root'])

        start = time.time()

        tower_indices = None
        if 'idebug' in fnames.keys():
            debug_fname = fnames['idebug']
            with open(debug_fname, 'r') as fobj:
                tower_indices = [[int(idx.strip()) for idx in l.split()]
                                 for l in fobj]

        out_handle = Handle('BXVector<l1t::Muon>')
        imd_bmtf_handle = Handle('BXVector<l1t::Muon>')
        imd_emtf_p_handle = Handle('BXVector<l1t::Muon>')
        imd_emtf_n_handle = Handle('BXVector<l1t::Muon>')
        imd_omtf_p_handle = Handle('BXVector<l1t::Muon>')
        imd_omtf_n_handle = Handle('BXVector<l1t::Muon>')
        bar_handle = Handle('BXVector<l1t::RegionalMuonCand>')
        fwd_handle = Handle('BXVector<l1t::RegionalMuonCand>')
        ovl_handle = Handle('BXVector<l1t::RegionalMuonCand>')
        calo_handle = Handle('BXVector<l1t::MuonCaloSum>')

        basedir_testbench = "data/patterns/testbench/"
        basedir_mp7 = "data/patterns/mp7/"

        input_buffer = PatternDumper(basedir_mp7 + pattern + ".txt", vhdl_dict,
                                     BufferWriter)
        output_buffer = PatternDumper(basedir_mp7 + pattern + "_out.txt",
                                      vhdl_dict, BufferWriter)
        input_testbench = PatternDumper(basedir_testbench + pattern + ".txt",
                                        vhdl_dict, TestbenchWriter)
        serializer_testbench = PatternDumper(
            basedir_testbench + "serializer_" + pattern + ".txt", vhdl_dict,
            TestbenchWriter)
        deserializer_testbench = PatternDumper(
            basedir_testbench + "deserializer_" + pattern + ".txt", vhdl_dict,
            TestbenchWriter)
        integration_testbench = PatternDumper(
            basedir_testbench + "integration_" + pattern + ".txt", vhdl_dict,
            TestbenchWriter)

        if opts.delay > 0:
            input_buffer.writeEmptyFrames(opts.delay)

        setup_time = time.time() - start

        avg_get_label_time = 0
        avg_conversion_time = 0
        avg_write_time = 0
        n_twrs = 0
        for i, event in enumerate(events):
            evt_start = time.time()
            event_head = "#" * 80 + "\n"
            event_head += "# Event: {ievent}\n".format(ievent=i)
            event_head += "#" * 80 + "\n"
            input_testbench.addLine(event_head)
            serializer_testbench.addLine(event_head)
            deserializer_testbench.addLine(event_head)
            integration_testbench.addLine(event_head)

            event.getByLabel("simGmtDigis", out_handle)
            event.getByLabel("simGmtDigis", "imdMuonsBMTF", imd_bmtf_handle)
            event.getByLabel("simGmtDigis", "imdMuonsEMTFPos",
                             imd_emtf_p_handle)
            event.getByLabel("simGmtDigis", "imdMuonsEMTFNeg",
                             imd_emtf_n_handle)
            event.getByLabel("simGmtDigis", "imdMuonsOMTFPos",
                             imd_omtf_p_handle)
            event.getByLabel("simGmtDigis", "imdMuonsOMTFNeg",
                             imd_omtf_n_handle)
            event.getByLabel("simBmtfDigis", "BMTF", bar_handle)
            event.getByLabel("simEmtfDigis", "EMTF", fwd_handle)
            event.getByLabel("simOmtfDigis", "OMTF", ovl_handle)

            event.getByLabel("simGmtCaloSumDigis", "TriggerTowerSums",
                             calo_handle)
            get_label_time = time.time() - evt_start
            calo_sums_raw = calo_handle.product()
            calo_sums = get_calo_list(calo_sums_raw)

            emu_out_muons = out_handle.product()
            outmuons = get_muon_list_out(emu_out_muons, "OUT", vhdl_dict)
            imd_emtf_p_prod = imd_emtf_p_handle.product()
            imdmuons = get_muon_list_out(imd_emtf_p_prod, "IMD", vhdl_dict, 4)
            imd_omtf_p_prod = imd_omtf_p_handle.product()
            imdmuons += get_muon_list_out(imd_omtf_p_prod, "IMD", vhdl_dict, 4)
            imd_bmtf_prod = imd_bmtf_handle.product()
            imdmuons += get_muon_list_out(imd_bmtf_prod, "IMD", vhdl_dict, 8)
            imd_omtf_n_prod = imd_omtf_n_handle.product()
            imdmuons += get_muon_list_out(imd_omtf_n_prod, "IMD", vhdl_dict, 4)
            imd_emtf_n_prod = imd_emtf_n_handle.product()
            imdmuons += get_muon_list_out(imd_emtf_n_prod, "IMD", vhdl_dict, 4)

            emu_bar_muons = bar_handle.product()
            bar_muons = get_muon_list(emu_bar_muons, "BMTF", vhdl_dict, i)
            emu_ovl_muons = ovl_handle.product()
            ovlp_muons = get_muon_list(emu_ovl_muons, "OMTF_POS", vhdl_dict, i)
            ovln_muons = get_muon_list(emu_ovl_muons, "OMTF_NEG", vhdl_dict, i)
            emu_fwd_muons = fwd_handle.product()
            fwdp_muons = get_muon_list(emu_fwd_muons, "EMTF_POS", vhdl_dict, i)
            fwdn_muons = get_muon_list(emu_fwd_muons, "EMTF_NEG", vhdl_dict, i)

            conversion_time = time.time() - evt_start - get_label_time
            input_buffer.writeFrameBasedInputBX(bar_muons, fwdp_muons,
                                                fwdn_muons, ovlp_muons,
                                                ovln_muons, calo_sums)
            integration_testbench.writeFrameBasedInputBX(
                bar_muons, fwdp_muons, fwdn_muons, ovlp_muons, ovln_muons,
                calo_sums)
            deserializer_testbench.writeFrameBasedInputBX(
                bar_muons, fwdp_muons, fwdn_muons, ovlp_muons, ovln_muons,
                calo_sums)
            output_buffer.writeFrameBasedOutputBX(outmuons, imdmuons)

            input_testbench.writeMuonBasedInputBX(bar_muons,
                                                  fwdp_muons,
                                                  fwdn_muons,
                                                  ovlp_muons,
                                                  ovln_muons,
                                                  calosums=calo_sums,
                                                  addTracks=True)
            input_testbench.addLine("# Expected emulator output\n")
            input_testbench.writeMuonBasedOutputBX(outmuons, imdmuons)
            deserializer_testbench.addLine("# Expected emulator output\n")
            deserializer_testbench.writeMuonBasedInputBX(bar_muons,
                                                         fwdp_muons,
                                                         fwdn_muons,
                                                         ovlp_muons,
                                                         ovln_muons,
                                                         calosums=calo_sums,
                                                         addTracks=True)
            if tower_indices is not None:
                input_testbench.addLine("# Tower indices:\n")
                cntr = 0
                for mu in outmuons:
                    if mu.bitword != 0:
                        cntr += 1
                input_testbench.writeTowerIndices(tower_indices[n_twrs:n_twrs +
                                                                cntr])
                n_twrs += cntr

            serializer_testbench.writeMuonBasedOutputBX(outmuons, imdmuons)
            serializer_testbench.addLine("# Expected emulator output\n")
            serializer_testbench.writeFrameBasedOutputBX(outmuons, imdmuons)
            integration_testbench.addLine("# Expected emulator output\n")
            integration_testbench.writeFrameBasedOutputBX(outmuons, imdmuons)
            write_time = time.time() - evt_start - conversion_time
            avg_get_label_time += get_label_time
            avg_conversion_time += conversion_time
            avg_write_time += write_time
        print "total: ", time.time() - start
        print "setup: ", setup_time
        print "get_label:", "avg", avg_get_label_time / float(
            i + 1), "last", get_label_time
        print "conversion: avg", avg_conversion_time / float(
            i + 1), "last", conversion_time
        print "write: avg", avg_write_time / float(i + 1), "last", write_time
        output_buffer.dump(True)
        input_testbench.dump()
        serializer_testbench.dump()
        deserializer_testbench.dump()
        input_buffer.dump()
        integration_testbench.dump()
Beispiel #6
0
ROOT.FWLiteEnabler.enable()

outputFile = ROOT.TFile.Open(output, 'recreate')
outputTree = ROOT.TTree('digiTree', 'digis')
adc = array.array('d', [0.] * 10)
energy = array.array('d', [0.])
time = array.array('d', [0.])
outputTree.Branch('adc', adc, 'adc[10]/D')
outputTree.Branch('energy', energy, 'energy/D')
outputTree.Branch('time', time, 'time/D')

# load FWlite python libraries
from DataFormats.FWLite import Handle, Events

scHandle, scLabel = Handle(
    'std::vector<reco::SuperCluster>'
), 'particleFlowSuperClusterECAL:particleFlowSuperClusterECALBarrel'
urHandle, urLabel = Handle('EcalRecHitCollection'), 'reducedEcalRecHitsEB'
dgHandle, dgLabel = Handle(
    "EBDigiCollection"), "selectDigi:selectedEcalEBDigiCollection"

events = Events(source)

for event in events:
    eid = event.object().id()
    eventId = (eid.run(), eid.luminosityBlock(), eid.event())

    event.getByLabel(scLabel, scHandle)
    scs = scHandle.product()

    seedId = 0
import ROOT

from DataFormats.FWLite import Handle, Events
from DevTools.Utilities.utilities import *

DeltaR = ROOT.Math.VectorUtil.DeltaR

ISMC = True
LUMI = 35900
XSEC = XSECVALUE
SUMMEDWEIGHTS = SUMMEDWEIGHTSVALUE
ENDFILENUM = ENDFILENUMVALUE
APPLYFAKERATE = False

lheEvent, lheEventLabel = Handle("LHEEventProduct"), "externalLHEProducer"
mu12, mu12Label = Handle("std::vector<pat::Muon>"), "Mu1Mu2"
mu3,  mu3Label = Handle("std::vector<pat::Muon>"), "Mu3"
mets, metsLabel = Handle("std::vector<pat::MET>"), "slimmedMETs"
taus, tausLabel = Handle("std::vector<pat::Tau>"), "muHadTauDMIsoSelector"
jets, jetsLabel = Handle("std::vector<pat::Jet>"), "slimmedJets"
outputFile  = ROOT.TFile("/afs/cern.ch/work/k/ktos/public/DevAnalysis/CMSSW_8_1_0/src/DevTools/Analyzer/python/BSUB/DIRNAME/DIRNAME_Plots.root", "recreate")
mumu_Mass   = ROOT.TH1F("mumu_Mass", "", 600, 0, 30)
tautau_Mass = ROOT.TH1F("tautau_Mass", "", 600, 0, 30)
h_Mass      = ROOT.TH1F("h_Mass", "", 3000, 0, 1000)
hKF_Mass    = ROOT.TH1F("hKF_Mass", "", 3000, 0, 1000)
hKF_ChiSq   = ROOT.TH1F("hKF_ChiSq", "", 30000, 0, 300)
TotalWeight = ROOT.TH1F("TotalWeight", "", 1000, 0, 20)
DiTauMassVSMVA = ROOT.TH2F("DiTauMassVSMVA", "", 25, 0, 25, 20, -10, 1)
DiTauMassVSTauMu3dR = ROOT.TH2F("DiTauMassVSTauMu3dR", "", 25, 0, 25, 20, 0, 4)
DiTauMassVSDiMudR = ROOT.TH2F("DiTauMassVSDiMudR", "", 25, 0, 25, 20, 0, 4)
Beispiel #8
0
def makepu_fwlite(argv):
    parser = OptionParser()

    parser.add_option(
        '--files',
        type='string',
        action='store',
        dest='files',
        help='Input files')  # Should be file containing a list of xrootd files

    parser.add_option('--outname',
                      type='string',
                      action='store',
                      default='pumc.root',
                      dest='outname',
                      help='Name of output file')

    parser.add_option('--verbose',
                      action='store_true',
                      default=False,
                      dest='verbose',
                      help='Print debugging info')

    parser.add_option('--maxevents',
                      type='int',
                      action='store',
                      default=-1,
                      dest='maxevents',
                      help='Number of events to run. -1 is all events')

    (options, args) = parser.parse_args(argv)
    argv = []

    print '===== Command line options ====='
    print options
    print '================================'

    ## _____________      __.____    .__  __             _________ __          _____  _____
    ## \_   _____/  \    /  \    |   |__|/  |_  ____    /   _____//  |_ __ ___/ ____\/ ____\
    ##  |    __) \   \/\/   /    |   |  \   __\/ __ \   \_____  \\   __\  |  \   __\\   __\
    ##  |     \   \        /|    |___|  ||  | \  ___/   /        \|  | |  |  /|  |   |  |
    ##  \___  /    \__/\  / |_______ \__||__|  \___  > /_______  /|__| |____/ |__|   |__|
    ##      \/          \/          \/             \/          \/

    import ROOT
    import sys
    from DataFormats.FWLite import Events, Handle
    ROOT.gROOT.Macro("rootlogon.C")

    vertices, vertexLabel = Handle(
        "std::vector<reco::Vertex>"), "offlineSlimmedPrimaryVertices"
    pileups, pileuplabel = Handle(
        "std::vector<PileupSummaryInfo>"), "slimmedAddPileupInfo"

    ##   ___ ___ .__          __
    ##  /   |   \|__| _______/  |_  ____   ________________    _____   ______
    ## /    ~    \  |/  ___/\   __\/  _ \ / ___\_  __ \__  \  /     \ /  ___/
    ## \    Y    /  |\___ \  |  | (  <_> ) /_/  >  | \// __ \|  Y Y  \\___ \
    ##  \___|_  /|__/____  > |__|  \____/\___  /|__|  (____  /__|_|  /____  >
    ##        \/         \/             /_____/            \/      \/     \/

    f = ROOT.TFile(options.outname, "RECREATE")
    f.cd()
    # and also make a few 1-d histograms
    pileup = ROOT.TH1F("pileup", "Pileup", 100, 0, 100)

    ## ___________                    __    .____
    ## \_   _____/__  __ ____   _____/  |_  |    |    ____   ____ ______
    ##  |    __)_\  \/ // __ \ /    \   __\ |    |   /  _ \ /  _ \\____ \
    ##  |        \\   /\  ___/|   |  \  |   |    |__(  <_> |  <_> )  |_> >
    ## /_______  / \_/  \___  >___|  /__|   |_______ \____/ \____/|   __/
    ##         \/           \/     \/               \/            |__|

    # IMPORTANT : Run one FWLite instance per file. Otherwise,
    # FWLite aggregates ALL of the information immediately, which
    # can take a long time to parse.
    filelist = file(options.files)
    filesraw = filelist.readlines()
    files = []
    nevents = 0
    for ifile in filesraw:
        print("HERE")
        print(ifile)
        if len(ifile) > 2:
            s = 'root://cmsxrootd.fnal.gov/' + ifile.rstrip()
            #s = 'root://xrootd-cms.infn.it/' + ifile.rstrip()
            #s = 'root://eoscms.cern.ch/' + ifile.rstrip()  #we know ttbar is at CERN
            #s = ifile # Trying this?????
            files.append(s)
            print 'Added ' + s

    #exit()

    # loop over files
    for ifile in files:
        print 'Processing file ' + ifile
        events = Events(ifile)
        if options.maxevents > 0 and nevents > options.maxevents:
            break

        # loop over events in this file
        i = 0
        for iev, event in enumerate(events):
            evWeight = 1.0

            if options.maxevents > 0 and nevents > options.maxevents:
                break
            i += 1
            nevents += 1

            if nevents % 1000 == 0:
                print '    ---> Event ' + str(nevents)
            if options.verbose:
                print '==============================================='
                print '    ---> Event ' + str(nevents)

            ## ____   ____             __                    _________      .__                 __  .__
            ## \   \ /   /____________/  |_  ____ ___  ___  /   _____/ ____ |  |   ____   _____/  |_|__| ____   ____
            ##  \   Y   // __ \_  __ \   __\/ __ \\  \/  /  \_____  \_/ __ \|  | _/ __ \_/ ___\   __\  |/  _ \ /    \
            ##   \     /\  ___/|  | \/|  | \  ___/ >    <   /        \  ___/|  |_\  ___/\  \___|  | |  (  <_> )   |  \
            ##    \___/  \___  >__|   |__|  \___  >__/\_ \ /_______  /\___  >____/\___  >\___  >__| |__|\____/|___|  /
            ##               \/                 \/      \/         \/     \/          \/     \/                    \/

            event.getByLabel(vertexLabel, vertices)
            # Vertices
            NPV = len(vertices.product())
            if len(vertices.product()
                   ) == 0 or vertices.product()[0].ndof() < 4:
                if options.verbose:
                    print "Event has no good primary vertex."
                continue
            else:
                PV = vertices.product()[0]
                if options.verbose:
                    print "PV at x,y,z = %+5.3f, %+5.3f, %+6.3f (ndof %.1f)" % (
                        PV.x(), PV.y(), PV.z(), PV.ndof())

            event.getByLabel(pileuplabel, pileups)

            TrueNumInteractions = 0
            if len(pileups.product()) > 0:
                TrueNumInteractions = pileups.product(
                )[0].getTrueNumInteractions()
            else:
                print 'Event has no pileup information, setting TrueNumInteractions to 0.'

            pileup.Fill(TrueNumInteractions)

    ## _________ .__
    ## \_   ___ \|  |   ____ _____    ____  __ ________
    ## /    \  \/|  | _/ __ \\__  \  /    \|  |  \____ \
    ## \     \___|  |_\  ___/ / __ \|   |  \  |  /  |_> >
    ##  \______  /____/\___  >____  /___|  /____/|   __/
    ##         \/          \/     \/     \/      |__|
    f.cd()
    f.Write()
    f.Close()
Beispiel #9
0
def compare(target_file, ref_file, file_prefix="file:", out_dir="./"):

    ### Objects from file ###
    eles, ele_label = Handle("std::vector<pat::Electron>"), "slimmedElectrons"
    eles_ref = Handle("std::vector<pat::Electron>")
    phos, pho_label = Handle("std::vector<pat::Photon>"), "slimmedPhotons"
    phos_ref = Handle("std::vector<pat::Photon>")
    ### Events loop ###

    min_pho_et = 10
    min_ele_et = 5
    do_phos = True
    do_eles = True

    evtLUT = {}

    events_ref = Events(file_prefix + ref_file)
    for event_nr, event in enumerate(events_ref):
        runnr = event.eventAuxiliary().run()
        eventnr = event.eventAuxiliary().event()
        lumi = event.eventAuxiliary().luminosityBlock()
        if runnr not in evtLUT:
            evtLUT[runnr] = {}
        if lumi not in evtLUT[runnr]:
            evtLUT[runnr][lumi] = {}
        evtLUT[runnr][lumi][eventnr] = event_nr

    events = Events(file_prefix + target_file)

    ele_diffs = EleDiffSummary()
    pho_diffs = PhoDiffSummary()

    for event_nr, event in enumerate(events):
        runnr = event.eventAuxiliary().run()
        eventnr = event.eventAuxiliary().event()
        lumi = event.eventAuxiliary().luminosityBlock()
        event_found = events_ref.to(evtLUT[runnr][lumi][eventnr])

        event_id = str(event.eventAuxiliary().run()) + ":" + str(
            event.eventAuxiliary().luminosityBlock()) + ":" + str(
                event.eventAuxiliary().event())

        if do_phos:
            event.getByLabel(pho_label, phos)
            events_ref.getByLabel(pho_label, phos_ref)

            for pho_nr, pho in enumerate(phos.product()):
                if pho.et() < min_pho_et: continue
                pho_ref = match_by_sc(pho, phos_ref.product())
                pho_diffs.fill(pho, pho_ref)

        if do_eles:
            event.getByLabel(ele_label, eles)
            events_ref.getByLabel(ele_label, eles_ref)

            for ele_nr, ele in enumerate(eles.product()):
                if ele.et() < min_ele_et: continue
                ele_ref = match_by_sc(ele, eles_ref.product())
                ele_diffs.fill(ele, ele_ref)

    target_path_file = os.path.split(target_file)
    ref_path_file = os.path.split(ref_file)

    hashstr = hashlib.md5(target_file).hexdigest()
    out_tag_phos = "pho_{}".format(hashstr)
    out_tag_eles = "ele_{}".format(hashstr)

    comp_strs = []
    comp_strs.append("<br><br>file = {}<br>".format(target_path_file[1]))
    comp_strs.append("target dir = {}<br>".format(target_path_file[0]))
    comp_strs.append("reference dir = {}<br>".format(ref_path_file[0]))
    comp_strs.append("Photons<br>")
    comp_strs.append(pho_diffs.create_summary(out_dir, out_tag_phos))
    comp_strs.append("Electrons<br>")
    comp_strs.append(ele_diffs.create_summary(out_dir, out_tag_eles))
    #    pho_diffs.create_summary(out_dir)
    return '\n'.join(comp_strs)
        'type': 'vector<reco:GenParticle>',
        'label': ("genParticles", "", "GEN")
    },
    'genMET': {
        'type': 'vector<reco::GenMET>',
        'label': ("genMetTrue", "", "GEN")
    },
    'ak4GenJets': {
        'type': 'vector<reco:GenJet>',
        'label': ("ak4GenJets", "", "GEN")
    }
}

# add handles
for k, v in edmCollections.iteritems():
    v['handle'] = Handle(v['type'])

nevents = events.size()
#nevents = 100

cutflowfile = open(outdir + '/stop_cutflow_eff.txt', 'w')

f = ROOT.TFile(outdir + '/stop_tot.root', 'recreate')
hist_MET = ROOT.TH1F("MET", "MET of events", 1000, 0, 1000)
hist_UNMET = ROOT.TH1F("UnMET", "MET of unweighted events", 1000, 0, 1000)
hist_REMET = ROOT.TH1F("ReMET", "MET of reweighted events", 1000, 0, 1000)
hist_stop_time_from_rho = ROOT.TH1F("stop_time_from_rho", "stop time", 5000, 0,
                                    5000)
hist_stop_time_rwt = ROOT.TH1F("stop_time_rwt", "reweighted stop time", 5000,
                               0, 5000)
hist_muon_lxy = ROOT.TH1F("muon_lxy", "Lxy of the muon emerging from stop",
import ROOT  # provides ROOT
import math  # provides fabs
from DataFormats.FWLite import Events, Handle  # cmssw
from ROOT import TLorentzVector

##### collections
jetsLabel = "selectedPatJetsPFlow"
jetsHandle = Handle("vector<pat::Jet>")
muonsRecoLabel = "selectedPatMuonsPFlow"
muonsRecoHandle = Handle("vector<pat::Muon>")
TrigResultslabel = ("TriggerResults")
TrigResultshandle = Handle("edm::TriggerResults")
vtxRecoHandle = Handle("vector<reco::Vertex>")
vtxRecoLabel = "offlinePrimaryVertices"
##
##### histos
genMuonsPtHist = ROOT.TH1D("genMuonsPtHist", "genMuonsPtHist", 200, 0, 200)
##
#### input
events = Events([
    'dcap://grid-dcap-extern.physik.rwth-aachen.de/pnfs/physik.rwth-aachen.de/cms///store/user/fhohle/TTJets_FullLeptMGDecays_8TeV-madgraph-tauola/BScSkim_TTJets_fullLep_2014-06-02_11-12-02/6eea63ca40c7f36421b750ebc0e3ead7/TTTT_TuneZ2star_8TeV-madgraph-tauola_patTuple_TTJets_FullLeptMGDecays_8TeV-madgraph-tauola__Summer12_DR53X-PU_S10_START53_V7C-v2__AODSIM_10_1_2AV.root'
])
maxEvents = 1000
###
##### event processing
for i, event in enumerate(events):
    if i >= maxEvents:
        break
    numberofmuons = 0
    numberofjets = 0
    event.getByLabel(muonsRecoLabel, muonsRecoHandle)
Beispiel #12
0
    d = d_flightB * (1 / d_flightB.Mag())
    p_B = d * (pt_B / d.Perp())

    p_nu_vec = p_B - p_vis.Vect()
    p_nu = rt.TLorentzVector(p_nu_vec, p_nu_vec.Mag())
    return p_nu


def addToOutput(p, tag, outmap):
    outmap[tag + '_pt'] = p.pt()
    outmap[tag + '_eta'] = p.eta()
    outmap[tag + '_phi'] = p.phi()
    outmap[tag + '_pdgId'] = p.pdgId()


handlePruned = Handle("std::vector<reco::GenParticle>")
handlePacked = Handle("std::vector<pat::PackedGenParticle>")
labelPruned = ("prunedGenParticles")
labelPacked = ("packedGenParticles")

c_light = 2.99792458e1  #cm/ns


class MC_ProcessTag:
    def __init__(self, tag_pdgId=-521):
        self.tag_pdgId = tag_pdgId

    def process(self, event, output, verbose):
        out = output.evt_out

        event.getByLabel(labelPacked, handlePacked)
Beispiel #13
0
from DataFormats.FWLite import Handle, Events
import ROOT
#events = Events('root://cms-xrd-global.cern.ch//store/data/Run2017B/Charmonium/MINIAOD/PromptReco-v1/000/297/046/00000/88DF6C6A-4556-E711-A5C0-02163E01A630.root')
events = Events('root://cms-xrd-global.cern.ch//store/mc/RunIISummer16MiniAODv2/DarkMatter_MonoZToLL_NLO_Vector_Mx-150_Mv-500_gDM1_gQ0p25_TuneCUETP8M1_13TeV-madgraph/MINIAODSIM/PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v1/60000/1E74A3C2-6FD2-E611-BB27-24BE05CEEB31.root')

#tracks = Handle("std::vector")
#tracks = Handle('vector<reco::GenParticle>')
#tracks = Handle('vector<pat::Jet>')
tracks = Handle('vector<reco::GenJet>')
#tracks = Handle('BXVector<l1t::Jet>')
histogram = ROOT.TH1F("histogram", "histogram", 100, 0, 100)

i = 0
for event in events:
    print "Event", i 
   event.getByLabel("packedPFCandidates", tracks)
#    event.getByLabel("slimmedJets", tracks)
    j = 0
    for track in tracks.product():
        print "    Track", j, track.charge() / track.pt(), track.phi(), track.eta(), track.mass(), track.fromPV()
        histogram.Fill(track.pt())
        j += 1
    i += 1
    if i >= 5: break


c = ROOT.TCanvas ( "c" , "c" , 800, 800 )
c.cd()
histogram.Draw()
c.SaveAs("PtFW.png")
Beispiel #14
0
                  dest='deweightFlat',
                  help='unweights flat samples')

(options, args) = parser.parse_args()
argv = []

#@ FWLITE STUFF

import ROOT
import sys
from DataFormats.FWLite import Events, Handle
ROOT.gROOT.Macro("rootlogon.C")
import copy

#gen labels and handles
h_genPartCharge = Handle("std::vector<float>")
l_genPartCharge = ("genPart", "genPartCharge")
h_genPartE = Handle("std::vector<float>")
l_genPartE = ("genPart", "genPartE")
h_genPartEta = Handle("std::vector<float>")
l_genPartEta = ("genPart", "genPartEta")
h_genPartID = Handle("std::vector<float>")
l_genPartID = ("genPart", "genPartID")
h_genPartMass = Handle("std::vector<float>")
l_genPartMass = ("genPart", "genPartMass")
h_genPartMomID = Handle("std::vector<float>")
l_genPartMomID = ("genPart", "genPartMomID")
h_genPartPhi = Handle("std::vector<float>")
l_genPartPhi = ("genPart", "genPartPhi")
h_genPartPt = Handle("std::vector<float>")
l_genPartPt = ("genPart", "genPartPt")
Beispiel #15
0
                  default=2.4,
                  dest='maxAK8Rapidity',
                  help='Maximum AK8 rapidity')

(options, args) = parser.parse_args()
argv = []

#FWLITE STUFF

import ROOT
import sys
from DataFormats.FWLite import Events, Handle
ROOT.gROOT.Macro("rootlogon.C")
import copy

h_NPV = Handle("std::int")
l_NPV = ("eventUserData", "npv")

h_jetsAK8Area = Handle("std::vector<float>")
l_jetsAK8Area = ("jetsAK8", "jetAK8jetArea")

h_rho = Handle("double")
l_rho = ("fixedGridRhoFastjetAll", "")

#MET label and Handles
h_metPt = Handle("std::vector<float>")
l_metPt = ("met", "metPt")
h_metPx = Handle("std::vector<float>")
l_metPx = ("met", "metPx")
h_metPy = Handle("std::vector<float>")
l_metPy = ("met", "metPy")
Beispiel #16
0
ntuple = ROOT.TNtuple('tree', 'tree', ':'.join(branches_all_names))
tofill = OrderedDict(zip(branches_all_names, [-99.]*len(branches_all_names))) # initialise all branches to unphysical -99       

##########################################################################################
# Get ahold of the events
files = files_jpsi_munu if channel=='mu' else files_jpsi_taunu
events = Events(files)
# events = Events('miniAOD_1_muon.root')
maxevents = -1
maxevents = maxevents if maxevents>=0 else events.size() # total number of events in the files
totevents = events.size() # total number of events in the files

##########################################################################################
# instantiate the handles to the relevant collections.
handles = OrderedDict()
handles['taus' ] = ('slimmedTaus'       , Handle('std::vector<pat::Tau>')              )
handles['muon' ] = ('slimmedMuons'      , Handle('std::vector<pat::Muon>')             )
handles['genp' ] = ('prunedGenParticles', Handle('std::vector<reco::GenParticle>')     )
handles['trig' ] = (('TriggerResults','','HLT'),  Handle('edm::TriggerResults')     )
# handles['genpk'] = ('packedGenParticles', Handle('std::vector<pat::PackedGenParticle>'))

##########################################################################################
# start looping on the events
start = time()
for i, ev in enumerate(events):
    
    ######################################################################################
    # controls on the events being processed
    if maxevents>0 and i>maxevents:
        break
        
h1_topPt = ROOT.TH1D("h1_topPt", "h1_topPt", 200, 0, 400)
h1_topEnergy = ROOT.TH1D("h1_topEnergy", "h1_topEnergy", 200, 0, 800)
h1_lepPt = ROOT.TH1D("h1_lepPt", "h1_lepPt", 200, 0, 400)
h1_lepEnergy = ROOT.TH1D("h1_lepEnergy", "h1_lepEnergy", 250, 0, 500)
h1_ptTopPair = ROOT.TH1D("h1_ptTopPair", "h1_ptTopPair", 200, 0, 200)
events = Events()  #testFileName)
#events._filenames.append('dcap://grid-dcap.physik.rwth-aachen.de/pnfs/physik.rwth-aachen.de/cms/store/mc/Fall11/TT_TuneZ2_7TeV-mcatnlo/AODSIM/PU_S6_START42_V14B-v1/0001/FA02E2E1-682A-E111-AB7B-003048678B18.root')
prefix = 'dcap://grid-dcap.physik.rwth-aachen.de/pnfs/physik.rwth-aachen.de/cms'
mcatnloFiles = open('mcatnlo_files.txt').readlines()
maxFiles = 200
del events._filenames[-1]
for i, mcFile in enumerate(mcatnloFiles):
    if i == maxFiles: break
    events._filenames.append(prefix + mcFile.strip())
print "files processing ", events._filenames
lheHandle = Handle('LHEEventProduct')
lheLabel = "source"
genEvtInfoHandle = Handle("GenEventInfoProduct")
genEvtInfoLabel = "generator"  # using MCweights
for evtNo, event in enumerate(events):
    event.getByLabel(genEvtInfoLabel, genEvtInfoHandle)
    genEvtInfo = genEvtInfoHandle.product()
    mcWeight = genEvtInfo.weight()
    mcSign = mcWeight / abs(mcWeight)
    event.getByLabel(lheLabel, lheHandle)
    lheHandle.product()
    hepupParts = lheHandle.product().hepeup()
    firstTopIdx = -1
    pdgIds = hepupParts.IDUP
    vecs = hepupParts.PUP
    if len(pdgIds) != len(vecs):
Beispiel #18
0
    from aux import scoutingStreamOK
    from aux import parkingStreamOK
    from aux import belongsToPAG

elif opts.maps == "nomaps":
    bUseMaps = False
else:
    print "<maps> input '%s' is wrong" %opts.maps
    print error_text
    print help_text
    sys.exit(2)
    

#Handles and labels
if isRawFiles:
    triggerBits, triggerBitLabel = Handle("edm::TriggerResults"), ("TriggerResults::HLT")
else:
    triggerBits, triggerBitLabel = Handle("edm::TriggerResults"), ("TriggerResults::MYHLT")


#Looping over the inputfiles
n = -1
nPassed_Physics = 0
nPassed_Scouting = 0
nPassed_Parking = 0
nPassed_Misc = 0

#List of triggers
myPaths = []
myPassedEvents = {}
from DataFormats.FWLite import Events, Handle
import ROOT
from math import pi, sqrt, copysign
from ROOT import TH1F, TFile, TTree, TString, gSystem, gROOT, AddressOf, TLorentzVector, TVector, TMath
import sys 
import os
import numpy as np

gSystem.Load("libFWCoreFWLite.so") 
ROOT.AutoLibraryLoader.enable()
gSystem.Load("libDataFormatsFWLite.so")
gSystem.Load("libDataFormatsPatCandidates.so")

events = Events (sys.argv[1])
weighthandle = Handle ('LHEEventProduct')
weightlabel = ("source")

evt_i = 0
stat_i = 0

number_of_weights = 0

for event in events:
        if evt_i > 0:
                break

        event.getByLabel(weightlabel,weighthandle)      
        Weightvector = weighthandle.product()
	number_of_weights = Weightvector.weights().size()
	
	evt_i = evt_i + 1
Beispiel #20
0
from DataFormats.FWLite import Handle, Events
import inspect
events = Events("root://cmseos.fnal.gov//store/user/jmanagan/TrackingHATS2017/tracks_and_vertices_DoubleMuon2017C_299370.root")
tracks = Handle("std::vector<reco::Track>")
i = 0
print "Printing 5 events"
for event in events:
    print "Event", i
    print "Track q*pT, Dxy, Dz, chi2, ndof, N valid hits, Algo"
    event.getByLabel("generalTracks", tracks)
    j = 0
    for track in tracks.product():
        #if j > 24: continue
        print "    Track", j, track.charge()*track.pt(), track.dxy(), track.dz(), track.chi2(), track.ndof(), track.numberOfValidHits(), track.algoName()
        j += 1
    i += 1
    if i >= 5: break
Beispiel #21
0
# allow termination by ctrl+c
try:

    for f in files:

        # tries to fetch the file from eos, pass if fetching is unsuccessful for one file
        try:
            # open file (you can use 'edmFileUtil -d /store/whatever.root' to get the physical file name)
            print "->Opening file", f.split()[0]
            if 'file:' in f.split()[0]:
                events = Events(f.split()[0])
            else:
                events = Events(eos_redirector + f.split()[0])
                #events = Events("root://xrootd-cms.infn.it//"+f.split()[0]) #AAA

            lhe, lheLabel = Handle("LHEEventProduct"), "externalLHEProducer"
            handlePruned = Handle("std::vector<reco::GenParticle>")
            handleJets = Handle("std::vector<reco::GenJet>")

            if onMiniAOD:
                labelPruned = ("prunedGenParticles")
                labelJets = ("slimmedGenJets")
                labelMuon = ("slimmedMuons")
                handleMuon = Handle("vector<pat::Muon>")
            else:
                labelPruned = ("genParticles")
                labelJets = ("ak4GenJets")
                labelMuon = ("muons")
                handleMuon = Handle("vector<reco::Muon>")

            if events == None:
Beispiel #22
0
ROOT.gROOT.SetBatch()

plt.style.use("default")
plt.rcParams["grid.linestyle"] = ":"
plt.rcParams["savefig.dpi"] = 120
plt.rcParams["savefig.bbox"] = "tight"

bkgType = "ZZZ"
# ZZZ
fn = samples[bkgType]
events = Events(fn)
print("- Sample: {}".format(fn))
print("- Number of events: {}".format(events.size()))

genHdl = Handle("std::vector<reco::GenParticle>")
genLbl = ("genParticles", "", "HLT")

recoMuHdl = Handle("std::vector<reco::Muon>")
recoMuLbl = ("muons", "", "RECO")

res_pt = defaultdict(list)
res_eta = defaultdict(list)
res_phi = defaultdict(list)
res_dR = defaultdict(list)

recoMu_n = list()
recoMu_pt = list()
recoMu_eta = list()
recoMu_dR = list()  # deltaR between leading and subleading
Beispiel #23
0
        'label': ("particleFlowRecHitHBHE", "", "RECO2"),
        'edmType': "vector<reco::PFRecHit>"
    },
    #  'pfClusters':{'label':("particleFlowClusterHBHE", "",  "RECO2"), 'edmType':"vector<reco::PFCluster>"},
    'caloRecHits': {
        'label': ("hbhereco", "", "RECO2"),
        'edmType':
        'edm::SortedCollection<HBHERecHit,edm::StrictWeakOrdering<HBHERecHit> >'
    },
    'jets': {
        'label': ("ak4PFJetsCHS", "", "RECO2"),
        'edmType': 'vector<reco::PFJet>'
    }
}
handles = {
    v: Handle(edmCollections[v]['edmType'])
    for v in edmCollections.keys()
}


def getProd(name):
    events.getByLabel(edmCollections[name]['label'], handles[name])
    return handles[name].product()


#binning=range(20)+[x*10 for x in range(2,20)]+[x*100 for x in range(2,20)]
#m0_energy  = ROOT.TH1F("m0_energy","m0_energy",len(binning)-1,array('d',binning))
#m21_energy = ROOT.TH1F("m21_energy","m21_energy",len(binning)-1,array('d',binning))
#m23_energy = ROOT.TH1F("m23_energy","m23_energy",len(binning)-1,array('d',binning))

nevents = 10 if small else events.size()
import ROOT
from DataFormats.FWLite import Events, Handle

gemRecHitsLabel, gemRecHits = "gemRecHits", Handle(
    "edm::RangeMap<GEMDetId,edm::OwnVector<GEMRecHit,edm::ClonePolicy<GEMRecHit> >,edm::ClonePolicy<GEMRecHit> >"
)
simHitsLabel, simHits = ("g4SimHits", "MuonGEMHits"), Handle("vector<PSimHit>")

h_cls = ROOT.TH2D("GEM RecHit Cluster size",
                  "GEM RecHit Cluster size; Cluster size; i#eta", 10, 0, 10, 8,
                  1, 9)
h_dx = ROOT.TH1D("GEM RecHit Resolution X",
                 "GEM RecHit Resolution X; #delta x; i#eta", 30, -5, 5)
h_sim_ieta = ROOT.TH1D("GEM SimHit i#eta",
                       "GEM SimHit i#eta; i#eta; Number of GEMSimHit", 8, 1, 9)
h_sim_ieta_matched = ROOT.TH1D(
    "GEM SimHit i#eta matched",
    "GEM SimHit i#eta matched; #ieta; Number of GEMSimHit", 8, 1, 9)

fdir = "../step3.root"

events = Events(fdir)
for iev, event in enumerate(events):
    print "iev", iev

    event.getByLabel(simHitsLabel, simHits)
    event.getByLabel(gemRecHitsLabel, gemRecHits)

    for rh in gemRecHits.product():
        h_cls.Fill(rh.gemId().roll(), rh.clusterSize())
Beispiel #25
0
t.Branch('ZfinalState', ZDecay, 'ZfinalState/I')
t.Branch('HfinalState', HDecayMode, 'HfinalState/I')
t.Branch('HfinalStateNew', HDecayModeNew, 'HfinalStateNew/I')

events = Events([
    "/storage/data/cms/store/mc/RunIISummer16MiniAODv2/ZHToTauTau_M125_13TeV_powheg_pythia8/MINIAODSIM/PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v1/70000/20245004-44C7-E611-A5AF-A0369F3016EC.root",
    "/storage/data/cms/store/mc/RunIISummer16MiniAODv2/ZHToTauTau_M125_13TeV_powheg_pythia8/MINIAODSIM/PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v1/70000/220CB8B6-53C7-E611-BC88-0CC47AD99052.root",
    #"/storage/data/cms/store/mc/RunIISummer16MiniAODv2/ZHToTauTau_M125_13TeV_powheg_pythia8/MINIAODSIM/PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v1/70000/2411BE9B-74C8-E611-84FA-02163E019D73.root",
    #"/storage/data/cms/store/mc/RunIISummer16MiniAODv2/ZHToTauTau_M125_13TeV_powheg_pythia8/MINIAODSIM/PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v1/70000/2A9B92A1-89C6-E611-A50D-002590E2D9FE.root",
    #"/storage/data/cms/store/mc/RunIISummer16MiniAODv2/ZHToTauTau_M125_13TeV_powheg_pythia8/MINIAODSIM/PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v1/70000/4C20BEC8-D9C7-E611-B74B-FA163E2D1FE1.root",
    #"/storage/data/cms/store/mc/RunIISummer16MiniAODv2/ZHToTauTau_M125_13TeV_powheg_pythia8/MINIAODSIM/PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v1/70000/505A0021-F7C7-E611-9687-D067E5F91E51.root",
    #"/storage/data/cms/store/mc/RunIISummer16MiniAODv2/ZHToTauTau_M125_13TeV_powheg_pythia8/MINIAODSIM/PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v1/70000/600D3FD8-48C7-E611-B341-90B11C0BD210.root",
    #"/storage/data/cms/store/mc/RunIISummer16MiniAODv2/ZHToTauTau_M125_13TeV_powheg_pythia8/MINIAODSIM/PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v1/70000/88867835-A7C7-E611-B26A-008CFA11113C.root",
])

handlePruned, labelPruned = Handle(
    "std::vector<reco::GenParticle>"), "prunedGenParticles"
handlePacked, labelPacked = Handle(
    "std::vector<pat::PackedGenParticle> "), "packedGenParticles"
triggerBits, triggerBitLabel = Handle("edm::TriggerResults"), (
    "TriggerResults", "", "HLT")
triggerPrescales, triggerPrescaleLabel = Handle(
    "pat::PackedTriggerPrescales"), "patTrigger"
# loop over events
count = 0
for iev, event in enumerate(events):
    event.getByLabel(labelPacked, handlePacked)
    event.getByLabel(labelPruned, handlePruned)
    event.getByLabel(triggerBitLabel, triggerBits)
    event.getByLabel(triggerPrescaleLabel, triggerPrescales)
    # get the product
    packed = handlePacked.product()
Beispiel #26
0
 def declareHandles(self):
     super(SkimAnalyzerCount, self).declareHandles()
     self.counterHandle = Handle("edm::MergeableCounter")
     self.mchandles['GenInfo'] = AutoHandle(('generator', '', ''),
                                            'GenEventInfoProduct')
Beispiel #27
0
eventTree.Branch('jetPhi_j2', jetPhi_j2, 'jetPhi_j2/F')
eventTree.Branch('jetEta_j2', jetEta_j2, 'jetEta_j2/F')
eventTree.Branch('jetSDmass_j2', jetSDmass_j2, 'jetSDmass_j2/F')
eventTree.Branch('best_class_j2', best_class_j2, 'best_class_j2/I')
eventTree.Branch('prob_t_j3', prob_t_j3, 'prob_t_j3/F')
eventTree.Branch('prob_W_j3', prob_W_j3, 'prob_W_j3/F')
eventTree.Branch('prob_Z_j3', prob_Z_j3, 'prob_Z_j3/F')
eventTree.Branch('prob_H_j3', prob_H_j3, 'prob_H_j3/F')
eventTree.Branch('prob_j_j3', prob_j_j3, 'prob_j_j3/F')
eventTree.Branch('jetPt_j3', jetPt_j3, 'jetPt_j3/F')
eventTree.Branch('jetPhi_j3', jetPhi_j3, 'jetPhi_j3/F')
eventTree.Branch('jetEta_j3', jetEta_j3, 'jetEta_j3/F')
eventTree.Branch('jetSDmass_j3', jetSDmass_j3, 'jetSDmass_j3/F')
eventTree.Branch('best_class_j3', best_class_j3, 'best_class_j3/I')

jetsHandle = Handle("std::vector<pat::Jet>")
jetsLabel = ("BESTProducer", "savedJets", "run")
modeHandle = Handle("std::vector<int>")
modeLabel = ("BESTProducer", "decayMode", "run")
npvHandle = Handle("std::vector<int>")
npvLabel = ("BESTProducer", "nPV", "run")
nnLabels = []
nnLabels.append( ("BESTProducer", "FWmoment1H", "run") )
nnLabels.append( ("BESTProducer", "FWmoment1W", "run") )
nnLabels.append( ("BESTProducer", "FWmoment1Z", "run") )
nnLabels.append( ("BESTProducer", "FWmoment1top", "run") )
nnLabels.append( ("BESTProducer", "FWmoment2H", "run") )
nnLabels.append( ("BESTProducer", "FWmoment2W", "run") )
nnLabels.append( ("BESTProducer", "FWmoment2Z", "run") )
nnLabels.append( ("BESTProducer", "FWmoment2top", "run") )
nnLabels.append( ("BESTProducer", "FWmoment3H", "run") )
Beispiel #28
0
ROOT.gROOT.SetBatch()

#inputFileListDir="./filelists/"+Sample+"/"
inputFileListName=sys.argv[1]

#inputFileList=inputFileListDir+inputFileListName
inputFileList=inputFileListName

if len(sys.argv)>2:
    outputFileDir=sys.argv[2]
else:
    outputFileDir = "./plots/"
outputFileName = outputFileDir+"h_"+inputFileListName.split("/")[-1].replace(".txt",".root")
print outputFileName

handleMuon = Handle ('vector<pat::Muon>')
labelMuon = ('slimmedMuons')

handleElectron = Handle ('vector<pat::Electron>')
labelElectron = ('slimmedElectrons')

handleJet = Handle ('vector<pat::Jet>')
labelJet = ('slimmedJets')

handleVertex = Handle ('vector<reco::Vertex>')
labelVertex = ('offlineSlimmedPrimaryVertices')

handleGenParticle = Handle ('vector<reco::GenParticle>')
labelGenParticle = ('genParticles')

handleHLT = Handle ('edm::TriggerResults')
fout = ROOT.TFile(options.outputFile, "recreate")
t = ROOT.TTree("events", "events")

declare_branches(t)

# load FWLite C++ libraries
ROOT.gSystem.Load("libFWCoreFWLite.so")
ROOT.gSystem.Load("libDataFormatsFWLite.so")
ROOT.FWLiteEnabler.enable()

# load FWlite python libraries
from DataFormats.FWLite import Handle, Events

mahi, mahiLabel = Handle(
    "edm::SortedCollection<HBHERecHit,edm::StrictWeakOrdering<HBHERecHit> >"
), "slimmedHcalRecHits"
#facile, facileLabel      = Handle("edm::SortedCollection<HBHERecHit,edm::StrictWeakOrdering<HBHERecHit> >"), "hltHbherecofacile"
#simhit, simhitLabel  = Handle("std::vector<PCaloHit>"), "g4SimHits"
#vector<PCaloHit>                      "g4SimHits"                 "HcalHits"        "SIM"

events = Events(options)

mahi = Handle(
    "edm::SortedCollection<HBHERecHit,edm::StrictWeakOrdering<HBHERecHit> >")
print(options.inputFiles)
#print(events.GetEntriesFast())
for ievent, event in enumerate(events):
    print('event', ievent)
    event.getByLabel("slimmedHcalRecHits", "reducedHcalRecHits", mahi)
    print(mahi)
#fout = ROOT.TFile ("jetmet.root","recreate")
fout = ROOT.TFile (options.outputFile,"recreate")
t    = ROOT.TTree ("events","events")

declare_branches(t)

# load FWLite C++ libraries
ROOT.gSystem.Load("libFWCoreFWLite.so");
ROOT.gSystem.Load("libDataFormatsFWLite.so");
ROOT.FWLiteEnabler.enable()

# load FWlite python libraries
from DataFormats.FWLite import Handle, Events

pfs, pfLabel        = Handle("std::vector<pat::PackedCandidate>"), "packedPFCandidates"
jets, jetLabel      = Handle("std::vector<pat::Jet>"), "slimmedJets"
mets, metLabel      = Handle("std::vector<pat::MET>"), "slimmedMETs"
vertex, vertexLabel = Handle("std::vector<reco::Vertex>"),"offlineSlimmedPrimaryVertices"

rhoall_, rhoallLabel         = Handle("double"), "fixedGridRhoFastjetAll"
rhocentral_, rhocentralLabel = Handle("double"), "fixedGridRhoFastjetCentral"
rhoneutral_, rhoneutralLabel = Handle("double"), "fixedGridRhoFastjetCentralNeutral"
rhochargedpileup_, rhochargedpileupLabel = Handle("double"), "fixedGridRhoFastjetCentralChargedPileUp"

# open file (you can use 'edmFileUtil -d /store/whatever.root' to get the physical file name)
#events = Events("file:/eos/cms/store/relval/CMSSW_9_4_0_pre3/RelValTTbar_13/MINIAODSIM/PU25ns_94X_mc2017_realistic_PixFailScenario_Run305081_FIXED_HS_AVE50-v1/10000/02B605A1-86C2-E711-A445-4C79BA28012B.root")
events = Events(options)

for ievent,event in enumerate(events):