def plot_ratios(cut_name, cut, samples, out_dir, recreate, flavour_scenario=flavour_scenarios[0]): out_dir += "/" + cut_name mkdir_p(out_dir) colls = dict() samples_WJets = filter(lambda x: sample_types.is_wjets(x.name), samples) for sc in flavour_scenario: logger.info("Drawing ratio with cut %s" % sc) cut_ = cut*getattr(Cuts, sc) colls[sc] = data_mc(costheta["var"], cut_name + "__" + sc, cut_, Weights.total()*Weights.mu, samples_WJets, out_dir, recreate, LUMI_TOTAL, plot_range=costheta["range"]) logger.debug(colls[flavour_scenario[0]].hists["weight__nominal/cut__all/WJets_sherpa_nominal"].Integral()) logger.debug(colls[flavour_scenario[1]].hists["weight__nominal/cut__all/WJets_sherpa_nominal"].Integral()) coll = dict() for k, c in colls.items(): for hn, h in c.hists.items(): coll[hn + "/" + k] = h for k, h in coll.items(): logger.debug("%s = %s" % (k, str([y for y in h.y()]))) logger.debug(coll) #coll = HistCollection(coll, name=cut_name) merges = {} for sc in flavour_scenario: merges["madgraph/%s" % sc] = ["weight__nominal/cut__all/W[1-4]Jets_exclusive/%s" % sc] merges["sherpa/unweighted/%s" % sc] = ["weight__nominal/cut__all/WJets_sherpa_nominal/%s" % sc] merges["sherpa/weighted/%s" % sc] = ["weight__sherpa_flavour/cut__all/WJets_sherpa_nominal/%s" % sc] merged = merge_hists(coll, merges) for k, h in merged.items(): logger.debug("%s = %s" % (k, str([y for y in h.y()]))) hists_flavour = dict() hists_flavour["madgraph"] = ROOT.TH1F("madgraph", "madgraph", len(flavour_scenario), 0, len(flavour_scenario)-1) hists_flavour["sherpa/unweighted"] = ROOT.TH1F("sherpa_unw", "sherpa unweighted", len(flavour_scenario), 0, len(flavour_scenario)-1) hists_flavour["sherpa/weighted"] = ROOT.TH1F("sherpa_rew", "sherpa weighted", len(flavour_scenario), 0, len(flavour_scenario)-1) for i, sc in zip(range(1,len(flavour_scenario)+1), flavour_scenario): sh1_int, sh1_err = calc_int_err(merged["sherpa/unweighted/%s" % sc]) sh2_int, sh2_err = calc_int_err(merged["sherpa/weighted/%s" % sc]) mg_int, mg_err = calc_int_err(merged["madgraph/%s" % sc]) logger.debug("%.2f %.2f" % (sh1_int, sh1_err)) logger.debug("%.2f %.2f" % (sh2_int, sh2_err)) logger.debug("%.2f %.2f" % (mg_int, mg_err)) hists_flavour["madgraph"].SetBinContent(i, mg_int) hists_flavour["madgraph"].SetBinError(i, mg_err) hists_flavour["sherpa/unweighted"].SetBinContent(i, sh1_int) hists_flavour["sherpa/unweighted"].SetBinError(i, sh1_err) hists_flavour["sherpa/weighted"].SetBinContent(i, sh2_int) hists_flavour["sherpa/weighted"].SetBinError(i, sh2_err) hists_flavour["madgraph"].GetXaxis().SetBinLabel(i, sc) hists_flavour["sherpa/unweighted"].GetXaxis().SetBinLabel(i, sc) hists_flavour["sherpa/weighted"].GetXaxis().SetBinLabel(i, sc) hists_flavour["sherpa/weighted"].Sumw2() hists_flavour["sherpa/unweighted"].Sumw2() hists_flavour["madgraph"].Sumw2() hists_flavour["ratio/unweighted"] = hists_flavour["madgraph"].Clone("ratio_unw") hists_flavour["ratio/unweighted"].Divide(hists_flavour["sherpa/unweighted"]) hists_flavour["ratio/weighted"] = hists_flavour["madgraph"].Clone("ratio_rew") hists_flavour["ratio/weighted"].Divide(hists_flavour["sherpa/weighted"]) for i, sc in zip(range(1,len(flavour_scenario)+1), flavour_scenario): logger.info("weights[%s] = %.6f; //error=%.6f [%d]" % (sc, hists_flavour["ratio/unweighted"].GetBinContent(i), hists_flavour["ratio/unweighted"].GetBinError(i), i)) flavour_ratio_coll = HistCollection(hists_flavour, name="hists__flavour_ratios") flavour_ratio_coll.save(out_dir) for sc in flavour_scenario: hists = [merged["madgraph/%s" % sc], merged["sherpa/unweighted/%s" % sc], merged["sherpa/weighted/%s" % sc]] for hist in hists: norm(hist) #hist.SetName(sc) #hist.SetTitle(sc) ColorStyleGen.style_hists(hists) canv = plot_hists(hists, x_label=costheta["varname"]) leg = legend(hists, styles=["f", "f"], nudge_x=-0.2) chi2 = hists[0].Chi2Test(hists[1], "WW CHI2/NDF") hists[0].SetTitle("madgraph to sherpa comparison #chi^{2}/ndf=%.2f" % chi2) canv.Update() canv.SaveAs(out_dir + "/flavours__%s.png" % (sc)) md_merged = dict() for sc in flavour_scenario: logger.info("Calculating ratio for %s" % sc) hi = merged["sherpa/unweighted/%s" % sc].Clone("ratio__%s" % sc) hi.Divide(merged["madgraph/%s" % sc]) merged[hi.GetName()] = hi hc_merged = HistCollection(merged, md_merged, "hists__costheta_flavours_merged") hc_merged.save(out_dir) logger.info("Saved merged histogram collection")
def SingleTopStep2(): options = VarParsing("analysis") options.register( "subChannel", "T_t", VarParsing.multiplicity.singleton, VarParsing.varType.string, "The sample that you are running on", ) options.register( "reverseIsoCut", False, VarParsing.multiplicity.singleton, VarParsing.varType.bool, "Consider anti-isolated region", ) options.register( "doDebug", False, VarParsing.multiplicity.singleton, VarParsing.varType.bool, "Turn on debugging messages" ) options.register("isMC", True, VarParsing.multiplicity.singleton, VarParsing.varType.bool, "Run on MC") options.register( "doGenParticlePath", True, VarParsing.multiplicity.singleton, VarParsing.varType.bool, "Run the gen particle paths (only works on specific MC)", ) options.register( "globalTag", Config.globalTagMC, VarParsing.multiplicity.singleton, VarParsing.varType.string, "Global tag" ) options.register( "srcPUDistribution", "S10", VarParsing.multiplicity.singleton, VarParsing.varType.string, "Source pile-up distribution", ) options.register( "destPUDistribution", "data", VarParsing.multiplicity.singleton, VarParsing.varType.string, "destination pile-up distribution", ) options.register( "isComphep", False, VarParsing.multiplicity.singleton, VarParsing.varType.bool, "Use CompHep-specific processing", ) options.register( "isAMCatNLO", False, VarParsing.multiplicity.singleton, VarParsing.varType.bool, "Use aMC@NLO-specific processing", ) options.register( "isSherpa", False, VarParsing.multiplicity.singleton, VarParsing.varType.bool, "Use sherpa-specific processing" ) options.register( "systematic", "", VarParsing.multiplicity.singleton, VarParsing.varType.string, "Apply Systematic variation" ) options.register( "dataRun", "RunABCD", VarParsing.multiplicity.singleton, VarParsing.varType.string, "A string Run{A,B,C,D} to specify the data period", ) options.register( "doSync", False, VarParsing.multiplicity.singleton, VarParsing.varType.bool, "Synchronization exercise" ) options.parseArguments() if options.isMC: Config.srcPUDistribution = pileUpDistributions.distributions[options.srcPUDistribution] Config.Leptons.reverseIsoCut = options.reverseIsoCut Config.subChannel = options.subChannel Config.doDebug = options.doDebug Config.isMC = options.isMC Config.doSkim = options.doSync or not sample_types.is_signal(Config.subChannel) Config.isCompHep = options.isComphep or "comphep" in Config.subChannel Config.isAMCatNLO = Config.isAMCatNLO or options.isAMCatNLO or "aMCatNLO" in Config.subChannel Config.isSherpa = options.isSherpa or "sherpa" in Config.subChannel Config.systematic = options.systematic Config.doSync = options.doSync print "Systematic: ", Config.systematic if Config.isMC and not Config.doSync: logging.info("Changing jet source from %s to smearedPatJetsWithOwnRef" % Config.Jets.source) Config.Jets.source = "smearedPatJetsWithOwnRef" if Config.systematic in ["ResUp", "ResDown"]: logging.info( "Changing jet source from %s to smearedPatJetsWithOwnRef%s" % (Config.Jets.source, Config.systematic) ) Config.Jets.source = "smearedPatJetsWithOwnRef" + Config.systematic logging.info( "Changing MET source from %s to patType1CorrectedPFMetJet%s" % (Config.metSource, Config.systematic) ) Config.metSource = "patType1CorrectedPFMetJet" + Config.systematic elif Config.systematic in ["EnUp", "EnDown"]: logging.info( "Changing jet source from %s to shiftedPatJetsWithOwnRef%sForCorrMEt" % (Config.Jets.source, Config.systematic) ) Config.Jets.source = "shiftedPatJetsWithOwnRef" + Config.systematic + "ForCorrMEt" logging.info( "Changing MET source from %s to patType1CorrectedPFMetJet%s" % (Config.metSource, Config.systematic) ) Config.metSource = "patType1CorrectedPFMetJet" + Config.systematic elif Config.systematic in ["UnclusteredEnUp", "UnclusteredEnDown"]: logging.info( "Changing MET source from %s to patType1CorrectedPFMet%s" % (Config.metSource, Config.systematic) ) Config.metSource = "patType1CorrectedPFMet" + Config.systematic print "Configuration" print Config._toStr() print Config.Jets._toStr() print Config.Muons._toStr() print Config.Electrons._toStr() print "" process = cms.Process("STPOLSEL2") eventCounting.countProcessed(process) process.load("Configuration.Geometry.GeometryIdeal_cff") process.load("Configuration.StandardSequences.FrontierConditions_GlobalTag_cff") from Configuration.AlCa.autoCond import autoCond process.GlobalTag.globaltag = cms.string(options.globalTag) process.load("Configuration.StandardSequences.MagneticField_cff") if Config.doDebug: process.load("FWCore.MessageLogger.MessageLogger_cfi") process.MessageLogger = cms.Service( "MessageLogger", destinations=cms.untracked.vstring("cout", "debug"), debugModules=cms.untracked.vstring("*"), cout=cms.untracked.PSet(threshold=cms.untracked.string("INFO")), debug=cms.untracked.PSet(threshold=cms.untracked.string("DEBUG")), ) logging.basicConfig(level=logging.DEBUG) else: process.load("FWCore.MessageLogger.MessageLogger_cfi") process.MessageLogger.cerr.FwkReport.reportEvery = 1000 process.MessageLogger.cerr.threshold = cms.untracked.string("INFO") logging.basicConfig(level=logging.DEBUG) process.maxEvents = cms.untracked.PSet(input=cms.untracked.int32(options.maxEvents)) process.options = cms.untracked.PSet(wantSummary=cms.untracked.bool(True)) import os from FWCore.PythonUtilities.LumiList import LumiList if not Config.isMC: ll1 = LumiList( os.environ["CMSSW_BASE"] + "/../crabs/lumis/Cert_190456-208686_8TeV_22Jan2013ReReco_Collisions12_JSON.txt" ) process.source = cms.Source( "PoolSource", fileNames=cms.untracked.vstring(options.inputFiles), cacheSize=cms.untracked.uint32(50 * 1024 * 1024), lumisToProcess=ll1.getVLuminosityBlockRange() if not Config.isMC else cms.untracked.VLuminosityBlockRange(), ) print options # ------------------------------------------------- # Jets # ------------------------------------------------- from SingleTopPolarization.Analysis.jets_step2_cfi import JetSetup JetSetup(process, Config) # ------------------------------------------------- # Leptons # ------------------------------------------------- from SingleTopPolarization.Analysis.muons_step2_cfi import MuonSetup MuonSetup(process, Config) from SingleTopPolarization.Analysis.electrons_step2_cfi import ElectronSetup ElectronSetup(process, Config) process.looseVetoMuCount = cms.EDProducer( "CollectionSizeProducer<reco::Candidate>", src=cms.InputTag("looseVetoMuons") ) process.looseVetoEleCount = cms.EDProducer( "CollectionSizeProducer<reco::Candidate>", src=cms.InputTag("looseVetoElectrons") ) process.decayTreeProducerMu = cms.EDProducer( "GenParticleDecayTreeProducer", src=cms.untracked.InputTag("singleIsoMu") ) process.decayTreeProducerEle = cms.EDProducer( "GenParticleDecayTreeProducer", src=cms.untracked.InputTag("singleIsoEle") ) # ----------------------------------------------- # Top reco and cosine calcs # ----------------------------------------------- from SingleTopPolarization.Analysis.top_step2_cfi import TopRecoSetup TopRecoSetup(process, Config) process.allEventObjects = cms.EDProducer( "CandRefCombiner", sources=cms.vstring(["goodJets", "goodSignalLeptons", Config.metSource]), maxOut=cms.uint32(9999), minOut=cms.uint32(0), logErrors=cms.bool(False), ) process.hadronicEventObjects = cms.EDProducer( "CandRefCombiner", sources=cms.vstring(["goodJets"]), maxOut=cms.uint32(9999), minOut=cms.uint32(0), logErrors=cms.bool(False), ) process.allEventObjectsWithNu = cms.EDProducer( "CandRefCombiner", sources=cms.vstring(["goodJets", "goodSignalLeptons", Config.metSource, "recoNuProducer"]), maxOut=cms.uint32(9999), minOut=cms.uint32(0), logErrors=cms.bool(False), ) process.eventShapeVars = cms.EDProducer("EventShapeVarsProducer", src=cms.InputTag("allEventObjects")) process.eventShapeVarsWithNu = cms.EDProducer("EventShapeVarsProducer", src=cms.InputTag("allEventObjectsWithNu")) # Vector sum of all reconstructed objects process.shat = cms.EDProducer("SimpleCompositeCandProducer", sources=cms.VInputTag(["allEventObjects"])) # Hadronic final state process.ht = cms.EDProducer("SimpleCompositeCandProducer", sources=cms.VInputTag(["hadronicEventObjects"])) process.shatNTupleProducer = cms.EDProducer( "CandViewNtpProducer2", src=cms.InputTag("shat"), lazyParser=cms.untracked.bool(True), prefix=cms.untracked.string(""), # eventInfo = cms.untracked.bool(True), variables=ntupleCollection([["Pt", "pt"], ["Eta", "eta"], ["Phi", "phi"], ["Mass", "mass"]]), ) process.htNTupleProducer = process.shatNTupleProducer.clone(src=cms.InputTag("ht")) process.eventShapeSequence = cms.Sequence( process.allEventObjects * process.hadronicEventObjects * process.eventShapeVars * process.allEventObjectsWithNu * process.eventShapeVarsWithNu * process.shat * process.ht * process.shatNTupleProducer * process.htNTupleProducer ) # ----------------------------------------------- # Treemaking # ----------------------------------------------- process.recoTopNTupleProducer = cms.EDProducer( "CandViewNtpProducer2", src=cms.InputTag("recoTop"), lazyParser=cms.untracked.bool(True), prefix=cms.untracked.string(""), # eventInfo = cms.untracked.bool(True), variables=ntupleCollection([["Pt", "pt"], ["Eta", "eta"], ["Phi", "phi"], ["Mass", "mass"]]), ) process.recoNuNTupleProducer = cms.EDProducer( "CandViewNtpProducer2", src=cms.InputTag("recoNu"), lazyParser=cms.untracked.bool(True), prefix=cms.untracked.string(""), # eventInfo = cms.untracked.bool(True), variables=ntupleCollection( [ ["Pt", "pt"], ["Eta", "eta"], ["Phi", "phi"], ["Px", "p4().Px()"], ["Py", "p4().Py()"], ["Pz", "p4().Pz()"], ] ), ) process.recoWNTupleProducer = cms.EDProducer( "CandViewNtpProducer2", src=cms.InputTag("recoW"), lazyParser=cms.untracked.bool(True), prefix=cms.untracked.string(""), variables=ntupleCollection([["Pt", "pt"], ["Eta", "eta"], ["Phi", "phi"], ["Mass", "mass"]]), ) process.trueNuNTupleProducer = process.recoNuNTupleProducer.clone( src=cms.InputTag("genParticleSelector", "trueNeutrino", "STPOLSEL2") ) process.trueWNTupleProducer = process.recoTopNTupleProducer.clone( src=cms.InputTag("genParticleSelector", "trueWboson", "STPOLSEL2") ) process.trueTopNTupleProducer = process.recoTopNTupleProducer.clone( src=cms.InputTag("genParticleSelector", "trueTop", "STPOLSEL2") ) process.patMETDeltaRProducer = cms.EDProducer( "DeltaRProducerMET", muonSrc=cms.InputTag("goodSignalMuons"), electronSrc=cms.InputTag("goodSignalElectrons"), metSrc=cms.InputTag(Config.metSource), ) process.patMETNTupleProducer = cms.EDProducer( "CandViewNtpProducer2", src=cms.InputTag(Config.metSource), lazyParser=cms.untracked.bool(True), prefix=cms.untracked.string(""), variables=ntupleCollection( [ ["Pt", "pt"], ["Eta", "eta"], ["Phi", "phi"], ["Px", "p4().Px()"], ["Py", "p4().Py()"], ["Pz", "p4().Pz()"], ] ), ) process.trueLeptonNTupleProducer = process.recoTopNTupleProducer.clone( src=cms.InputTag("genParticleSelector", "trueLepton", "STPOLSEL2") ) process.trueLightJetNTupleProducer = process.recoTopNTupleProducer.clone( src=cms.InputTag("genParticleSelector", "trueLightJet", "STPOLSEL2") ) def userfloat(key): return "? hasUserFloat('{0}') ? userFloat('{0}') : {1}".format(key, nanval) def userint(key): return "? hasUserInt('{0}') ? userInt('{0}') : {1}".format(key, nanval) process.goodSignalMuonsNTupleProducer = cms.EDProducer( "CandViewNtpProducer2", src=cms.InputTag("patMETDeltaRProducer", "muons"), lazyParser=cms.untracked.bool(True), prefix=cms.untracked.string(""), # eventInfo = cms.untracked.bool(True), variables=ntupleCollection( [ ["Pt", "pt"], ["Eta", "eta"], ["Phi", "phi"], ["relIso", userfloat(Config.Muons.relIsoType)], ["Charge", "charge"], ["genPdgId", "? genParticlesSize() > 0 ? genParticle(0).pdgId() : {0}".format(nanval)], ["motherGenPdgId", "? genParticlesSize() > 0 ? genParticle(0).mother(0).pdgId() : {0}".format(nanval)], ["normChi2", "? globalTrack().isNonnull() ? normChi2 : {0}".format(nanval)], [ "trackhitPatterntrackerLayersWithMeasurement", userfloat("track_hitPattern_trackerLayersWithMeasurement"), ], [ "globalTrackhitPatternnumberOfValidMuonHits", userfloat("globalTrack_hitPattern_numberOfValidMuonHits"), ], [ "innerTrackhitPatternnumberOfValidPixelHits", userfloat("innerTrack_hitPattern_numberOfValidPixelHits"), ], ["db", "dB"], ["dz", userfloat("dz")], ["numberOfMatchedStations", "numberOfMatchedStations"], [ "triggerMatch", "? triggerObjectMatchesByPath('{0}').size()==1 ? triggerObjectMatchByPath('{0}').hasPathLastFilterAccepted() : {1}".format( Config.Muons.triggerPath, nanval ), ], ["deltaRMET", userfloat("deltaRMET")], ["deltaPhiMET", userfloat("deltaPhiMET")], ] ), ) process.isoMuonsNTP = process.goodSignalMuonsNTupleProducer.clone(src=cms.InputTag("muonsWithIso")) process.allMuonsNTP = process.goodSignalMuonsNTupleProducer.clone(src=cms.InputTag("muonsWithIDAll")) process.goodSignalElectronsNTupleProducer = cms.EDProducer( "CandViewNtpProducer2", src=cms.InputTag("patMETDeltaRProducer", "electrons"), lazyParser=cms.untracked.bool(True), prefix=cms.untracked.string(""), # eventInfo = cms.untracked.bool(True), variables=ntupleCollection( [ ["Pt", "%s" % Config.Electrons.pt], ["Eta", "eta"], ["Phi", "phi"], ["relIso", userfloat(Config.Electrons.relIsoType)], ["mvaID", "electronID('mvaTrigV0')"], ["Charge", "charge"], ["superClustereta", "superCluster.eta"], ["passConversionVeto", "passConversionVeto()"], [ "gsfTracktrackerExpectedHitsInnernumberOfHits", userint("gsfTrack_trackerExpectedHitsInner_numberOfHits"), ], [ "triggerMatch", "? triggerObjectMatchesByPath('{0}').size()==1 ? triggerObjectMatchByPath('{0}').hasPathLastFilterAccepted() : {1}".format( Config.Electrons.triggerPath, nanval ), ], ["genPdgId", "? genParticlesSize() > 0 ? genParticle(0).pdgId() : {0}".format(nanval)], ["motherGenPdgId", "? genParticlesSize() > 0 ? genParticle(0).mother(0).pdgId() : {0}".format(nanval)], ["deltaRMET", userfloat("deltaRMET")], ["deltaPhiMET", userfloat("deltaPhiMET")], ] ), ) process.isoElectronsNTP = process.goodSignalElectronsNTupleProducer.clone(src=cms.InputTag("electronsWithIso")) process.allElectronsNTP = process.goodSignalElectronsNTupleProducer.clone(src=cms.InputTag("electronsWithIDAll")) process.goodJetsNTupleProducer = cms.EDProducer( "CandViewNtpProducer2", src=cms.InputTag("goodJets"), lazyParser=cms.untracked.bool(True), prefix=cms.untracked.string(""), eventInfo=cms.untracked.bool(False), variables=ntupleCollection( [ ["Pt", "pt"], ["Eta", "eta"], ["Phi", "phi"], ["Mass", "mass"], # ["bDiscriminator", "bDiscriminator('%s')" % Config.Jets.bTagDiscriminant], ["bDiscriminatorTCHP", "bDiscriminator('%s')" % Config.Jets.BTagDiscriminant.TCHP], ["bDiscriminatorCSV", "bDiscriminator('%s')" % Config.Jets.BTagDiscriminant.CSV], ["rms", userfloat("rms")], ["partonFlavour", "partonFlavour()"], ["area", "jetArea()"], # These require PFCandidates to be present (huge collection) # ["n90", "n90()"], # ["n60", "n60()"], # ["genJetFlavour", "? genJet()>0 ? (genJet()->pdgId()) : 0"], #FIXME ["deltaR", userfloat("deltaR")], ["deltaPhi", userfloat("deltaPhi")], ["numberOfDaughters", "numberOfDaughters"], ["neutralHadronEnergy", "neutralHadronEnergy"], ["HFHadronEnergy", "HFHadronEnergy"], ["chargedEmEnergyFraction", "chargedEmEnergyFraction"], ["neutralEmEnergyFraction", "neutralEmEnergyFraction"], ["chargedHadronEnergyFraction", "chargedHadronEnergyFraction"], ["chargedMultiplicity", "chargedMultiplicity"], ["nParticles", userfloat("nParticles")], ["puMva", userfloat("mva")], ["nCharged", userfloat("nCharged")], ["nNeutral", userfloat("nNeutral")], ["deltaRMET", userfloat("deltaRMET")], ["deltaPhiMET", userfloat("deltaPhiMET")], ] ), ) process.lowestBTagJetNTupleProducer = process.goodJetsNTupleProducer.clone(src=cms.InputTag("lowestBTagJet")) process.highestBTagJetNTupleProducer = process.goodJetsNTupleProducer.clone(src=cms.InputTag("highestBTagJet")) process.treeSequenceNew = cms.Sequence( process.patMETNTupleProducer * process.recoTopNTupleProducer * process.recoNuNTupleProducer * process.recoWNTupleProducer * process.trueTopNTupleProducer * process.trueNuNTupleProducer * process.trueWNTupleProducer * process.trueLeptonNTupleProducer * process.trueLightJetNTupleProducer * process.goodJetsNTupleProducer * process.lowestBTagJetNTupleProducer * process.highestBTagJetNTupleProducer * process.goodSignalMuonsNTupleProducer * process.goodSignalElectronsNTupleProducer * process.isoMuonsNTP * process.isoElectronsNTP ) # ----------------------------------------------- # Flavour analyzer # ----------------------------------------------- Config.doWJetsFlavour = Config.isMC and sample_types.is_wjets(Config.subChannel) and not Config.isSherpa if Config.doWJetsFlavour: process.flavourAnalyzer = cms.EDProducer( "FlavourAnalyzer", genParticles=cms.InputTag("genParticles"), generator=cms.InputTag("generator"), genJets=cms.InputTag("selectedPatJets", "genJets"), saveGenJets=cms.bool(False), savePDFInfo=cms.bool(True), ) # ----------------------------------------------- # Paths # ----------------------------------------------- from SingleTopPolarization.Analysis.hlt_step2_cfi import HLTSetup HLTSetup(process, Config) from SingleTopPolarization.Analysis.leptons_cfg import LeptonSetup LeptonSetup(process, Config) if Config.isMC: WeightSetup(process, Config) if Config.isMC and options.doGenParticlePath: if Config.isCompHep: from SingleTopPolarization.Analysis.partonStudy_comphep_step2_cfi import PartonStudySetup elif Config.isAMCatNLO: from SingleTopPolarization.Analysis.partonStudy_aMCatNLO_step2_cfi import PartonStudySetup else: from SingleTopPolarization.Analysis.partonStudy_step2_cfi import PartonStudySetup PartonStudySetup(process) process.partonPath = cms.Path() # NOTE: this path will REJECT events not having a true t-channel lepton if sample_types.is_signal(Config.subChannel): logging.warning( "Using signal-only sequence 'process.partonStudyTrueSequence' on subChannel=%s" % Config.subChannel ) process.partonPath += process.partonStudyTrueSequence from SingleTopPolarization.Analysis.muons_step2_cfi import MuonPath MuonPath(process, Config) from SingleTopPolarization.Analysis.electrons_step2_cfi import ElectronPath ElectronPath(process, Config) if Config.isMC: process.muPath += process.weightSequence process.elePath += process.weightSequence if Config.isMC and sample_types.is_signal(Config.subChannel): process.muPath += process.partonStudyCompareSequence process.elePath += process.partonStudyCompareSequence process.treePath = cms.Path(process.treeSequenceNew) process.eventVarsPath = cms.Path(process.eventShapeSequence) # enable embedding the gen-level weight, which is relevant for the Sherpa sample if Config.isMC: process.genWeightProducer = cms.EDProducer("GenWeightProducer") process.eventVarsPath += process.genWeightProducer if Config.isAMCatNLO: process.lheWeightProducer = cms.EDProducer("LHEWeightProducer") process.eventVarsPath += process.lheWeightProducer if Config.doWJetsFlavour: process.treePath += process.flavourAnalyzer if Config.isMC: if not Config.isSherpa: process.meWeightProducer = cms.EDProducer("MEWeightProducer") process.eventVarsPath += process.meWeightProducer process.load("SimGeneral.HepPDTESSource.pythiapdt_cfi") process.prunedGenParticles = cms.EDProducer( "GenParticlePruner", src=cms.InputTag("genParticles"), select=cms.vstring( "drop *", "keep status = 3", # keeps all particles from the hard matrix element "+keep abs(pdgId) = 15 & status = 1", # keeps intermediate decaying tau ), ) """process.pat2pxlio=cms.EDAnalyzer('EDM2PXLIO', SelectEventsFromProcess=cms.vstring("USER"), SelectEventsFromPath = cms.vstring("p0"), OutFileName=cms.untracked.string("wjets.pxlio"), process=cms.untracked.string("test"), genCollection = cms.PSet( type=cms.string("GenParticle2Pxlio"), srcs=cms.VInputTag(cms.InputTag("prunedGenParticles")), EventInfo=cms.InputTag('generator') ), genJets = cms.PSet( type=cms.string("GenJet2Pxlio"), srcs=cms.VInputTag("ak5GenJets","kt4GenJets","kt6GenJets"), names=cms.vstring("AK5GenJets","KT4GenJets","KT6GenJets") ), q2weights = cms.PSet( type=cms.string("ValueList2Pxlio"), srcs=cms.VInputTag( cms.InputTag("extraPartons","nExtraPartons"), ), names = cms.vstring("nExtraPartons") ) )""" process.extraPartons = cms.EDProducer("ExtraPartonCounter", isTTJets=cms.bool("TTJets" in Config.subChannel)) process.extraPartonSequence = cms.Sequence(process.prunedGenParticles * process.extraPartons) # process.pxlioOut=cms.EndPath(process.out*process.pat2pxlio) process.eventVarsPath += process.extraPartonSequence # ----------------------------------------------- # Outpath # ----------------------------------------------- process.out = cms.OutputModule( "PoolOutputModule", dropMetaData=cms.untracked.string("DROPPED"), splitLevel=cms.untracked.int32(99), fileName=cms.untracked.string(options.outputFile), SelectEvents=cms.untracked.PSet(SelectEvents=cms.vstring(["*"])), outputCommands=cms.untracked.vstring( "drop *", #'keep *', "keep edmMergeableCounter_*__*", "keep *_generator__*", #'keep *_genParticles__*', #hack for powheg PDF sets "keep edmTriggerResults_TriggerResults__*", "keep *_flavourAnalyzer_*_STPOLSEL2", "keep floats_*_*_STPOLSEL2", "keep double_*__STPOLSEL2", "keep float_*__STPOLSEL2", "keep double_*_*_STPOLSEL2", "keep float_*_*_STPOLSEL2", "keep int_*__STPOLSEL2", "keep int_*_*_STPOLSEL2", "keep int_*_*_*", "keep String_*_*_*", # the decay trees "keep *_pdfInfo1_*_STPOLSEL2", "keep *_pdfInfo2_*_STPOLSEL2", "keep *_pdfInfo3_*_STPOLSEL2", "keep *_pdfInfo4_*_STPOLSEL2", "keep *_pdfInfo5_*_STPOLSEL2", #'keep *', #'keep *_recoTop_*_*', #'keep *_goodSignalMuons_*_*', #'keep *_goodSignalElectrons_*_*', #'keep *_goodJets_*_*', #'keep *_bTaggedJets_*_*', #'keep *_untaggedJets_*_*', ), ) if Config.doDebug: process.out.outputCommands.append("keep *") process.debugpath = cms.Path( process.muAnalyzer * process.eleAnalyzer * process.jetAnalyzer * process.metAnalyzer ) process.outpath = cms.EndPath(process.out) if Config.doSkim: process.out.SelectEvents.SelectEvents = [] process.out.SelectEvents.SelectEvents.append("elePath") process.out.SelectEvents.SelectEvents.append("muPath") # ----------------------------------------------- # Final printout # ----------------------------------------------- if hasattr(process, "out"): print "Output patTuples: %s" % process.out.fileName.value() print 80 * "-" print "Step2 configured" return process
#logging.getLogger("utils").setLevel(logging.ERROR) #logging.getLogger("histogram").setLevel(logging.ERROR) #logging.getLogger("plot_utils").setLevel(logging.ERROR) ROOT.gStyle.SetOptTitle(True) import argparse parser = argparse.ArgumentParser(description='Draw WJets sherpa plots') parser.add_argument('--recreate', dest='recreate', action='store_true') parser.add_argument('--tag', type=str, default="test") args = parser.parse_args() if args.recreate: samples = load_samples(os.environ["STPOL_DIR"]) for s in samples.values(): if sample_types.is_wjets(s.name): s.tree.AddFriend("trees/WJets_weights", s.tfile) else: samples = {} out_dir = os.environ["STPOL_DIR"] + "/out/plots/wjets" if args.tag: out_dir += "/" + args.tag mkdir_p(out_dir) # plot_ratios("2J0T", Cuts.final(2,0), samples, out_dir, args.recreate) # plot_ratios("2J1T", Cuts.final(2,1), samples, out_dir, args.recreate) colls_in, colls_out = plot_sherpa_vs_madgraph( costheta, "2J",