Back to home page

Project CMSSW displayed by LXR

 
 

    


File indexing completed on 2025-02-20 03:45:56

0001 #!/usr/bin/env python
0002 
0003 
0004 # Various set of customise functions needed for embedding
0005 import FWCore.ParameterSet.Config as cms
0006 from Configuration.Eras.Modifier_run2_common_cff import run2_common
0007 from Configuration.Eras.Modifier_run3_common_cff import run3_common
0008 from PhysicsTools.NanoAOD.common_cff import ExtVar
0009 
0010 ################################ Customizer for skimming ###########################
0011 ### There are four different parts.
0012 ##First step is the SELECT (former SKIM) part, where we identfy the events which are good for Embedding. Need to store RAWRECO [RAW is needed for the MERG and RECO for the CLEAN step]
0013 ##Second step is the CLEAN input are PAT muons with RECO information. After this step only RAW plus some special collections needed for the MERG step must be saved
0014 ##Third step is the SIM. The input is the externalLHEProducer, which must be produced before (At the moment we do it parallel to the CLEAN step). Again only save RAW of the SELECT and only save what is need for the MERG step
0015 ##Last step is the MERG step. Which is the usally reconstruction, where the input produces are replaced by merg producer, which mix the SIM and CLEAN inputs.
0016 
0017 ## Some comments on this approach. All steps runs the RECO sequence until the end in the moment. It would be possible to stop after the all inputs which are needed for the MERG step are generated (which happens at a very early state of the reconstruction. But with this approach we are able to get the RECO (and PAT aka miniAOD) of all four step SELECT (orginal event), SIM, CLEAN and MERGED. Therefor one only needs to SAVE the corresponding output (in cmsDriver change output to RAW -> RAW,RECO,PAT)
0018 
0019 #######################  Some basic functions ####################
0020 ## Helper Class, which summerizes in which step which Producer (Cleaner Merger), should be loaded. It is also usefull to define which collection should be stored for the next step
0021 ## E.g What is needed for MERGE must be produce in the CLEAN and SIM step
0022 
0023 
0024 class module_manipulate:
0025     def __init__(
0026         self,
0027         module_name,
0028         manipulator_name,
0029         steps=["SELECT", "CLEAN", "SIM", "MERGE"],
0030         instance=[""],
0031         merge_prefix="",
0032     ):
0033         self.module_name = module_name
0034         self.manipulator_name = manipulator_name
0035         self.steps = steps
0036         self.instance = instance
0037         self.merger_name = manipulator_name + "ColMerger"
0038         self.cleaner_name = manipulator_name + "ColCleaner"
0039         self.merge_prefix = merge_prefix
0040 
0041 
0042 to_bemanipulate = []
0043 
0044 
0045 to_bemanipulate.append(
0046     module_manipulate(
0047         module_name="siPixelClusters",
0048         manipulator_name="Pixel",
0049         steps=["SELECT", "CLEAN"],
0050     )
0051 )
0052 to_bemanipulate.append(
0053     module_manipulate(
0054         module_name="siStripClusters",
0055         manipulator_name="Strip",
0056         steps=["SELECT", "CLEAN"],
0057     )
0058 )
0059 
0060 to_bemanipulate.append(
0061     module_manipulate(
0062         module_name="generalTracks", manipulator_name="Track", steps=["SIM", "MERGE"]
0063     )
0064 )
0065 # needed by the PFLinker:particleFlow to create MuonProducer:muons
0066 to_bemanipulate.append(
0067     module_manipulate(
0068         module_name="cosmicsVetoTracksRaw", manipulator_name="Track", steps=["SIM", "MERGE"]
0069     )
0070 )
0071 to_bemanipulate.append(
0072     module_manipulate(
0073         module_name="electronGsfTracks",
0074         manipulator_name="GsfTrack",
0075         steps=["SIM", "MERGE"],
0076     )
0077 )
0078 to_bemanipulate.append(
0079     module_manipulate(
0080         module_name="lowPtGsfEleGsfTracks",
0081         manipulator_name="GsfTrack",
0082         steps=["SIM", "MERGE"],
0083     )
0084 )
0085 # This is needed by displacedMuonReducedTrackExtras which is specifically added in the merging_step
0086 to_bemanipulate.append(
0087     module_manipulate(
0088         module_name="displacedTracks",
0089         manipulator_name="Track",
0090         steps=["SIM", "MERGE"],
0091     )
0092 )
0093 # This is needed by the conversion producer which is run by the highlevelreco task
0094 to_bemanipulate.append(
0095     module_manipulate(
0096         module_name="ckfOutInTracksFromConversions",
0097         manipulator_name="Track",
0098         steps=["SIM", "MERGE"],
0099     )
0100 )
0101 
0102 to_bemanipulate.append(
0103     module_manipulate(
0104         module_name="muons1stStep", manipulator_name="Muon", steps=["SIM", "MERGE"]
0105     )
0106 )
0107 # needed by  MuIsoDepositCopyProducer/'muIsoDepositTkDisplaced'
0108 to_bemanipulate.append(
0109     module_manipulate(
0110         module_name="displacedMuons1stStep", manipulator_name="Muon", steps=["SIM", "MERGE"]
0111     )
0112 )
0113 # to_bemanipulate.append(module_manipulate(module_name = 'gedGsfElectronsTmp', manipulator_name = "GsfElectron", steps = ["SIM", "MERGE"]))
0114 # to_bemanipulate.append(module_manipulate(module_name = 'gedPhotonsTmp', manipulator_name = "Photon", steps = ["SIM", "MERGE"]))
0115 to_bemanipulate.append(
0116     module_manipulate(
0117         module_name="conversions", manipulator_name="Conversion", steps=["SIM", "MERGE"]
0118     )
0119 )
0120 to_bemanipulate.append(
0121     module_manipulate(
0122         module_name="allConversions",
0123         manipulator_name="Conversion",
0124         steps=["SIM", "MERGE"],
0125     )
0126 )
0127 # needed by the PFLinker:particleFlow to create MuonProducer:muons
0128 to_bemanipulate.append(
0129     module_manipulate(
0130         module_name="particleFlowTmp",
0131         manipulator_name="PF",
0132         steps=["SIM", "MERGE"],
0133         instance=[
0134             "",
0135             "CleanedHF",
0136             "CleanedCosmicsMuons",
0137             "CleanedTrackerAndGlobalMuons",
0138             "CleanedFakeMuons",
0139             "CleanedPunchThroughMuons",
0140             "CleanedPunchThroughNeutralHadrons",
0141             "AddedMuonsAndHadrons",
0142         ],
0143     )
0144 )
0145 to_bemanipulate.append(
0146     module_manipulate(
0147         module_name="ecalDigis", manipulator_name="EcalSrFlag", steps=["SIM", "MERGE"]
0148     )
0149 )
0150 # this is needed by the HcalNoiseInfoProducer/'hcalnoise'
0151 to_bemanipulate.append(
0152     module_manipulate(
0153         module_name="hcalDigis", manipulator_name="HcalDigi", steps=["SIM", "MERGE"]
0154     )
0155 )
0156 
0157 to_bemanipulate.append(
0158     module_manipulate(
0159         module_name="ecalRecHit",
0160         manipulator_name="EcalRecHit",
0161         instance=["EcalRecHitsEB", "EcalRecHitsEE"],
0162     )
0163 )
0164 to_bemanipulate.append(
0165     module_manipulate(
0166         module_name="ecalPreshowerRecHit",
0167         manipulator_name="EcalRecHit",
0168         instance=["EcalRecHitsES"],
0169     )
0170 )
0171 
0172 to_bemanipulate.append(
0173     module_manipulate(module_name="hbhereco", manipulator_name="HBHERecHit")
0174 )
0175 
0176 to_bemanipulate.append(
0177     module_manipulate(module_name="horeco", manipulator_name="HORecHit")
0178 )
0179 to_bemanipulate.append(
0180     module_manipulate(module_name="hfreco", manipulator_name="HFRecHit")
0181 )
0182 
0183 
0184 to_bemanipulate.append(
0185     module_manipulate(
0186         module_name="dt1DRecHits",
0187         manipulator_name="DTRecHit",
0188         steps=["SELECT", "CLEAN"],
0189     )
0190 )
0191 to_bemanipulate.append(
0192     module_manipulate(
0193         module_name="dt1DCosmicRecHits",
0194         manipulator_name="DTRecHit",
0195         steps=["SELECT", "CLEAN"],
0196     )
0197 )
0198 
0199 to_bemanipulate.append(
0200     module_manipulate(
0201         module_name="dt4DSegments",
0202         manipulator_name="DTRecSegment4D",
0203         steps=["SELECT", "CLEAN"],
0204     )
0205 )
0206 
0207 to_bemanipulate.append(
0208     module_manipulate(
0209         module_name="dt4DCosmicSegments",
0210         manipulator_name="DTRecSegment4D",
0211         steps=["SELECT", "CLEAN"],
0212     )
0213 )
0214 
0215 to_bemanipulate.append(
0216     module_manipulate(
0217         module_name="csc2DRecHits",
0218         manipulator_name="CSCRecHit",
0219         steps=["SELECT", "CLEAN"],
0220     )
0221 )
0222 
0223 to_bemanipulate.append(
0224     module_manipulate(
0225         module_name="cscSegments",
0226         manipulator_name="CSCSegment",
0227         steps=["SELECT", "CLEAN"],
0228     )
0229 )
0230 
0231 to_bemanipulate.append(
0232     module_manipulate(
0233         module_name="rpcRecHits",
0234         manipulator_name="RPCRecHit",
0235         steps=["SELECT", "CLEAN"],
0236     )
0237 )
0238 
0239 # add some collections for run2
0240 # The era Modifier/ModifierChain is specified with the cmsDriver `--era` option or the cms.Process('NAME', era=...) constructor in the python config.
0241 # The `Modifier.toModify` method is executed if the Modifier is in the ModifierChain. (see https://github.com/cms-sw/cmssw/blob/master/FWCore/ParameterSet/python/Config.py#L1831)
0242 # The Run3 ModifierChain is based on the Run2 ModifierChain. Therefore the `run2_common` Modifier is included in both ModifierChains.
0243 # Those Modifiers allow bool operators to combine them. With `(run2_common & ~run3_common)` the `toModify` function is only executed if the era ModifierChain contains `run2_common` but not `run3_common`.
0244 (run2_common & ~run3_common).toModify(
0245     to_bemanipulate,
0246     lambda l: l.extend(
0247         [
0248             module_manipulate(
0249                 module_name="conversionStepTracks",
0250                 manipulator_name="Track",
0251                 steps=["SIM", "MERGE"],
0252             ),
0253             module_manipulate(
0254                 module_name="ckfInOutTracksFromConversions",
0255                 manipulator_name="Track",
0256                 steps=["SIM", "MERGE"],
0257             ),
0258             module_manipulate(
0259                 module_name="electronMergedSeeds",
0260                 manipulator_name="ElectronSeed",
0261                 steps=["SIM", "MERGE"],
0262             ),
0263             module_manipulate(
0264                 module_name="ecalDrivenElectronSeeds",
0265                 manipulator_name="EcalDrivenElectronSeed",
0266                 steps=["SIM", "MERGE"],
0267             ),
0268             module_manipulate(module_name="hbheprereco", manipulator_name="HBHERecHit"),
0269             module_manipulate(module_name="zdcreco", manipulator_name="ZDCRecHit"),
0270         ]
0271     ),
0272 )
0273 
0274 
0275 def modify_outputModules(process, keep_drop_list=[], module_veto_list=[]):
0276     outputModulesList = [key for key, value in process.outputModules.items()]
0277     for outputModule in outputModulesList:
0278         if outputModule in module_veto_list:
0279             continue
0280         outputModule = getattr(process, outputModule)
0281         for add_element in keep_drop_list:
0282             outputModule.outputCommands.extend(add_element)
0283     return process
0284 
0285 
0286 ################################ Customizer for Selecting ###########################
0287 
0288 
0289 def keepSelected(dataTier):
0290     ret_vstring = cms.untracked.vstring(
0291         # "drop *_*_*_"+dataTier,
0292         "keep *_patMuonsAfterID_*_" + dataTier,
0293         "keep *_slimmedMuons_*_" + dataTier,
0294         "keep *_slimmedMuonTrackExtras_*_" + dataTier,
0295         "keep *_selectedMuonsForEmbedding_*_" + dataTier,
0296         "keep recoVertexs_offlineSlimmedPrimaryVertices_*_" + dataTier,
0297         "keep *_firstStepPrimaryVertices_*_" + dataTier,
0298         "keep *_offlineBeamSpot_*_" + dataTier,
0299         "keep *_ecalDrivenElectronSeeds_*_" + dataTier,
0300     )
0301     for akt_manimod in to_bemanipulate:
0302         if "CLEAN" in akt_manimod.steps:
0303             ret_vstring.append("keep *_" + akt_manimod.module_name + "_*_" + dataTier)
0304     return ret_vstring
0305 
0306 
0307 def customiseSelecting(process, reselect=False):
0308     if reselect:
0309         process._Process__name = "RESELECT"
0310         dataTier = "RESELECT"
0311         # process.source.inputCommands = cms.untracked.vstring("drop *",
0312         #     "keep *_*_*_LHC",
0313         #     "keep *_*_*_HLT",
0314         # )
0315     else:
0316         process._Process__name = "SELECT"
0317         dataTier = "SELECT"
0318 
0319     process.load("TauAnalysis.MCEmbeddingTools.SelectingProcedure_cff")
0320     process.patMuonsAfterKinCuts.src = cms.InputTag("slimmedMuons", "", dataTier)
0321     process.selectedMuonsForEmbedding.PuppiMet = cms.InputTag(
0322         "slimmedMETsPuppi", "", dataTier
0323     )
0324     process.selectedMuonsForEmbedding.Met = cms.InputTag("slimmedMETs", "", dataTier)
0325     process.patMuonsAfterID = process.patMuonsAfterLooseID.clone()
0326 
0327     process.selecting = cms.Path(process.makePatMuonsZmumuSelection)
0328     process.schedule.insert(-1, process.selecting)
0329 
0330     outputModulesList = [key for key, value in process.outputModules.items()]
0331     for outputModule in outputModulesList:
0332         outputModule = getattr(process, outputModule)
0333         outputModule.SelectEvents = cms.untracked.PSet(
0334             SelectEvents=cms.vstring("selecting")
0335         )
0336         outputModule.outputCommands.extend(keepSelected(dataTier))
0337 
0338     process = customisoptions(process)
0339     return modify_outputModules(process, [keepSelected(dataTier)])
0340 
0341 
0342 def customiseSelecting_Reselect(process):
0343     return customiseSelecting(process, reselect=True)
0344 
0345 
0346 ################################ Customizer for cleaning ###########################
0347 
0348 
0349 def keepCleaned(dataTier):
0350     ret_vstring = cms.untracked.vstring(
0351         #                        "drop *_*_*_LHEembeddingCLEAN",
0352         #                        "drop *_*_*_CLEAN"
0353         "drop *_*_*_" + dataTier,
0354         "keep *_patMuonsAfterID_*_" + dataTier,
0355         "keep *_slimmedMuons_*_" + dataTier,
0356         # "keep *_slimmedMuonTrackExtras_*_" + dataTier,
0357         "keep *_selectedMuonsForEmbedding_*_" + dataTier,
0358         "keep recoVertexs_offlineSlimmedPrimaryVertices_*_" + dataTier,
0359         "keep *_firstStepPrimaryVertices_*_" + dataTier,
0360         "keep *_offlineBeamSpot_*_" + dataTier,
0361         "keep *_l1extraParticles_*_" + dataTier,
0362         "keep TrajectorySeeds_*_*_*",
0363         "keep recoElectronSeeds_*_*_*",
0364         "drop recoIsoDepositedmValueMap_muIsoDepositTk_*_*",
0365         "drop recoIsoDepositedmValueMap_muIsoDepositTkDisplaced_*_*",
0366         "drop *_ctppsProtons_*_*",
0367         "drop *_ctppsLocalTrackLiteProducer_*_*",
0368         "drop *_ctppsDiamondLocalTracks_*_*",
0369         "drop *_ctppsDiamondRecHits_*_*",
0370         "drop *_ctppsDiamondRawToDigi_*_*",
0371         "drop *_ctppsPixelLocalTracks_*_*",
0372         "drop *_ctppsPixelRecHits_*_*",
0373         "drop *_ctppsPixelClusters_*_*",
0374         "drop *_ctppsPixelDigis_*_*",
0375         "drop *_totemRPLocalTrackFitter_*_*",
0376         "drop *_totemRPUVPatternFinder_*_*",
0377         "drop *_totemRPRecHitProducer_*_*",
0378         "drop *_totemRPClusterProducer_*_*",
0379         "drop *_totemRPRawToDigi_*_*",
0380         "drop *_muonSimClassifier_*_*",
0381         # "keep recoPFClusters_*_*_*",
0382         # "keep recoPFRecHits_*_*_*"
0383     )
0384 
0385     for akt_manimod in to_bemanipulate:
0386         if "MERGE" in akt_manimod.steps:
0387             ret_vstring.append(
0388                 "keep *_" + akt_manimod.module_name + "_*_LHEembeddingCLEAN"
0389             )
0390             ret_vstring.append("keep *_" + akt_manimod.module_name + "_*_CLEAN")
0391     ret_vstring.append("keep *_standAloneMuons_*_LHEembeddingCLEAN")
0392     ret_vstring.append("keep *_glbTrackQual_*_LHEembeddingCLEAN")
0393     return ret_vstring
0394 
0395 
0396 def customiseCleaning(process, changeProcessname=True, reselect=False):
0397     if changeProcessname:
0398         process._Process__name = "CLEAN"
0399     if reselect:
0400         dataTier = "RESELECT"
0401     else:
0402         dataTier = "SELECT"
0403     ## Needed for the Calo Cleaner, could also be put into a function wich fix the input parameters
0404     from TrackingTools.TrackAssociator.default_cfi import TrackAssociatorParameterBlock
0405 
0406     TrackAssociatorParameterBlock.TrackAssociatorParameters.CSCSegmentCollectionLabel = cms.InputTag(
0407         "cscSegments", "", dataTier
0408     )
0409     TrackAssociatorParameterBlock.TrackAssociatorParameters.CaloTowerCollectionLabel = (
0410         cms.InputTag("towerMaker", "", dataTier)
0411     )
0412     TrackAssociatorParameterBlock.TrackAssociatorParameters.DTRecSegment4DCollectionLabel = cms.InputTag(
0413         "dt4DSegments", "", dataTier
0414     )
0415     TrackAssociatorParameterBlock.TrackAssociatorParameters.EBRecHitCollectionLabel = (
0416         cms.InputTag("ecalRecHit", "EcalRecHitsEB", dataTier)
0417     )
0418     TrackAssociatorParameterBlock.TrackAssociatorParameters.EERecHitCollectionLabel = (
0419         cms.InputTag("ecalRecHit", "EcalRecHitsEE", dataTier)
0420     )
0421     TrackAssociatorParameterBlock.TrackAssociatorParameters.HBHERecHitCollectionLabel = cms.InputTag(
0422         "hbhereco", "", dataTier
0423     )
0424     TrackAssociatorParameterBlock.TrackAssociatorParameters.HORecHitCollectionLabel = (
0425         cms.InputTag("horeco", "", dataTier)
0426     )
0427     TrackAssociatorParameterBlock.TrackAssociatorParameters.ME0HitCollectionLabel = (
0428         cms.InputTag("me0RecHits", "", dataTier)
0429     )
0430     TrackAssociatorParameterBlock.TrackAssociatorParameters.ME0SegmentCollectionLabel = (
0431         cms.InputTag("me0Segments", "", dataTier)
0432     )
0433     TrackAssociatorParameterBlock.TrackAssociatorParameters.RPCHitCollectionLabel = (
0434         cms.InputTag("rpcRecHits", "", dataTier)
0435     )
0436 
0437     MuonImput = cms.InputTag("selectedMuonsForEmbedding", "", "")  ## This are the muon
0438     for akt_manimod in to_bemanipulate:
0439         if "CLEAN" in akt_manimod.steps:
0440             oldCollections_in = cms.VInputTag()
0441             for instance in akt_manimod.instance:
0442                 oldCollections_in.append(
0443                     cms.InputTag(akt_manimod.module_name, instance, dataTier)
0444                 )
0445             setattr(
0446                 process,
0447                 akt_manimod.module_name,
0448                 cms.EDProducer(
0449                     akt_manimod.cleaner_name,
0450                     MuonCollection=MuonImput,
0451                     TrackAssociatorParameters=TrackAssociatorParameterBlock.TrackAssociatorParameters,
0452                     oldCollection=oldCollections_in,
0453                     cscDigiCollectionLabel = cms.InputTag("muonCSCDigis","MuonCSCStripDigi"),
0454                     digiMaxDistanceX = cms.double(25.0),
0455                     dtDigiCollectionLabel = cms.InputTag("muonDTDigis"),
0456                 ),
0457             )
0458     process.ecalPreshowerRecHit.TrackAssociatorParameters.usePreshower = cms.bool(True)
0459     process = customisoptions(process)
0460     return modify_outputModules(
0461         process, [keepSelected(dataTier), keepCleaned(dataTier)], ["MINIAODoutput"]
0462     )
0463 
0464 
0465 ################################ Customizer for LHE ###########################
0466 
0467 
0468 def keepLHE():
0469     ret_vstring = cms.untracked.vstring()
0470     ret_vstring.append("keep *_externalLHEProducer_*_LHEembedding")
0471     ret_vstring.append("keep *_externalLHEProducer_*_LHEembeddingCLEAN")
0472     return ret_vstring
0473 
0474 
0475 def customiseLHE(process, changeProcessname=True, reselect=False):
0476     if reselect:
0477         dataTier = "RESELECT"
0478     else:
0479         dataTier = "SELECT"
0480     if changeProcessname:
0481         process._Process__name = "LHEembedding"
0482     process.load("TauAnalysis.MCEmbeddingTools.EmbeddingLHEProducer_cfi")
0483     if reselect:
0484         process.externalLHEProducer.vertices = cms.InputTag(
0485             "offlineSlimmedPrimaryVertices", "", "RESELECT"
0486         )
0487     process.lheproduction = cms.Path(process.makeexternalLHEProducer)
0488     process.schedule.insert(0, process.lheproduction)
0489 
0490     process = customisoptions(process)
0491     return modify_outputModules(
0492         process,
0493         [keepSelected(dataTier), keepCleaned(dataTier), keepLHE()],
0494         ["MINIAODoutput"],
0495     )
0496 
0497 
0498 def customiseLHEandCleaning(process, reselect=False):
0499     process._Process__name = "LHEembeddingCLEAN"
0500     process = customiseCleaning(process, changeProcessname=False, reselect=reselect)
0501     process = customiseLHE(process, changeProcessname=False, reselect=reselect)
0502     return process
0503 
0504 
0505 def customiseLHEandCleaning_Reselect(process):
0506     return customiseLHEandCleaning(process, reselect=True)
0507 
0508 
0509 ################################ Customizer for simulaton ###########################
0510 
0511 
0512 def keepSimulated(process, processname="SIMembedding"):
0513     ret_vstring = cms.untracked.vstring()
0514     for akt_manimod in to_bemanipulate:
0515         if "MERGE" in akt_manimod.steps:
0516             ret_vstring.append(
0517                 "keep *_" + akt_manimod.module_name + "_*_{}".format(processname)
0518             )
0519     ret_vstring.append("keep *_genParticles_*_{}".format(processname))
0520     ret_vstring.append("keep *_standAloneMuons_*_{}".format(processname))
0521     ret_vstring.append("keep *_glbTrackQual_*_{}".format(processname))
0522     ret_vstring.append("keep *_generator_*_{}".format(processname))
0523     ret_vstring.append("keep *_addPileupInfo_*_{}".format(processname))
0524     ret_vstring.append("keep *_selectedMuonsForEmbedding_*_*")
0525     ret_vstring.append("keep *_slimmedAddPileupInfo_*_*")
0526     ret_vstring.append("keep *_embeddingHltPixelVertices_*_*")
0527     ret_vstring.append("keep *_*_vertexPosition_*")
0528     ret_vstring.append("keep recoMuons_muonsFromCosmics_*_*")
0529     ret_vstring.append("keep recoTracks_cosmicMuons1Leg_*_*")
0530     ret_vstring.append("keep recoMuons_muonsFromCosmics1Leg_*_*")
0531     ret_vstring.append("keep *_muonDTDigis_*_*")
0532     ret_vstring.append("keep *_muonCSCDigis_*_*")
0533     ret_vstring.append("keep TrajectorySeeds_*_*_*")
0534     ret_vstring.append("keep recoElectronSeeds_*_*_*")
0535     ret_vstring.append("drop recoIsoDepositedmValueMap_muIsoDepositTk_*_*")
0536     ret_vstring.append("drop recoIsoDepositedmValueMap_muIsoDepositTkDisplaced_*_*")
0537     ret_vstring.append("drop *_ctppsProtons_*_*")
0538     ret_vstring.append("drop *_ctppsLocalTrackLiteProducer_*_*")
0539     ret_vstring.append("drop *_ctppsDiamondLocalTracks_*_*")
0540     ret_vstring.append("drop *_ctppsDiamondRecHits_*_*")
0541     ret_vstring.append("drop *_ctppsDiamondRawToDigi_*_*")
0542     ret_vstring.append("drop *_ctppsPixelLocalTracks_*_*")
0543     ret_vstring.append("drop *_ctppsPixelRecHits_*_*")
0544     ret_vstring.append("drop *_ctppsPixelClusters_*_*")
0545     ret_vstring.append("drop *_ctppsPixelDigis_*_*")
0546     ret_vstring.append("drop *_totemRPLocalTrackFitter_*_*")
0547     ret_vstring.append("drop *_totemRPUVPatternFinder_*_*")
0548     ret_vstring.append("drop *_totemRPRecHitProducer_*_*")
0549     ret_vstring.append("drop *_totemRPClusterProducer_*_*")
0550     ret_vstring.append("drop *_totemRPRawToDigi_*_*")
0551     ret_vstring.append("drop *_muonSimClassifier_*_*")
0552 
0553     # for those two steps, the output has to be modified
0554     # to keep the information from the cleaning step in the output file
0555     if processname == "SIMembeddingpreHLT" or processname == "SIMembeddingHLT":
0556         rawreco_commands = set(process.RAWRECOEventContent.outputCommands)
0557         rawreco_commands_excl = rawreco_commands - set(
0558             process.RAWSIMEventContent.outputCommands
0559         )
0560         for entry in rawreco_commands_excl:
0561             if (
0562                 processname == "SIMembeddingpreHLT"
0563                 and "muonReducedTrackExtras" in entry
0564             ):
0565                 continue
0566             if not any(
0567                 x in entry
0568                 for x in [
0569                     "TotemTimingLocalTrack",
0570                     "ForwardProton",
0571                     "ctppsDiamondLocalTracks",
0572                 ]
0573             ):
0574                 ret_vstring.append(entry)
0575     return ret_vstring
0576 
0577 def customiseGenerator_preHLT(process, changeProcessname=True, reselect=False):
0578     if reselect:
0579         dataTier = "RESELECT"
0580     else:
0581         dataTier = "SELECT"
0582     if changeProcessname:
0583         process._Process__name = "SIMembeddingpreHLT"
0584 
0585     ## here correct the vertex collection
0586 
0587     process.load("TauAnalysis.MCEmbeddingTools.EmbeddingVertexCorrector_cfi")
0588     process.VtxSmeared = process.VtxCorrectedToInput.clone()
0589     print(
0590         "Correcting Vertex in genEvent to one from input. Replaced 'VtxSmeared' with the Corrector."
0591     )
0592 
0593     #### Disable noise simulation ####
0594     # Castor was a detector in CMS till 2018.
0595     (run2_common & ~run3_common).toModify(process, lambda p: setattr(p.mix.digitizers.castor, "doNoise", cms.bool(False)))
0596     process.mix.digitizers.ecal.doESNoise = cms.bool(False)
0597     process.mix.digitizers.ecal.doENoise = cms.bool(False)
0598 
0599     process.mix.digitizers.hcal.doNoise = cms.bool(False)
0600     process.mix.digitizers.hcal.doThermalNoise = cms.bool(False)
0601     process.mix.digitizers.hcal.doHPDNoise = cms.bool(False)
0602 
0603     process.mix.digitizers.pixel.AddNoisyPixels = cms.bool(False)
0604     process.mix.digitizers.pixel.AddNoise = cms.bool(False)
0605 
0606     process.mix.digitizers.strip.Noise = cms.bool(False)
0607 
0608     process = customisoptions(process)
0609     ##process = fix_input_tags(process)
0610 
0611     return modify_outputModules(
0612         process,
0613         [
0614             keepSelected(dataTier),
0615             keepCleaned(dataTier),
0616             keepSimulated(process, processname="SIMembeddingpreHLT"),
0617         ],
0618         ["AODSIMoutput"],
0619     )
0620 
0621 
0622 def customiseGenerator_preHLT_Reselect(process):
0623     return customiseGenerator_preHLT(process, reselect=True)
0624 
0625 
0626 def customiseGenerator_HLT(process, changeProcessname=True, reselect=False):
0627     if reselect:
0628         dataTier = "RESELECT"
0629     else:
0630         dataTier = "SELECT"
0631     if changeProcessname:
0632         process._Process__name = "SIMembeddingHLT"
0633 
0634     ## here correct the vertex collection
0635     process.load("TauAnalysis.MCEmbeddingTools.EmbeddingBeamSpotOnline_cfi")
0636     process.hltOnlineBeamSpot = process.onlineEmbeddingBeamSpotProducer.clone()
0637     print(
0638         "Setting online beam spot in HLTSchedule to the one from input data. Replaced 'hltOnlineBeamSpot' with the offline beam spot."
0639     )
0640 
0641     # Replace HLT vertexing with vertex taken from LHE step
0642     process.load("TauAnalysis.MCEmbeddingTools.EmbeddingHltPixelVerticesProducer_cfi")
0643     process.hltPixelVertices = process.embeddingHltPixelVertices.clone()
0644     process.offlinePrimaryVertices = process.embeddingHltPixelVertices.clone()
0645     process.firstStepPrimaryVerticesUnsorted = process.embeddingHltPixelVertices.clone()
0646     process.firstStepPrimaryVerticesPreSplitting = (
0647         process.embeddingHltPixelVertices.clone()
0648     )
0649 
0650     # Replace the original detector state filters in the HLT with a dummy module with 100% efficiency.
0651     # Those original filters have a efficiency of 0% for embedding samples.
0652     # This is due to the fact that the simulation of the tau decay happens in an empty detector.
0653     # For more info see https://github.com/cms-sw/cmssw/pull/47299#discussion_r1949023230
0654     process.hltPixelTrackerHVOn = cms.EDFilter("HLTBool",
0655         result = cms.bool(True)
0656     )
0657 
0658     process.hltStripTrackerHVOn = cms.EDFilter("HLTBool",
0659         result = cms.bool(True)
0660     )
0661 
0662     process = customisoptions(process)
0663     ##process = fix_input_tags(process)
0664 
0665     return modify_outputModules(
0666         process,
0667         [
0668             keepSelected(dataTier),
0669             keepCleaned(dataTier),
0670             keepLHE(),
0671             keepSimulated(process, processname="SIMembeddingpreHLT"),
0672             keepSimulated(process, processname="SIMembeddingHLT"),
0673         ],
0674         ["AODSIMoutput"],
0675     )
0676 
0677 
0678 def customiseGenerator_HLT_Reselect(process):
0679     return customiseGenerator_HLT(process, reselect=True)
0680 
0681 
0682 def customiseGenerator_postHLT(process, changeProcessname=True, reselect=False):
0683     if reselect:
0684         dataTier = "RESELECT"
0685     else:
0686         dataTier = "SELECT"
0687     if changeProcessname:
0688         process._Process__name = "SIMembedding"
0689 
0690     ## here correct the vertex collection
0691 
0692     # process.load('TauAnalysis.MCEmbeddingTools.EmbeddingVertexCorrector_cfi')
0693     # process.VtxSmeared = process.VtxCorrectedToInput.clone()
0694     # print "Correcting Vertex in genEvent to one from input. Replaced 'VtxSmeared' with the Corrector."
0695     # process.load('TauAnalysis.MCEmbeddingTools.EmbeddingBeamSpotOnline_cfi')
0696     # process.hltOnlineBeamSpot = process.onlineEmbeddingBeamSpotProducer.clone()
0697     # print "Setting online beam spot in HLTSchedule to the one from input data. Replaced 'hltOnlineBeamSpot' with the offline beam spot."
0698 
0699     # Remove BeamSpot Production, use the one from selected data instead.
0700     process.reconstruction.remove(process.offlineBeamSpot)
0701 
0702     process = customisoptions(process)
0703     ##process = fix_input_tags(process)
0704 
0705     return modify_outputModules(
0706         process,
0707         [
0708             keepSelected(dataTier),
0709             keepCleaned(dataTier),
0710             keepLHE(),
0711             keepSimulated(process, processname="SIMembeddingpreHLT"),
0712             keepSimulated(process, processname="SIMembeddingHLT"),
0713             keepSimulated(process, processname="SIMembedding"),
0714         ],
0715         ["AODSIMoutput"],
0716     )
0717 
0718 
0719 def customiseGenerator_postHLT_Reselect(process):
0720     return customiseGenerator_postHLT(process, reselect=True)
0721 
0722 
0723 ################################ Customizer for merging ###########################
0724 
0725 
0726 def keepMerged(dataTier="SELECT"):
0727     ret_vstring = cms.untracked.vstring()
0728     ret_vstring.append("drop *_*_*_" + dataTier)
0729     ret_vstring.append("keep *_prunedGenParticles_*_MERGE")
0730     ret_vstring.append("keep *_generator_*_SIMembeddingpreHLT")
0731     ret_vstring.append("keep *_generator_*_SIMembeddingHLT")
0732     ret_vstring.append("keep *_generator_*_SIMembedding")
0733     ret_vstring.append("keep *_selectedMuonsForEmbedding_*_*")
0734     ret_vstring.append("keep *_unpackedPatTrigger_*_*")
0735     ret_vstring.extend(cms.untracked.vstring(
0736         'keep patPackedGenParticles_packedGenParticles_*_*',
0737         'keep recoGenParticles_prunedGenParticles_*_*',
0738         'keep *_packedPFCandidateToGenAssociation_*_*',
0739         'keep *_lostTracksToGenAssociation_*_*',
0740         'keep LHEEventProduct_*_*_*',
0741         'keep GenFilterInfo_*_*_*',
0742         'keep GenLumiInfoHeader_generator_*_*',
0743         'keep GenLumiInfoProduct_*_*_*',
0744         'keep GenEventInfoProduct_generator_*_*',
0745         'keep recoGenParticles_genPUProtons_*_*',
0746         'keep *_slimmedGenJetsFlavourInfos_*_*',
0747         'keep *_slimmedGenJets__*',
0748         'keep *_slimmedGenJetsAK8__*',
0749         'keep *_slimmedGenJetsAK8SoftDropSubJets__*',
0750         'keep *_genMetTrue_*_*',
0751         # RUN
0752         'keep LHERunInfoProduct_*_*_*',
0753         'keep GenRunInfoProduct_*_*_*',
0754         'keep *_genParticles_xyz0_*',
0755         'keep *_genParticles_t0_*'))
0756     return ret_vstring
0757 
0758 
0759 def customiseKeepPrunedGenParticles(process, reselect=False):
0760     if reselect:
0761         dataTier = "RESELECT"
0762     else:
0763         dataTier = "SELECT"
0764 
0765     process.keep_step = cms.Path()
0766 
0767     process.load("PhysicsTools.PatAlgos.slimming.genParticles_cff")
0768     process.keep_step += process.prunedGenParticlesWithStatusOne
0769     process.load("PhysicsTools.PatAlgos.slimming.prunedGenParticles_cfi")
0770     process.keep_step += process.prunedGenParticles
0771     process.load("PhysicsTools.PatAlgos.slimming.packedGenParticles_cfi")
0772     process.keep_step += process.packedGenParticles
0773     process.load("PhysicsTools.PatAlgos.slimming.slimmedGenJets_cfi")
0774     process.keep_step += process.slimmedGenJets
0775 
0776     process.load("PhysicsTools.PatAlgos.mcMatchLayer0.muonMatch_cfi")
0777     process.keep_step += process.muonMatch
0778     process.load("PhysicsTools.PatAlgos.mcMatchLayer0.electronMatch_cfi")
0779     process.keep_step += process.electronMatch
0780     process.load("PhysicsTools.PatAlgos.mcMatchLayer0.photonMatch_cfi")
0781     process.keep_step += process.photonMatch
0782     process.load("PhysicsTools.PatAlgos.mcMatchLayer0.tauMatch_cfi")
0783     process.keep_step += process.tauMatch
0784     process.load("PhysicsTools.JetMCAlgos.TauGenJets_cfi")
0785     process.keep_step += process.tauGenJets
0786     process.load("PhysicsTools.PatAlgos.mcMatchLayer0.jetFlavourId_cff")
0787     process.keep_step += process.patJetPartons
0788     process.load("PhysicsTools.PatAlgos.mcMatchLayer0.jetMatch_cfi")
0789     process.keep_step += process.patJetPartonMatch
0790 
0791     process.muonMatch.matched = "prunedGenParticles"
0792     process.electronMatch.matched = "prunedGenParticles"
0793     process.electronMatch.src = cms.InputTag("reducedEgamma", "reducedGedGsfElectrons")
0794     process.photonMatch.matched = "prunedGenParticles"
0795     process.photonMatch.src = cms.InputTag("reducedEgamma", "reducedGedPhotons")
0796     process.tauMatch.matched = "prunedGenParticles"
0797     process.tauGenJets.GenParticles = "prunedGenParticles"
0798     ##Boosted taus
0799     # process.tauMatchBoosted.matched = "prunedGenParticles"
0800     # process.tauGenJetsBoosted.GenParticles = "prunedGenParticles"
0801     process.patJetPartons.particles = "prunedGenParticles"
0802     process.patJetPartonMatch.matched = "prunedGenParticles"
0803     process.patJetPartonMatch.mcStatus = [3, 23]
0804     process.patJetGenJetMatch.matched = "slimmedGenJets"
0805     process.patJetGenJetMatchAK8.matched = "slimmedGenJetsAK8"
0806     process.patMuons.embedGenMatch = False
0807     process.patElectrons.embedGenMatch = False
0808     process.patPhotons.embedGenMatch = False
0809     process.patTaus.embedGenMatch = False
0810     process.patTausBoosted.embedGenMatch = False
0811     process.patJets.embedGenPartonMatch = False
0812     # also jet flavour must be switched
0813     process.patJetFlavourAssociation.rParam = 0.4
0814 
0815     process.schedule.insert(0, process.keep_step)
0816     process = customisoptions(process)
0817     return modify_outputModules(process, [keepMerged(dataTier)])
0818 
0819 
0820 def customiseMerging(process, changeProcessname=True, reselect=False):
0821 
0822     print("**** Attention: overriding behaviour of 'removeMCMatching' ****")
0823 
0824     import PhysicsTools.PatAlgos.tools.coreTools
0825     from PhysicsTools.PatAlgos.slimming.miniAOD_tools import miniAOD_customizeMC
0826 
0827     PhysicsTools.PatAlgos.tools.coreTools.removeMCMatching = lambda process, names, postfix, outputModules : miniAOD_customizeMC(process)
0828 
0829     if changeProcessname:
0830         process._Process__name = "MERGE"
0831     if reselect:
0832         dataTier = "RESELECT"
0833     else:
0834         dataTier = "SELECT"
0835 
0836     process.source.inputCommands = cms.untracked.vstring()
0837     process.source.inputCommands.append("keep *_*_*_*")
0838     process.load("PhysicsTools.PatAlgos.slimming.unpackedPatTrigger_cfi")
0839     process.unpackedPatTrigger.triggerResults = cms.InputTag("TriggerResults::SIMembeddingHLT")
0840 
0841     # process.source.inputCommands.append("drop *_*_*_SELECT")
0842     # process.source.inputCommands.append("drop *_*_*_SIMembedding")
0843     # process.source.inputCommands.append("drop *_*_*_LHEembeddingCLEAN")
0844     # process.source.inputCommands.extend(keepSimulated())
0845     # process.source.inputCommands.extend(keepCleaned())
0846 
0847     process.load('Configuration.StandardSequences.RawToDigi_cff')
0848     process.load("Configuration.StandardSequences.Reconstruction_Data_cff")
0849     process.merge_step = cms.Path()
0850     # produce local CT PPS reco
0851     process.load("RecoPPS.Configuration.recoCTPPS_cff")
0852     process.totemRPRawToDigi.rawDataTag = cms.InputTag("rawDataCollector", "", "LHC")
0853     process.ctppsDiamondRawToDigi.rawDataTag = cms.InputTag("rawDataCollector", "", "LHC")
0854     process.ctppsPixelDigis.inputLabel = cms.InputTag("rawDataCollector", "", "LHC")
0855     process.merge_step += process.totemRPRawToDigi
0856     process.merge_step += process.ctppsDiamondRawToDigi
0857     process.merge_step += process.ctppsPixelDigis
0858     process.merge_step += cms.Sequence(process.recoCTPPSTask)
0859     # produce local Calo
0860     process.load("RecoLocalCalo.Configuration.RecoLocalCalo_cff")
0861     process.merge_step += process.calolocalreco
0862     #process.merge_step += process.caloglobalreco
0863     process.merge_step += process.reducedHcalRecHitsSequence
0864 
0865     # produce hcal towers
0866     process.load("RecoLocalCalo.CaloTowersCreator.calotowermaker_cfi")
0867     process.merge_step += process.calotowermaker
0868     process.merge_step += process.towerMaker
0869 
0870     # produce clusters
0871     process.load("RecoEcal.Configuration.RecoEcal_cff")
0872     process.merge_step += process.ecalClusters
0873 
0874     # produce PFCluster Collections
0875     process.load("RecoParticleFlow.PFClusterProducer.particleFlowCluster_cff")
0876     process.merge_step += process.particleFlowCluster
0877     process.load(
0878         "RecoEcal.EgammaClusterProducers.particleFlowSuperClusteringSequence_cff"
0879     )
0880     process.merge_step += process.particleFlowSuperClusteringSequence
0881 
0882     # muonEcalDetIds
0883     process.load("RecoMuon.MuonIdentification.muons1stStep_cfi")
0884     process.merge_step += process.muonEcalDetIds
0885     process.merge_step += process.muonShowerInformation
0886 
0887     # muon Isolation sequences
0888     process.load("RecoMuon.MuonIsolationProducers.muIsolation_cff")
0889     process.merge_step += process.muIsolation
0890     process.merge_step += process.muIsolationDisplaced
0891 
0892     # muon ID selection type sequences
0893     process.load("RecoMuon.MuonIdentification.muonSelectionTypeValueMapProducer_cff")
0894     process.merge_step += process.muonSelectionTypeSequence
0895 
0896     # displaced muons extras & tracks
0897     process.load("RecoMuon.MuonIdentification.displacedMuonReducedTrackExtras_cfi")
0898     process.merge_step += process.displacedMuonReducedTrackExtras
0899 
0900     process.load("RecoMuon.Configuration.MergeDisplacedTrackCollections_cff")
0901     process.merge_step += process.displacedTracksSequence
0902 
0903     # Other things
0904     process.merge_step += process.doAlldEdXEstimators
0905     process.merge_step += process.vertexreco
0906     process.unsortedOfflinePrimaryVertices.beamSpotLabel = cms.InputTag(
0907         "offlineBeamSpot", "", dataTier
0908     )
0909     process.ak4CaloJetsForTrk.srcPVs = cms.InputTag(
0910         "firstStepPrimaryVertices", "", dataTier
0911     )
0912     process.dedxHitInfo.clusterShapeCache = cms.InputTag("")
0913 
0914     process.merge_step += process.highlevelreco
0915 
0916     process.load("CommonTools.ParticleFlow.genForPF2PAT_cff")
0917 
0918 
0919     process.merge_step += process.genForPF2PATSequence
0920 
0921     # Replace manipulated modules contained in merg_step with Mergers, and
0922     # put remaining ones into a list to be sorted to avoid deadlocks
0923     modules_to_be_ordered = {}
0924     # prepare reco list to determine indices
0925     reconstruction_modules_list = str(process.RawToDigi).split(",")
0926     reconstruction_modules_list += str(process.reconstruction).split(",")
0927     for akt_manimod in to_bemanipulate:
0928         if "MERGE" in akt_manimod.steps:
0929             mergCollections_in = cms.VInputTag()
0930             for instance in akt_manimod.instance:
0931                 mergCollections_in.append(
0932                     cms.InputTag(
0933                         akt_manimod.merge_prefix + akt_manimod.module_name,
0934                         instance,
0935                         "SIMembedding",
0936                     )
0937                 )
0938                 mergCollections_in.append(
0939                     cms.InputTag(
0940                         akt_manimod.merge_prefix + akt_manimod.module_name,
0941                         instance,
0942                         "LHEembeddingCLEAN",
0943                     )
0944                 )
0945             setattr(
0946                 process,
0947                 akt_manimod.module_name,
0948                 cms.EDProducer(
0949                     akt_manimod.merger_name, mergCollections=mergCollections_in
0950                 ),
0951             )
0952             if not process.merge_step.contains(getattr(process, akt_manimod.module_name)):
0953                 modules_to_be_ordered[akt_manimod.module_name] = -1
0954     # Determine indices and place them in right order into the list
0955     for name,index in modules_to_be_ordered.items():
0956         if name in reconstruction_modules_list:
0957             modules_to_be_ordered[name] = reconstruction_modules_list.index(name)
0958         else:
0959             import sys
0960             print("ERROR:",name,"not prepared in modules list. Please adapt 'customiseMerging'")
0961             sys.exit(1)
0962 
0963     modules_ordered = sorted(list(modules_to_be_ordered.items()), key=lambda x : -x[1])
0964     for m in modules_ordered:
0965         process.merge_step.insert(0, getattr(process, m[0]))
0966 
0967 
0968     process.schedule.insert(0, process.merge_step)
0969     # process.load('PhysicsTools.PatAlgos.slimming.slimmedGenJets_cfi')
0970     process = customisoptions(process)
0971     return modify_outputModules(process, [keepMerged(dataTier)])
0972 
0973 
0974 def customiseMerging_Reselect(process, changeProcessname=True):
0975     return customiseMerging(process, changeProcessname=changeProcessname, reselect=True)
0976 
0977 
0978 ################################ Customize NanoAOD ################################
0979 
0980 
0981 def customiseNanoAOD(process):
0982 
0983     process.load("PhysicsTools.NanoAOD.nano_cff")
0984     process.nanoAOD_step.insert(0, cms.Sequence(process.nanoTableTaskFS))
0985 
0986 
0987     for outputModule in process.outputModules.values():
0988        outputModule.outputCommands.append("keep edmTriggerResults_*_*_SIMembeddingpreHLT")
0989        outputModule.outputCommands.append("keep edmTriggerResults_*_*_SIMembeddingHLT")
0990        outputModule.outputCommands.append("keep edmTriggerResults_*_*_SIMembedding")
0991        outputModule.outputCommands.append("keep edmTriggerResults_*_*_MERGE")
0992        outputModule.outputCommands.append("keep edmTriggerResults_*_*_NANO")
0993        outputModule.outputCommands.remove("keep edmTriggerResults_*_*_*")
0994 
0995     process.load("PhysicsTools.NanoAOD.l1trig_cff")
0996     process.nanoAOD_step.insert(0, cms.Sequence(process.l1TablesTask))
0997 
0998     process.embeddingTable = cms.EDProducer(
0999         "GlobalVariablesTableProducer",
1000         name=cms.string("TauEmbedding"),
1001         # doc=cms.string("TauEmbedding"),
1002         variables=cms.PSet(
1003             nInitialPairCandidates=ExtVar(
1004                 cms.InputTag("selectedMuonsForEmbedding", "nPairCandidates"),
1005                 float,
1006                 doc="number of muons pairs suitable for selection (for internal studies only)",
1007             ),
1008             SelectionOldMass=ExtVar(
1009                 cms.InputTag("selectedMuonsForEmbedding", "oldMass"),
1010                 float,
1011                 doc="Mass of the Dimuon pair using the old selection algorithm (for internal studies only)",
1012             ),
1013             SelectionNewMass=ExtVar(
1014                 cms.InputTag("selectedMuonsForEmbedding", "newMass"),
1015                 float,
1016                 doc="Mass of the Dimuon pair using the new selection algorithm (for internal studies only)",
1017             ),
1018             isMediumLeadingMuon=ExtVar(
1019                 cms.InputTag("selectedMuonsForEmbedding", "isMediumLeadingMuon"),
1020                 bool,
1021                 doc="leading muon ID (medium)",
1022             ),
1023             isMediumTrailingMuon=ExtVar(
1024                 cms.InputTag("selectedMuonsForEmbedding", "isMediumTrailingMuon"),
1025                 bool,
1026                 doc="trailing muon ID (medium)",
1027             ),
1028             isTightLeadingMuon=ExtVar(
1029                 cms.InputTag("selectedMuonsForEmbedding", "isTightLeadingMuon"),
1030                 bool,
1031                 doc="leading muon ID (tight)",
1032             ),
1033             isTightTrailingMuon=ExtVar(
1034                 cms.InputTag("selectedMuonsForEmbedding", "isTightTrailingMuon"),
1035                 bool,
1036                 doc="trailing muon ID (tight)",
1037             ),
1038             initialMETEt=ExtVar(
1039                 cms.InputTag("selectedMuonsForEmbedding", "initialMETEt"),
1040                 float,
1041                 doc="MET Et of selected event",
1042             ),
1043             initialMETphi=ExtVar(
1044                 cms.InputTag("selectedMuonsForEmbedding", "initialMETphi"),
1045                 float,
1046                 doc="MET phi of selected event",
1047             ),
1048             initialPuppiMETEt=ExtVar(
1049                 cms.InputTag("selectedMuonsForEmbedding", "initialPuppiMETEt"),
1050                 float,
1051                 doc="PuppiMET Et of selected event",
1052             ),
1053             initialPuppiMETphi=ExtVar(
1054                 cms.InputTag("selectedMuonsForEmbedding", "initialPuppiMETphi"),
1055                 float,
1056                 doc="PuppiMET phi of selected event",
1057             ),
1058         ),
1059     )
1060     process.embeddingTableTask = cms.Task(process.embeddingTable)
1061     process.schedule.associate(process.embeddingTableTask)
1062 
1063     return process
1064 
1065 
1066 ################################ cross Customizers ###########################
1067 
1068 
1069 ################################ additional Customizer ###########################
1070 
1071 
1072 def customisoptions(process):
1073     if not hasattr(process, "options"):
1074         process.options = cms.untracked.PSet()
1075     process.options.emptyRunLumiMode = cms.untracked.string(
1076         "doNotHandleEmptyRunsAndLumis"
1077     )
1078     if not hasattr(process, "bunchSpacingProducer"):
1079         process.bunchSpacingProducer = cms.EDProducer("BunchSpacingProducer")
1080     process.bunchSpacingProducer.bunchSpacingOverride = cms.uint32(25)
1081     process.bunchSpacingProducer.overrideBunchSpacing = cms.bool(True)
1082     process.options.numberOfThreads = cms.untracked.uint32(1)
1083     process.options.numberOfStreams = cms.untracked.uint32(0)
1084     return process
1085 
1086 
1087 ############################### MC specific Customizer ###########################
1088 
1089 
1090 def customiseFilterZToMuMu(process):
1091     process.load("TauAnalysis.MCEmbeddingTools.DYToMuMuGenFilter_cfi")
1092     process.ZToMuMuFilter = cms.Path(process.dYToMuMuGenFilter)
1093     process.schedule.insert(-1, process.ZToMuMuFilter)
1094     return process
1095 
1096 
1097 def customiseFilterTTbartoMuMu(process):
1098     process.load("TauAnalysis.MCEmbeddingTools.TTbartoMuMuGenFilter_cfi")
1099     process.MCFilter = cms.Path(process.TTbartoMuMuGenFilter)
1100     return customiseMCFilter(process)
1101 
1102 
1103 def customiseMCFilter(process):
1104     process.schedule.insert(-1, process.MCFilter)
1105     outputModulesList = [key for key, value in process.outputModules.items()]
1106     for outputModule in outputModulesList:
1107         outputModule = getattr(process, outputModule)
1108         outputModule.SelectEvents = cms.untracked.PSet(
1109             SelectEvents=cms.vstring("MCFilter")
1110         )
1111     return process
1112 
1113 
1114 def fix_input_tags(
1115     process, formodules=["generalTracks", "cscSegments", "dt4DSegments", "rpcRecHits"]
1116 ):
1117     def change_tags_process(test_input):
1118         if isinstance(test_input, cms.InputTag):
1119             if test_input.getModuleLabel() in formodules:
1120                 test_input.setProcessName(process._Process__name)
1121 
1122     def search_for_tags(pset):
1123         if isinstance(pset, dict):
1124             for key in pset:
1125                 if isinstance(pset[key], cms.VInputTag):
1126                     for akt_inputTag in pset[key]:
1127                         change_tags_process(akt_inputTag)
1128                 elif isinstance(pset[key], cms.PSet):
1129                     search_for_tags(pset[key].__dict__)
1130                 elif isinstance(pset[key], cms.VPSet):
1131                     for akt_pset in pset[key]:
1132                         search_for_tags(akt_pset.__dict__)
1133                 else:
1134                     change_tags_process(pset[key])
1135         else:
1136             print("must be python dict not a {}".format(type(pset)))
1137 
1138     for module in process.producers_():
1139         search_for_tags(getattr(process, module).__dict__)
1140     for module in process.filters_():
1141         search_for_tags(getattr(process, module).__dict__)
1142     for module in process.analyzers_():
1143         search_for_tags(getattr(process, module).__dict__)
1144 
1145     return process