diff --git a/Alignment/CommonAlignmentProducer/python/ALCARECOMuAlCalIsolatedMu_Output_cff.py b/Alignment/CommonAlignmentProducer/python/ALCARECOMuAlCalIsolatedMu_Output_cff.py index 3f20e519bd343..e89d50923d659 100644 --- a/Alignment/CommonAlignmentProducer/python/ALCARECOMuAlCalIsolatedMu_Output_cff.py +++ b/Alignment/CommonAlignmentProducer/python/ALCARECOMuAlCalIsolatedMu_Output_cff.py @@ -1,5 +1,6 @@ import FWCore.ParameterSet.Config as cms + # AlCaReco output for track based muon alignment using muons from collisions OutALCARECOMuAlCalIsolatedMu_noDrop = cms.PSet( SelectEvents = cms.untracked.PSet( @@ -16,6 +17,8 @@ 'keep *_dt4DSegments_*_*', 'keep *_csc2DRecHits_*_*', 'keep *_cscSegments_*_*', + 'keep *_gemRecHits_*_*', + 'keep *_gemSegments_*_*', 'keep *_rpcRecHits_*_*', 'keep L1AcceptBunchCrossings_*_*_*', 'keep L1GlobalTriggerReadoutRecord_gtDigis_*_*', diff --git a/Alignment/CommonAlignmentProducer/python/ALCARECOMuAlGlobalCosmicsInCollisions_Output_cff.py b/Alignment/CommonAlignmentProducer/python/ALCARECOMuAlGlobalCosmicsInCollisions_Output_cff.py index 385e376fc708d..803489b9cde80 100644 --- a/Alignment/CommonAlignmentProducer/python/ALCARECOMuAlGlobalCosmicsInCollisions_Output_cff.py +++ b/Alignment/CommonAlignmentProducer/python/ALCARECOMuAlGlobalCosmicsInCollisions_Output_cff.py @@ -16,6 +16,8 @@ 'keep *_dt4DSegments_*_*', 'keep *_csc2DRecHits_*_*', 'keep *_cscSegments_*_*', + 'keep *_gemRecHits_*_*', + 'keep *_gemSegments_*_*', 'keep *_rpcRecHits_*_*', 'keep L1AcceptBunchCrossings_*_*_*', 'keep L1GlobalTriggerReadoutRecord_gtDigis_*_*', diff --git a/Alignment/CommonAlignmentProducer/python/ALCARECOMuAlGlobalCosmics_Output_cff.py b/Alignment/CommonAlignmentProducer/python/ALCARECOMuAlGlobalCosmics_Output_cff.py index 8a4f38060d60d..dc9a13fa68325 100644 --- a/Alignment/CommonAlignmentProducer/python/ALCARECOMuAlGlobalCosmics_Output_cff.py +++ b/Alignment/CommonAlignmentProducer/python/ALCARECOMuAlGlobalCosmics_Output_cff.py @@ -19,6 +19,8 @@ 'keep *_dt4DSegments_*_*', 'keep *_csc2DRecHits_*_*', 'keep *_cscSegments_*_*', + 'keep *_gemRecHits_*_*', + 'keep *_gemSegments_*_*', 'keep *_rpcRecHits_*_*', 'keep L1AcceptBunchCrossings_*_*_*', 'keep L1GlobalTriggerReadoutRecord_gtDigis_*_*', diff --git a/CondCore/Utilities/scripts/conddb b/CondCore/Utilities/scripts/conddb index 862209888895a..a72ff3db7cfb8 100755 --- a/CondCore/Utilities/scripts/conddb +++ b/CondCore/Utilities/scripts/conddb @@ -2555,16 +2555,16 @@ def dump(args): filter(IOV.tag_name == name).\ distinct(): if args.format == 'xml': - xmlProcessor.payload2xml(session, payload) + xmlProcessor.payload2xml(session, payload, args.destfile) else: _dump_payload(session, payload, args.loadonly) - elif args.type == 'gt' and _exists(session, conddb.GlobalTag.name, name) != None: + elif args.type == 'gt' and _exists(session, GlobalTag.name, name) != None: for payload, in session.query(IOV.payload_hash).\ filter(GlobalTagMap.global_tag_name == name, IOV.tag_name == GlobalTagMap.tag_name).\ distinct(): if args.format == 'xml': - xmlProcessor.payload2xml(session, payload) + xmlProcessor.payload2xml(session, payload, args.destfile) else: _dump_payload(session, payload, args.loadonly) diff --git a/CondCore/Utilities/test/test_conddb.sh b/CondCore/Utilities/test/test_conddb.sh index 3858ce8f79bb3..aedac38dc0ce5 100755 --- a/CondCore/Utilities/test/test_conddb.sh +++ b/CondCore/Utilities/test/test_conddb.sh @@ -43,7 +43,12 @@ conddb diffGlobalTagsAtRun -R 120X_mcRun3_2021_realistic_v1 -T 120X_mcRun3_2021_ echo -ne '\n\n' echo "===========> testing conddb dump" -conddb dump 4b97f78682aac6254bbcba54cedbde468202bf5b || die 'failed comparing metadata with reference' $? +conddb dump 4b97f78682aac6254bbcba54cedbde468202bf5b || die 'failed conddb dump payload' $? +conddb dump 4b97f78682aac6254bbcba54cedbde468202bf5b --destfile payload_dump.xml || die 'failed conddb dump payload to file' $? +conddb dump SiPixelQuality_phase1_2021_v1 || die 'failed conddb dump tag' $? +conddb dump SiPixelQuality_phase1_2021_v1 --destfile tag_dump.xml || die 'failed conddb dump tag to file' $? +conddb dump Test_CMSSW_IB_unitTest_v1 || die 'failed conddb dump gt' $? +conddb dump Test_CMSSW_IB_unitTest_v1 --destfile gt_dump.xml || die 'failed conddb dump gt to file' $? echo -ne '\n\n' #conddb showFCSR || die 'failed conddb showFCSR' $? # the FCSR is not always a real run... diff --git a/CondFormats/Common/test/DropBoxMetadataReader.py b/CondFormats/Common/test/DropBoxMetadataReader.py index 3c0ff3012bb3b..1ccc826ae3b01 100644 --- a/CondFormats/Common/test/DropBoxMetadataReader.py +++ b/CondFormats/Common/test/DropBoxMetadataReader.py @@ -47,8 +47,7 @@ "SiPixelQualityFromDbRcd_other", "SiPixelLorentzAngleRcd", "CTPPSRPAlignmentCorrectionsDataRcd", - "PPSTimingCalibrationRcd", - "PPSTimingCalibrationRcd_Sampic" + "PPSTimingCalibrationRcd" ) # same strings as fType ) diff --git a/CondFormats/Common/test/ProduceDropBoxMetadata.py b/CondFormats/Common/test/ProduceDropBoxMetadata.py index c77da20320f14..9e850d2a29b22 100644 --- a/CondFormats/Common/test/ProduceDropBoxMetadata.py +++ b/CondFormats/Common/test/ProduceDropBoxMetadata.py @@ -228,13 +228,7 @@ def encodeJsonInString(filename): FileClass = cms.untracked.string("ALCA"), prodMetaData = cms.untracked.string(PPSTimingCalibrationRcd_prod_str), prepMetaData = cms.untracked.string(PPSTimingCalibrationRcd_prep_str), - ), - cms.PSet(record = cms.untracked.string('PPSTimingCalibrationRcd_Sampic'), - Source = cms.untracked.string("AlcaHarvesting"), - FileClass = cms.untracked.string("ALCA"), - prodMetaData = cms.untracked.string(PPSTimingCalibrationRcd_Sampic_prod_str), - prepMetaData = cms.untracked.string(PPSTimingCalibrationRcd_Sampic_prep_str), - ), + ) ), # this boolean will read the content of whichever payload is available and print its content to stoutput # set this to false if you write out a sqlite.db translating the json's into a payload diff --git a/CondFormats/SiPixelTransient/src/SiPixelTemplate.cc b/CondFormats/SiPixelTransient/src/SiPixelTemplate.cc index 57e7806db0326..a409f97615ad4 100644 --- a/CondFormats/SiPixelTransient/src/SiPixelTemplate.cc +++ b/CondFormats/SiPixelTransient/src/SiPixelTemplate.cc @@ -1328,6 +1328,12 @@ void SiPixelTemplate::postInit(std::vector& thePixelTemp_) bool SiPixelTemplate::interpolate(int id, float cotalpha, float cotbeta, float locBz, float locBx) { // Interpolate for a new set of track angles + //check for nan's + if (!edm::isFinite(cotalpha) || !edm::isFinite(cotbeta)) { + success_ = false; + return success_; + } + // Local variables int i, j; int ilow, ihigh, iylow, iyhigh, Ny, Nxx, Nyx, imidy, imaxx; @@ -1393,12 +1399,6 @@ bool SiPixelTemplate::interpolate(int id, float cotalpha, float cotbeta, float l throw cms::Exception("DataCorrupt") << "SiPixelTemplate::interpolate can't find needed template ID = " << id << std::endl; } - - //check for nan's - if (!edm::isFinite(cotalpha) || !edm::isFinite(cotbeta)) { - success_ = false; - return success_; - } #else assert(index_id_ >= 0 && index_id_ < (int)thePixelTemp_.size()); #endif diff --git a/CondFormats/SiPixelTransient/src/SiPixelTemplate2D.cc b/CondFormats/SiPixelTransient/src/SiPixelTemplate2D.cc index d9e3441e357d0..9380f61f63e1a 100644 --- a/CondFormats/SiPixelTransient/src/SiPixelTemplate2D.cc +++ b/CondFormats/SiPixelTransient/src/SiPixelTemplate2D.cc @@ -626,6 +626,12 @@ bool SiPixelTemplate2D::getid(int id) { bool SiPixelTemplate2D::interpolate(int id, float cotalpha, float cotbeta, float locBz, float locBx) { // Interpolate for a new set of track angles + //check for nan's + if (!edm::isFinite(cotalpha) || !edm::isFinite(cotbeta)) { + success_ = false; + return success_; + } + // Local variables float acotb, dcota, dcotb; @@ -680,12 +686,6 @@ bool SiPixelTemplate2D::interpolate(int id, float cotalpha, float cotbeta, float #ifndef SI_PIXEL_TEMPLATE_STANDALONE throw cms::Exception("DataCorrupt") << "SiPixelTemplate2D::illegal subdetector ID = " << thePixelTemp_[index_id_].head.Dtype << std::endl; - - //check for nan's - if (!edm::isFinite(cotalpha) || !edm::isFinite(cotbeta)) { - success_ = false; - return success_; - } #else std::cout << "SiPixelTemplate:2D:illegal subdetector ID = " << thePixelTemp_[index_id_].head.Dtype << std::endl; #endif diff --git a/CondTools/RunInfo/plugins/BuildFile.xml b/CondTools/RunInfo/plugins/BuildFile.xml index f1ed6cfc4fc16..cd0651742643b 100644 --- a/CondTools/RunInfo/plugins/BuildFile.xml +++ b/CondTools/RunInfo/plugins/BuildFile.xml @@ -46,3 +46,7 @@ + + + + diff --git a/CondTools/RunInfo/plugins/L1TriggerScalerESAnalyzer.cc b/CondTools/RunInfo/plugins/L1TriggerScalerESAnalyzer.cc index 35bf1fd3882c7..fa257617a2024 100644 --- a/CondTools/RunInfo/plugins/L1TriggerScalerESAnalyzer.cc +++ b/CondTools/RunInfo/plugins/L1TriggerScalerESAnalyzer.cc @@ -2,86 +2,72 @@ #include #include #include -#include "FWCore/Framework/interface/EDAnalyzer.h" +#include "FWCore/Framework/interface/one/EDAnalyzer.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/ESHandle.h" #include "FWCore/Framework/interface/MakerMacros.h" - +#include "FWCore/MessageLogger/interface/MessageLogger.h" #include "FWCore/Framework/interface/EventSetup.h" #include "CondFormats/RunInfo/interface/L1TriggerScaler.h" #include "CondFormats/DataRecord/interface/L1TriggerScalerRcd.h" -using namespace std; - - - - - -namespace edmtest -{ - class L1TriggerScalerESAnalyzer : public edm::EDAnalyzer - { +namespace edmtest { + class L1TriggerScalerESAnalyzer : public edm::one::EDAnalyzer { public: - explicit L1TriggerScalerESAnalyzer(edm::ParameterSet const& p) - { - std::cout<<"L1TriggerScalerESAnalyzer"<()), + scaler2Token_(esConsumes()) { + edm::LogVerbatim("L1TriggerScaler") << "L1TriggerScalerESAnalyzer"; } - explicit L1TriggerScalerESAnalyzer(int i) - { std::cout<<"L1TriggerScalerESAnalyzer "<()), + scaler2Token_(esConsumes()) { + edm::LogVerbatim("L1TriggerScaler") << "L1TriggerScalerESAnalyzer " << i; } - virtual void beginJob(); - virtual void beginRun(const edm::Run&, const edm::EventSetup& context); - virtual void analyze(const edm::Event& e, const edm::EventSetup& c); + ~L1TriggerScalerESAnalyzer() override { edm::LogVerbatim("L1TriggerScaler") << "~L1TriggerScalerESAnalyzer "; } + void beginJob() override; + void beginRun(const edm::Run&, const edm::EventSetup& context) override; + void analyze(const edm::Event& e, const edm::EventSetup& c) override; + void endRun(const edm::Run&, const edm::EventSetup& context) override {} + private: + const edm::ESGetToken scaler1Token_; + const edm::ESGetToken scaler2Token_; }; - - - void - L1TriggerScalerESAnalyzer::beginRun(const edm::Run&, const edm::EventSetup& context){ - std::cout<<"###L1TriggerScalerESAnalyzer::beginRun"< L1TriggerScaler_lumiarray; - std::cout<<"got eshandle"<().get(L1TriggerScaler_lumiarray); - std::cout<<"got data"<& L1TriggerScaler_lumiarray = context.getHandle(scaler1Token_); + edm::LogVerbatim("L1TriggerScaler") << " got eshandle with flag " << L1TriggerScaler_lumiarray.isValid() + << " got data"; } - - void - L1TriggerScalerESAnalyzer::beginJob(){ - std::cout<<"###L1TriggerScalerESAnalyzer::beginJob"< l1tr; - std::cout<<"got eshandle"<().get(l1tr); - std::cout<<"got context"<& l1tr = context.getHandle(scaler2Token_); + edm::LogVerbatim("L1TriggerScaler") << " got eshandle\n got context"; + const L1TriggerScaler* l1lumiscaler = l1tr.product(); + edm::LogVerbatim("L1TriggerScaler") << "got L1TriggerScaler* "; - /* let's user the printValues method - std::cout<< "print result" << std::endl; - l1lumiscaler->printAllValues(); - std::cout<< "print finished" << std::endl; - */ -std::cout<< "print result" << std::endl; + edm::LogVerbatim("L1TriggerScaler") << "print result"; l1lumiscaler->printRunValue(); l1lumiscaler->printLumiSegmentValues(); l1lumiscaler->printFormat(); @@ -95,50 +81,7 @@ std::cout<< "print result" << std::endl; l1lumiscaler->printGTPartition0TriggerRates(); l1lumiscaler->printGTPartition0DeadTime(); l1lumiscaler->printGTPartition0DeadTimeRatio(); - std::cout<< "print finished" << std::endl; - - - - /* - for(std::vector::const_iterator it=l1lumiscaler->m_run.begin(); it!=l1lumiscaler->m_run.end(); ++it){ - std::cout << " run: " <m_rn<< - "\nlumisegment: " << it->m_lumisegment<m_GTAlgoRates.size(); i++ ){ - std::cout << "m_GTAlgoRates["<m_GTAlgoRates[i]<m_GTAlgoPrescaling.size(); i++ ){ - std::cout << "m_GTAlgoPrescaling["<m_GTAlgoPrescaling[i]<m_GTTechCounts.size(); i++ ){ - std::cout << " m_GTTechCounts["<m_GTTechCounts[i]<m_GTTechRates.size(); i++ ){ - std::cout << " m_GTTechRates["<m_GTTechRates[i]<m_GTTechPrescaling.size(); i++ ){ - std::cout << " m_GTTechPrescaling["<m_GTTechPrescaling[i]<m_GTPartition0TriggerCounts.size(); i++ ){ - std::cout << " m_GTPartition0TriggerCounts["<m_GTPartition0TriggerCounts[i]<m_GTPartition0TriggerRates.size(); i++ ){ - std::cout << " m_GTPartition0TriggerRates["<m_GTPartition0TriggerRates[i]<m_GTPartition0DeadTime.size(); i++ ){ - std::cout << " m_GTPartition0DeadTime["<m_GTPartition0DeadTime[i]<m_GTPartition0DeadTimeRatio.size(); i++ ){ - std::cout << " m_GTPartition0DeadTimeRatio["<m_GTPartition0DeadTimeRatio[i]<X(mumu)X(mumu) decay + "35:addChannel = 1 1. 100 6000113 6000113",# Enable H0-->X(mumu)X(jetjet) decay +# "35:addChannel = 1 1. 100 6000111 6000113", + "35:onMode = off", +#` "35:onIfAny = 6000111 6000113" + "35:onIfAny = 6000113 6000113" + ), + + parameterSets = cms.vstring( + 'pythia8CommonSettings', +# 'pythia8CUEP8M1Settings', #Old Pythia Tune + 'pythia8CP5Settings', + 'pythia8PSweightsSettings', + 'processParameters' + ) + ) +) + +ProductionFilterSequence = cms.Sequence(generator) diff --git a/Configuration/PyReleaseValidation/python/relval_standard.py b/Configuration/PyReleaseValidation/python/relval_standard.py index c4ded01d2c8e8..006548e91c630 100644 --- a/Configuration/PyReleaseValidation/python/relval_standard.py +++ b/Configuration/PyReleaseValidation/python/relval_standard.py @@ -457,8 +457,26 @@ workflows[139.005] = ['',['AlCaPhiSym2021','RECOALCAECALPHISYMDR3','ALCAECALPHISYM']] ### run3 (2022) ### -workflows[140.001] = ['',['RunMinimumBias2022','HLTRUN3','RECONANORUN3','HARVESTRUN3']] -workflows[140.002] = ['',['RunZeroBias2022','HLTRUN3','RECONANORUN3','HARVESTRUN3']] +workflows[140.001] = ['',['RunMinimumBias2022B','HLTRUN3','RECONANORUN3','HARVESTRUN3']] +workflows[140.002] = ['',['RunZeroBias2022B','HLTRUN3','RECONANORUN3','HARVESTRUN3']] + +### run3 (2022) skims ### +workflows[140.103] = ['',['RunSingleMuon2022B','HLTRUN3','RECONANORUN3','SKIMSINGLEMUONRUN3']] +workflows[140.104] = ['',['RunZeroBias2022B','HLTRUN3','RECONANORUN3','SKIMZEROBIASRUN3']] +workflows[140.105] = ['',['RunBTagMu2022B','HLTRUN3','RECONANORUN3','SKIMBTAGMURUN3']] +workflows[140.106] = ['',['RunJetHT2022B','HLTRUN3','RECONANORUN3','SKIMJETHTRUN3']] +workflows[140.107] = ['',['RunDisplacedJet2022B','HLTRUN3','RECONANORUN3','SKIMDISPLACEDJETRUN3']] +workflows[140.108] = ['',['RunMET2022B','HLTRUN3','RECONANORUN3','SKIMMETRUN3']] +workflows[140.109] = ['',['RunEGamma2022B','HLTRUN3','RECONANORUN3','SKIMEGAMMARUN3']] +workflows[140.110] = ['',['RunTau2022B','HLTRUN3','RECONANORUN3','SKIMTAURUN3']] +workflows[140.111] = ['',['RunDoubleMuon2022B','HLTRUN3','RECONANORUN3','SKIMDOUBLEMUONRUN3']] +workflows[140.112] = ['',['RunMuonEG2022B','HLTRUN3','RECONANORUN3','SKIMMUONEGRUN3']] +workflows[140.113] = ['',['RunNoBPTX2022B','HLTRUN3','RECONANORUN3','SKIMNOBPTXRUN3']] +workflows[140.114] = ['',['RunHcalNZS2022B','HLTRUN3','RECONANORUN3','SKIMHCALNZSRUN3']] +workflows[140.115] = ['',['RunHLTPhysics2022B','HLTRUN3','RECONANORUN3','SKIMHLTPHYSICSRUN3']] +workflows[140.116] = ['',['RunCommissioning2022B','HLTRUN3','RECONANORUN3','SKIMCOMMISSIONINGRUN3']] +workflows[140.117] = ['',['RunCosmics2022B','HLTRUN3','RECOCOSMRUN3','SKIMCOSMICSRUN3']] +#workflows[140.118] = ['',['RunParkingBPH2022B','HLTRUN3','RECONANORUN3','SKIMPARKINGBPHRUN3']] ### fastsim ### workflows[5.1] = ['TTbar', ['TTbarFS','HARVESTFS']] @@ -724,6 +742,7 @@ workflows[158.2] = ['',['PhotonJets_Pt_10_13_HI','DIGIHI2018PPRECO','RECOHI2018PPRECO','HARVESTHI2018PPRECO']] workflows[158.3] = ['',['ZEEMM_13_HI','DIGIHI2018PPRECO','RECOHI2018PPRECO','HARVESTHI2018PPRECO']] workflows[159] = ['',['HydjetQ_B12_5020GeV_2021_ppReco','DIGIHI2021PPRECO','RECOHI2021PPRECOMB','ALCARECOHI2021PPRECO','HARVESTHI2021PPRECO']] +workflows[159.01] = ['',['HydjetQ_reminiaodPbPb2021_INPUT','REMINIAODHI2021PPRECOMB','HARVESTHI2021PPRECOMINIAOD']] workflows[159.1] = ['',['QCD_Pt_80_120_14_HI_2021','DIGIHI2021PPRECO','RECOHI2021PPRECO','HARVESTHI2021PPRECO']] workflows[159.2] = ['',['PhotonJets_Pt_10_14_HI_2021','DIGIHI2021PPRECO','RECOHI2021PPRECO','HARVESTHI2021PPRECO']] workflows[159.3] = ['',['ZMM_14_HI_2021','DIGIHI2021PPRECO','RECOHI2021PPRECO','HARVESTHI2021PPRECO']] diff --git a/Configuration/PyReleaseValidation/python/relval_steps.py b/Configuration/PyReleaseValidation/python/relval_steps.py index 0736df59c3819..7adce85ca00c3 100644 --- a/Configuration/PyReleaseValidation/python/relval_steps.py +++ b/Configuration/PyReleaseValidation/python/relval_steps.py @@ -3,6 +3,7 @@ from Configuration.HLT.autoHLT import autoHLT from Configuration.AlCa.autoPCL import autoPCL +from Configuration.Skimming.autoSkim import autoSkim from .upgradeWorkflowComponents import step3_trackingOnly # step1 gensim: for run1 @@ -469,14 +470,30 @@ # UL AOD steps['RunJetHT2018D_reminiaodUL']={'INPUT':InputInfo(dataSet='/JetHT/Run2018D-12Nov2019_UL2018-v4/AOD',label='2018DrmaodUL',events=100000,location='STD', ls=Run2018D)} - -#### run3 2022B #### -Run2022A={353706: [[1, 40]]} -steps['RunSingleMuon2022A']={'INPUT':InputInfo(dataSet='/SingleMuon/Run2022A-v1/RAW',label='2022A',events=100000,location='STD', ls=Run2022A)} -Run2022B={355130: [[1, 40]]} +#### run3 #### +Run2022B={355351: [[712, 768]]} +steps['RunMinimumBias2022B']={'INPUT':InputInfo(dataSet='/MinimumBias/Run2022B-v1/RAW',label='2022B',events=100000,location='STD', ls=Run2022B)} +Run2022B={355680: [[21, 24]]} steps['RunSingleMuon2022B']={'INPUT':InputInfo(dataSet='/SingleMuon/Run2022B-v1/RAW',label='2022B',events=100000,location='STD', ls=Run2022B)} steps['RunZeroBias2022B']={'INPUT':InputInfo(dataSet='/ZeroBias/Run2022B-v1/RAW',label='2022B',events=100000,location='STD', ls=Run2022B)} - +Run2022B={355456: [[446, 467]]} +steps['RunBTagMu2022B']={'INPUT':InputInfo(dataSet='/BTagMu/Run2022B-v1/RAW',label='2022B',events=100000,location='STD', ls=Run2022B)} +steps['RunNoBPTX2022B']={'INPUT':InputInfo(dataSet='/NoBPTX/Run2022B-v1/RAW',label='2022B',events=100000,location='STD', ls=Run2022B)} +steps['RunHcalNZS2022B']={'INPUT':InputInfo(dataSet='/HcalNZS/Run2022B-v1/RAW',label='2022B',events=100000,location='STD', ls=Run2022B)} +steps['RunHLTPhysics2022B']={'INPUT':InputInfo(dataSet='/HLTPhysics/Run2022B-v1/RAW',label='2022B',events=100000,location='STD', ls=Run2022B)} +steps['RunCommissioning2022B']={'INPUT':InputInfo(dataSet='/Commissioning/Run2022B-v1/RAW',label='2022B',events=100000,location='STD', ls=Run2022B)} +Run2022B={355383: [[267, 269]]} +steps['RunJetHT2022B']={'INPUT':InputInfo(dataSet='/JetHT/Run2022B-v1/RAW',label='2022B',events=100000,location='STD', ls=Run2022B)} +Run2022B={355727: [[55, 108]]} +steps['RunCosmics2022B']={'INPUT':InputInfo(dataSet='/Cosmics/Run2022B-v1/RAW',label='2022B',events=100000,location='STD', ls=Run2022B)} +Run2022B={355680: [[21, 24]]} +steps['RunDisplacedJet2022B']={'INPUT':InputInfo(dataSet='/DisplacedJet/Run2022B-v1/RAW',label='2022B',events=100000,location='STD', ls=Run2022B)} +steps['RunMET2022B']={'INPUT':InputInfo(dataSet='/MET/Run2022B-v1/RAW',label='2022B',events=100000,location='STD', ls=Run2022B)} +steps['RunEGamma2022B']={'INPUT':InputInfo(dataSet='/EGamma/Run2022B-v1/RAW',label='2022B',events=100000,location='STD', ls=Run2022B)} +steps['RunTau2022B']={'INPUT':InputInfo(dataSet='/Tau/Run2022B-v1/RAW',label='2022B',events=100000,location='STD', ls=Run2022B)} +steps['RunDoubleMuon2022B']={'INPUT':InputInfo(dataSet='/DoubleMuon/Run2022B-v1/RAW',label='2022B',events=100000,location='STD', ls=Run2022B)} +steps['RunMuonEG2022B']={'INPUT':InputInfo(dataSet='/MuonEG/Run2022B-v1/RAW',label='2022B',events=100000,location='STD', ls=Run2022B)} +#steps['RunParkingBPH2022B']={'INPUT':InputInfo(dataSet='/ParkingBPH/Run2022B-v1/RAW',label='2022B',events=100000,location='STD', ls=Run2022B)} # Highstat HLTPhysics Run2015DHS=selectedLS([258712,258713,258714,258741,258742,258745,258749,258750,259626,259637,259683,259685,259686,259721,259809,259810,259818,259820,259821,259822,259862,259890,259891]) @@ -515,10 +532,6 @@ steps['AlCaPhiSym2021']={'INPUT':InputInfo(dataSet='/AlCaPhiSym/Commissioning2021-v1/RAW',label='2021Commissioning',run=[346512],location='STD')} steps['AlCaLumiPixels2021']={'INPUT':InputInfo(dataSet='/AlCaLumiPixelsCountsExpress/Commissioning2021-v1/RAW',label='2021Commissioning',run=[346512],events=100000,location='STD')} -Run2022={353053: [[0, 100]]} -steps['RunMinimumBias2022']={'INPUT':InputInfo(dataSet='/MinimumBias/Run2022A-v1/RAW',label='2022',events=100000,location='STD', ls=Run2022)} -steps['RunZeroBias2022']={'INPUT':InputInfo(dataSet='/ZeroBias/Run2022A-v1/RAW',label='2022',events=100000,location='STD', ls=Run2022)} - #### Test of lumi section boundary crossing with run2 2018D #### Run2018Dml1={320822: [[1,1]] , 320823: [[1,1]]} Run2018Dml2={320822: [[1,2]]} @@ -745,6 +758,7 @@ def identitySim(wf): steps['TTbar_13_reminiaod2018UL_INPUT']={'INPUT':InputInfo(dataSet='/RelValProdTTbar_13_pmx25ns/CMSSW_10_6_4-PUpmx25ns_106X_upgrade2018_realistic_v9-v1/AODSIM',label='rmaod',location='STD')} # INPUT command for reminiAOD wfs on PbPb relval inputs steps['HydjetQ_reminiaodPbPb2018_INPUT']={'INPUT':InputInfo(dataSet='/RelValHydjetQ_B12_5020GeV_2018_ppReco/CMSSW_10_3_3-PU_103X_upgrade2018_realistic_HI_v11-v1/GEN-SIM-RECO',label='rmaod',location='STD')} +steps['HydjetQ_reminiaodPbPb2021_INPUT']={'INPUT':InputInfo(dataSet='/RelValHydjetQ_B12_5020GeV_2021_ppReco/CMSSW_12_5_0_pre3-124X_mcRun3_2022_realistic_HI_v8-v1/GEN-SIM-RECO',label='rmaod',location='STD')} #input for a NANOAOD from MINIAOD workflow steps['ZEE_13_80XNanoAODINPUT']={'INPUT':InputInfo(dataSet='/RelValZEE_13/CMSSW_8_0_21-PU25ns_80X_mcRun2_asymptotic_2016_TrancheIV_v6_Tr4GT_v6-v1/MINIAODSIM',label='nanoaod80X',location='STD')} @@ -1938,7 +1952,7 @@ def lhegensim2018ml(fragment,howMuch): hltKey2022='relval2022' steps['HLTDR3_2021']=merge( [ {'-s':'L1REPACK:Full,HLT:@%s'%hltKey2022,},{'--conditions':'auto:run3_hlt_relval'},{'--era':'Run3'},steps['HLTD'] ] ) -steps['HLTRUN3']=merge( [ {'-s':'HLT:@%s'%hltKey2022,},{'--conditions':'auto:run3_hlt_relval'},{'--era':'Run3'},steps['HLTD'] ] ) +steps['HLTRUN3']=merge( [ {'-s':'L1REPACK:Full,HLT:@%s'%hltKey2022,},{'--conditions':'auto:run3_hlt_relval'},{'--era':'Run3'},steps['HLTD'] ] ) # special setting for lumi section boundary crossing in RunEGamma2018Dml steps['HLTDR2_2018ml']=merge( [ {'--customise_commands':'"process.source.skipEvents=cms.untracked.uint32(7000)"'},steps['HLTDR2_2018'] ] ) @@ -2353,6 +2367,15 @@ def lhegensim2018ml(fragment,howMuch): '-n':'-1', '-s':'RECO:bunchSpacingProducer+ecalMultiFitUncalibRecHitTask+ecalCalibratedRecHitTask', '--customise':'Calibration/EcalCalibAlgos/EcalPhiSymRecoSequence_cff'},dataReco]) + +# Run3 skims +for s in autoSkim.keys(): + steps['SKIM'+s.upper()+'RUN3']={'-s':'SKIM:%s'%(autoSkim[s]), + '--data':'', + '--era':'Run3', + '--scenario':'pp', + '--conditions':'auto:run3_data_relval'} + if 'Cosmics' in s: steps['SKIM'+s.upper()+'RUN3']['--scenario'] = 'cosmics' # step1 gensim for HI mixing step1Up2018HiMixDefaults = merge ([{'--beamspot':'MatchHI', '--pileup':'HiMixGEN', '--scenario':'HeavyIons'},hiDefaults2018_ppReco,PUHI,step1Up2018HiProdDefaults]) @@ -2636,6 +2659,7 @@ def gen2021HiMix(fragment,howMuch): steps['RECODR3_AlCaTkCosmics_Offline']=merge([{'-s':'RAW2DIGI,L1Reco,RECO,SKIM:EXONoBPTXSkim,PAT,ALCA:TkAlCosmicsInCollisions,DQM:@standardDQMFakeHLT+@miniAODDQM'},steps['RECODR3_2021']]) steps['RECONANORUN3']=merge([{'-s':'RAW2DIGI,L1Reco,RECO,PAT,NANO,DQM:@miniAODDQM+@nanoAODDQM'},steps['RECODR3']]) +steps['RECOCOSMRUN3']=merge([{'--scenario':'cosmics','-s':'RAW2DIGI,L1Reco,RECO,DQM','--datatier':'RECO,DQMIO','--eventcontent':'RECO,DQM'},steps['RECONANORUN3']]) steps['RECONANORUN3']['--customise'] += ',PhysicsTools/NanoAOD/V10/nano_cff.nanoAOD_customizeV10' # mask away - to be removed once we'll migrate the matrix to be fully unscheduled for RECO step @@ -2722,6 +2746,13 @@ def gen2021HiMix(fragment,howMuch): '--era':'Run3_pp_on_PbPb', '--procModifiers':'genJetSubEvent', },step3Up2015Defaults]) +steps['REMINIAODHI2021PPRECOMB']=merge([{'-s':'PAT,VALIDATION:@miniAODValidation,DQM:@miniAODDQM', + '--datatier':'MINIAODSIM,DQMIO', + '--eventcontent':'MINIAODSIM,DQM', + '-n':100, + '--era':'Run3_pp_on_PbPb', + '--procModifiers':'genJetSubEvent', + },hiDefaults2021_ppReco,step3Up2015Defaults]) steps['ALCARECOHI2021PPRECO']=merge([hiDefaults2021_ppReco,{'-s':'ALCA:TkAlMinBias+SiStripCalMinBias', '--datatier':'ALCARECO', @@ -3265,6 +3296,12 @@ def gen2021HiMix(fragment,howMuch): '--mc':'', '--era' : 'Run3_pp_on_PbPb', '--filetype':'DQM'}]) +steps['HARVESTHI2021PPRECOMINIAOD']=merge([{'-s':'HARVESTING:@miniAODValidation+@miniAODDQM', + '--filein':'file:step2_inDQM.root', + '--mc':'', + '--era' : 'Run3_pp_on_PbPb', + '--filetype':'DQM', + '-n':100},hiDefaults2021_ppReco]) steps['HARVESTHI2018PPRECO']=merge([hiDefaults2018_ppReco,{'-s':'HARVESTING:validationHarvestingNoHLT+dqmHarvestingFakeHLT', '--filein':'file:step3_inDQM.root', diff --git a/Configuration/PyReleaseValidation/python/upgradeWorkflowComponents.py b/Configuration/PyReleaseValidation/python/upgradeWorkflowComponents.py index 6d1e641ca683c..6838d90f7b7af 100644 --- a/Configuration/PyReleaseValidation/python/upgradeWorkflowComponents.py +++ b/Configuration/PyReleaseValidation/python/upgradeWorkflowComponents.py @@ -2207,7 +2207,7 @@ def condition(self, fragment, stepList, key, hasHarvest): 'Geom' : 'Extended2026D94', 'HLTmenu': '@fake2', 'GT' : 'auto:phase2_realistic_T21', - 'Era' : 'Phase2C17I13M9', + 'Era' : 'Phase2C18I13M9', 'ScenToRun' : ['GenSimHLBeamSpot','DigiTrigger','RecoGlobal', 'HARVESTGlobal'], }, } diff --git a/Configuration/StandardSequences/python/AlCaHarvesting_cff.py b/Configuration/StandardSequences/python/AlCaHarvesting_cff.py index 2fba7c2062fdf..d1c1c01b771ba 100644 --- a/Configuration/StandardSequences/python/AlCaHarvesting_cff.py +++ b/Configuration/StandardSequences/python/AlCaHarvesting_cff.py @@ -254,8 +254,8 @@ timetype = cms.untracked.string('runnumber') ) -ALCAHARVESTPPSDiamondSampicTimingCalibration_metadata = cms.PSet(record = cms.untracked.string('PPSTimingCalibrationRcd_Sampic')) -ALCAHARVESTPPSDiamondSampicTimingCalibration_dbOutput = cms.PSet(record = cms.string('PPSTimingCalibrationRcd_Sampic'), +ALCAHARVESTPPSDiamondSampicTimingCalibration_metadata = cms.PSet(record = cms.untracked.string('PPSTimingCalibrationRcd')) +ALCAHARVESTPPSDiamondSampicTimingCalibration_dbOutput = cms.PSet(record = cms.string('PPSTimingCalibrationRcd'), tag = cms.string('DiamondSampicCalibration'), timetype = cms.untracked.string('runnumber')) diff --git a/Configuration/StandardSequences/python/Eras.py b/Configuration/StandardSequences/python/Eras.py index 3f6765d4c3b46..78255fada01b3 100644 --- a/Configuration/StandardSequences/python/Eras.py +++ b/Configuration/StandardSequences/python/Eras.py @@ -54,7 +54,8 @@ def __init__(self): 'Phase2C11I13M9', 'Phase2C11I13T25M9', 'Phase2C11I13T26M9', - 'Phase2C17I13M9' + 'Phase2C17I13M9', + 'Phase2C18I13M9' ] internalUseMods = ['run2_common', 'run2_25ns_specific', diff --git a/DQM/CTPPS/plugins/CTPPSCommonDQMSource.cc b/DQM/CTPPS/plugins/CTPPSCommonDQMSource.cc index 018058234091d..7920ec8c8495c 100644 --- a/DQM/CTPPS/plugins/CTPPSCommonDQMSource.cc +++ b/DQM/CTPPS/plugins/CTPPSCommonDQMSource.cc @@ -297,8 +297,10 @@ CTPPSCommonDQMSource::ArmPlots::ArmPlots(DQMStore::IBooker &ibooker, int _id, bo CTPPSCommonDQMSource::CTPPSCommonDQMSource(const edm::ParameterSet &ps) : verbosity(ps.getUntrackedParameter("verbosity", 0)), ctppsRecordToken(consumes(ps.getUntrackedParameter("ctppsmetadata"))), - tokenLocalTrackLite(consumes>(ps.getParameter("tagLocalTrackLite"))), - tokenRecoProtons(consumes>(ps.getParameter("tagRecoProtons"))), + tokenLocalTrackLite( + consumes>(ps.getUntrackedParameter("tagLocalTrackLite"))), + tokenRecoProtons( + consumes>(ps.getUntrackedParameter("tagRecoProtons"))), makeProtonRecoPlots_(ps.getParameter("makeProtonRecoPlots")), perLSsaving_(ps.getUntrackedParameter("perLSsaving", false)) { currentLS = 0; diff --git a/DQM/CTPPS/plugins/CTPPSDiamondDQMSource.cc b/DQM/CTPPS/plugins/CTPPSDiamondDQMSource.cc index ffb949752dfc4..55d1903020a23 100644 --- a/DQM/CTPPS/plugins/CTPPSDiamondDQMSource.cc +++ b/DQM/CTPPS/plugins/CTPPSDiamondDQMSource.cc @@ -587,12 +587,12 @@ CTPPSDiamondDQMSource::ChannelPlots::ChannelPlots(DQMStore::IBooker& ibooker, un CTPPSDiamondDQMSource::CTPPSDiamondDQMSource(const edm::ParameterSet& ps) : perLSsaving_(ps.getUntrackedParameter("perLSsaving", false)), - tokenPixelTrack_( - consumes>(ps.getParameter("tagPixelLocalTracks"))), - tokenDiamondHit_( - consumes>(ps.getParameter("tagDiamondRecHits"))), - tokenDiamondTrack_( - consumes>(ps.getParameter("tagDiamondLocalTracks"))), + tokenPixelTrack_(consumes>( + ps.getUntrackedParameter("tagPixelLocalTracks"))), + tokenDiamondHit_(consumes>( + ps.getUntrackedParameter("tagDiamondRecHits"))), + tokenDiamondTrack_(consumes>( + ps.getUntrackedParameter("tagDiamondLocalTracks"))), ctppsGeometryRunToken_(esConsumes()), ctppsGeometryEventToken_(esConsumes()), // ctppsLhcInfoToken_(esConsumes()), @@ -607,9 +607,9 @@ CTPPSDiamondDQMSource::CTPPSDiamondDQMSource(const edm::ParameterSet& ps) EC_difference_56_(-500), EC_difference_45_(-500) { if (extract_digi_info_) { - tokenStatus_ = consumes>(ps.getParameter("tagStatus")); - tokenFEDInfo_ = consumes>(ps.getParameter("tagFEDInfo")); - tokenDigi_ = consumes>(ps.getParameter("tagDigi")); + tokenStatus_ = consumes>(ps.getUntrackedParameter("tagStatus")); + tokenFEDInfo_ = consumes>(ps.getUntrackedParameter("tagFEDInfo")); + tokenDigi_ = consumes>(ps.getUntrackedParameter("tagDigi")); } for (const auto& pset : ps.getParameter>("offsetsOOT")) { runParameters_.emplace_back( diff --git a/DQM/CTPPS/plugins/CTPPSPixelDQMSource.cc b/DQM/CTPPS/plugins/CTPPSPixelDQMSource.cc index 3d8a783dfae4d..a0b8bd10cb6c9 100644 --- a/DQM/CTPPS/plugins/CTPPSPixelDQMSource.cc +++ b/DQM/CTPPS/plugins/CTPPSPixelDQMSource.cc @@ -164,9 +164,9 @@ using namespace edm; CTPPSPixelDQMSource::CTPPSPixelDQMSource(const edm::ParameterSet &ps) : verbosity(ps.getUntrackedParameter("verbosity", 0)), rpStatusWord(ps.getUntrackedParameter("RPStatusWord", 0x8008)) { - tokenDigi = consumes>(ps.getParameter("tagRPixDigi")); - tokenCluster = consumes>(ps.getParameter("tagRPixCluster")); - tokenTrack = consumes>(ps.getParameter("tagRPixLTrack")); + tokenDigi = consumes>(ps.getUntrackedParameter("tagRPixDigi")); + tokenCluster = consumes>(ps.getUntrackedParameter("tagRPixCluster")); + tokenTrack = consumes>(ps.getUntrackedParameter("tagRPixLTrack")); offlinePlots = ps.getUntrackedParameter("offlinePlots", true); onlinePlots = ps.getUntrackedParameter("onlinePlots", true); diff --git a/DQM/CTPPS/plugins/DiamondSampicCalibrationDQMSource.cc b/DQM/CTPPS/plugins/DiamondSampicCalibrationDQMSource.cc index 81a5cf0e4ba71..84ee200cb9515 100644 --- a/DQM/CTPPS/plugins/DiamondSampicCalibrationDQMSource.cc +++ b/DQM/CTPPS/plugins/DiamondSampicCalibrationDQMSource.cc @@ -174,8 +174,9 @@ DiamondSampicCalibrationDQMSource::ChannelPlots::ChannelPlots(DQMStore::IBooker DiamondSampicCalibrationDQMSource::DiamondSampicCalibrationDQMSource(const edm::ParameterSet &ps) : totemTimingDigiToken_( - consumes>(ps.getParameter("totemTimingDigiTag"))), - tokenRecHit_(consumes>(ps.getParameter("tagRecHits"))), + consumes>(ps.getUntrackedParameter("totemTimingDigiTag"))), + tokenRecHit_( + consumes>(ps.getUntrackedParameter("tagRecHits"))), timingCalibrationToken_(esConsumes()), geomEsToken_(esConsumes()), verbosity_(ps.getUntrackedParameter("verbosity", 0)), diff --git a/DQM/CTPPS/plugins/DiamondSampicDQMSource.cc b/DQM/CTPPS/plugins/DiamondSampicDQMSource.cc index 0e78861951c29..f867d8ffa9bc3 100644 --- a/DQM/CTPPS/plugins/DiamondSampicDQMSource.cc +++ b/DQM/CTPPS/plugins/DiamondSampicDQMSource.cc @@ -381,11 +381,14 @@ DiamondSampicDQMSource::ChannelPlots::ChannelPlots(DQMStore::IBooker &ibooker, u //---------------------------------------------------------------------------------------------------- DiamondSampicDQMSource::DiamondSampicDQMSource(const edm::ParameterSet &ps) - : tokenLocalTrack_(consumes>(ps.getParameter("tagLocalTrack"))), - tokenDigi_(consumes>(ps.getParameter("tagDigi"))), - tokenRecHit_(consumes>(ps.getParameter("tagRecHits"))), - tokenTrack_(consumes>(ps.getParameter("tagTracks"))), - tokenFEDInfo_(consumes>(ps.getParameter("tagFEDInfo"))), + : tokenLocalTrack_( + consumes>(ps.getUntrackedParameter("tagLocalTrack"))), + tokenDigi_(consumes>(ps.getUntrackedParameter("tagDigi"))), + tokenRecHit_( + consumes>(ps.getUntrackedParameter("tagRecHits"))), + tokenTrack_( + consumes>(ps.getUntrackedParameter("tagTracks"))), + tokenFEDInfo_(consumes>(ps.getUntrackedParameter("tagFEDInfo"))), ctppsGeometryRunToken_(esConsumes()), samplesForNoise_(ps.getUntrackedParameter("samplesForNoise", 5)), verbosity_(ps.getUntrackedParameter("verbosity", 0)), diff --git a/DQM/CTPPS/plugins/ElasticPlotDQMSource.cc b/DQM/CTPPS/plugins/ElasticPlotDQMSource.cc index 1cd2d1c50e050..5a6f7b253e342 100644 --- a/DQM/CTPPS/plugins/ElasticPlotDQMSource.cc +++ b/DQM/CTPPS/plugins/ElasticPlotDQMSource.cc @@ -185,9 +185,9 @@ ElasticPlotDQMSource::PotPlots::PotPlots(DQMStore::IBooker &ibooker, unsigned in ElasticPlotDQMSource::ElasticPlotDQMSource(const edm::ParameterSet &ps) : verbosity(ps.getUntrackedParameter("verbosity", 0)) { - tokenRecHit = consumes>(ps.getParameter("tagRecHit")); - tokenUVPattern = consumes>(ps.getParameter("tagUVPattern")); - tokenLocalTrack = consumes>(ps.getParameter("tagLocalTrack")); + tokenRecHit = consumes>(ps.getUntrackedParameter("tagRecHit")); + tokenUVPattern = consumes>(ps.getUntrackedParameter("tagUVPattern")); + tokenLocalTrack = consumes>(ps.getUntrackedParameter("tagLocalTrack")); } //---------------------------------------------------------------------------------------------------- diff --git a/DQM/CTPPS/plugins/TotemDAQTriggerDQMSource.cc b/DQM/CTPPS/plugins/TotemDAQTriggerDQMSource.cc index 85f6030349fca..1ea50842ce631 100644 --- a/DQM/CTPPS/plugins/TotemDAQTriggerDQMSource.cc +++ b/DQM/CTPPS/plugins/TotemDAQTriggerDQMSource.cc @@ -52,7 +52,7 @@ using namespace edm; TotemDAQTriggerDQMSource::TotemDAQTriggerDQMSource(const edm::ParameterSet &ps) : verbosity(ps.getUntrackedParameter("verbosity", 0)) { - tokenFEDInfo = consumes>(ps.getParameter("tagFEDInfo")); + tokenFEDInfo = consumes>(ps.getUntrackedParameter("tagFEDInfo")); } //---------------------------------------------------------------------------------------------------- diff --git a/DQM/CTPPS/plugins/TotemRPDQMSource.cc b/DQM/CTPPS/plugins/TotemRPDQMSource.cc index db7eeba360782..da62e61b9e154 100644 --- a/DQM/CTPPS/plugins/TotemRPDQMSource.cc +++ b/DQM/CTPPS/plugins/TotemRPDQMSource.cc @@ -182,13 +182,13 @@ TotemRPDQMSource::TotemRPDQMSource(const edm::ParameterSet &ps) geometryToken_(esConsumes()) { - tokenStatus = consumes>(ps.getParameter("tagStatus")); + tokenStatus = consumes>(ps.getUntrackedParameter("tagStatus")); - tokenDigi = consumes>(ps.getParameter("tagDigi")); - tokenCluster = consumes>(ps.getParameter("tagCluster")); - tokenRecHit = consumes>(ps.getParameter("tagRecHit")); - tokenUVPattern = consumes>(ps.getParameter("tagUVPattern")); - tokenLocalTrack = consumes>(ps.getParameter("tagLocalTrack")); + tokenDigi = consumes>(ps.getUntrackedParameter("tagDigi")); + tokenCluster = consumes>(ps.getUntrackedParameter("tagCluster")); + tokenRecHit = consumes>(ps.getUntrackedParameter("tagRecHit")); + tokenUVPattern = consumes>(ps.getUntrackedParameter("tagUVPattern")); + tokenLocalTrack = consumes>(ps.getUntrackedParameter("tagLocalTrack")); } //---------------------------------------------------------------------------------------------------- diff --git a/DQM/CTPPS/plugins/TotemTimingDQMSource.cc b/DQM/CTPPS/plugins/TotemTimingDQMSource.cc index 2d618b48e01d2..a863e564ff112 100644 --- a/DQM/CTPPS/plugins/TotemTimingDQMSource.cc +++ b/DQM/CTPPS/plugins/TotemTimingDQMSource.cc @@ -404,12 +404,14 @@ TotemTimingDQMSource::ChannelPlots::ChannelPlots(DQMStore::IBooker &ibooker, uns //---------------------------------------------------------------------------------------------------- TotemTimingDQMSource::TotemTimingDQMSource(const edm::ParameterSet &ps) - : tokenLocalTrack_(consumes>(ps.getParameter("tagLocalTrack"))), - tokenDigi_(consumes>(ps.getParameter("tagDigi"))), - tokenRecHit_(consumes>(ps.getParameter("tagRecHits"))), + : tokenLocalTrack_( + consumes>(ps.getUntrackedParameter("tagLocalTrack"))), + tokenDigi_(consumes>(ps.getUntrackedParameter("tagDigi"))), + tokenRecHit_( + consumes>(ps.getUntrackedParameter("tagRecHits"))), // tokenTrack_(consumes>( // ps.getParameter("tagLocalTracks"))), - tokenFEDInfo_(consumes>(ps.getParameter("tagFEDInfo"))), + tokenFEDInfo_(consumes>(ps.getUntrackedParameter("tagFEDInfo"))), geometryToken_(esConsumes()), geometryTokenBeginRun_(esConsumes()), minimumStripAngleForTomography_(ps.getParameter("minimumStripAngleForTomography")), diff --git a/DQM/CTPPS/python/ctppsCommonDQMSource_cfi.py b/DQM/CTPPS/python/ctppsCommonDQMSource_cfi.py index d05e70d2d807b..1820520472dd1 100644 --- a/DQM/CTPPS/python/ctppsCommonDQMSource_cfi.py +++ b/DQM/CTPPS/python/ctppsCommonDQMSource_cfi.py @@ -4,8 +4,8 @@ ctppsCommonDQMSource = DQMEDAnalyzer('CTPPSCommonDQMSource', ctppsmetadata = cms.untracked.InputTag("onlineMetaDataDigis"), - tagLocalTrackLite = cms.InputTag('ctppsLocalTrackLiteProducer'), - tagRecoProtons = cms.InputTag("ctppsProtons", "multiRP"), + tagLocalTrackLite = cms.untracked.InputTag('ctppsLocalTrackLiteProducer'), + tagRecoProtons = cms.untracked.InputTag("ctppsProtons", "multiRP"), makeProtonRecoPlots = cms.bool(True), diff --git a/DQM/CTPPS/python/ctppsDiamondDQMSource_cfi.py b/DQM/CTPPS/python/ctppsDiamondDQMSource_cfi.py index 905c436dfcebf..867ba8b926e21 100644 --- a/DQM/CTPPS/python/ctppsDiamondDQMSource_cfi.py +++ b/DQM/CTPPS/python/ctppsDiamondDQMSource_cfi.py @@ -2,12 +2,12 @@ from DQMServices.Core.DQMEDAnalyzer import DQMEDAnalyzer ctppsDiamondDQMSource = DQMEDAnalyzer('CTPPSDiamondDQMSource', - tagStatus = cms.InputTag("ctppsDiamondRawToDigi", "TimingDiamond"), - tagDigi = cms.InputTag("ctppsDiamondRawToDigi", "TimingDiamond"), - tagFEDInfo = cms.InputTag("ctppsDiamondRawToDigi", "TimingDiamond"), - tagDiamondRecHits = cms.InputTag("ctppsDiamondRecHits"), - tagDiamondLocalTracks = cms.InputTag("ctppsDiamondLocalTracks"), - tagPixelLocalTracks = cms.InputTag("ctppsPixelLocalTracks"), + tagStatus = cms.untracked.InputTag("ctppsDiamondRawToDigi", "TimingDiamond"), + tagDigi = cms.untracked.InputTag("ctppsDiamondRawToDigi", "TimingDiamond"), + tagFEDInfo = cms.untracked.InputTag("ctppsDiamondRawToDigi", "TimingDiamond"), + tagDiamondRecHits = cms.untracked.InputTag("ctppsDiamondRecHits"), + tagDiamondLocalTracks = cms.untracked.InputTag("ctppsDiamondLocalTracks"), + tagPixelLocalTracks = cms.untracked.InputTag("ctppsPixelLocalTracks"), excludeMultipleHits = cms.bool(True), extractDigiInfo = cms.bool(True), @@ -45,12 +45,12 @@ ) ctppsDiamondDQMOfflineSource = DQMEDAnalyzer('CTPPSDiamondDQMSource', - tagStatus = cms.InputTag("ctppsDiamondRawToDigi", "TimingDiamond"), - tagDigi = cms.InputTag("ctppsDiamondRawToDigi", "TimingDiamond"), - tagFEDInfo = cms.InputTag("ctppsDiamondRawToDigi", "TimingDiamond"), - tagDiamondRecHits = cms.InputTag("ctppsDiamondRecHits"), - tagDiamondLocalTracks = cms.InputTag("ctppsDiamondLocalTracks"), - tagPixelLocalTracks = cms.InputTag("ctppsPixelLocalTracks"), + tagStatus = cms.untracked.InputTag("ctppsDiamondRawToDigi", "TimingDiamond"), + tagDigi = cms.untracked.InputTag("ctppsDiamondRawToDigi", "TimingDiamond"), + tagFEDInfo = cms.untracked.InputTag("ctppsDiamondRawToDigi", "TimingDiamond"), + tagDiamondRecHits = cms.untracked.InputTag("ctppsDiamondRecHits"), + tagDiamondLocalTracks = cms.untracked.InputTag("ctppsDiamondLocalTracks"), + tagPixelLocalTracks = cms.untracked.InputTag("ctppsPixelLocalTracks"), excludeMultipleHits = cms.bool(True), extractDigiInfo = cms.bool(True), diff --git a/DQM/CTPPS/python/ctppsPixelDQMSource_cfi.py b/DQM/CTPPS/python/ctppsPixelDQMSource_cfi.py index 2cb39ab593d33..ff7d0ad8bf929 100644 --- a/DQM/CTPPS/python/ctppsPixelDQMSource_cfi.py +++ b/DQM/CTPPS/python/ctppsPixelDQMSource_cfi.py @@ -3,9 +3,9 @@ #ctppsPixelDQMSource = cms.EDAnalyzer("CTPPSPixelDQMSource", from DQMServices.Core.DQMEDAnalyzer import DQMEDAnalyzer ctppsPixelDQMSource = DQMEDAnalyzer('CTPPSPixelDQMSource', - tagRPixDigi = cms.InputTag("ctppsPixelDigis", ""), - tagRPixCluster = cms.InputTag("ctppsPixelClusters", ""), - tagRPixLTrack = cms.InputTag("ctppsPixelLocalTracks", ""), + tagRPixDigi = cms.untracked.InputTag("ctppsPixelDigis", ""), + tagRPixCluster = cms.untracked.InputTag("ctppsPixelClusters", ""), + tagRPixLTrack = cms.untracked.InputTag("ctppsPixelLocalTracks", ""), RPStatusWord = cms.untracked.uint32(0x8008), # rpots in readout:220_fr_hr; 210_fr_hr verbosity = cms.untracked.uint32(0), offlinePlots = cms.untracked.bool(False), @@ -15,13 +15,13 @@ ) ctppsPixelDQMOfflineSource = DQMEDAnalyzer('CTPPSPixelDQMSource', - tagRPixDigi = cms.InputTag("ctppsPixelDigis", ""), - tagRPixCluster = cms.InputTag("ctppsPixelClusters", ""), - tagRPixLTrack = cms.InputTag("ctppsPixelLocalTracks", ""), + tagRPixDigi = cms.untracked.InputTag("ctppsPixelDigis", ""), + tagRPixCluster = cms.untracked.InputTag("ctppsPixelClusters", ""), + tagRPixLTrack = cms.untracked.InputTag("ctppsPixelLocalTracks", ""), RPStatusWord = cms.untracked.uint32(0x8008), # rpots in readout: 220_fr_hr; 210_fr_hr verbosity = cms.untracked.uint32(0), offlinePlots = cms.untracked.bool(True), onlinePlots = cms.untracked.bool(False), turnOffPlanePlots = cms.untracked.vstring(), # add tags for planes to be shut off, # e.g. "0_2_3_4" for arm 0 station 2 rp 3 plane 4 -) \ No newline at end of file +) diff --git a/DQM/CTPPS/python/diamondSampicDQMSource_cfi.py b/DQM/CTPPS/python/diamondSampicDQMSource_cfi.py index 2604c4e9362b7..0b45f0ff7c3e4 100644 --- a/DQM/CTPPS/python/diamondSampicDQMSource_cfi.py +++ b/DQM/CTPPS/python/diamondSampicDQMSource_cfi.py @@ -2,11 +2,11 @@ from DQMServices.Core.DQMEDAnalyzer import DQMEDAnalyzer diamondSampicDQMSourceOnline = DQMEDAnalyzer('DiamondSampicDQMSource', - tagDigi = cms.InputTag("totemTimingRawToDigi", "TotemTiming"), - tagFEDInfo = cms.InputTag("totemTimingRawToDigi", "TotemTiming"), - tagRecHits = cms.InputTag("totemTimingRecHits"), - tagTracks = cms.InputTag("diamondSampicLocalTracks"), - tagLocalTrack = cms.InputTag("totemRPLocalTrackFitter"), + tagDigi = cms.untracked.InputTag("totemTimingRawToDigi", "TotemTiming"), + tagFEDInfo = cms.untracked.InputTag("totemTimingRawToDigi", "TotemTiming"), + tagRecHits = cms.untracked.InputTag("totemTimingRecHits"), + tagTracks = cms.untracked.InputTag("diamondSampicLocalTracks"), + tagLocalTrack = cms.untracked.InputTag("totemRPLocalTrackFitter"), samplesForNoise = cms.untracked.uint32(6), @@ -15,11 +15,11 @@ ) diamondSampicDQMSourceOffline = DQMEDAnalyzer('DiamondSampicDQMSource', - tagDigi = cms.InputTag("totemTimingRawToDigi", "TotemTiming"), - tagFEDInfo = cms.InputTag("totemTimingRawToDigi", "TotemTiming"), - tagRecHits = cms.InputTag("totemTimingRecHits"), - tagTracks = cms.InputTag("diamondSampicLocalTracks"), - tagLocalTrack = cms.InputTag("totemRPLocalTrackFitter"), + tagDigi = cms.untracked.InputTag("totemTimingRawToDigi", "TotemTiming"), + tagFEDInfo = cms.untracked.InputTag("totemTimingRawToDigi", "TotemTiming"), + tagRecHits = cms.untracked.InputTag("totemTimingRecHits"), + tagTracks = cms.untracked.InputTag("diamondSampicLocalTracks"), + tagLocalTrack = cms.untracked.InputTag("totemRPLocalTrackFitter"), samplesForNoise = cms.untracked.uint32(6), diff --git a/DQM/CTPPS/python/elasticPlotDQMSource_cfi.py b/DQM/CTPPS/python/elasticPlotDQMSource_cfi.py index c9738f9d9f1f7..fe1cc853827ff 100644 --- a/DQM/CTPPS/python/elasticPlotDQMSource_cfi.py +++ b/DQM/CTPPS/python/elasticPlotDQMSource_cfi.py @@ -2,9 +2,9 @@ from DQMServices.Core.DQMEDAnalyzer import DQMEDAnalyzer elasticPlotDQMSource = DQMEDAnalyzer("ElasticPlotDQMSource", - tagRecHit = cms.InputTag("totemRPRecHitProducer"), - tagUVPattern = cms.InputTag("totemRPUVPatternFinder"), - tagLocalTrack = cms.InputTag("totemRPLocalTrackFitter"), + tagRecHit = cms.untracked.InputTag("totemRPRecHitProducer"), + tagUVPattern = cms.untracked.InputTag("totemRPUVPatternFinder"), + tagLocalTrack = cms.untracked.InputTag("totemRPLocalTrackFitter"), verbosity = cms.untracked.uint32(0), ) diff --git a/DQM/CTPPS/python/totemDAQTriggerDQMSource_cfi.py b/DQM/CTPPS/python/totemDAQTriggerDQMSource_cfi.py index 400123d0b5ae4..6ecdeac95446a 100644 --- a/DQM/CTPPS/python/totemDAQTriggerDQMSource_cfi.py +++ b/DQM/CTPPS/python/totemDAQTriggerDQMSource_cfi.py @@ -2,7 +2,7 @@ from DQMServices.Core.DQMEDAnalyzer import DQMEDAnalyzer totemDAQTriggerDQMSource = DQMEDAnalyzer('TotemDAQTriggerDQMSource', - tagFEDInfo = cms.InputTag("totemRPRawToDigi", "TrackingStrip"), + tagFEDInfo = cms.untracked.InputTag("totemRPRawToDigi", "TrackingStrip"), tagTriggerCounters = cms.InputTag("totemTriggerRawToDigi"), verbosity = cms.untracked.uint32(0) diff --git a/DQM/CTPPS/python/totemRPDQMSource_cfi.py b/DQM/CTPPS/python/totemRPDQMSource_cfi.py index 5cfed99ebd39a..6c8f352606209 100644 --- a/DQM/CTPPS/python/totemRPDQMSource_cfi.py +++ b/DQM/CTPPS/python/totemRPDQMSource_cfi.py @@ -3,11 +3,11 @@ from DQMServices.Core.DQMEDAnalyzer import DQMEDAnalyzer totemRPDQMSource = DQMEDAnalyzer('TotemRPDQMSource', tagStatus = cms.InputTag("totemRPRawToDigi", "TrackingStrip"), - tagDigi = cms.InputTag("totemRPRawToDigi", "TrackingStrip"), - tagCluster = cms.InputTag("totemRPClusterProducer"), - tagRecHit = cms.InputTag("totemRPRecHitProducer"), - tagUVPattern = cms.InputTag("totemRPUVPatternFinder"), - tagLocalTrack = cms.InputTag("totemRPLocalTrackFitter"), + tagDigi = cms.untracked.InputTag("totemRPRawToDigi", "TrackingStrip"), + tagCluster = cms.untracked.InputTag("totemRPClusterProducer"), + tagRecHit = cms.untracked.InputTag("totemRPRecHitProducer"), + tagUVPattern = cms.untracked.InputTag("totemRPUVPatternFinder"), + tagLocalTrack = cms.untracked.InputTag("totemRPLocalTrackFitter"), verbosity = cms.untracked.uint32(0), ) diff --git a/DQM/CTPPS/python/totemTimingDQMSource_cfi.py b/DQM/CTPPS/python/totemTimingDQMSource_cfi.py index cc6bc9876d62d..36b45215022bb 100644 --- a/DQM/CTPPS/python/totemTimingDQMSource_cfi.py +++ b/DQM/CTPPS/python/totemTimingDQMSource_cfi.py @@ -2,11 +2,11 @@ from DQMServices.Core.DQMEDAnalyzer import DQMEDAnalyzer totemTimingDQMSource = DQMEDAnalyzer('TotemTimingDQMSource', - tagDigi = cms.InputTag("totemTimingRawToDigi", "TotemTiming"), - tagFEDInfo = cms.InputTag("totemTimingRawToDigi", "TotemTiming"), - tagRecHits = cms.InputTag("totemTimingRecHits"), - # tagTracks = cms.InputTag("totemTimingLocalTracks"), - tagLocalTrack = cms.InputTag("totemRPLocalTrackFitter"), + tagDigi = cms.untracked.InputTag("totemTimingRawToDigi", "TotemTiming"), + tagFEDInfo = cms.untracked.InputTag("totemTimingRawToDigi", "TotemTiming"), + tagRecHits = cms.untracked.InputTag("totemTimingRecHits"), + # tagTracks = cms.untracked.InputTag("totemTimingLocalTracks"), + tagLocalTrack = cms.untracked.InputTag("totemRPLocalTrackFitter"), minimumStripAngleForTomography = cms.double(0), maximumStripAngleForTomography = cms.double(1), diff --git a/DQM/DTMonitorModule/python/dtChamberEfficiencyHI_cfi.py b/DQM/DTMonitorModule/python/dtChamberEfficiencyHI_cfi.py index bd59112785127..594dbf056ea7e 100644 --- a/DQM/DTMonitorModule/python/dtChamberEfficiencyHI_cfi.py +++ b/DQM/DTMonitorModule/python/dtChamberEfficiencyHI_cfi.py @@ -6,14 +6,14 @@ dtEfficiencyMonitor = DQMEDAnalyzer('DTChamberEfficiency', MuonServiceProxy, debug = cms.untracked.bool(True), - TrackCollection = cms.InputTag('standAloneMuons'), + TrackCollection = cms.untracked.InputTag('standAloneMuons'), theMaxChi2 = cms.double(1000.), theNSigma = cms.double(3.), theMinNrec = cms.double(5.), - dt4DSegments = cms.InputTag('dt4DSegments'), - theRPCRecHits = cms.InputTag('dummy'), + dt4DSegments = cms.untracked.InputTag('dt4DSegments'), + theRPCRecHits = cms.untracked.InputTag('dummy'), thegemRecHits = cms.InputTag('dummy'), - cscSegments = cms.InputTag('dummy'), + cscSegments = cms.untracked.InputTag('dummy'), RPCLayers = cms.bool(False), NavigationType = cms.string('Standard') ) diff --git a/DQM/DTMonitorModule/python/dtChamberEfficiencyTask_cfi.py b/DQM/DTMonitorModule/python/dtChamberEfficiencyTask_cfi.py index b807ceb1fbddc..9caa0e5d1e685 100644 --- a/DQM/DTMonitorModule/python/dtChamberEfficiencyTask_cfi.py +++ b/DQM/DTMonitorModule/python/dtChamberEfficiencyTask_cfi.py @@ -7,7 +7,7 @@ # parameter for check on extrapolated check minCloseDist = cms.double(20.0), # labels of 4D segments - recHits4DLabel = cms.string('dt4DSegments'), + recHits4DLabel = cms.untracked.string('dt4DSegments'), # switch for verbosity debug = cms.untracked.bool(False), minChi2NormSegment = cms.double(20.0), diff --git a/DQM/DTMonitorModule/python/dtChamberEfficiency_Cosmics_cfi.py b/DQM/DTMonitorModule/python/dtChamberEfficiency_Cosmics_cfi.py index 1b9cfe9a9da36..c5b06effd21f5 100644 --- a/DQM/DTMonitorModule/python/dtChamberEfficiency_Cosmics_cfi.py +++ b/DQM/DTMonitorModule/python/dtChamberEfficiency_Cosmics_cfi.py @@ -6,13 +6,13 @@ dtEfficiencyMonitor = DQMEDAnalyzer('DTChamberEfficiency', MuonServiceProxy, debug = cms.untracked.bool(True), - TrackCollection = cms.InputTag('cosmicMuons'), + TrackCollection = cms.untracked.InputTag('cosmicMuons'), theMaxChi2 = cms.double(100.), theNSigma = cms.double(3.), theMinNrec = cms.double(20.), - dt4DSegments = cms.InputTag('dt4DSegments'), - theRPCRecHits = cms.InputTag('dummy'), - cscSegments = cms.InputTag('dummy'), + dt4DSegments = cms.untracked.InputTag('dt4DSegments'), + theRPCRecHits = cms.untracked.InputTag('dummy'), + cscSegments = cms.untracked.InputTag('dummy'), RPCLayers = cms.bool(False), NavigationType = cms.string('Direct') ) diff --git a/DQM/DTMonitorModule/python/dtChamberEfficiency_cfi.py b/DQM/DTMonitorModule/python/dtChamberEfficiency_cfi.py index 29ad350c421f9..b1d645ac25beb 100644 --- a/DQM/DTMonitorModule/python/dtChamberEfficiency_cfi.py +++ b/DQM/DTMonitorModule/python/dtChamberEfficiency_cfi.py @@ -6,13 +6,13 @@ dtEfficiencyMonitor = DQMEDAnalyzer('DTChamberEfficiency', MuonServiceProxy, debug = cms.untracked.bool(True), - TrackCollection = cms.InputTag("standAloneMuons"), + TrackCollection = cms.untracked.InputTag("standAloneMuons"), theMaxChi2 = cms.double(1000.), theNSigma = cms.double(3.), theMinNrec = cms.double(3.), - dt4DSegments = cms.InputTag('dt4DSegments'), - theRPCRecHits = cms.InputTag('dummy'), - cscSegments = cms.InputTag('dummy'), + dt4DSegments = cms.untracked.InputTag('dt4DSegments'), + theRPCRecHits = cms.untracked.InputTag('dummy'), + cscSegments = cms.untracked.InputTag('dummy'), RPCLayers = cms.bool(False), NavigationType = cms.string('Standard') ) diff --git a/DQM/DTMonitorModule/python/dtDataIntegrityTask_cfi.py b/DQM/DTMonitorModule/python/dtDataIntegrityTask_cfi.py index 01df2fe2d2557..3ab5d402040dc 100644 --- a/DQM/DTMonitorModule/python/dtDataIntegrityTask_cfi.py +++ b/DQM/DTMonitorModule/python/dtDataIntegrityTask_cfi.py @@ -5,21 +5,21 @@ fedIntegrityFolder = cms.untracked.string('DT/FEDIntegrity'), nLinksForFatal = cms.untracked.int32(15), processingMode = cms.untracked.string('Online'), - dtFEDlabel = cms.InputTag('dtDataIntegrityUnpacker') + dtFEDlabel = cms.untracked.InputTag('dtDataIntegrityUnpacker') ) dtDataIntegrityTaskOffline = DQMEDAnalyzer('DTDataIntegrityROSOffline', getSCInfo = cms.untracked.bool(True), fedIntegrityFolder = cms.untracked.string('DT/FEDIntegrity'), - dtDDULabel = cms.InputTag('dtDataIntegrityUnpacker'), - dtROS25Label = cms.InputTag('dtDataIntegrityUnpacker'), + dtDDULabel = cms.untracked.InputTag('dtDataIntegrityUnpacker'), + dtROS25Label = cms.untracked.InputTag('dtDataIntegrityUnpacker'), ) dtDataIntegrityUrosOffline = DQMEDAnalyzer('DTDataIntegrityTask', fedIntegrityFolder = cms.untracked.string('DT/FEDIntegrity'), nLinksForFatal = cms.untracked.int32(15), processingMode = cms.untracked.string('Offline'), - dtFEDlabel = cms.InputTag('dtDataIntegrityUnpacker') + dtFEDlabel = cms.untracked.InputTag('dtDataIntegrityUnpacker') ) from Configuration.Eras.Modifier_run2_DT_2018_cff import run2_DT_2018 diff --git a/DQM/DTMonitorModule/python/dtDigiTask_TP_cfi.py b/DQM/DTMonitorModule/python/dtDigiTask_TP_cfi.py index 5fd19458de6d7..b55dd701201e6 100644 --- a/DQM/DTMonitorModule/python/dtDigiTask_TP_cfi.py +++ b/DQM/DTMonitorModule/python/dtDigiTask_TP_cfi.py @@ -11,7 +11,7 @@ # Value of the ttrig pedestal used when not reading from DB defaultTtrig = cms.int32(3450), # the label to retrieve the DT digis - dtDigiLabel = cms.InputTag('dtunpacker'), + dtDigiLabel = cms.untracked.InputTag('dtunpacker'), # check the noisy flag in the DB and use it checkNoisyChannels = cms.untracked.bool(True), # set static booking (all the detector) diff --git a/DQM/DTMonitorModule/python/dtDigiTask_cfi.py b/DQM/DTMonitorModule/python/dtDigiTask_cfi.py index 0bc0f551070c1..0a1e3f0e92238 100644 --- a/DQM/DTMonitorModule/python/dtDigiTask_cfi.py +++ b/DQM/DTMonitorModule/python/dtDigiTask_cfi.py @@ -11,7 +11,7 @@ # Value of the ttrig pedestal used when not reading from DB defaultTtrig = cms.int32(2700), # the label to retrieve the DT digis - dtDigiLabel = cms.InputTag('dtunpacker'), + dtDigiLabel = cms.untracked.InputTag('dtunpacker'), # check the noisy flag in the DB and use it checkNoisyChannels = cms.untracked.bool(True), # set static booking (all the detector) diff --git a/DQM/DTMonitorModule/python/dtEfficiencyTask_cfi.py b/DQM/DTMonitorModule/python/dtEfficiencyTask_cfi.py index 2435714a87f0b..ddb06afb5e3ef 100644 --- a/DQM/DTMonitorModule/python/dtEfficiencyTask_cfi.py +++ b/DQM/DTMonitorModule/python/dtEfficiencyTask_cfi.py @@ -5,8 +5,8 @@ # switch for verbosity debug = cms.untracked.bool(False), # labels of 4D and 1D hits - recHits4DLabel = cms.string('dt4DSegments'), - recHitLabel = cms.string('dt1DRecHits'), + recHits4DLabel = cms.untracked.string('dt4DSegments'), + recHitLabel = cms.untracked.string('dt1DRecHits'), # interval of lumi block after which we reset the histos ResetCycle = cms.untracked.int32(10000) ) diff --git a/DQM/DTMonitorModule/python/dtNoiseTask_cfi.py b/DQM/DTMonitorModule/python/dtNoiseTask_cfi.py index f51f2b0bc3409..804cf41b3adf2 100644 --- a/DQM/DTMonitorModule/python/dtNoiseTask_cfi.py +++ b/DQM/DTMonitorModule/python/dtNoiseTask_cfi.py @@ -4,11 +4,11 @@ from DQMServices.Core.DQMEDAnalyzer import DQMEDAnalyzer dtNoiseMonitor = DQMEDAnalyzer('DTNoiseTask', # the label to retrieve the DT digis - dtDigiLabel = cms.InputTag('dtunpacker'), + dtDigiLabel = cms.untracked.InputTag('dtunpacker'), # switch for time box booking doTbHistos = cms.untracked.bool(False), # the name of the 4D rec hits collection - recHits4DLabel = cms.string('dt4DSegments'), + recHits4DLabel = cms.untracked.string('dt4DSegments'), # switch for segment veto doSegmentVeto = cms.untracked.bool(False), # safe margin (ns) between ttrig and beginning of counting area diff --git a/DQM/DTMonitorModule/python/dtOccupancyEfficiency_cfi.py b/DQM/DTMonitorModule/python/dtOccupancyEfficiency_cfi.py index bab1e21734f1c..702defa65dfc1 100644 --- a/DQM/DTMonitorModule/python/dtOccupancyEfficiency_cfi.py +++ b/DQM/DTMonitorModule/python/dtOccupancyEfficiency_cfi.py @@ -5,10 +5,10 @@ # switch for verbosity debug = cms.untracked.bool(False), # label for dtDigis - digiLabel = cms.string('muonDTDigis'), + digiLabel = cms.untracked.string('muonDTDigis'), # labels of 4D and 1D hits - recHits4DLabel = cms.string('dt4DSegments'), - recHitLabel = cms.string('dt1DRecHits'), + recHits4DLabel = cms.untracked.string('dt4DSegments'), + recHitLabel = cms.untracked.string('dt1DRecHits'), ) diff --git a/DQM/DTMonitorModule/python/dtResolutionTask_cfi.py b/DQM/DTMonitorModule/python/dtResolutionTask_cfi.py index fb2bba585b40b..93c692b87442c 100644 --- a/DQM/DTMonitorModule/python/dtResolutionTask_cfi.py +++ b/DQM/DTMonitorModule/python/dtResolutionTask_cfi.py @@ -3,7 +3,7 @@ from DQMServices.Core.DQMEDAnalyzer import DQMEDAnalyzer dtResolutionAnalysisMonitor = DQMEDAnalyzer('DTResolutionAnalysisTask', # labels of 4D hits - recHits4DLabel = cms.string('dt4DSegments'), + recHits4DLabel = cms.untracked.string('dt4DSegments'), # interval of lumi block after which we reset the histos ResetCycle = cms.untracked.int32(10000), # cut on the hits of segments considered for resolution diff --git a/DQM/DTMonitorModule/python/dtResolutionTask_hlt_cfi.py b/DQM/DTMonitorModule/python/dtResolutionTask_hlt_cfi.py index 8eb689a398302..2a87a1958ce0c 100644 --- a/DQM/DTMonitorModule/python/dtResolutionTask_hlt_cfi.py +++ b/DQM/DTMonitorModule/python/dtResolutionTask_hlt_cfi.py @@ -3,7 +3,7 @@ from DQMServices.Core.DQMEDAnalyzer import DQMEDAnalyzer dtResolutionTaskHLT = DQMEDAnalyzer('DTResolutionAnalysisTask', # labels of 4D hits - recHits4DLabel = cms.string('hltDt4DSegments'), + recHits4DLabel = cms.untracked.string('hltDt4DSegments'), # interval of lumi block after which we reset the histos ResetCycle = cms.untracked.int32(10000), # top folder for the histograms in DQMStore diff --git a/DQM/DTMonitorModule/python/dtRunConditionVar_cfi.py b/DQM/DTMonitorModule/python/dtRunConditionVar_cfi.py index 766b8a36637b4..ab2ce12844b9b 100644 --- a/DQM/DTMonitorModule/python/dtRunConditionVar_cfi.py +++ b/DQM/DTMonitorModule/python/dtRunConditionVar_cfi.py @@ -5,7 +5,7 @@ debug = cms.untracked.bool(False), nMinHitsPhi = cms.untracked.int32(5), maxAnglePhiSegm = cms.untracked.double(30.), - recoSegments = cms.InputTag('dt4DSegments'), + recoSegments = cms.untracked.InputTag('dt4DSegments'), readLegacyVDriftDB =cms.bool(True), ) diff --git a/DQM/DTMonitorModule/python/dtSegmentTask_cfi.py b/DQM/DTMonitorModule/python/dtSegmentTask_cfi.py index 79a3cbdd533fa..947ebcd7f7b86 100644 --- a/DQM/DTMonitorModule/python/dtSegmentTask_cfi.py +++ b/DQM/DTMonitorModule/python/dtSegmentTask_cfi.py @@ -5,7 +5,7 @@ # switch for verbosity debug = cms.untracked.bool(False), # label of 4D segments - recHits4DLabel = cms.string('dt4DSegments'), + recHits4DLabel = cms.untracked.string('dt4DSegments'), # skip segments with noisy cells (reads from DB) checkNoisyChannels = cms.untracked.bool(True), # switch off uneeded histograms diff --git a/DQM/DTMonitorModule/python/dtSegmentTask_hlt_cfi.py b/DQM/DTMonitorModule/python/dtSegmentTask_hlt_cfi.py index a1317a2b8357c..94e673062cfdd 100644 --- a/DQM/DTMonitorModule/python/dtSegmentTask_hlt_cfi.py +++ b/DQM/DTMonitorModule/python/dtSegmentTask_hlt_cfi.py @@ -5,7 +5,7 @@ # switch for verbosity debug = cms.untracked.bool(False), # label of 4D segments - recHits4DLabel = cms.string('hltDt4DSegments'), + recHits4DLabel = cms.untracked.string('hltDt4DSegments'), # skip segments with noisy cells (reads from DB) checkNoisyChannels = cms.untracked.bool(True), # switch off uneeded histograms diff --git a/DQM/DTMonitorModule/python/dtTriggerSynchTask_cfi.py b/DQM/DTMonitorModule/python/dtTriggerSynchTask_cfi.py index 31732f999d129..c7e6f4607997b 100644 --- a/DQM/DTMonitorModule/python/dtTriggerSynchTask_cfi.py +++ b/DQM/DTMonitorModule/python/dtTriggerSynchTask_cfi.py @@ -4,8 +4,8 @@ dtTriggerSynchMonitor = DQMEDAnalyzer('DTLocalTriggerSynchTask', staticBooking = cms.untracked.bool(True), # labels of TM data and 4D segments - TMInputTag = cms.InputTag('dttfDigis'), - SEGInputTag = cms.InputTag('dt4DSegments'), + TMInputTag = cms.untracked.InputTag('dttfDigis'), + SEGInputTag = cms.untracked.InputTag('dt4DSegments'), bxTimeInterval = cms.double(25), rangeWithinBX = cms.bool(True), nBXHigh = cms.int32(0), diff --git a/DQM/DTMonitorModule/src/DTChamberEfficiency.cc b/DQM/DTMonitorModule/src/DTChamberEfficiency.cc index 3f84739a97738..58c910eee7a8f 100644 --- a/DQM/DTMonitorModule/src/DTChamberEfficiency.cc +++ b/DQM/DTMonitorModule/src/DTChamberEfficiency.cc @@ -56,17 +56,17 @@ DTChamberEfficiency::DTChamberEfficiency(const ParameterSet& pSet) { ParameterSet serviceParameters = pSet.getParameter("ServiceParameters"); theService = new MuonServiceProxy(serviceParameters, consumesCollector()); - theTracksLabel_ = pSet.getParameter("TrackCollection"); + theTracksLabel_ = pSet.getUntrackedParameter("TrackCollection"); theTracksToken_ = consumes(theTracksLabel_); theMaxChi2 = static_cast(pSet.getParameter("theMaxChi2")); theNSigma = pSet.getParameter("theNSigma"); theMinNrec = static_cast(pSet.getParameter("theMinNrec")); - labelRPCRecHits = pSet.getParameter("theRPCRecHits"); + labelRPCRecHits = pSet.getUntrackedParameter("theRPCRecHits"); - thedt4DSegments = pSet.getParameter("dt4DSegments"); - thecscSegments = pSet.getParameter("cscSegments"); + thedt4DSegments = pSet.getUntrackedParameter("dt4DSegments"); + thecscSegments = pSet.getUntrackedParameter("cscSegments"); edm::ConsumesCollector iC = consumesCollector(); diff --git a/DQM/DTMonitorModule/src/DTChamberEfficiencyTask.cc b/DQM/DTMonitorModule/src/DTChamberEfficiencyTask.cc index dcfce017b775b..38740f51224e6 100644 --- a/DQM/DTMonitorModule/src/DTChamberEfficiencyTask.cc +++ b/DQM/DTMonitorModule/src/DTChamberEfficiencyTask.cc @@ -30,7 +30,7 @@ DTChamberEfficiencyTask::DTChamberEfficiencyTask(const ParameterSet& pset) // the name of the 4D rec hits collection recHits4DToken_ = - consumes(edm::InputTag(parameters.getParameter("recHits4DLabel"))); + consumes(edm::InputTag(parameters.getUntrackedParameter("recHits4DLabel"))); // parameters to use for the segment quality check theMinHitsSegment = static_cast(parameters.getParameter("minHitsSegment")); diff --git a/DQM/DTMonitorModule/src/DTDataIntegrityROSOffline.cc b/DQM/DTMonitorModule/src/DTDataIntegrityROSOffline.cc index adffdf25eeade..cd5e7f3d0ef26 100644 --- a/DQM/DTMonitorModule/src/DTDataIntegrityROSOffline.cc +++ b/DQM/DTMonitorModule/src/DTDataIntegrityROSOffline.cc @@ -30,8 +30,8 @@ DTDataIntegrityROSOffline::DTDataIntegrityROSOffline(const edm::ParameterSet& ps LogTrace("DTRawToDigi|DTDQM|DTMonitorModule|DTDataIntegrityROSOffline") << "[DTDataIntegrityROSOffline]: Constructor" << endl; - dduToken = consumes(ps.getParameter("dtDDULabel")); - ros25Token = consumes(ps.getParameter("dtROS25Label")); + dduToken = consumes(ps.getUntrackedParameter("dtDDULabel")); + ros25Token = consumes(ps.getUntrackedParameter("dtROS25Label")); FEDIDmin = FEDNumbering::MINDTFEDID; FEDIDmax = FEDNumbering::MAXDTFEDID; diff --git a/DQM/DTMonitorModule/src/DTDataIntegrityTask.cc b/DQM/DTMonitorModule/src/DTDataIntegrityTask.cc index f061de8c4d587..707f064b6802f 100644 --- a/DQM/DTMonitorModule/src/DTDataIntegrityTask.cc +++ b/DQM/DTMonitorModule/src/DTDataIntegrityTask.cc @@ -33,7 +33,7 @@ using namespace edm; DTDataIntegrityTask::DTDataIntegrityTask(const edm::ParameterSet& ps) : nevents(0) { LogTrace("DTRawToDigi|DTDQM|DTMonitorModule|DTDataIntegrityTask") << "[DTDataIntegrityTask]: Constructor" << endl; - fedToken = consumes(ps.getParameter("dtFEDlabel")); + fedToken = consumes(ps.getUntrackedParameter("dtFEDlabel")); FEDIDmin = FEDNumbering::MINDTUROSFEDID; FEDIDmax = FEDNumbering::MAXDTUROSFEDID; diff --git a/DQM/DTMonitorModule/src/DTDigiTask.cc b/DQM/DTMonitorModule/src/DTDigiTask.cc index 500b74536542b..ea7d54bfc65a0 100644 --- a/DQM/DTMonitorModule/src/DTDigiTask.cc +++ b/DQM/DTMonitorModule/src/DTDigiTask.cc @@ -40,7 +40,7 @@ DTDigiTask::DTDigiTask(const edm::ParameterSet& ps) LogTrace("DTDQM|DTMonitorModule|DTDigiTask") << "[DTDigiTask]: Constructor" << endl; // The label to retrieve the digis - dtDigiToken_ = consumes(ps.getParameter("dtDigiLabel")); + dtDigiToken_ = consumes(ps.getUntrackedParameter("dtDigiLabel")); // Read the configuration parameters maxTDCHits = ps.getUntrackedParameter("maxTDCHitsPerChamber", 30000); // Set to true to read the ttrig from DB (useful to determine in-time and out-of-time hits) @@ -55,7 +55,8 @@ DTDigiTask::DTDigiTask(const edm::ParameterSet& ps) // Switch for local/global runs isLocalRun = ps.getUntrackedParameter("localrun", true); if (!isLocalRun) { - ltcDigiCollectionToken_ = consumes(ps.getParameter("ltcDigiCollectionTag")); + ltcDigiCollectionToken_ = + consumes(ps.getUntrackedParameter("ltcDigiCollectionTag")); } // Setting for the reset of the ME after n (= ResetCycle) luminosity sections diff --git a/DQM/DTMonitorModule/src/DTEfficiencyTask.cc b/DQM/DTMonitorModule/src/DTEfficiencyTask.cc index 0e4c1cd99e891..26d07a1ef72f0 100644 --- a/DQM/DTMonitorModule/src/DTEfficiencyTask.cc +++ b/DQM/DTMonitorModule/src/DTEfficiencyTask.cc @@ -34,9 +34,10 @@ DTEfficiencyTask::DTEfficiencyTask(const ParameterSet& pset) : muonGeomToken_(esConsumes()), dtGeomToken_(esConsumes()) { debug = pset.getUntrackedParameter("debug", false); // the name of the 4D rec hits collection - recHits4DToken_ = consumes(edm::InputTag(pset.getParameter("recHits4DLabel"))); + recHits4DToken_ = + consumes(edm::InputTag(pset.getUntrackedParameter("recHits4DLabel"))); // the name of the rechits collection - recHitToken_ = consumes(edm::InputTag(pset.getParameter("recHitLabel"))); + recHitToken_ = consumes(edm::InputTag(pset.getUntrackedParameter("recHitLabel"))); parameters = pset; } diff --git a/DQM/DTMonitorModule/src/DTLocalTriggerSynchTask.cc b/DQM/DTMonitorModule/src/DTLocalTriggerSynchTask.cc index d87827426097f..fd5b7448b880b 100644 --- a/DQM/DTMonitorModule/src/DTLocalTriggerSynchTask.cc +++ b/DQM/DTMonitorModule/src/DTLocalTriggerSynchTask.cc @@ -45,8 +45,8 @@ DTLocalTriggerSynchTask::DTLocalTriggerSynchTask(const edm::ParameterSet& ps) consumesCollector())}, muonGeomToken_(esConsumes()) { edm::LogVerbatim("DTLocalTriggerSynchTask") << "[DTLocalTriggerSynchTask]: Constructor" << endl; - tm_Token_ = consumes(ps.getParameter("TMInputTag")); - seg_Token_ = consumes(ps.getParameter("SEGInputTag")); + tm_Token_ = consumes(ps.getUntrackedParameter("TMInputTag")); + seg_Token_ = consumes(ps.getUntrackedParameter("SEGInputTag")); bxTime = ps.getParameter("bxTimeInterval"); // CB move this to static const or DB rangeInBX = ps.getParameter("rangeWithinBX"); diff --git a/DQM/DTMonitorModule/src/DTNoiseTask.cc b/DQM/DTMonitorModule/src/DTNoiseTask.cc index 27b25b71fbfe1..9a466569f9715 100644 --- a/DQM/DTMonitorModule/src/DTNoiseTask.cc +++ b/DQM/DTMonitorModule/src/DTNoiseTask.cc @@ -44,10 +44,11 @@ DTNoiseTask::DTNoiseTask(const ParameterSet& ps) doTimeBoxHistos = ps.getUntrackedParameter("doTbHistos", false); // The label to retrieve the digis - dtDigiToken_ = consumes(ps.getParameter("dtDigiLabel")); + dtDigiToken_ = consumes(ps.getUntrackedParameter("dtDigiLabel")); // the name of the 4D rec hits collection - recHits4DToken_ = consumes(edm::InputTag(ps.getParameter("recHits4DLabel"))); + recHits4DToken_ = + consumes(edm::InputTag(ps.getUntrackedParameter("recHits4DLabel"))); // switch for segment veto doSegmentVeto = ps.getUntrackedParameter("doSegmentVeto", false); diff --git a/DQM/DTMonitorModule/src/DTOccupancyEfficiency.cc b/DQM/DTMonitorModule/src/DTOccupancyEfficiency.cc index 8f27378ced056..8658c22d34300 100644 --- a/DQM/DTMonitorModule/src/DTOccupancyEfficiency.cc +++ b/DQM/DTMonitorModule/src/DTOccupancyEfficiency.cc @@ -22,11 +22,12 @@ using namespace std; DTOccupancyEfficiency::DTOccupancyEfficiency(const ParameterSet& pset) { debug = pset.getUntrackedParameter("debug", false); // label for dtDigis - dtDigiToken_ = consumes(edm::InputTag(pset.getParameter("digiLabel"))); + dtDigiToken_ = consumes(edm::InputTag(pset.getUntrackedParameter("digiLabel"))); // the name of the 4D rec hits collection - recHits4DToken_ = consumes(edm::InputTag(pset.getParameter("recHits4DLabel"))); + recHits4DToken_ = + consumes(edm::InputTag(pset.getUntrackedParameter("recHits4DLabel"))); // the name of the rechits collection - recHitToken_ = consumes(edm::InputTag(pset.getParameter("recHitLabel"))); + recHitToken_ = consumes(edm::InputTag(pset.getUntrackedParameter("recHitLabel"))); parameters = pset; } diff --git a/DQM/DTMonitorModule/src/DTResolutionAnalysisTask.cc b/DQM/DTMonitorModule/src/DTResolutionAnalysisTask.cc index c77596ec765e2..5034e3f366728 100644 --- a/DQM/DTMonitorModule/src/DTResolutionAnalysisTask.cc +++ b/DQM/DTMonitorModule/src/DTResolutionAnalysisTask.cc @@ -35,7 +35,8 @@ DTResolutionAnalysisTask::DTResolutionAnalysisTask(const ParameterSet& pset) << "[DTResolutionAnalysisTask] Constructor called!" << endl; // the name of the 4D rec hits collection - recHits4DToken_ = consumes(edm::InputTag(pset.getParameter("recHits4DLabel"))); + recHits4DToken_ = + consumes(edm::InputTag(pset.getUntrackedParameter("recHits4DLabel"))); prescaleFactor = pset.getUntrackedParameter("diagnosticPrescale", 1); resetCycle = pset.getUntrackedParameter("ResetCycle", -1); diff --git a/DQM/DTMonitorModule/src/DTRunConditionVar.cc b/DQM/DTMonitorModule/src/DTRunConditionVar.cc index 163ff0e8e085c..1c86dfceff3bf 100644 --- a/DQM/DTMonitorModule/src/DTRunConditionVar.cc +++ b/DQM/DTMonitorModule/src/DTRunConditionVar.cc @@ -44,7 +44,7 @@ DTRunConditionVar::DTRunConditionVar(const ParameterSet& pSet) debug(pSet.getUntrackedParameter("debug", false)), nMinHitsPhi(pSet.getUntrackedParameter("nMinHitsPhi")), maxAnglePhiSegm(pSet.getUntrackedParameter("maxAnglePhiSegm")), - dt4DSegmentsToken_(consumes(pSet.getParameter("recoSegments"))), + dt4DSegmentsToken_(consumes(pSet.getUntrackedParameter("recoSegments"))), muonGeomToken_(esConsumes()), readLegacyVDriftDB(pSet.getParameter("readLegacyVDriftDB")) { if (readLegacyVDriftDB) { diff --git a/DQM/DTMonitorModule/src/DTSegmentAnalysisTask.cc b/DQM/DTMonitorModule/src/DTSegmentAnalysisTask.cc index 1eab7fa4cee2f..0394a52cafe8e 100644 --- a/DQM/DTMonitorModule/src/DTSegmentAnalysisTask.cc +++ b/DQM/DTMonitorModule/src/DTSegmentAnalysisTask.cc @@ -37,7 +37,8 @@ DTSegmentAnalysisTask::DTSegmentAnalysisTask(const edm::ParameterSet& pset) // switch for detailed analysis detailedAnalysis = pset.getUntrackedParameter("detailedAnalysis", false); // the name of the 4D rec hits collection - recHits4DToken_ = consumes(edm::InputTag(pset.getParameter("recHits4DLabel"))); + recHits4DToken_ = + consumes(edm::InputTag(pset.getUntrackedParameter("recHits4DLabel"))); // Get the map of noisy channels checkNoisyChannels = pset.getUntrackedParameter("checkNoisyChannels", false); phiSegmCut = pset.getUntrackedParameter("phiSegmCut", 30.); diff --git a/DQM/L1TMonitor/plugins/L1TStage2CPPF.cc b/DQM/L1TMonitor/plugins/L1TStage2CPPF.cc new file mode 100644 index 0000000000000..21b6b71cf5c77 --- /dev/null +++ b/DQM/L1TMonitor/plugins/L1TStage2CPPF.cc @@ -0,0 +1,163 @@ +#include +#include + +#include "FWCore/MessageLogger/interface/MessageLogger.h" +#include "FWCore/Framework/interface/Event.h" +#include "FWCore/ParameterSet/interface/ParameterSet.h" + +#include "DQMServices/Core/interface/MonitorElement.h" +#include "DQMServices/Core/interface/DQMEDAnalyzer.h" +#include "FWCore/Framework/interface/MakerMacros.h" + +#include "Geometry/RPCGeometry/interface/RPCRoll.h" +#include "Geometry/RPCGeometry/interface/RPCGeometry.h" +#include "Geometry/Records/interface/MuonGeometryRecord.h" +#include "DataFormats/L1TMuon/interface/CPPFDigi.h" + +// class decleration + +class L1TStage2CPPF : public DQMEDAnalyzer { +public: + // class constructor + L1TStage2CPPF(const edm::ParameterSet& ps); + // class destructor + ~L1TStage2CPPF() override; + + // member functions + edm::ESHandle rpcGeom; + +protected: + void analyze(const edm::Event&, const edm::EventSetup&) override; + void bookHistograms(DQMStore::IBooker&, const edm::Run&, const edm::EventSetup&) override; + + // data members +private: + std::string monitorDir; + bool verbose; + float global_phi; + const edm::EDGetTokenT cppfDigiToken_; + int EMTF_sector; + int EMTF_subsector; + int EMTF_bx; + + std::vector EMTFsector1bins; + std::vector EMTFsector2bins; + std::vector EMTFsector3bins; + std::vector EMTFsector4bins; + std::vector EMTFsector5bins; + std::vector EMTFsector6bins; + + std::map> fill_info; + + MonitorElement* Occupancy_EMTFSector; + MonitorElement* Track_Bx; +}; + +L1TStage2CPPF::L1TStage2CPPF(const edm::ParameterSet& ps) + : monitorDir(ps.getUntrackedParameter("monitorDir", "")), + verbose(ps.getUntrackedParameter("verbose", false)), + global_phi(-1000), + cppfDigiToken_(consumes(ps.getParameter("cppfSource"))) {} + +L1TStage2CPPF::~L1TStage2CPPF() {} + +void L1TStage2CPPF::bookHistograms(DQMStore::IBooker& ibooker, const edm::Run& iRun, const edm::EventSetup& eveSetup) { + ibooker.setCurrentFolder(monitorDir); + + Occupancy_EMTFSector = ibooker.book2D("Occupancy_EMTFSector", "Occupancy_EMTFSector", 36, 1., 37., 12, 1., 13.); + Track_Bx = ibooker.book2D("Track_Bx", "Track_Bx", 12, 1., 13., 7, -3., 4.); +} + +void L1TStage2CPPF::analyze(const edm::Event& eve, const edm::EventSetup& eveSetup) { + if (verbose) { + edm::LogInfo("L1TStage2CPPF") << "L1TStage2CPPF: analyze...."; + } + + edm::Handle CppfDigis; + eve.getByToken(cppfDigiToken_, CppfDigis); + + //Fill the specific bin for each EMTF sector + EMTFsector1bins.clear(); + EMTFsector2bins.clear(); + EMTFsector3bins.clear(); + EMTFsector4bins.clear(); + EMTFsector5bins.clear(); + EMTFsector6bins.clear(); + for (int i = 1; i < 7; i++) { + EMTFsector1bins.push_back(i); + EMTFsector2bins.push_back(i + 6); + EMTFsector3bins.push_back(i + 12); + EMTFsector4bins.push_back(i + 18); + EMTFsector5bins.push_back(i + 24); + EMTFsector6bins.push_back(i + 30); + } + //FIll the map for each EMTF sector + fill_info[1] = EMTFsector1bins; + fill_info[2] = EMTFsector2bins; + fill_info[3] = EMTFsector3bins; + fill_info[4] = EMTFsector4bins; + fill_info[5] = EMTFsector5bins; + fill_info[6] = EMTFsector6bins; + + for (auto& cppf_digis : *CppfDigis) { + RPCDetId rpcId = cppf_digis.rpcId(); + int ring = rpcId.ring(); + int station = rpcId.station(); + int region = rpcId.region(); + int subsector = rpcId.subsector(); + + //Region - + if (region == -1) { + //for Occupancy + EMTF_sector = rpcId.sector(); + EMTF_subsector = fill_info[EMTF_sector][subsector - 1]; + + if ((station == 4) && (ring == 3)) { + Occupancy_EMTFSector->Fill(EMTF_subsector, 1); + } else if ((station == 4) && (ring == 2)) { + Occupancy_EMTFSector->Fill(EMTF_subsector, 2); + } else if ((station == 3) && (ring == 3)) { + Occupancy_EMTFSector->Fill(EMTF_subsector, 3); + } else if ((station == 3) && (ring == 2)) { + Occupancy_EMTFSector->Fill(EMTF_subsector, 4); + } else if ((station == 2) && (ring == 2)) { + Occupancy_EMTFSector->Fill(EMTF_subsector, 5); + } else if ((station == 1) && (ring == 2)) { + Occupancy_EMTFSector->Fill(EMTF_subsector, 6); + } + + //for Track_Bx + if (EMTF_sector >= 1 && EMTF_sector <= 6) { + EMTF_bx = cppf_digis.bx(); + Track_Bx->Fill(7 - EMTF_sector, EMTF_bx); + } + } + //Region + + if (region == 1) { + //for Occupancy + EMTF_sector = rpcId.sector(); + EMTF_subsector = fill_info[EMTF_sector][subsector - 1]; + + if ((station == 1) && (ring == 2)) { + Occupancy_EMTFSector->Fill(EMTF_subsector, 7); + } else if ((station == 2) && (ring == 2)) { + Occupancy_EMTFSector->Fill(EMTF_subsector, 8); + } else if ((station == 3) && (ring == 2)) { + Occupancy_EMTFSector->Fill(EMTF_subsector, 9); + } else if ((station == 3) && (ring == 3)) { + Occupancy_EMTFSector->Fill(EMTF_subsector, 10); + } else if ((station == 4) && (ring == 2)) { + Occupancy_EMTFSector->Fill(EMTF_subsector, 11); + } else if ((station == 4) && (ring == 3)) { + Occupancy_EMTFSector->Fill(EMTF_subsector, 12); + } + + //for Track_Bx + if (EMTF_sector >= 1 && EMTF_sector <= 6) { + EMTF_bx = cppf_digis.bx(); + Track_Bx->Fill(6 + EMTF_sector, EMTF_bx); + } + } + } //loop over CPPFDigis +} +DEFINE_FWK_MODULE(L1TStage2CPPF); diff --git a/DQM/L1TMonitor/plugins/L1TdeStage2CPPF.cc b/DQM/L1TMonitor/plugins/L1TdeStage2CPPF.cc new file mode 100644 index 0000000000000..3c61fa4994c7f --- /dev/null +++ b/DQM/L1TMonitor/plugins/L1TdeStage2CPPF.cc @@ -0,0 +1,515 @@ +#include "FWCore/Framework/interface/Event.h" +#include "FWCore/MessageLogger/interface/MessageLogger.h" +#include "FWCore/ParameterSet/interface/ParameterSet.h" + +#include "Geometry/RPCGeometry/interface/RPCRoll.h" +#include "Geometry/RPCGeometry/interface/RPCGeometry.h" +#include "Geometry/Records/interface/MuonGeometryRecord.h" + +#include "DQMServices/Core/interface/DQMEDAnalyzer.h" +#include "DQMServices/Core/interface/MonitorElement.h" + +#include "DataFormats/L1TMuon/interface/CPPFDigi.h" +#include + +class L1TdeStage2CPPF : public DQMEDAnalyzer { +public: + L1TdeStage2CPPF(const edm::ParameterSet& ps); + ~L1TdeStage2CPPF() override; + +protected: + void bookHistograms(DQMStore::IBooker&, const edm::Run&, const edm::EventSetup&) override; + void analyze(const edm::Event&, const edm::EventSetup&) override; + +private: + int occupancy_value(int region_, int station_, int ring_); + int bx_value(int region_, int emtfsector_); + int GetSubsector(int emtfsector_, int lsubsector_); + + edm::EDGetTokenT dataToken; + edm::EDGetTokenT emulToken; + std::string monitorDir; + bool verbose; + + MonitorElement* h2_Matching_SameKey_OnPhi_phi_Ce_phi_Cu_bx; + MonitorElement* h2_Matching_SameKey_OnPhi_theta_Ce_theta_Cu_bx; + MonitorElement* h2_Matching_SameKey_OnPhi_zone_Ce_zone_Cu_bx; + MonitorElement* h2_Matching_SameKey_OnPhi_ID_Ce_ID_Cu_bx; + MonitorElement* h2_Matching_SameKey_OnPhi_ID_Ce_roll_Ce_bx; + + MonitorElement* h2_Matching_SameKey_OffPhi_phi_Ce_phi_Cu_bx; + MonitorElement* h2_Matching_SameKey_OffPhi_theta_Ce_theta_Cu_bx; + MonitorElement* h2_Matching_SameKey_OffPhi_zone_Ce_zone_Cu_bx; + MonitorElement* h2_Matching_SameKey_OffPhi_ID_Ce_ID_Cu_bx; + MonitorElement* h2_Matching_SameKey_OffPhi_ID_Ce_roll_Ce_bx; + + MonitorElement* h2_Matching_SameKey_OnTheta_phi_Ce_phi_Cu_bx; + MonitorElement* h2_Matching_SameKey_OnTheta_theta_Ce_theta_Cu_bx; + MonitorElement* h2_Matching_SameKey_OnTheta_zone_Ce_zone_Cu_bx; + + MonitorElement* h2_Matching_SameKey_OffTheta_phi_Ce_phi_Cu_bx; + MonitorElement* h2_Matching_SameKey_OffTheta_theta_Ce_theta_Cu_bx; + MonitorElement* h2_Matching_SameKey_OffTheta_zone_Ce_zone_Cu_bx; + + MonitorElement* h1_Matching_SameKey_bx_Summary; +}; + +L1TdeStage2CPPF::L1TdeStage2CPPF(const edm::ParameterSet& ps) + : dataToken(consumes(ps.getParameter("dataSource"))), + emulToken(consumes(ps.getParameter("emulSource"))), + monitorDir(ps.getUntrackedParameter("monitorDir", "")), + verbose(ps.getUntrackedParameter("verbose", false)) {} + +L1TdeStage2CPPF::~L1TdeStage2CPPF() {} + +void L1TdeStage2CPPF::bookHistograms(DQMStore::IBooker& ibooker, const edm::Run&, const edm::EventSetup&) { + ibooker.setCurrentFolder(monitorDir); + + h2_Matching_SameKey_OnPhi_phi_Ce_phi_Cu_bx = + ibooker.book2D("h2_Matching_SameKey_OnPhi_phi_Ce_phi_Cu_bx", + "Matching && Same SubSector && OnPhi ; Emulator #phi ; Unpacker #phi", + 62, + 0.0, + 1240., + 62, + 0.0, + 1240.); + h2_Matching_SameKey_OnPhi_theta_Ce_theta_Cu_bx = + ibooker.book2D("h2_Matching_SameKey_OnPhi_theta_Ce_theta_Cu_bx", + "Matching && Same SubSector && bx==0 && OnPhi ; Emulator #theta ; Unpacker #theta ", + 32, + 0, + 32., + 32, + 0, + 32.); + h2_Matching_SameKey_OnPhi_zone_Ce_zone_Cu_bx = + ibooker.book2D("h2_Matching_SameKey_OnPhi_zone_Ce_zone_Cu_bx", + "Matching && Same SubSector && bx==0 && OnPhi ;Emulator Zone ;Unpacker Zone ", + 15, + 0, + 15, + 15, + 0, + 15); + h2_Matching_SameKey_OnPhi_ID_Ce_ID_Cu_bx = + ibooker.book2D("h2_Matching_SameKey_OnPhi_ID_Ce_ID_Cu_bx", + "Matching && Same SubSector && bx==0 && OnPhi ; Emulator Chamber ID;Unpacker Chamber ID ", + 38, + 0, + 38, + 38, + 0, + 38); + h2_Matching_SameKey_OnPhi_ID_Ce_roll_Ce_bx = + ibooker.book2D("h2_Matching_SameKey_OnPhi_ID_Ce_roll_Ce_bx", + "Matching && Same SubSector && bx==0 && OnPhi ;Emulator Chamber ID ;Emulator Roll ", + 38, + 0, + 38, + 4, + 0, + 4); + + h2_Matching_SameKey_OffPhi_phi_Ce_phi_Cu_bx = + ibooker.book2D("h2_Matching_SameKey_OffPhi_phi_Ce_phi_Cu_bx", + "Matching && Same SubSector && OffPhi ; Emulator #phi ; Unpacker #phi", + 62, + 0.0, + 1240., + 62, + 0.0, + 1240.); + h2_Matching_SameKey_OffPhi_theta_Ce_theta_Cu_bx = + ibooker.book2D("h2_Matching_SameKey_OffPhi_theta_Ce_theta_Cu_bx", + "Matching && Same SubSector && bx==0 && OffPhi ; Emulator #theta ; Unpacker #theta ", + 32, + 0, + 32., + 32, + 0, + 32.); + h2_Matching_SameKey_OffPhi_zone_Ce_zone_Cu_bx = + ibooker.book2D("h2_Matching_SameKey_OffPhi_zone_Ce_zone_Cu_bx", + "Matching && Same SubSector && bx==0 && OffPhi ;Emulator Zone ;Unpacker Zone ", + 15, + 0, + 15, + 15, + 0, + 15); + h2_Matching_SameKey_OffPhi_ID_Ce_ID_Cu_bx = + ibooker.book2D("h2_Matching_SameKey_OffPhi_ID_Ce_ID_Cu_bx", + "Matching && Same SubSector && bx==0 && OffPhi ; Emulator Chamber ID;Unpacker Chamber ID ", + 38, + 0, + 38, + 38, + 0, + 38); + h2_Matching_SameKey_OffPhi_ID_Ce_roll_Ce_bx = + ibooker.book2D("h2_Matching_SameKey_OffPhi_ID_Ce_roll_Ce_bx", + "Matching && Same SubSector && bx==0 && OffPhi ;Emulator Chamber ID ;Emulator Roll ", + 38, + 0, + 38, + 4, + 0, + 4); + + h2_Matching_SameKey_OnTheta_phi_Ce_phi_Cu_bx = + ibooker.book2D("h2_Matching_SameKey_OnTheta_phi_Ce_phi_Cu_bx", + "Matching && Same SubSector && OnTheta ; Emulator #phi ; Unpacker #phi", + 62, + 0.0, + 1240., + 62, + 0.0, + 1240.); + h2_Matching_SameKey_OnTheta_theta_Ce_theta_Cu_bx = + ibooker.book2D("h2_Matching_SameKey_OnTheta_theta_Ce_theta_Cu_bx", + "Matching && Same SubSector && bx==0 && OnTheta ; Emulator #theta ; Unpacker #theta ", + 32, + 0, + 32., + 32, + 0, + 32.); + h2_Matching_SameKey_OnTheta_zone_Ce_zone_Cu_bx = + ibooker.book2D("h2_Matching_SameKey_OnTheta_zone_Ce_zone_Cu_bx", + "Matching && Same SubSector && bx==0 && OnTheta ;Emulator Zone ;Unpacker Zone ", + 15, + 0, + 15, + 15, + 0, + 15); + + h2_Matching_SameKey_OffTheta_phi_Ce_phi_Cu_bx = + ibooker.book2D("h2_Matching_SameKey_OffTheta_phi_Ce_phi_Cu_bx", + "Matching && Same SubSector && OffTheta ; Emulator #phi ; Unpacker #phi", + 62, + 0.0, + 1240., + 62, + 0.0, + 1240.); + h2_Matching_SameKey_OffTheta_theta_Ce_theta_Cu_bx = + ibooker.book2D("h2_Matching_SameKey_OffTheta_theta_Ce_theta_Cu_bx", + "Matching && Same SubSector && bx==0 && OffTheta ; Emulator #theta ; Unpacker #theta ", + 32, + 0, + 32., + 32, + 0, + 32.); + h2_Matching_SameKey_OffTheta_zone_Ce_zone_Cu_bx = + ibooker.book2D("h2_Matching_SameKey_OffTheta_zone_Ce_zone_Cu_bx", + "Matching && Same SubSector && bx==0 && OffTheta ;Emulator Zone ;Unpacker Zone ", + 15, + 0, + 15, + 15, + 0, + 15); + + h1_Matching_SameKey_bx_Summary = + ibooker.book1D("h1_Matching_SameKey_bx_Summary", + "cppf data-emul mismatch fraction summary; ; Fraction events with mismatch", + 2, + 1, + 3); + h1_Matching_SameKey_bx_Summary->setBinLabel(1, "off/on-phi"); + h1_Matching_SameKey_bx_Summary->setBinLabel(2, "off/on-theta"); + h1_Matching_SameKey_bx_Summary->setAxisRange(0, 0.01, 2); +} + +void L1TdeStage2CPPF::analyze(const edm::Event& e, const edm::EventSetup& c) { + if (verbose) + edm::LogInfo("L1TdeStage2CPPF") << "L1TdeStage2CPPF: analyze..."; + + edm::Handle dataCPPFs; + e.getByToken(dataToken, dataCPPFs); + + edm::Handle emulCPPFs; + e.getByToken(emulToken, emulCPPFs); + + std::unordered_map _nHit_Ce; + std::unordered_map _nHit_Cu; + std::unordered_map> _phi_Ce; + std::unordered_map> _phi_Cu; + std::unordered_map> _phi_glob_Ce; + std::unordered_map> _phi_glob_Cu; + std::unordered_map> _theta_Ce; + std::unordered_map> _theta_Cu; + std::unordered_map> _theta_glob_Ce; + std::unordered_map> _theta_glob_Cu; + std::unordered_map> _roll_Ce; + std::unordered_map> _roll_Cu; + std::unordered_map> _zone_Ce; + std::unordered_map> _zone_Cu; + std::unordered_map> _ID_Ce; + std::unordered_map> _ID_Cu; + std::unordered_map> _emtfSubsector_Ce; + std::unordered_map> _emtfSubsector_Cu; + std::unordered_map> _emtfSector_Ce; + std::unordered_map> _emtfSector_Cu; + std::unordered_map> _bx_Ce; + std::unordered_map> _bx_Cu; + std::unordered_map> _cluster_size_Ce; + std::unordered_map> _cluster_size_Cu; + + for (auto& cppf_digis : *emulCPPFs) { + RPCDetId rpcIdCe = (int)cppf_digis.rpcId(); + int regionCe = (int)rpcIdCe.region(); + int stationCe = (int)rpcIdCe.station(); + int sectorCe = (int)rpcIdCe.sector(); + int subsectorCe = (int)rpcIdCe.subsector(); + int ringCe = (int)rpcIdCe.ring(); + int rollCe = (int)(rpcIdCe.roll()); + int phiIntCe = (int)cppf_digis.phi_int(); + int thetaIntCe = (int)cppf_digis.theta_int(); + int phiGlobalCe = (int)cppf_digis.phi_glob(); + int thetaGlobalCe = (int)cppf_digis.theta_glob(); + int cluster_sizeCe = (int)cppf_digis.cluster_size(); + int bxCe = cppf_digis.bx(); + int emtfSectorCe = (int)cppf_digis.emtf_sector(); + int emtfSubsectorCe = GetSubsector(emtfSectorCe, subsectorCe); + int fillOccupancyCe = occupancy_value(regionCe, stationCe, ringCe); + + int nsubCe = 6; + (ringCe == 1 && stationCe > 1) ? nsubCe = 3 : nsubCe = 6; + int chamberIDCe = subsectorCe + nsubCe * (sectorCe - 1); + + std::ostringstream oss; + oss << regionCe << stationCe << ringCe << sectorCe << subsectorCe << emtfSectorCe << emtfSubsectorCe; + std::istringstream iss(oss.str()); + int unique_id; + iss >> unique_id; + + if (_nHit_Ce.find(unique_id) == _nHit_Ce.end()) { + _nHit_Ce.insert({unique_id, 1}); + _phi_Ce[unique_id].push_back(phiIntCe); + _phi_glob_Ce[unique_id].push_back(phiGlobalCe); + _theta_Ce[unique_id].push_back(thetaIntCe); + _theta_glob_Ce[unique_id].push_back(thetaGlobalCe); + _roll_Ce[unique_id].push_back(rollCe); + _ID_Ce[unique_id].push_back(chamberIDCe); + _zone_Ce[unique_id].push_back(fillOccupancyCe); + _emtfSubsector_Ce[unique_id].push_back(emtfSubsectorCe); + _emtfSector_Ce[unique_id].push_back(emtfSectorCe); + _bx_Ce[unique_id].push_back(bxCe); + _cluster_size_Ce[unique_id].push_back(cluster_sizeCe); + } else { + _nHit_Ce.at(unique_id) += 1; + _phi_Ce[unique_id].push_back(phiIntCe); + _phi_glob_Ce[unique_id].push_back(phiGlobalCe); + _theta_Ce[unique_id].push_back(thetaIntCe); + _theta_glob_Ce[unique_id].push_back(thetaGlobalCe); + _roll_Ce[unique_id].push_back(rollCe); + _ID_Ce[unique_id].push_back(chamberIDCe); + _zone_Ce[unique_id].push_back(fillOccupancyCe); + _emtfSubsector_Ce[unique_id].push_back(emtfSubsectorCe); + _emtfSector_Ce[unique_id].push_back(emtfSectorCe); + _bx_Ce[unique_id].push_back(bxCe); + _cluster_size_Ce[unique_id].push_back(cluster_sizeCe); + } + + } // END :: for(auto& cppf_digis : *CppfDigis1) + + for (auto& cppf_digis2 : *dataCPPFs) { + RPCDetId rpcIdCu = cppf_digis2.rpcId(); + int regionCu = (int)rpcIdCu.region(); + int stationCu = (int)rpcIdCu.station(); + int sectorCu = (int)rpcIdCu.sector(); + int subsectorCu = (int)rpcIdCu.subsector(); + int ringCu = (int)rpcIdCu.ring(); + int rollCu = (int)(rpcIdCu.roll()); + int phiIntCu = (int)cppf_digis2.phi_int(); + int thetaIntCu = (int)cppf_digis2.theta_int(); + int phiGlobalCu = (int)cppf_digis2.phi_glob(); + int thetaGlobalCu = (int)cppf_digis2.theta_glob(); + int cluster_sizeCu = (int)cppf_digis2.cluster_size(); + int bxCu = (int)cppf_digis2.bx(); + int emtfSectorCu = (int)cppf_digis2.emtf_sector(); + int emtfSubsectorCu = GetSubsector(emtfSectorCu, subsectorCu); + int fillOccupancyCu = occupancy_value(regionCu, stationCu, ringCu); + + int nsubCu = 6; + (ringCu == 1 && stationCu > 1) ? nsubCu = 3 : nsubCu = 6; + int chamberIDCu = subsectorCu + nsubCu * (sectorCu - 1); + + std::ostringstream oss2; + oss2 << regionCu << stationCu << ringCu << sectorCu << subsectorCu << emtfSectorCu << emtfSubsectorCu; + std::istringstream iss2(oss2.str()); + int unique_id; + iss2 >> unique_id; + + if (_nHit_Cu.find(unique_id) == _nHit_Cu.end()) { // chamber had no hit so far + _nHit_Cu.insert({unique_id, 1}); + _phi_Cu[unique_id].push_back(phiIntCu); + _theta_Cu[unique_id].push_back(thetaIntCu); + _phi_glob_Cu[unique_id].push_back(phiGlobalCu); + _theta_glob_Cu[unique_id].push_back(thetaGlobalCu); + _ID_Cu[unique_id].push_back(chamberIDCu); + _zone_Cu[unique_id].push_back(fillOccupancyCu); + _roll_Cu[unique_id].push_back(rollCu); + _emtfSubsector_Cu[unique_id].push_back(emtfSubsectorCu); + _emtfSector_Cu[unique_id].push_back(emtfSectorCu); + _bx_Cu[unique_id].push_back(bxCu); + _cluster_size_Cu[unique_id].push_back(cluster_sizeCu); + } else { + _nHit_Cu.at(unique_id) += 1; + _phi_Cu[unique_id].push_back(phiIntCu); + _theta_Cu[unique_id].push_back(thetaIntCu); + _phi_glob_Cu[unique_id].push_back(phiGlobalCu); + _theta_glob_Cu[unique_id].push_back(thetaGlobalCu); + _ID_Cu[unique_id].push_back(chamberIDCu); + _zone_Cu[unique_id].push_back(fillOccupancyCu); + _roll_Cu[unique_id].push_back(rollCu); + _emtfSubsector_Cu[unique_id].push_back(emtfSubsectorCu); + _emtfSector_Cu[unique_id].push_back(emtfSectorCu); + _bx_Cu[unique_id].push_back(bxCu); + _cluster_size_Cu[unique_id].push_back(cluster_sizeCu); + } + } // END: : for(auto& cppf_digis2 : *CppfDigis2) + + for (auto const& Ce : _nHit_Ce) { + int key_Ce = Ce.first; + int nHit_Ce = Ce.second; + + for (auto const& Cu : _nHit_Cu) { + int key_Cu = Cu.first; + int nHit_Cu = Cu.second; + + if (key_Ce != key_Cu) + continue; + if (nHit_Ce != nHit_Cu) + continue; + + for (int vecSize = 0; vecSize < nHit_Cu; ++vecSize) { + if (_bx_Cu.at(key_Cu)[vecSize] != _bx_Ce.at(key_Ce)[vecSize]) + continue; + + bool OnPhi_Matching = false; + int index_Ce = vecSize; + int index_Cu = vecSize; + for (int i = 0; i < nHit_Ce; ++i) { + if (_phi_Ce.at(key_Ce)[i] == _phi_Cu.at(key_Cu)[vecSize]) { + OnPhi_Matching = true; + index_Cu = vecSize; + index_Ce = i; + } + } + if (OnPhi_Matching) { + h2_Matching_SameKey_OnPhi_phi_Ce_phi_Cu_bx->Fill(_phi_Ce.at(key_Ce)[index_Ce], _phi_Cu.at(key_Cu)[index_Cu]); + h2_Matching_SameKey_OnPhi_theta_Ce_theta_Cu_bx->Fill(_theta_Ce.at(key_Ce)[index_Ce], + _theta_Cu.at(key_Cu)[index_Cu]); + h2_Matching_SameKey_OnPhi_zone_Ce_zone_Cu_bx->Fill(_zone_Ce.at(key_Ce)[index_Ce], + _zone_Cu.at(key_Cu)[index_Cu]); + h2_Matching_SameKey_OnPhi_ID_Ce_ID_Cu_bx->Fill(_ID_Ce.at(key_Ce)[index_Ce], _ID_Cu.at(key_Cu)[index_Cu]); + h2_Matching_SameKey_OnPhi_ID_Ce_roll_Ce_bx->Fill(_ID_Ce.at(key_Ce)[index_Ce], _roll_Ce.at(key_Ce)[index_Ce]); + } else { + h2_Matching_SameKey_OffPhi_phi_Ce_phi_Cu_bx->Fill(_phi_Ce.at(key_Ce)[index_Ce], _phi_Cu.at(key_Cu)[index_Cu]); + h2_Matching_SameKey_OffPhi_theta_Ce_theta_Cu_bx->Fill(_theta_Ce.at(key_Ce)[index_Ce], + _theta_Cu.at(key_Cu)[index_Cu]); + h2_Matching_SameKey_OffPhi_zone_Ce_zone_Cu_bx->Fill(_zone_Ce.at(key_Ce)[index_Ce], + _zone_Cu.at(key_Cu)[index_Cu]); + h2_Matching_SameKey_OffPhi_ID_Ce_ID_Cu_bx->Fill(_ID_Ce.at(key_Ce)[index_Ce], _ID_Cu.at(key_Cu)[index_Cu]); + h2_Matching_SameKey_OffPhi_ID_Ce_roll_Ce_bx->Fill(_ID_Ce.at(key_Ce)[index_Ce], _roll_Ce.at(key_Ce)[index_Ce]); + } + + bool OnTheta_Matching = false; + for (int i = 0; i < nHit_Ce; ++i) { + if (_theta_Ce.at(key_Ce)[i] == _theta_Cu.at(key_Cu)[index_Cu]) { + OnTheta_Matching = true; + index_Cu = vecSize; + index_Ce = i; + } + } + if (OnTheta_Matching) { + h2_Matching_SameKey_OnTheta_phi_Ce_phi_Cu_bx->Fill(_phi_Ce.at(key_Ce)[index_Ce], + _phi_Cu.at(key_Cu)[index_Cu]); + h2_Matching_SameKey_OnTheta_theta_Ce_theta_Cu_bx->Fill(_theta_Ce.at(key_Ce)[index_Ce], + _theta_Cu.at(key_Cu)[index_Cu]); + h2_Matching_SameKey_OnTheta_zone_Ce_zone_Cu_bx->Fill(_zone_Ce.at(key_Ce)[index_Ce], + _zone_Cu.at(key_Cu)[index_Cu]); + } else { + h2_Matching_SameKey_OffTheta_phi_Ce_phi_Cu_bx->Fill(_phi_Ce.at(key_Ce)[index_Ce], + _phi_Cu.at(key_Cu)[index_Cu]); + h2_Matching_SameKey_OffTheta_theta_Ce_theta_Cu_bx->Fill(_theta_Ce.at(key_Ce)[index_Ce], + _theta_Cu.at(key_Cu)[index_Cu]); + h2_Matching_SameKey_OffTheta_zone_Ce_zone_Cu_bx->Fill(_zone_Ce.at(key_Ce)[index_Ce], + _zone_Cu.at(key_Cu)[index_Cu]); + } + } + + double off_phi, on_phi, off_theta, on_theta; + on_phi = h2_Matching_SameKey_OnPhi_phi_Ce_phi_Cu_bx->getEntries(); + off_phi = h2_Matching_SameKey_OffPhi_phi_Ce_phi_Cu_bx->getEntries(); + on_theta = h2_Matching_SameKey_OnTheta_theta_Ce_theta_Cu_bx->getEntries(); + off_theta = h2_Matching_SameKey_OffTheta_theta_Ce_theta_Cu_bx->getEntries(); + if (on_phi == 0) + on_phi = 0.0001; + if (on_theta == 0) + on_theta = 0.0001; + h1_Matching_SameKey_bx_Summary->setBinContent(1, off_phi / on_phi); + h1_Matching_SameKey_bx_Summary->setBinContent(2, off_theta / on_theta); + } + } +} + +int L1TdeStage2CPPF::GetSubsector(int emtfsector_, int lsubsector_) { + const int nsectors = 6; + int gsubsector = 0; + if ((emtfsector_ != -99) and (lsubsector_ != 0)) { + gsubsector = (emtfsector_ - 1) * nsectors + lsubsector_; + } + return gsubsector; +} + +int L1TdeStage2CPPF::occupancy_value(int region_, int station_, int ring_) { + int fill_val = 0; + if (region_ == -1) { + if ((station_ == 4) && (ring_ == 3)) + fill_val = 1; + else if ((station_ == 4) && (ring_ == 2)) + fill_val = 2; + else if ((station_ == 3) && (ring_ == 3)) + fill_val = 3; + else if ((station_ == 3) && (ring_ == 2)) + fill_val = 4; + else if ((station_ == 2) && (ring_ == 2)) + fill_val = 5; + else if ((station_ == 1) && (ring_ == 2)) + fill_val = 6; + + } else if (region_ == +1) { + if ((station_ == 1) && (ring_ == 2)) + fill_val = 7; + else if ((station_ == 2) && (ring_ == 2)) + fill_val = 8; + else if ((station_ == 3) && (ring_ == 2)) + fill_val = 9; + else if ((station_ == 3) && (ring_ == 3)) + fill_val = 10; + else if ((station_ == 4) && (ring_ == 2)) + fill_val = 11; + else if ((station_ == 4) && (ring_ == 3)) + fill_val = 12; + } + return fill_val; +} + +int L1TdeStage2CPPF::bx_value(int region_, int emtfsector_) { + int fill_val = 0; + + if (region_ == -1) { + fill_val = 7 - emtfsector_; + } else if (region_ == +1) { + fill_val = 6 + emtfsector_; + } + return fill_val; +} +#include "FWCore/Framework/interface/MakerMacros.h" +DEFINE_FWK_MODULE(L1TdeStage2CPPF); diff --git a/DQM/L1TMonitor/python/L1TStage2CPPF_cfi.py b/DQM/L1TMonitor/python/L1TStage2CPPF_cfi.py new file mode 100644 index 0000000000000..7226d2faa360a --- /dev/null +++ b/DQM/L1TMonitor/python/L1TStage2CPPF_cfi.py @@ -0,0 +1,9 @@ +import FWCore.ParameterSet.Config as cms + +from DQMServices.Core.DQMEDAnalyzer import DQMEDAnalyzer +l1tStage2Cppf = DQMEDAnalyzer( + "L1TStage2CPPF", + cppfSource = cms.InputTag("rpcCPPFRawToDigi"), + monitorDir = cms.untracked.string("L1T/L1TStage2CPPF"), + verbose = cms.untracked.bool(False), +) diff --git a/DQM/L1TMonitor/python/L1TStage2Emulator_cff.py b/DQM/L1TMonitor/python/L1TStage2Emulator_cff.py index a808fa90cab31..acbd5c1387b01 100644 --- a/DQM/L1TMonitor/python/L1TStage2Emulator_cff.py +++ b/DQM/L1TMonitor/python/L1TStage2Emulator_cff.py @@ -83,6 +83,16 @@ from Configuration.Eras.Modifier_run3_GEM_cff import run3_GEM run3_GEM.toModify( valCscStage2Digis, GEMPadDigiClusterProducer = "valMuonGEMPadDigiClusters" , commonParam = dict(runME11ILT = True) ) +# CPPF +from RecoLocalMuon.RPCRecHit.rpcRecHits_cfi import * +valRpcRecHits = rpcRecHits.clone( + rpcDigiLabel = 'rpcunpacker' +) +from L1Trigger.L1TMuonCPPF.emulatorCppfDigis_cfi import * +valCppfStage2Digis = emulatorCppfDigis.clone( + recHitLabel = 'valRpcRecHits' +) + # EMTF from L1Trigger.L1TMuonEndCap.simEmtfDigis_cfi import * valEmtfStage2Digis = simEmtfDigis.clone( @@ -139,6 +149,8 @@ valKBmtfDigis + valBmtfAlgoSel + valOmtfDigis + + valRpcRecHits + + valCppfStage2Digis + valEmtfStage2Digis + valGmtCaloSumDigis + valGmtStage2Digis + @@ -180,6 +192,9 @@ # OMTF from DQM.L1TMonitor.L1TdeStage2OMTF_cfi import * +# CPPF +from DQM.L1TMonitor.L1TdeStage2CPPF_cff import * + # EMTF from DQM.L1TMonitor.L1TdeStage2EMTF_cff import * @@ -199,6 +214,7 @@ l1tdeStage2BmtfSecond + l1tdeStage2Omtf + l1tdeCSCTPG + + l1tdeStage2CppfOnlineDQMSeq + l1tdeStage2EmtfOnlineDQMSeq + l1tStage2uGMTEmulatorOnlineDQMSeq + l1tdeStage2uGT + diff --git a/DQM/L1TMonitor/python/L1TStage2_cff.py b/DQM/L1TMonitor/python/L1TStage2_cff.py index 2267dced63505..0d830856c7396 100644 --- a/DQM/L1TMonitor/python/L1TStage2_cff.py +++ b/DQM/L1TMonitor/python/L1TStage2_cff.py @@ -15,6 +15,9 @@ # OMTF from DQM.L1TMonitor.L1TStage2OMTF_cfi import * +# CPPF +from DQM.L1TMonitor.L1TStage2CPPF_cfi import * + # EMTF from DQM.L1TMonitor.L1TStage2EMTF_cfi import * @@ -40,6 +43,7 @@ l1tStage2BmtfOnlineDQMSeq + l1tStage2Omtf + l1tStage2Emtf + + l1tStage2Cppf + l1tStage2RegionalShower + l1tStage2uGMTOnlineDQMSeq + l1tObjectsTiming + diff --git a/DQM/L1TMonitor/python/L1TdeStage2CPPF_cff.py b/DQM/L1TMonitor/python/L1TdeStage2CPPF_cff.py new file mode 100644 index 0000000000000..5fc35e3a1b148 --- /dev/null +++ b/DQM/L1TMonitor/python/L1TdeStage2CPPF_cff.py @@ -0,0 +1,10 @@ +import FWCore.ParameterSet.Config as cms + +from DQM.L1TMonitor.L1TdeStage2CPPF_cfi import * + + +# sequences +l1tdeStage2CppfOnlineDQMSeq = cms.Sequence( + l1tdeStage2Cppf +) + diff --git a/DQM/L1TMonitor/python/L1TdeStage2CPPF_cfi.py b/DQM/L1TMonitor/python/L1TdeStage2CPPF_cfi.py new file mode 100644 index 0000000000000..9d3a4b5a343e0 --- /dev/null +++ b/DQM/L1TMonitor/python/L1TdeStage2CPPF_cfi.py @@ -0,0 +1,11 @@ +import FWCore.ParameterSet.Config as cms + +from DQMServices.Core.DQMEDAnalyzer import DQMEDAnalyzer +l1tdeStage2Cppf = DQMEDAnalyzer( + "L1TdeStage2CPPF", + dataSource = cms.InputTag("rpcCPPFRawToDigi"), + emulSource = cms.InputTag("valCppfStage2Digis","recHit"), + monitorDir = cms.untracked.string("L1TEMU/L1TdeStage2CPPF"), + verbose = cms.untracked.bool(False), +) + diff --git a/DQMServices/Core/src/DQMStore.cc b/DQMServices/Core/src/DQMStore.cc index dccbf954c64ff..69c5e90c6d277 100644 --- a/DQMServices/Core/src/DQMStore.cc +++ b/DQMServices/Core/src/DQMStore.cc @@ -13,6 +13,10 @@ namespace dqm::implementation { + // list of acceptable characters for ME path names, in order to be able to upload to the CMS DQM GUI + // See https://github.com/cms-DQM/dqmgui_prod/blob/af0a388e8f57c60e51111585d298aeeea943367f/src/cpp/DQM/DQMStore.cc#L56 + static const std::string s_safe = "/ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-+=_()# "; + std::string NavigatorBase::pwd() { if (cwd_.empty()) { return ""; @@ -66,6 +70,13 @@ namespace dqm::implementation { bool forceReplace /* = false */) { MonitorElementData::Path path; std::string fullpath = cwd_ + std::string(name.View()); + + if (fullpath.find_first_not_of(s_safe) != std::string::npos) { + throw cms::Exception("BadMonitorElementPathName") + << " Monitor element path name: '" << fullpath.c_str() << "' uses unacceptable characters." + << "\n Acceptable characters are: " << s_safe.c_str(); + } + path.set(fullpath, MonitorElementData::Path::Type::DIR_AND_NAME); // We should check if there is a local ME for this module and name already. diff --git a/DataFormats/Portable/BuildFile.xml b/DataFormats/Portable/BuildFile.xml new file mode 100644 index 0000000000000..7a845459f17c2 --- /dev/null +++ b/DataFormats/Portable/BuildFile.xml @@ -0,0 +1,3 @@ + + + diff --git a/DataFormats/Portable/README.md b/DataFormats/Portable/README.md new file mode 100644 index 0000000000000..167039a8fdebe --- /dev/null +++ b/DataFormats/Portable/README.md @@ -0,0 +1,38 @@ +## Define portable data formats that wrap SoA data structures and can be persisted to ROOT files + +### `PortableHostCollection` + +`PortableHostCollection` is a class template that wraps a SoA type `T` and an alpaka host buffer, which owns the +memory where the SoA is allocated. The content of the SoA is persistent, while the buffer itself is transient. +Specialisations of this template can be persisted, and can be read back also in "bare ROOT" mode, without any +dictionaries. +They have no implicit or explicit references to alpaka (neither as part of the class signature nor as part of its name). +This could make it possible to read them back with different portability solutions in the future. + +### `PortableDeviceCollection` + +`PortableDeviceCollection` is a class template that wraps a SoA type `T` and an alpaka device buffer, which +owns the memory where the SoA is allocated. +To avoid confusion and ODR-violations, the `PortableDeviceCollection` template cannot be used with the `Host` +device type. +Specialisations of this template are transient and cannot be persisted. + +### `ALPAKA_ACCELERATOR_NAMESPACE::PortableCollection` + +`ALPAKA_ACCELERATOR_NAMESPACE::PortableCollection` is a template alias that resolves to either +`PortableHostCollection` or `PortableDeviceCollection`, depending on the +backend. + +### `PortableCollection` + +`PortableCollection` is an alias template that resolves to `ALPAKA_ACCELERATOR_NAMESPACE::PortableCollection` +for the matching device. + + +## Notes + +Modules that are supposed to work with only host types (_e.g._ dealing with de/serialisation, data transfers, _etc._) +should explicitly use the `PortableHostCollection` types. + +Modules that implement portable interfaces (_e.g._ producers) should use the generic types based on +`ALPAKA_ACCELERATOR_NAMESPACE::PortableCollection` or `PortableCollection`. diff --git a/DataFormats/Portable/interface/PortableCollection.h b/DataFormats/Portable/interface/PortableCollection.h new file mode 100644 index 0000000000000..4d3b4a9b1a269 --- /dev/null +++ b/DataFormats/Portable/interface/PortableCollection.h @@ -0,0 +1,16 @@ +#ifndef DataFormats_Portable_interface_PortableCollection_h +#define DataFormats_Portable_interface_PortableCollection_h + +namespace traits { + + // trait for a generic SoA-based product + template + class PortableCollectionTrait; + +} // namespace traits + +// type alias for a generic SoA-based product +template +using PortableCollection = typename traits::PortableCollectionTrait::CollectionType; + +#endif // DataFormats_Portable_interface_PortableCollection_h diff --git a/DataFormats/Portable/interface/PortableDeviceCollection.h b/DataFormats/Portable/interface/PortableDeviceCollection.h new file mode 100644 index 0000000000000..64b3b3ae55b15 --- /dev/null +++ b/DataFormats/Portable/interface/PortableDeviceCollection.h @@ -0,0 +1,65 @@ +#ifndef DataFormats_Portable_interface_PortableDeviceCollection_h +#define DataFormats_Portable_interface_PortableDeviceCollection_h + +#include +#include + +#include + +#include "HeterogeneousCore/AlpakaInterface/interface/config.h" + +// generic SoA-based product in device memory +template +class PortableDeviceCollection { + static_assert(not std::is_same_v, + "Use PortableHostCollection instead of PortableDeviceCollection"); + +public: + using Layout = T; + using View = typename Layout::View; + using ConstView = typename Layout::ConstView; + using Buffer = alpaka::Buf, uint32_t>; + using ConstBuffer = alpaka::ViewConst; + + PortableDeviceCollection() = default; + + PortableDeviceCollection(int32_t elements, TDev const &device) + : buffer_{alpaka::allocBuf( + device, alpaka::Vec, uint32_t>{Layout::computeDataSize(elements)})}, + layout_{buffer_->data(), elements}, + view_{layout_} { + // Alpaka set to a default alignment of 128 bytes defining ALPAKA_DEFAULT_HOST_MEMORY_ALIGNMENT=128 + assert(reinterpret_cast(buffer_->data()) % Layout::alignment == 0); + } + + ~PortableDeviceCollection() = default; + + // non-copyable + PortableDeviceCollection(PortableDeviceCollection const &) = delete; + PortableDeviceCollection &operator=(PortableDeviceCollection const &) = delete; + + // movable + PortableDeviceCollection(PortableDeviceCollection &&other) = default; + PortableDeviceCollection &operator=(PortableDeviceCollection &&other) = default; + + View &view() { return view_; } + ConstView const &view() const { return view_; } + ConstView const &const_view() const { return view_; } + + View &operator*() { return view_; } + ConstView const &operator*() const { return view_; } + + View *operator->() { return &view_; } + ConstView const *operator->() const { return &view_; } + + Buffer buffer() { return *buffer_; } + ConstBuffer buffer() const { return *buffer_; } + ConstBuffer const_buffer() const { return *buffer_; } + +private: + std::optional buffer_; //! + Layout layout_; // + View view_; //! +}; + +#endif // DataFormats_Portable_interface_PortableDeviceCollection_h diff --git a/DataFormats/Portable/interface/PortableHostCollection.h b/DataFormats/Portable/interface/PortableHostCollection.h new file mode 100644 index 0000000000000..28e5da86ccc00 --- /dev/null +++ b/DataFormats/Portable/interface/PortableHostCollection.h @@ -0,0 +1,83 @@ +#ifndef DataFormats_Portable_interface_PortableHostCollection_h +#define DataFormats_Portable_interface_PortableHostCollection_h + +#include + +#include + +#include "DataFormats/SoATemplate/interface/SoACommon.h" +#include "HeterogeneousCore/AlpakaInterface/interface/config.h" +#include "HeterogeneousCore/AlpakaInterface/interface/host.h" + +// generic SoA-based product in host memory +template +class PortableHostCollection { +public: + using Layout = T; + using View = typename Layout::View; + using ConstView = typename Layout::ConstView; + using Buffer = alpaka::Buf, uint32_t>; + using ConstBuffer = alpaka::ViewConst; + + PortableHostCollection() = default; + + PortableHostCollection(int32_t elements, alpaka_common::DevHost const &host) + // allocate pageable host memory + : buffer_{alpaka::allocBuf( + host, alpaka::Vec, uint32_t>{Layout::computeDataSize(elements)})}, + layout_{buffer_->data(), elements}, + view_{layout_} { + // Alpaka set to a default alignment of 128 bytes defining ALPAKA_DEFAULT_HOST_MEMORY_ALIGNMENT=128 + assert(reinterpret_cast(buffer_->data()) % Layout::alignment == 0); + } + + template + PortableHostCollection(int32_t elements, alpaka_common::DevHost const &host, TDev const &device) + // allocate pinned host memory, accessible by the given device + : buffer_{alpaka::allocMappedBuf( + host, device, alpaka::Vec, uint32_t>{Layout::computeDataSize(elements)})}, + layout_{buffer_->data(), elements}, + view_{layout_} { + // Alpaka set to a default alignment of 128 bytes defining ALPAKA_DEFAULT_HOST_MEMORY_ALIGNMENT=128 + assert(reinterpret_cast(buffer_->data()) % Layout::alignment == 0); + } + + ~PortableHostCollection() = default; + + // non-copyable + PortableHostCollection(PortableHostCollection const &) = delete; + PortableHostCollection &operator=(PortableHostCollection const &) = delete; + + // movable + PortableHostCollection(PortableHostCollection &&other) = default; + PortableHostCollection &operator=(PortableHostCollection &&other) = default; + + View &view() { return view_; } + ConstView const &view() const { return view_; } + ConstView const &const_view() const { return view_; } + + View &operator*() { return view_; } + ConstView const &operator*() const { return view_; } + + View *operator->() { return &view_; } + ConstView const *operator->() const { return &view_; } + + Buffer buffer() { return *buffer_; } + ConstBuffer buffer() const { return *buffer_; } + ConstBuffer const_buffer() const { return *buffer_; } + + // part of the ROOT read streamer + static void ROOTReadStreamer(PortableHostCollection *newObj, Layout const &layout) { + newObj->~PortableHostCollection(); + // use the global "host" object returned by alpaka_common::host() + new (newObj) PortableHostCollection(layout.metadata().size(), alpaka_common::host()); + newObj->layout_.ROOTReadStreamer(layout); + } + +private: + std::optional buffer_; //! + Layout layout_; // + View view_; //! +}; + +#endif // DataFormats_Portable_interface_PortableHostCollection_h diff --git a/DataFormats/Portable/interface/alpaka/PortableCollection.h b/DataFormats/Portable/interface/alpaka/PortableCollection.h new file mode 100644 index 0000000000000..d9cfaf5c66bed --- /dev/null +++ b/DataFormats/Portable/interface/alpaka/PortableCollection.h @@ -0,0 +1,42 @@ +#ifndef DataFormats_Portable_interface_alpaka_PortableDeviceCollection_h +#define DataFormats_Portable_interface_alpaka_PortableDeviceCollection_h + +#include + +#include + +#include "DataFormats/Portable/interface/PortableCollection.h" +#include "DataFormats/Portable/interface/PortableHostCollection.h" +#include "DataFormats/Portable/interface/PortableDeviceCollection.h" +#include "HeterogeneousCore/AlpakaInterface/interface/config.h" + +namespace ALPAKA_ACCELERATOR_NAMESPACE { + +#if defined ALPAKA_ACC_CPU_B_SEQ_T_SEQ_ENABLED + // ... or any other CPU-based accelerators + + // generic SoA-based product in host memory + template + using PortableCollection = ::PortableHostCollection; + +#else + + // generic SoA-based product in device memory + template + using PortableCollection = ::PortableDeviceCollection; + +#endif // ALPAKA_ACC_CPU_B_SEQ_T_SEQ_ENABLED + +} // namespace ALPAKA_ACCELERATOR_NAMESPACE + +namespace traits { + + // specialise the trait for the device provided by the ALPAKA_ACCELERATOR_NAMESPACE + template + class PortableCollectionTrait { + using CollectionType = ALPAKA_ACCELERATOR_NAMESPACE::PortableCollection; + }; + +} // namespace traits + +#endif // DataFormats_Portable_interface_alpaka_PortableDeviceCollection_h diff --git a/DataFormats/PortableTestObjects/BuildFile.xml b/DataFormats/PortableTestObjects/BuildFile.xml new file mode 100644 index 0000000000000..1ea43eb400166 --- /dev/null +++ b/DataFormats/PortableTestObjects/BuildFile.xml @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/DataFormats/PortableTestObjects/README.md b/DataFormats/PortableTestObjects/README.md new file mode 100644 index 0000000000000..1814c02dfd42d --- /dev/null +++ b/DataFormats/PortableTestObjects/README.md @@ -0,0 +1,10 @@ +## Define the portable SoA-based data formats + +Notes: + - define a full dictionary for `portabletest::TestSoA` and `portabletest::TestHostCollection` + - do not define a dictionary for `alpaka_serial_sync::portabletest::TestDeviceCollection`, + because it is the same class as `portabletest::TestHostCollection`; + - define the dictionary for `alpaka_cuda_async::portabletest::TestDeviceCollection` + as _transient_ only; + - the dictionary for `alpaka_cuda_async::portabletest::TestDeviceCollection` should + be defined in a separate library, to factor out the CUDA dependency. diff --git a/DataFormats/PortableTestObjects/interface/TestHostCollection.h b/DataFormats/PortableTestObjects/interface/TestHostCollection.h new file mode 100644 index 0000000000000..f7f4ffd64b7d8 --- /dev/null +++ b/DataFormats/PortableTestObjects/interface/TestHostCollection.h @@ -0,0 +1,14 @@ +#ifndef DataFormats_PortableTestObjects_interface_TestHostCollection_h +#define DataFormats_PortableTestObjects_interface_TestHostCollection_h + +#include "DataFormats/Portable/interface/PortableHostCollection.h" +#include "DataFormats/PortableTestObjects/interface/TestSoA.h" + +namespace portabletest { + + // SoA with x, y, z, id fields in host memory + using TestHostCollection = PortableHostCollection; + +} // namespace portabletest + +#endif // DataFormats_PortableTestObjects_interface_TestHostCollection_h diff --git a/DataFormats/PortableTestObjects/interface/TestSoA.h b/DataFormats/PortableTestObjects/interface/TestSoA.h new file mode 100644 index 0000000000000..3d2152d866ba1 --- /dev/null +++ b/DataFormats/PortableTestObjects/interface/TestSoA.h @@ -0,0 +1,22 @@ +#ifndef DataFormats_PortableTestObjects_interface_TestSoA_h +#define DataFormats_PortableTestObjects_interface_TestSoA_h + +#include "DataFormats/SoATemplate/interface/SoACommon.h" +#include "DataFormats/SoATemplate/interface/SoALayout.h" +#include "DataFormats/SoATemplate/interface/SoAView.h" + +namespace portabletest { + + // SoA layout with x, y, z, id fields + GENERATE_SOA_LAYOUT(TestSoALayout, + // columns: one value per element + SOA_COLUMN(double, x), + SOA_COLUMN(double, y), + SOA_COLUMN(double, z), + SOA_COLUMN(int32_t, id)) + + using TestSoA = TestSoALayout<>; + +} // namespace portabletest + +#endif // DataFormats_PortableTestObjects_interface_TestSoA_h diff --git a/DataFormats/PortableTestObjects/interface/alpaka/TestDeviceCollection.h b/DataFormats/PortableTestObjects/interface/alpaka/TestDeviceCollection.h new file mode 100644 index 0000000000000..3109bb15462f0 --- /dev/null +++ b/DataFormats/PortableTestObjects/interface/alpaka/TestDeviceCollection.h @@ -0,0 +1,22 @@ +#ifndef DataFormats_PortableTestObjects_interface_alpaka_TestDeviceCollection_h +#define DataFormats_PortableTestObjects_interface_alpaka_TestDeviceCollection_h + +#include "DataFormats/Portable/interface/alpaka/PortableCollection.h" +#include "DataFormats/PortableTestObjects/interface/TestSoA.h" +#include "HeterogeneousCore/AlpakaInterface/interface/config.h" + +namespace ALPAKA_ACCELERATOR_NAMESPACE { + + namespace portabletest { + + // import the top-level portabletest namespace + using namespace ::portabletest; + + // SoA with x, y, z, id fields in device global memory + using TestDeviceCollection = PortableCollection; + + } // namespace portabletest + +} // namespace ALPAKA_ACCELERATOR_NAMESPACE + +#endif // DataFormats_PortableTestObjects_interface_alpaka_TestDeviceCollection_h diff --git a/DataFormats/PortableTestObjects/src/alpaka/classes_cuda.h b/DataFormats/PortableTestObjects/src/alpaka/classes_cuda.h new file mode 100644 index 0000000000000..bcda8c64ea284 --- /dev/null +++ b/DataFormats/PortableTestObjects/src/alpaka/classes_cuda.h @@ -0,0 +1,3 @@ +#include "DataFormats/Common/interface/Wrapper.h" +#include "DataFormats/PortableTestObjects/interface/TestSoA.h" +#include "DataFormats/PortableTestObjects/interface/alpaka/TestDeviceCollection.h" diff --git a/DataFormats/PortableTestObjects/src/alpaka/classes_cuda_def.xml b/DataFormats/PortableTestObjects/src/alpaka/classes_cuda_def.xml new file mode 100644 index 0000000000000..4a4167944b259 --- /dev/null +++ b/DataFormats/PortableTestObjects/src/alpaka/classes_cuda_def.xml @@ -0,0 +1,4 @@ + + + + diff --git a/DataFormats/PortableTestObjects/src/alpaka/classes_serial.h b/DataFormats/PortableTestObjects/src/alpaka/classes_serial.h new file mode 100644 index 0000000000000..9405bbfd336e2 --- /dev/null +++ b/DataFormats/PortableTestObjects/src/alpaka/classes_serial.h @@ -0,0 +1,3 @@ +#include "DataFormats/Common/interface/Wrapper.h" +#include "DataFormats/PortableTestObjects/interface/TestHostCollection.h" +#include "DataFormats/PortableTestObjects/interface/TestSoA.h" diff --git a/DataFormats/PortableTestObjects/src/alpaka/classes_serial_def.xml b/DataFormats/PortableTestObjects/src/alpaka/classes_serial_def.xml new file mode 100644 index 0000000000000..cb12768035e4b --- /dev/null +++ b/DataFormats/PortableTestObjects/src/alpaka/classes_serial_def.xml @@ -0,0 +1,16 @@ + + + + + + + + diff --git a/DataFormats/PortableTestObjects/src/classes.h b/DataFormats/PortableTestObjects/src/classes.h new file mode 100644 index 0000000000000..46c07862b7db8 --- /dev/null +++ b/DataFormats/PortableTestObjects/src/classes.h @@ -0,0 +1 @@ +#include "DataFormats/PortableTestObjects/interface/TestSoA.h" diff --git a/DataFormats/PortableTestObjects/src/classes_def.xml b/DataFormats/PortableTestObjects/src/classes_def.xml new file mode 100644 index 0000000000000..21b727eee18c6 --- /dev/null +++ b/DataFormats/PortableTestObjects/src/classes_def.xml @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/DataFormats/Provenance/interface/branchIDToProductID.h b/DataFormats/Provenance/interface/branchIDToProductID.h new file mode 100644 index 0000000000000..5e5a585dbc3d8 --- /dev/null +++ b/DataFormats/Provenance/interface/branchIDToProductID.h @@ -0,0 +1,19 @@ +#ifndef DataFormats_Provenance_branchIDToProductID_h +#define DataFormats_Provenance_branchIDToProductID_h + +#include "DataFormats/Provenance/interface/BranchID.h" +#include "DataFormats/Provenance/interface/BranchIDListHelper.h" +#include "DataFormats/Provenance/interface/ProductID.h" + +#include + +namespace edm { + // Fill in helper map for Branch to ProductID mapping + std::vector makeBranchListIndexToProcessIndex(BranchListIndexes const& branchListIndexes); + + ProductID branchIDToProductID(BranchID const& bid, + BranchIDListHelper const& branchIDListHelper, + std::vector const& branchListIndexToProcessIndex); +} // namespace edm + +#endif diff --git a/DataFormats/Provenance/src/branchIDToProductID.cc b/DataFormats/Provenance/src/branchIDToProductID.cc new file mode 100644 index 0000000000000..b9b44d4000d20 --- /dev/null +++ b/DataFormats/Provenance/src/branchIDToProductID.cc @@ -0,0 +1,41 @@ +#include "DataFormats/Provenance/interface/branchIDToProductID.h" +#include "FWCore/Utilities/interface/EDMException.h" + +#include + +namespace edm { + std::vector makeBranchListIndexToProcessIndex(BranchListIndexes const& branchListIndexes) { + ProcessIndex pix = 0; + auto const nelem = 1 + *std::max_element(branchListIndexes.begin(), branchListIndexes.end()); + std::vector branchListIndexToProcessIndex(nelem, std::numeric_limits::max()); + for (auto const& blindex : branchListIndexes) { + branchListIndexToProcessIndex[blindex] = pix; + ++pix; + } + return branchListIndexToProcessIndex; + } + + ProductID branchIDToProductID(BranchID const& bid, + BranchIDListHelper const& branchIDListHelper, + std::vector const& branchListIndexToProcessIndex) { + if (not bid.isValid()) { + throw Exception(errors::NotFound, "InvalidID") << "branchIDToProductID: invalid BranchID supplied\n"; + } + + auto range = branchIDListHelper.branchIDToIndexMap().equal_range(bid); + for (auto it = range.first; it != range.second; ++it) { + edm::BranchListIndex blix = it->second.first; + if (blix < branchListIndexToProcessIndex.size()) { + auto v = branchListIndexToProcessIndex[blix]; + if (v != std::numeric_limits::max()) { + edm::ProductIndex productIndex = it->second.second; + edm::ProcessIndex processIndex = v; + return edm::ProductID(processIndex + 1, productIndex + 1); + } + } + } + // cannot throw, because some products may legitimately not have product ID's (e.g. pile-up). + return edm::ProductID(); + } + +} // namespace edm diff --git a/DataFormats/SoATemplate/BuildFile.xml b/DataFormats/SoATemplate/BuildFile.xml new file mode 100644 index 0000000000000..8267b0602e13a --- /dev/null +++ b/DataFormats/SoATemplate/BuildFile.xml @@ -0,0 +1,2 @@ + + diff --git a/DataFormats/SoATemplate/README.md b/DataFormats/SoATemplate/README.md new file mode 100644 index 0000000000000..ba1b00e70233d --- /dev/null +++ b/DataFormats/SoATemplate/README.md @@ -0,0 +1,222 @@ +# Structure of array (SoA) generation + +The two header files [`SoALayout.h`](SoALayout.h) and [`SoAView.h`](SoAView.h) define preprocessor macros that +allow generating SoA classes. The SoA classes generate multiple, aligned column from a memory buffer. The memory +buffer is allocated separately by the user, and can be located in a memory space different from the local one (for +example, a SoA located in a GPU device memory can be fully pre-defined on the host and the resulting structure is +passed to the GPU kernel). + +This columnar storage allows efficient memory access by GPU kernels (coalesced access on cache line aligned data) +and possibly vectorization. + +Additionally, templation of the layout and view classes allows compile-time variations of accesses and checks: +verification of alignment and corresponding compiler hinting, cache strategy (non-coherent, streaming with immediate +invalidation), range checking. + +Macro generation allows generating code that provides a clear and concise access of data when used. The code +generation uses the Boost Preprocessing library. + +## Layout + +`SoALayout` is a macro generated templated class that subdivides a provided buffer into a collection of columns, +Eigen columns and scalars. The buffer is expected to be aligned with a selectable alignment defaulting to the CUDA +GPU cache line (128 bytes). All columns and scalars within a `SoALayout` will be individually aligned, leaving +padding at the end of each if necessary. Eigen columns have each component of the vector or matrix properly aligned +in individual column (by defining the stride between components). Only compile-time sized Eigen vectors and matrices +are supported. Scalar members are members of layout with one element, irrespective of the size of the layout. + +Static utility functions automatically compute the byte size of a layout, taking into account all its columns and +alignment. + +## View + +`SoAView` is a macro generated templated class allowing access to columns defined in one or multiple `SoALayout`s or +`SoAViews`. The view can be generated in a constant and non-constant flavors. All view flavors provide with the same +interface where scalar elements are accessed with an `operator()`: `soa.scalar()` while columns (Eigen or not) are +accessed via a array of structure (AoS) -like syntax: `soa[index].x()`. The "struct" object returned by `operator[]` +can be used as a shortcut: `auto si = soa[index]; si.z() = si.x() + zi.y();` + +A view can be instanciated by being passed the layout(s) and view(s) it is defined against, or column by column. + +Layout classes also define a `View` and `ConstView` subclass that provide access to each column and +scalar of the layout. In addition to those fully parametrized templates, two others levels of parametrization are +provided: `ViewTemplate`, `ViewViewTemplateFreeParams` and respectively `ConstViewTemplate`, +`ConstViewTemplateFreeParams`. The parametrization of those templates is explained in the [Template +parameters section](#template-parameters). + +## Metadata subclass + +In order to no clutter the namespace of the generated class, a subclass name `Metadata` is generated. It is +instanciated with the `metadata()` member function and contains various utility functions, like `size()` (number +of elements in the SoA), `byteSize()`, `byteAlignment()`, `data()` (a pointer to the buffer). A `nextByte()` +function computes the first byte of a structure right after a layout, allowing using a single buffer for multiple +layouts. + +## ROOT serialization and de-serialization + +Layouts can be serialized and de-serialized with ROOT. In order to generate the ROOT dictionary, separate +`clases_def.xml` and `classes.h` should be prepared. `classes.h` ensures the inclusion of the proper header files to +get the definition of the serialized classes, and `classes_def.xml` needs to define the fixed list of members that +ROOT should ignore, plus the list of all the columns. [An example is provided below.](#examples) + +Serialization of Eigen data is not yet supported. + +## Template parameters + +The template shared by layouts and parameters are: +- Byte aligment (defaulting to the nVidia GPU cache line size (128 bytes)) +- Alignment enforcement (`relaxed` or `enforced`). When enforced, the alignment will be checked at construction + time, and the accesses are done with compiler hinting (using the widely supported `__builtin_assume_aligned` + intrinsic). + +In addition, the views also provide access parameters: +- Restrict qualify: add restrict hints to read accesses, so that the compiler knows it can relax accesses to the + data and assume it will not change. On nVidia GPUs, this leads to the generation of instruction using the faster + non-coherent cache. +- Range checking: add index checking on each access. As this is a compile time parameter, the cost of the feature at + run time is null if turned off. When turned on, the accesses will be slowed down by checks. Uppon error detection, + an exception is launched (on the CPU side) or the kernel is made to crash (on the GPU side). This feature can help + the debugging of index issues at runtime, but of course requires a recompilation. + +The trivial views subclasses come in a variety of parametrization levels: `View` uses the same byte +alignement and alignment enforcement as the layout, and defaults (off) for restrict qualifying and range checking. +`ViewTemplate` template allows setting of restrict qualifying and range checking, while +`ViewTemplateFreeParams` allows full re-customization of the template parameters. + +## Using SoA layouts and views with GPUs + +Instanciation of views and layouts is preferably done on the CPU side. The view object is lightweight, with only one +pointer per column, plus the global number of elements. Extra view class can be generated to restrict this number of +pointers to the strict minimum in scenarios where only a subset of columns are used in a given GPU kernel. + +## Examples + +A layout can be defined as: + +```C++ +#include "DataFormats/SoALayout.h" + +GENERATE_SOA_LAYOUT(SoA1LayoutTemplate, + // predefined static scalars + // size_t size; + // size_t alignment; + + // columns: one value per element + SOA_COLUMN(double, x), + SOA_COLUMN(double, y), + SOA_COLUMN(double, z), + SOA_EIGEN_COLUMN(Eigen::Vector3d, a), + SOA_EIGEN_COLUMN(Eigen::Vector3d, b), + SOA_EIGEN_COLUMN(Eigen::Vector3d, r), + SOA_COLUMN(uint16_t, color), + SOA_COLUMN(int32_t, value), + SOA_COLUMN(double *, py), + SOA_COLUMN(uint32_t, count), + SOA_COLUMN(uint32_t, anotherCount), + + // scalars: one value for the whole structure + SOA_SCALAR(const char *, description), + SOA_SCALAR(uint32_t, someNumber) +); + +// Default template parameters are < +// size_t ALIGNMENT = cms::soa::CacheLineSize::defaultSize, +// bool ALIGNMENT_ENFORCEMENT = cms::soa::AlignmentEnforcement::relaxed +// > +using SoA1Layout = SoA1LayoutTemplate<>; + +using SoA1LayoutAligned = SoA1LayoutTemplate; +``` + +The buffer of the proper size is allocated, and the layout is populated with: + +```C++ +// Allocation of aligned +size_t elements = 100; +using AlignedBuffer = std::unique_ptr; +AlignedBuffer h_buf (reinterpret_cast(aligned_alloc(SoA1LayoutAligned::byteAlignment, SoA1LayoutAligned::computeDataSize(elements))), std::free); +SoA1LayoutAligned soaLayout(h_buf.get(), elements); +``` + +A view will derive its column types from one or multiple layouts. The macro generating the view takes a list of layouts or views it +gets is data from as a first parameter, and the selection of the columns the view will give access to as a second parameter. + +```C++ +// A 1 to 1 view of the layout (except for unsupported types). +GENERATE_SOA_VIEW(SoA1ViewTemplate, + SOA_VIEW_LAYOUT_LIST( + SOA_VIEW_LAYOUT(SoA1Layout, soa1) + ), + SOA_VIEW_VALUE_LIST( + SOA_VIEW_VALUE(soa1, x), + SOA_VIEW_VALUE(soa1, y), + SOA_VIEW_VALUE(soa1, z), + SOA_VIEW_VALUE(soa1, color), + SOA_VIEW_VALUE(soa1, value), + SOA_VIEW_VALUE(soa1, py), + SOA_VIEW_VALUE(soa1, count), + SOA_VIEW_VALUE(soa1, anotherCount), + SOA_VIEW_VALUE(soa1, description), + SOA_VIEW_VALUE(soa1, someNumber) + ) +); + +using SoA1View = SoA1ViewTemplate<>; + +SoA1View soaView(soaLayout); + +for (size_t i=0; i < soaLayout.metadata().size(); ++i) { + auto si = soaView[i]; + si.x() = si.y() = i; + soaView.someNumber() += i; +} +``` + +The mutable and const views with the exact same set of columns and their parametrized variants are provided from the layout as: + +```C++ +// (Pseudo-code) +struct SoA1Layout::View; + +template +struct SoA1Layout::ViewTemplate; + +template +struct SoA1Layout::ViewTemplateFreeParams; + +struct SoA1Layout::ConstView; + +template +struct SoA1Layout::ConstViewTemplate; + +template +struct SoA1Layout::ConstViewTemplateFreeParams; +``` + + + +## Current status and further improvements + +### Available features + +- The layout and views support scalars and columns, alignment and alignment enforcement and hinting (linked). +- Automatic `__restrict__` compiler hinting is supported and can be enabled where appropriate. +- Automatic creation of trivial views and const views derived from a single layout. +- Cache access style, which was explored, was abandoned as this not-yet-used feature interferes with `__restrict__` + support (which is already in used in existing code). It could be made available as a separate tool that can be used + directly by the module developer, orthogonally from SoA. +- Optional (compile time) range checking validates the index of every column access, throwing an exception on the + CPU side and forcing a segmentation fault to halt kernels. When not enabled, it has no impact on performance (code + not compiled) +- Eigen columns are also suported, with both const and non-const flavors. +- ROOT serialization and deserialization is supported. In CMSSW, it is planned to be used through the memory + managing `PortableCollection` family of classes. +- An `operator<<()` is provided to print the layout of an SoA to standard streams. diff --git a/DataFormats/SoATemplate/interface/SoACommon.h b/DataFormats/SoATemplate/interface/SoACommon.h new file mode 100644 index 0000000000000..5fbb986f136d0 --- /dev/null +++ b/DataFormats/SoATemplate/interface/SoACommon.h @@ -0,0 +1,717 @@ +#ifndef DataFormats_SoATemplate_interface_SoACommon_h +#define DataFormats_SoATemplate_interface_SoACommon_h + +/* + * Definitions of SoA common parameters for SoA class generators + */ + +#include +#include +#include +#include +#include + +#include + +#include "FWCore/Utilities/interface/typedefs.h" + +// CUDA attributes +#ifdef __CUDACC__ +#define SOA_HOST_ONLY __host__ +#define SOA_DEVICE_ONLY __device__ +#define SOA_HOST_DEVICE __host__ __device__ +#define SOA_INLINE __forceinline__ +#else +#define SOA_HOST_ONLY +#define SOA_DEVICE_ONLY +#define SOA_HOST_DEVICE +#define SOA_INLINE inline __attribute__((always_inline)) +#endif + +// Exception throwing (or willful crash in kernels) +#if defined(__CUDACC__) && defined(__CUDA_ARCH__) +#define SOA_THROW_OUT_OF_RANGE(A) \ + { \ + printf("%s\n", (A)); \ + __trap(); \ + } +#else +#define SOA_THROW_OUT_OF_RANGE(A) \ + { throw std::out_of_range(A); } +#endif + +/* declare "scalars" (one value shared across the whole SoA) and "columns" (one value per element) */ +#define _VALUE_TYPE_SCALAR 0 +#define _VALUE_TYPE_COLUMN 1 +#define _VALUE_TYPE_EIGEN_COLUMN 2 + +/* The size type need to be "hardcoded" in the template parameters for classes serialized by ROOT */ +#define CMS_SOA_BYTE_SIZE_TYPE std::size_t + +namespace cms::soa { + + // size_type for indices. Compatible with ROOT Int_t, but limited to 2G entries + using size_type = cms_int32_t; + // byte_size_type for byte counts. Not creating an artificial limit (and not ROOT serialized). + using byte_size_type = CMS_SOA_BYTE_SIZE_TYPE; + + enum class SoAColumnType { + scalar = _VALUE_TYPE_SCALAR, + column = _VALUE_TYPE_COLUMN, + eigen = _VALUE_TYPE_EIGEN_COLUMN + }; + + namespace RestrictQualify { + constexpr bool enabled = true; + constexpr bool disabled = false; + constexpr bool Default = disabled; + } // namespace RestrictQualify + + namespace RangeChecking { + constexpr bool enabled = true; + constexpr bool disabled = false; + constexpr bool Default = disabled; + } // namespace RangeChecking + + template + struct add_restrict {}; + + template + struct add_restrict { + using Value = T; + using Pointer = T* __restrict__; + using Reference = T& __restrict__; + using ConstValue = const T; + using PointerToConst = const T* __restrict__; + using ReferenceToConst = const T& __restrict__; + }; + + template + struct add_restrict { + using Value = T; + using Pointer = T*; + using Reference = T&; + using ConstValue = const T; + using PointerToConst = const T*; + using ReferenceToConst = const T&; + }; + + // Forward declarations + template + struct SoAConstParametersImpl; + + template + struct SoAParametersImpl; + + // Templated const parameter sets for scalars, columns and Eigen columns + template + struct SoAConstParametersImpl { + static constexpr SoAColumnType columnType = COLUMN_TYPE; + + using ValueType = T; + using ScalarType = T; + using TupleOrPointerType = const ValueType*; + + // default constructor + SoAConstParametersImpl() = default; + + // constructor from an address + SOA_HOST_DEVICE SOA_INLINE constexpr SoAConstParametersImpl(ValueType const* addr) : addr_(addr) {} + + // constructor from a non-const parameter set + SOA_HOST_DEVICE SOA_INLINE constexpr SoAConstParametersImpl(SoAParametersImpl const& o) + : addr_{o.addr_} {} + + static constexpr bool checkAlignment(ValueType* addr, byte_size_type alignment) { + return reinterpret_cast(addr) % alignment; + } + + public: + // scalar or column + ValueType const* addr_ = nullptr; + }; + + // Templated const parameter specialisation for Eigen columns + template + struct SoAConstParametersImpl { + static constexpr SoAColumnType columnType = SoAColumnType::eigen; + + using ValueType = T; + using ScalarType = typename T::Scalar; + using TupleOrPointerType = std::tuple; + + // default constructor + SoAConstParametersImpl() = default; + + // constructor from individual address and stride + SOA_HOST_DEVICE SOA_INLINE constexpr SoAConstParametersImpl(ScalarType const* addr, byte_size_type stride) + : addr_(addr), stride_(stride) {} + + // constructor from address and stride packed in a tuple + SOA_HOST_DEVICE SOA_INLINE constexpr SoAConstParametersImpl(TupleOrPointerType const& tuple) + : addr_(std::get<0>(tuple)), stride_(std::get<1>(tuple)) {} + + // constructor from a non-const parameter set + SOA_HOST_DEVICE SOA_INLINE constexpr SoAConstParametersImpl(SoAParametersImpl const& o) + : addr_{o.addr_}, stride_{o.stride_} {} + + static constexpr bool checkAlignment(TupleOrPointerType const& tuple, byte_size_type alignment) { + const auto& [addr, stride] = tuple; + return reinterpret_cast(addr) % alignment; + } + + public: + // address and stride + ScalarType const* addr_ = nullptr; + byte_size_type stride_ = 0; + }; + + // Matryoshka template to avoid commas inside macros + template + struct SoAConstParameters_ColumnType { + template + using DataType = SoAConstParametersImpl; + }; + + // Templated parameter sets for scalars, columns and Eigen columns + template + struct SoAParametersImpl { + static constexpr SoAColumnType columnType = COLUMN_TYPE; + + using ValueType = T; + using ScalarType = T; + using TupleOrPointerType = ValueType*; + + using ConstType = SoAConstParametersImpl; + friend ConstType; + + // default constructor + SoAParametersImpl() = default; + + // constructor from an address + SOA_HOST_DEVICE SOA_INLINE constexpr SoAParametersImpl(ValueType* addr) : addr_(addr) {} + + static constexpr bool checkAlignment(ValueType* addr, byte_size_type alignment) { + return reinterpret_cast(addr) % alignment; + } + + public: + // scalar or column + ValueType* addr_ = nullptr; + }; + + // Templated parameter specialisation for Eigen columns + template + struct SoAParametersImpl { + static constexpr SoAColumnType columnType = SoAColumnType::eigen; + + using ValueType = T; + using ScalarType = typename T::Scalar; + using TupleOrPointerType = std::tuple; + + using ConstType = SoAConstParametersImpl; + friend ConstType; + + // default constructor + SoAParametersImpl() = default; + + // constructor from individual address and stride + SOA_HOST_DEVICE SOA_INLINE constexpr SoAParametersImpl(ScalarType* addr, byte_size_type stride) + : addr_(addr), stride_(stride) {} + + // constructor from address and stride packed in a tuple + SOA_HOST_DEVICE SOA_INLINE constexpr SoAParametersImpl(TupleOrPointerType const& tuple) + : addr_(std::get<0>(tuple)), stride_(std::get<1>(tuple)) {} + + static constexpr bool checkAlignment(TupleOrPointerType const& tuple, byte_size_type alignment) { + const auto& [addr, stride] = tuple; + return reinterpret_cast(addr) % alignment; + } + + public: + // address and stride + ScalarType* addr_ = nullptr; + byte_size_type stride_ = 0; + }; + + // Matryoshka template to avoid commas inside macros + template + struct SoAParameters_ColumnType { + template + using DataType = SoAParametersImpl; + }; + + // Helper converting a const parameter set to a non-const parameter set, to be used only in the constructor of non-const "element" + namespace { + template + constexpr inline std::remove_const_t* non_const_ptr(T* p) { + return const_cast*>(p); + } + } // namespace + + template + SOA_HOST_DEVICE SOA_INLINE constexpr SoAParametersImpl const_cast_SoAParametersImpl( + SoAConstParametersImpl const& o) { + return SoAParametersImpl{non_const_ptr(o.addr_)}; + } + + template + SOA_HOST_DEVICE SOA_INLINE constexpr SoAParametersImpl const_cast_SoAParametersImpl( + SoAConstParametersImpl const& o) { + return SoAParametersImpl{non_const_ptr(o.addr_), o.stride_}; + } + + // Helper template managing the value at index idx within a column. + // The optional compile time alignment parameter enables informing the + // compiler of alignment (enforced by caller). + template + class SoAValue { + // Eigen is implemented in a specialization + static_assert(COLUMN_TYPE != SoAColumnType::eigen); + + public: + using Restr = add_restrict; + using Val = typename Restr::Value; + using Ptr = typename Restr::Pointer; + using Ref = typename Restr::Reference; + using PtrToConst = typename Restr::PointerToConst; + using RefToConst = typename Restr::ReferenceToConst; + + SOA_HOST_DEVICE SOA_INLINE SoAValue(size_type i, T* col) : idx_(i), col_(col) {} + + SOA_HOST_DEVICE SOA_INLINE SoAValue(size_type i, SoAParametersImpl params) + : idx_(i), col_(params.addr_) {} + + SOA_HOST_DEVICE SOA_INLINE Ref operator()() { + // Ptr type will add the restrict qualifyer if needed + Ptr col = alignedCol(); + return col[idx_]; + } + + SOA_HOST_DEVICE SOA_INLINE RefToConst operator()() const { + // PtrToConst type will add the restrict qualifyer if needed + PtrToConst col = alignedCol(); + return col[idx_]; + } + + SOA_HOST_DEVICE SOA_INLINE Ptr operator&() { return &alignedCol()[idx_]; } + + SOA_HOST_DEVICE SOA_INLINE PtrToConst operator&() const { return &alignedCol()[idx_]; } + + /* This was an attempt to implement the syntax + * + * old_value = view.x + * view.x = new_value + * + * instead of + * + * old_value = view.x() + * view.x() = new_value + * + * but it was found to break in some corner cases. + * We keep them commented out for the time being. + + SOA_HOST_DEVICE SOA_INLINE operator T&() { return col_[idx_]; } + + template + SOA_HOST_DEVICE SOA_INLINE Ref operator=(const T2& v) { + return alignedCol()[idx_] = v; + } + */ + + using valueType = Val; + + static constexpr auto valueSize = sizeof(T); + + private: + SOA_HOST_DEVICE SOA_INLINE Ptr alignedCol() const { + if constexpr (ALIGNMENT) { + return reinterpret_cast(__builtin_assume_aligned(col_, ALIGNMENT)); + } + return reinterpret_cast(col_); + } + + size_type idx_; + T* col_; + }; + + // Eigen/Core should be pre-included before the SoA headers to enable support for Eigen columns. +#ifdef EIGEN_WORLD_VERSION + // Helper template managing an Eigen-type value at index idx within a column. + template + class SoAValue { + public: + using Type = C; + using MapType = Eigen::Map>; + using CMapType = const Eigen::Map>; + using Restr = add_restrict; + using Val = typename Restr::Value; + using Ptr = typename Restr::Pointer; + using Ref = typename Restr::Reference; + using PtrToConst = typename Restr::PointerToConst; + using RefToConst = typename Restr::ReferenceToConst; + + SOA_HOST_DEVICE SOA_INLINE SoAValue(size_type i, typename C::Scalar* col, byte_size_type stride) + : val_(col + i, C::RowsAtCompileTime, C::ColsAtCompileTime, Eigen::InnerStride(stride)), + crCol_(col), + cVal_(crCol_ + i, C::RowsAtCompileTime, C::ColsAtCompileTime, Eigen::InnerStride(stride)), + stride_(stride) {} + + SOA_HOST_DEVICE SOA_INLINE SoAValue(size_type i, SoAParametersImpl params) + : val_(params.addr_ + i, + C::RowsAtCompileTime, + C::ColsAtCompileTime, + Eigen::InnerStride(params.stride_)), + crCol_(params.addr_), + cVal_(crCol_ + i, + C::RowsAtCompileTime, + C::ColsAtCompileTime, + Eigen::InnerStride(params.stride_)), + stride_(params.stride_) {} + + SOA_HOST_DEVICE SOA_INLINE MapType& operator()() { return val_; } + + SOA_HOST_DEVICE SOA_INLINE const CMapType& operator()() const { return cVal_; } + + SOA_HOST_DEVICE SOA_INLINE operator C() { return val_; } + + SOA_HOST_DEVICE SOA_INLINE operator const C() const { return cVal_; } + + SOA_HOST_DEVICE SOA_INLINE C* operator&() { return &val_; } + + SOA_HOST_DEVICE SOA_INLINE const C* operator&() const { return &cVal_; } + + template + SOA_HOST_DEVICE SOA_INLINE MapType& operator=(const C2& v) { + return val_ = v; + } + + using ValueType = typename C::Scalar; + static constexpr auto valueSize = sizeof(C::Scalar); + SOA_HOST_DEVICE SOA_INLINE byte_size_type stride() const { return stride_; } + + private: + MapType val_; + const Ptr crCol_; + CMapType cVal_; + byte_size_type stride_; + }; +#else + // Raise a compile-time error + template + class SoAValue { + static_assert(!sizeof(C), + "Eigen/Core should be pre-included before the SoA headers to enable support for Eigen columns."); + }; +#endif + + // Helper template managing a const value at index idx within a column. + template + class SoAConstValue { + // Eigen is implemented in a specialization + static_assert(COLUMN_TYPE != SoAColumnType::eigen); + + public: + using Restr = add_restrict; + using Val = typename Restr::Value; + using Ptr = typename Restr::Pointer; + using Ref = typename Restr::Reference; + using PtrToConst = typename Restr::PointerToConst; + using RefToConst = typename Restr::ReferenceToConst; + using Params = SoAParametersImpl; + using ConstParams = SoAConstParametersImpl; + + SOA_HOST_DEVICE SOA_INLINE SoAConstValue(size_type i, const T* col) : idx_(i), col_(col) {} + + SOA_HOST_DEVICE SOA_INLINE SoAConstValue(size_type i, SoAParametersImpl params) + : idx_(i), col_(params.addr_) {} + + SOA_HOST_DEVICE SOA_INLINE SoAConstValue(size_type i, SoAConstParametersImpl params) + : idx_(i), col_(params.addr_) {} + + SOA_HOST_DEVICE SOA_INLINE RefToConst operator()() const { + // Ptr type will add the restrict qualifyer if needed + PtrToConst col = alignedCol(); + return col[idx_]; + } + + SOA_HOST_DEVICE SOA_INLINE const T* operator&() const { return &alignedCol()[idx_]; } + + /* This was an attempt to implement the syntax + * + * old_value = view.x + * + * instead of + * + * old_value = view.x() + * + * but it was found to break in some corner cases. + * We keep them commented out for the time being. + + SOA_HOST_DEVICE SOA_INLINE operator T&() { return col_[idx_]; } + */ + + using valueType = T; + static constexpr auto valueSize = sizeof(T); + + private: + SOA_HOST_DEVICE SOA_INLINE PtrToConst alignedCol() const { + if constexpr (ALIGNMENT) { + return reinterpret_cast(__builtin_assume_aligned(col_, ALIGNMENT)); + } + return reinterpret_cast(col_); + } + + size_type idx_; + const T* col_; + }; + + // Eigen/Core should be pre-included before the SoA headers to enable support for Eigen columns. +#ifdef EIGEN_WORLD_VERSION + // Helper template managing a const Eigen-type value at index idx within a column. + template + class SoAConstValue { + public: + using Type = C; + using CMapType = Eigen::Map>; + using RefToConst = const CMapType&; + using ConstParams = SoAConstParametersImpl; + + SOA_HOST_DEVICE SOA_INLINE SoAConstValue(size_type i, typename C::Scalar* col, byte_size_type stride) + : crCol_(col), + cVal_(crCol_ + i, C::RowsAtCompileTime, C::ColsAtCompileTime, Eigen::InnerStride(stride)), + stride_(stride) {} + + SOA_HOST_DEVICE SOA_INLINE SoAConstValue(size_type i, SoAConstParametersImpl params) + : crCol_(params.addr_), + cVal_(crCol_ + i, + C::RowsAtCompileTime, + C::ColsAtCompileTime, + Eigen::InnerStride(params.stride_)), + stride_(params.stride_) {} + + SOA_HOST_DEVICE SOA_INLINE const CMapType& operator()() const { return cVal_; } + + SOA_HOST_DEVICE SOA_INLINE operator const C() const { return cVal_; } + + SOA_HOST_DEVICE SOA_INLINE const C* operator&() const { return &cVal_; } + + using ValueType = typename C::Scalar; + static constexpr auto valueSize = sizeof(C::Scalar); + + SOA_HOST_DEVICE SOA_INLINE byte_size_type stride() const { return stride_; } + + private: + const typename C::Scalar* __restrict__ crCol_; + CMapType cVal_; + byte_size_type stride_; + }; +#else + // Raise a compile-time error + template + class SoAConstValue { + static_assert(!sizeof(C), + "Eigen/Core should be pre-included before the SoA headers to enable support for Eigen columns."); + }; +#endif + + // Helper template to avoid commas inside macros +#ifdef EIGEN_WORLD_VERSION + template + struct EigenConstMapMaker { + using Type = Eigen::Map>; + + class DataHolder { + public: + DataHolder(const typename C::Scalar* data) : data_(data) {} + + EigenConstMapMaker::Type withStride(byte_size_type stride) { + return EigenConstMapMaker::Type( + data_, C::RowsAtCompileTime, C::ColsAtCompileTime, Eigen::InnerStride(stride)); + } + + private: + const typename C::Scalar* const data_; + }; + + static DataHolder withData(const typename C::Scalar* data) { return DataHolder(data); } + }; +#else + template + struct EigenConstMapMaker { + // Eigen/Core should be pre-included before the SoA headers to enable support for Eigen columns. + static_assert(!sizeof(C), + "Eigen/Core should be pre-included before the SoA headers to enable support for Eigen columns."); + }; +#endif + + // Helper function to compute aligned size + constexpr inline byte_size_type alignSize(byte_size_type size, byte_size_type alignment) { + return ((size + alignment - 1) / alignment) * alignment; + } + +} // namespace cms::soa + +#define SOA_SCALAR(TYPE, NAME) (_VALUE_TYPE_SCALAR, TYPE, NAME) +#define SOA_COLUMN(TYPE, NAME) (_VALUE_TYPE_COLUMN, TYPE, NAME) +#define SOA_EIGEN_COLUMN(TYPE, NAME) (_VALUE_TYPE_EIGEN_COLUMN, TYPE, NAME) + +/* Iterate on the macro MACRO and return the result as a comma separated list */ +#define _ITERATE_ON_ALL_COMMA(MACRO, DATA, ...) \ + BOOST_PP_TUPLE_ENUM(BOOST_PP_SEQ_TO_TUPLE(_ITERATE_ON_ALL(MACRO, DATA, __VA_ARGS__))) + +/* Iterate MACRO on all elements */ +#define _ITERATE_ON_ALL(MACRO, DATA, ...) BOOST_PP_SEQ_FOR_EACH(MACRO, DATA, BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__)) + +/* Switch on macros depending on scalar / column type */ +#define _SWITCH_ON_TYPE(VALUE_TYPE, IF_SCALAR, IF_COLUMN, IF_EIGEN_COLUMN) \ + BOOST_PP_IF( \ + BOOST_PP_EQUAL(VALUE_TYPE, _VALUE_TYPE_SCALAR), \ + IF_SCALAR, \ + BOOST_PP_IF( \ + BOOST_PP_EQUAL(VALUE_TYPE, _VALUE_TYPE_COLUMN), \ + IF_COLUMN, \ + BOOST_PP_IF(BOOST_PP_EQUAL(VALUE_TYPE, _VALUE_TYPE_EIGEN_COLUMN), IF_EIGEN_COLUMN, BOOST_PP_EMPTY()))) + +namespace cms::soa { + + /* Column accessors: templates implementing the global accesors (soa::x() and soa::x(index) */ + enum class SoAAccessType : bool { mutableAccess, constAccess }; + + template + struct SoAColumnAccessorsImpl {}; + + // TODO from Eric Cano: + // - add alignment support + // - SFINAE-based const/non const variants + + // Column + template + struct SoAColumnAccessorsImpl { + //SOA_HOST_DEVICE SOA_INLINE SoAColumnAccessorsImpl(T* baseAddress) : baseAddress_(baseAddress) {} + SOA_HOST_DEVICE SOA_INLINE SoAColumnAccessorsImpl(const SoAParametersImpl& params) + : params_(params) {} + SOA_HOST_DEVICE SOA_INLINE T* operator()() { return params_.addr_; } + using NoParamReturnType = T*; + SOA_HOST_DEVICE SOA_INLINE T& operator()(size_type index) { return params_.addr_[index]; } + + private: + SoAParametersImpl params_; + }; + + // Const column + template + struct SoAColumnAccessorsImpl { + SOA_HOST_DEVICE SOA_INLINE SoAColumnAccessorsImpl(const SoAConstParametersImpl& params) + : params_(params) {} + SOA_HOST_DEVICE SOA_INLINE const T* operator()() const { return params_.addr_; } + using NoParamReturnType = const T*; + SOA_HOST_DEVICE SOA_INLINE T operator()(size_type index) const { return params_.addr_[index]; } + + private: + SoAConstParametersImpl params_; + }; + + // Scalar + template + struct SoAColumnAccessorsImpl { + SOA_HOST_DEVICE SOA_INLINE SoAColumnAccessorsImpl(const SoAParametersImpl& params) + : params_(params) {} + SOA_HOST_DEVICE SOA_INLINE T& operator()() { return *params_.addr_; } + using NoParamReturnType = T&; + SOA_HOST_DEVICE SOA_INLINE void operator()(size_type index) const { + assert(false && "Indexed access impossible for SoA scalars."); + } + + private: + SoAParametersImpl params_; + }; + + // Const scalar + template + struct SoAColumnAccessorsImpl { + SOA_HOST_DEVICE SOA_INLINE SoAColumnAccessorsImpl(const SoAConstParametersImpl& params) + : params_(params) {} + SOA_HOST_DEVICE SOA_INLINE T operator()() const { return *params_.addr_; } + using NoParamReturnType = T; + SOA_HOST_DEVICE SOA_INLINE void operator()(size_type index) const { + assert(false && "Indexed access impossible for SoA scalars."); + } + + private: + SoAConstParametersImpl params_; + }; + + // Eigen-type + template + struct SoAColumnAccessorsImpl { + //SOA_HOST_DEVICE SOA_INLINE SoAColumnAccessorsImpl(T* baseAddress) : baseAddress_(baseAddress) {} + SOA_HOST_DEVICE SOA_INLINE SoAColumnAccessorsImpl(const SoAParametersImpl& params) + : params_(params) {} + SOA_HOST_DEVICE SOA_INLINE typename T::Scalar* operator()() { return params_.addr_; } + using NoParamReturnType = typename T::Scalar*; + //SOA_HOST_DEVICE SOA_INLINE T& operator()(size_type index) { return params_.addr_[index]; } + + private: + SoAParametersImpl params_; + }; + + // Const Eigen-type + template + struct SoAColumnAccessorsImpl { + SOA_HOST_DEVICE SOA_INLINE SoAColumnAccessorsImpl(const SoAConstParametersImpl& params) + : params_(params) {} + SOA_HOST_DEVICE SOA_INLINE const typename T::Scalar* operator()() const { return params_.addr_; } + using NoParamReturnType = typename T::Scalar*; + //SOA_HOST_DEVICE SOA_INLINE T operator()(size_type index) const { return params_.addr_[index]; } + + private: + SoAConstParametersImpl params_; + }; + + /* A helper template stager to avoid commas inside macros */ + template + struct SoAAccessors { + template + struct ColumnType { + template + struct AccessType : public SoAColumnAccessorsImpl { + using SoAColumnAccessorsImpl::SoAColumnAccessorsImpl; + }; + }; + }; + + /* Enum parameters allowing templated control of layout/view behaviors */ + /* Alignment enforcement verifies every column is aligned, and + * hints the compiler that it can expect column pointers to be aligned */ + struct AlignmentEnforcement { + static constexpr bool relaxed = false; + static constexpr bool enforced = true; + }; + + struct CacheLineSize { + static constexpr byte_size_type NvidiaGPU = 128; + static constexpr byte_size_type IntelCPU = 64; + static constexpr byte_size_type AMDCPU = 64; + static constexpr byte_size_type ARMCPU = 64; + static constexpr byte_size_type defaultSize = NvidiaGPU; + }; + +} // namespace cms::soa + +// Small wrapper for stream insertion of SoA printing +template >> +SOA_HOST_ONLY std::ostream& operator<<(std::ostream& os, const SOA& soa) { + soa.soaToStreamInternal(os); + return os; +} + +#endif // DataFormats_SoATemplate_interface_SoACommon_h diff --git a/DataFormats/SoATemplate/interface/SoALayout.h b/DataFormats/SoATemplate/interface/SoALayout.h new file mode 100644 index 0000000000000..a4c429ad6e977 --- /dev/null +++ b/DataFormats/SoATemplate/interface/SoALayout.h @@ -0,0 +1,559 @@ +#ifndef DataFormats_SoATemplate_interface_SoALayout_h +#define DataFormats_SoATemplate_interface_SoALayout_h + +/* + * Structure-of-Arrays template with "columns" and "scalars", defined through preprocessor macros, + * with compile-time size and alignment, and accessors to the "rows" and "columns". + */ + +#include +#include + +#include "SoACommon.h" +#include "SoAView.h" + +/* dump SoA fields information; these should expand to, for columns: + * Example: + * GENERATE_SOA_LAYOUT(SoA, + * // predefined static scalars + * // size_t size; + * // size_t alignment; + * + * // columns: one value per element + * SOA_COLUMN(double, x), + * SOA_COLUMN(double, y), + * SOA_COLUMN(double, z), + * SOA_EIGEN_COLUMN(Eigen::Vector3d, a), + * SOA_EIGEN_COLUMN(Eigen::Vector3d, b), + * SOA_EIGEN_COLUMN(Eigen::Vector3d, r), + * SOA_COLUMN(uint16_t, colour), + * SOA_COLUMN(int32_t, value), + * SOA_COLUMN(double *, py), + * SOA_COLUMN(uint32_t, count), + * SOA_COLUMN(uint32_t, anotherCount), + * + * // scalars: one value for the whole structure + * SOA_SCALAR(const char *, description), + * SOA_SCALAR(uint32_t, someNumber) + * ); + * + * dumps as: + * SoA(32, 64): + * sizeof(SoA): 152 + * Column x_ at offset 0 has size 256 and padding 0 + * Column y_ at offset 256 has size 256 and padding 0 + * Column z_ at offset 512 has size 256 and padding 0 + * Eigen value a_ at offset 768 has dimension (3 x 1) and per column size 256 and padding 0 + * Eigen value b_ at offset 1536 has dimension (3 x 1) and per column size 256 and padding 0 + * Eigen value r_ at offset 2304 has dimension (3 x 1) and per column size 256 and padding 0 + * Column colour_ at offset 3072 has size 64 and padding 0 + * Column value_ at offset 3136 has size 128 and padding 0 + * Column py_ at offset 3264 has size 256 and padding 0 + * Column count_ at offset 3520 has size 128 and padding 0 + * Column anotherCount_ at offset 3648 has size 128 and padding 0 + * Scalar description_ at offset 3776 has size 8 and padding 56 + * Scalar someNumber_ at offset 3840 has size 4 and padding 60 + * Final offset = 3904 computeDataSize(...): 3904 + * + */ + +// clang-format off +#define _DECLARE_SOA_STREAM_INFO_IMPL(VALUE_TYPE, CPP_TYPE, NAME) \ + _SWITCH_ON_TYPE( \ + VALUE_TYPE, \ + /* Dump scalar */ \ + os << " Scalar " BOOST_PP_STRINGIZE(NAME) " at offset " << offset << " has size " << sizeof(CPP_TYPE) \ + << " and padding " << ((sizeof(CPP_TYPE) - 1) / alignment + 1) * alignment - sizeof(CPP_TYPE) \ + << std::endl; \ + offset += ((sizeof(CPP_TYPE) - 1) / alignment + 1) * alignment; \ + , \ + /* Dump column */ \ + os << " Column " BOOST_PP_STRINGIZE(NAME) " at offset " << offset << " has size " \ + << sizeof(CPP_TYPE) * nElements_ << " and padding " \ + << cms::soa::alignSize(nElements_ * sizeof(CPP_TYPE), alignment) - (nElements_ * sizeof(CPP_TYPE)) \ + << std::endl; \ + offset += cms::soa::alignSize(nElements_ * sizeof(CPP_TYPE), alignment); \ + , \ + /* Dump Eigen column */ \ + os << " Eigen value " BOOST_PP_STRINGIZE(NAME) " at offset " << offset << " has dimension " \ + << "(" << CPP_TYPE::RowsAtCompileTime << " x " << CPP_TYPE::ColsAtCompileTime << ")" \ + << " and per column size " \ + << sizeof(CPP_TYPE::Scalar) * nElements_ \ + << " and padding " \ + << cms::soa::alignSize(nElements_ * sizeof(CPP_TYPE::Scalar), alignment) \ + - (nElements_ * sizeof(CPP_TYPE::Scalar)) \ + << std::endl; \ + offset += cms::soa::alignSize(nElements_ * sizeof(CPP_TYPE::Scalar), alignment) \ + * CPP_TYPE::RowsAtCompileTime * CPP_TYPE::ColsAtCompileTime; \ + ) +// clang-format on + +#define _DECLARE_SOA_STREAM_INFO(R, DATA, TYPE_NAME) BOOST_PP_EXPAND(_DECLARE_SOA_STREAM_INFO_IMPL TYPE_NAME) + +/** + * Metadata member computing column pitch + */ +// clang-format off +#define _DEFINE_METADATA_MEMBERS_IMPL(VALUE_TYPE, CPP_TYPE, NAME) \ + _SWITCH_ON_TYPE(VALUE_TYPE, \ + /* Scalar */ \ + byte_size_type BOOST_PP_CAT(NAME, Pitch()) const { \ + return cms::soa::alignSize(sizeof(CPP_TYPE), ParentClass::alignment); \ + } \ + using BOOST_PP_CAT(TypeOf_, NAME) = CPP_TYPE; \ + constexpr static cms::soa::SoAColumnType BOOST_PP_CAT(ColumnTypeOf_, NAME) = cms::soa::SoAColumnType::scalar; \ + SOA_HOST_DEVICE SOA_INLINE \ + CPP_TYPE const* BOOST_PP_CAT(addressOf_, NAME)() const { \ + return parent_.metadata().BOOST_PP_CAT(parametersOf_, NAME)().addr_; \ + } \ + using BOOST_PP_CAT(ParametersTypeOf_, NAME) = \ + cms::soa::SoAParameters_ColumnType::DataType; \ + SOA_HOST_DEVICE SOA_INLINE \ + BOOST_PP_CAT(ParametersTypeOf_, NAME) BOOST_PP_CAT(parametersOf_, NAME)() const { \ + return BOOST_PP_CAT(ParametersTypeOf_, NAME) (parent_.BOOST_PP_CAT(NAME, _)); \ + } \ + SOA_HOST_DEVICE SOA_INLINE \ + CPP_TYPE* BOOST_PP_CAT(addressOf_, NAME)() { \ + return parent_.metadata().BOOST_PP_CAT(parametersOf_, NAME)().addr_; \ + }, \ + /* Column */ \ + using BOOST_PP_CAT(ParametersTypeOf_, NAME) = \ + cms::soa::SoAParameters_ColumnType::DataType; \ + SOA_HOST_DEVICE SOA_INLINE \ + BOOST_PP_CAT(ParametersTypeOf_, NAME) BOOST_PP_CAT(parametersOf_, NAME)() const { \ + return BOOST_PP_CAT(ParametersTypeOf_, NAME) (parent_.BOOST_PP_CAT(NAME, _)); \ + } \ + SOA_HOST_DEVICE SOA_INLINE \ + CPP_TYPE const* BOOST_PP_CAT(addressOf_, NAME)() const { \ + return parent_.metadata().BOOST_PP_CAT(parametersOf_, NAME)().addr_; \ + } \ + SOA_HOST_DEVICE SOA_INLINE \ + CPP_TYPE* BOOST_PP_CAT(addressOf_, NAME)() { \ + return parent_.metadata().BOOST_PP_CAT(parametersOf_, NAME)().addr_; \ + } \ + SOA_HOST_DEVICE SOA_INLINE \ + byte_size_type BOOST_PP_CAT(NAME, Pitch()) const { \ + return cms::soa::alignSize(parent_.nElements_ * sizeof(CPP_TYPE), ParentClass::alignment); \ + } \ + using BOOST_PP_CAT(TypeOf_, NAME) = CPP_TYPE; \ + constexpr static cms::soa::SoAColumnType BOOST_PP_CAT(ColumnTypeOf_, NAME) = cms::soa::SoAColumnType::column;, \ + /* Eigen column */ \ + using BOOST_PP_CAT(ParametersTypeOf_, NAME) = \ + cms::soa::SoAParameters_ColumnType::DataType; \ + SOA_HOST_DEVICE SOA_INLINE \ + BOOST_PP_CAT(ParametersTypeOf_, NAME) BOOST_PP_CAT(parametersOf_, NAME)() const { \ + return BOOST_PP_CAT(ParametersTypeOf_, NAME) ( \ + parent_.BOOST_PP_CAT(NAME, _), \ + parent_.BOOST_PP_CAT(NAME, Stride_)); \ + } \ + SOA_HOST_DEVICE SOA_INLINE \ + byte_size_type BOOST_PP_CAT(NAME, Pitch()) const { \ + return cms::soa::alignSize(parent_.nElements_ * sizeof(CPP_TYPE::Scalar), ParentClass::alignment) \ + * CPP_TYPE::RowsAtCompileTime * CPP_TYPE::ColsAtCompileTime; \ + } \ + using BOOST_PP_CAT(TypeOf_, NAME) = CPP_TYPE ; \ + constexpr static cms::soa::SoAColumnType BOOST_PP_CAT(ColumnTypeOf_, NAME) = cms::soa::SoAColumnType::eigen; \ + SOA_HOST_DEVICE SOA_INLINE \ + CPP_TYPE::Scalar const* BOOST_PP_CAT(addressOf_, NAME)() const { \ + return parent_.metadata().BOOST_PP_CAT(parametersOf_, NAME)().addr_; \ + } \ + SOA_HOST_DEVICE SOA_INLINE \ + CPP_TYPE::Scalar* BOOST_PP_CAT(addressOf_, NAME)() { \ + return parent_.metadata().BOOST_PP_CAT(parametersOf_, NAME)().addr_; \ + } \ +) +// clang-format on +#define _DEFINE_METADATA_MEMBERS(R, DATA, TYPE_NAME) _DEFINE_METADATA_MEMBERS_IMPL TYPE_NAME + +// clang-format off +#define _DECLARE_MEMBER_TRIVIAL_CONSTRUCTION_IMPL(VALUE_TYPE, CPP_TYPE, NAME) \ + _SWITCH_ON_TYPE(VALUE_TYPE, \ + /* Scalar */ \ + (BOOST_PP_CAT(NAME, _)(nullptr)), \ + /* Column */ \ + (BOOST_PP_CAT(NAME, _)(nullptr)), \ + /* Eigen column */ \ + (BOOST_PP_CAT(NAME, _)(nullptr)) \ + (BOOST_PP_CAT(NAME, Stride_)(0)) \ + ) +// clang-format on + +#define _DECLARE_MEMBER_TRIVIAL_CONSTRUCTION(R, DATA, TYPE_NAME) \ + BOOST_PP_EXPAND(_DECLARE_MEMBER_TRIVIAL_CONSTRUCTION_IMPL TYPE_NAME) + +/** + * Declare the value_element data members + */ +// clang-format off +#define _DEFINE_VALUE_ELEMENT_MEMBERS_IMPL(VALUE_TYPE, CPP_TYPE, NAME) \ + _SWITCH_ON_TYPE(VALUE_TYPE, \ + /* Scalar (empty) */ \ + , \ + /* Column */ \ + CPP_TYPE NAME; \ + , \ + /* Eigen column */ \ + CPP_TYPE NAME; \ + ) +// clang-format on + +#define _DEFINE_VALUE_ELEMENT_MEMBERS(R, DATA, TYPE_NAME) _DEFINE_VALUE_ELEMENT_MEMBERS_IMPL TYPE_NAME + +/** + * List of data members in the value_element constructor arguments + */ +// clang-format off +#define _VALUE_ELEMENT_CTOR_ARGS_IMPL(VALUE_TYPE, CPP_TYPE, NAME) \ + _SWITCH_ON_TYPE(VALUE_TYPE, \ + /* Scalar (empty) */ \ + , \ + /* Column */ \ + (CPP_TYPE NAME), \ + /* Eigen column */ \ + (CPP_TYPE NAME) \ + ) +// clang-format on + +#define _VALUE_ELEMENT_CTOR_ARGS(R, DATA, TYPE_NAME) BOOST_PP_EXPAND(_VALUE_ELEMENT_CTOR_ARGS_IMPL TYPE_NAME) + +/** + * List-initalise the value_element data members + */ +// clang-format off +#define _VALUE_ELEMENT_INITIALIZERS_IMPL(VALUE_TYPE, CPP_TYPE, NAME) \ + _SWITCH_ON_TYPE(VALUE_TYPE, \ + /* Scalar (empty) */ \ + , \ + /* Column */ \ + (NAME{NAME}), \ + /* Eigen column */ \ + (NAME{NAME}) \ + ) +// clang-format on + +#define _VALUE_ELEMENT_INITIALIZERS(R, DATA, TYPE_NAME) BOOST_PP_EXPAND(_VALUE_ELEMENT_INITIALIZERS_IMPL TYPE_NAME) + +/** + * Computation of the column or scalar pointer location in the memory layout (at SoA construction time) + */ +// clang-format off +#define _ASSIGN_SOA_COLUMN_OR_SCALAR_IMPL(VALUE_TYPE, CPP_TYPE, NAME) \ + _SWITCH_ON_TYPE(VALUE_TYPE, \ + /* Scalar */ \ + BOOST_PP_CAT(NAME, _) = reinterpret_cast(curMem); \ + curMem += cms::soa::alignSize(sizeof(CPP_TYPE), alignment); \ + , \ + /* Column */ \ + BOOST_PP_CAT(NAME, _) = reinterpret_cast(curMem); \ + curMem += cms::soa::alignSize(nElements_ * sizeof(CPP_TYPE), alignment); \ + , \ + /* Eigen column */ \ + BOOST_PP_CAT(NAME, _) = reinterpret_cast(curMem); \ + curMem += cms::soa::alignSize(nElements_ * sizeof(CPP_TYPE::Scalar), alignment) * CPP_TYPE::RowsAtCompileTime \ + * CPP_TYPE::ColsAtCompileTime; \ + BOOST_PP_CAT(NAME, Stride_) = cms::soa::alignSize(nElements_ * sizeof(CPP_TYPE::Scalar), alignment) \ + / sizeof(CPP_TYPE::Scalar); \ + ) \ + if constexpr (alignmentEnforcement == AlignmentEnforcement::enforced) \ + if (reinterpret_cast(BOOST_PP_CAT(NAME, _)) % alignment) \ + throw std::runtime_error("In layout constructor: misaligned column: " #NAME); +// clang-format on + +#define _ASSIGN_SOA_COLUMN_OR_SCALAR(R, DATA, TYPE_NAME) _ASSIGN_SOA_COLUMN_OR_SCALAR_IMPL TYPE_NAME + +/** + * Computation of the column or scalar size for SoA size computation + */ +// clang-format off +#define _ACCUMULATE_SOA_ELEMENT_IMPL(VALUE_TYPE, CPP_TYPE, NAME) \ + _SWITCH_ON_TYPE(VALUE_TYPE, \ + /* Scalar */ \ + ret += cms::soa::alignSize(sizeof(CPP_TYPE), alignment); \ + , \ + /* Column */ \ + ret += cms::soa::alignSize(nElements * sizeof(CPP_TYPE), alignment); \ + , \ + /* Eigen column */ \ + ret += cms::soa::alignSize(nElements * sizeof(CPP_TYPE::Scalar), alignment) * CPP_TYPE::RowsAtCompileTime \ + * CPP_TYPE::ColsAtCompileTime; \ + ) +// clang-format on + +#define _ACCUMULATE_SOA_ELEMENT(R, DATA, TYPE_NAME) _ACCUMULATE_SOA_ELEMENT_IMPL TYPE_NAME + +/** + * Direct access to column pointer and indexed access + */ +// clang-format off +#define _DECLARE_SOA_ACCESSOR_IMPL(VALUE_TYPE, CPP_TYPE, NAME) \ + _SWITCH_ON_TYPE(VALUE_TYPE, \ + /* Scalar */ \ + SOA_HOST_DEVICE SOA_INLINE CPP_TYPE& NAME() { return *BOOST_PP_CAT(NAME, _); } \ + , \ + /* Column */ \ + SOA_HOST_DEVICE SOA_INLINE CPP_TYPE* NAME() { return BOOST_PP_CAT(NAME, _); } \ + SOA_HOST_DEVICE SOA_INLINE CPP_TYPE& NAME(size_type index) { return BOOST_PP_CAT(NAME, _)[index]; } \ + , \ + /* Eigen column */ \ + /* TODO: implement*/ \ + BOOST_PP_EMPTY() \ + ) +// clang-format on + +#define _DECLARE_SOA_ACCESSOR(R, DATA, TYPE_NAME) BOOST_PP_EXPAND(_DECLARE_SOA_ACCESSOR_IMPL TYPE_NAME) + +/** + * Direct access to column pointer (const) and indexed access. + */ +// clang-format off +#define _DECLARE_SOA_CONST_ACCESSOR_IMPL(VALUE_TYPE, CPP_TYPE, NAME) \ + _SWITCH_ON_TYPE(VALUE_TYPE, \ + /* Scalar */ \ + SOA_HOST_DEVICE SOA_INLINE CPP_TYPE NAME() const { return *(BOOST_PP_CAT(NAME, _)); } \ + , \ + /* Column */ \ + SOA_HOST_DEVICE SOA_INLINE CPP_TYPE const* NAME() const { return BOOST_PP_CAT(NAME, _); } \ + SOA_HOST_DEVICE SOA_INLINE CPP_TYPE NAME(size_type index) const { return *(BOOST_PP_CAT(NAME, _) + index); } \ + , \ + /* Eigen column */ \ + SOA_HOST_DEVICE SOA_INLINE CPP_TYPE::Scalar const* NAME() const { return BOOST_PP_CAT(NAME, _); } \ + SOA_HOST_DEVICE SOA_INLINE size_type BOOST_PP_CAT(NAME, Stride)() { return BOOST_PP_CAT(NAME, Stride_); } \ + ) +// clang-format on + +#define _DECLARE_SOA_CONST_ACCESSOR(R, DATA, TYPE_NAME) BOOST_PP_EXPAND(_DECLARE_SOA_CONST_ACCESSOR_IMPL TYPE_NAME) + +/** + * SoA member ROOT streamer read (column pointers). + */ +// clang-format off +#define _STREAMER_READ_SOA_DATA_MEMBER_IMPL(VALUE_TYPE, CPP_TYPE, NAME) \ + _SWITCH_ON_TYPE(VALUE_TYPE, \ + /* Scalar */ \ + /* TODO: implement*/ \ + , \ + /* Column */ \ + memcpy(BOOST_PP_CAT(NAME, _), onfile.BOOST_PP_CAT(NAME, _), sizeof(CPP_TYPE) * onfile.nElements_); \ + , \ + /* Eigen column */ \ + /* TODO: implement*/ \ + ) +// clang-format on + +#define _STREAMER_READ_SOA_DATA_MEMBER(R, DATA, TYPE_NAME) \ + BOOST_PP_EXPAND(_STREAMER_READ_SOA_DATA_MEMBER_IMPL TYPE_NAME) + +/** + * SoA class member declaration (column pointers). + */ +// clang-format off +#define _DECLARE_SOA_DATA_MEMBER_IMPL(VALUE_TYPE, CPP_TYPE, NAME) \ + _SWITCH_ON_TYPE(VALUE_TYPE, \ + /* Scalar */ \ + CPP_TYPE* BOOST_PP_CAT(NAME, _) = nullptr; \ + , \ + /* Column */ \ + CPP_TYPE * BOOST_PP_CAT(NAME, _) = nullptr; \ + , \ + /* Eigen column */ \ + CPP_TYPE::Scalar * BOOST_PP_CAT(NAME, _) = nullptr; \ + byte_size_type BOOST_PP_CAT(NAME, Stride_) = 0; \ + ) +// clang-format on + +#define _DECLARE_SOA_DATA_MEMBER(R, DATA, TYPE_NAME) BOOST_PP_EXPAND(_DECLARE_SOA_DATA_MEMBER_IMPL TYPE_NAME) + +#ifdef DEBUG +#define _DO_RANGECHECK true +#else +#define _DO_RANGECHECK false +#endif + +/* + * A macro defining a SoA layout (collection of scalars and columns of equal lengths) + */ +// clang-format off +#define GENERATE_SOA_LAYOUT(CLASS, ...) \ + template \ + struct CLASS { \ + /* these could be moved to an external type trait to free up the symbol names */ \ + using self_type = CLASS; \ + using AlignmentEnforcement = cms::soa::AlignmentEnforcement; \ + \ + /* For CUDA applications, we align to the 128 bytes of the cache lines. \ + * See https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#global-memory-3-0 this is still valid \ + * up to compute capability 8.X. \ + */ \ + using size_type = cms::soa::size_type; \ + using byte_size_type = cms::soa::byte_size_type; \ + constexpr static byte_size_type defaultAlignment = 128; \ + constexpr static byte_size_type alignment = ALIGNMENT; \ + constexpr static bool alignmentEnforcement = ALIGNMENT_ENFORCEMENT; \ + constexpr static byte_size_type conditionalAlignment = \ + alignmentEnforcement == cms::soa::AlignmentEnforcement::enforced ? alignment : 0; \ + /* Those typedefs avoid having commas in macros (which is problematic) */ \ + template \ + using SoAValueWithConf = cms::soa::SoAValue; \ + \ + template \ + using SoAConstValueWithConf = cms::soa::SoAConstValue; \ + \ + template \ + struct ViewTemplateFreeParams; \ + \ + /* dump the SoA internal structure */ \ + SOA_HOST_ONLY \ + void soaToStreamInternal(std::ostream & os) const { \ + os << #CLASS "(" << nElements_ << " elements, byte alignement= " << alignment << ", @"<< mem_ <<"): " \ + << std::endl; \ + os << " sizeof(" #CLASS "): " << sizeof(CLASS) << std::endl; \ + byte_size_type offset = 0; \ + _ITERATE_ON_ALL(_DECLARE_SOA_STREAM_INFO, ~, __VA_ARGS__) \ + os << "Final offset = " << offset << " computeDataSize(...): " << computeDataSize(nElements_) \ + << std::endl; \ + os << std::endl; \ + } \ + \ + /* Helper function used by caller to externally allocate the storage */ \ + static constexpr byte_size_type computeDataSize(size_type nElements) { \ + byte_size_type ret = 0; \ + _ITERATE_ON_ALL(_ACCUMULATE_SOA_ELEMENT, ~, __VA_ARGS__) \ + return ret; \ + } \ + \ + /** \ + * Helper/friend class allowing SoA introspection. \ + */ \ + struct Metadata { \ + friend CLASS; \ + SOA_HOST_DEVICE SOA_INLINE size_type size() const { return parent_.nElements_; } \ + SOA_HOST_DEVICE SOA_INLINE byte_size_type byteSize() const { return parent_.byteSize_; } \ + SOA_HOST_DEVICE SOA_INLINE byte_size_type alignment() const { return CLASS::alignment; } \ + SOA_HOST_DEVICE SOA_INLINE std::byte* data() { return parent_.mem_; } \ + SOA_HOST_DEVICE SOA_INLINE const std::byte* data() const { return parent_.mem_; } \ + SOA_HOST_DEVICE SOA_INLINE std::byte* nextByte() const { return parent_.mem_ + parent_.byteSize_; } \ + SOA_HOST_DEVICE SOA_INLINE CLASS cloneToNewAddress(std::byte* addr) const { \ + return CLASS(addr, parent_.nElements_); \ + } \ + \ + _ITERATE_ON_ALL(_DEFINE_METADATA_MEMBERS, ~, __VA_ARGS__) \ + \ + struct value_element { \ + SOA_HOST_DEVICE SOA_INLINE value_element( \ + _ITERATE_ON_ALL_COMMA(_VALUE_ELEMENT_CTOR_ARGS, ~, __VA_ARGS__) \ + ) : \ + _ITERATE_ON_ALL_COMMA(_VALUE_ELEMENT_INITIALIZERS, ~, __VA_ARGS__) \ + {} \ + \ + _ITERATE_ON_ALL(_DEFINE_VALUE_ELEMENT_MEMBERS, ~, __VA_ARGS__) \ + }; \ + \ + Metadata& operator=(const Metadata&) = delete; \ + Metadata(const Metadata&) = delete; \ + \ + private: \ + SOA_HOST_DEVICE SOA_INLINE Metadata(const CLASS& parent) : parent_(parent) {} \ + const CLASS& parent_; \ + using ParentClass = CLASS; \ + }; \ + friend Metadata; \ + SOA_HOST_DEVICE SOA_INLINE const Metadata metadata() const { return Metadata(*this); } \ + SOA_HOST_DEVICE SOA_INLINE Metadata metadata() { return Metadata(*this); } \ + \ + /* Trivial constuctor */ \ + CLASS() \ + : mem_(nullptr), \ + nElements_(0), \ + byteSize_(0), \ + _ITERATE_ON_ALL_COMMA(_DECLARE_MEMBER_TRIVIAL_CONSTRUCTION, ~, __VA_ARGS__) {} \ + \ + /* Constructor relying on user provided storage (implementation shared with ROOT streamer) */ \ + SOA_HOST_ONLY CLASS(std::byte* mem, size_type nElements) : mem_(mem), nElements_(nElements), byteSize_(0) { \ + organizeColumnsFromBuffer(); \ + } \ + \ + private: \ + void organizeColumnsFromBuffer() { \ + if constexpr (alignmentEnforcement == cms::soa::AlignmentEnforcement::enforced) \ + if (reinterpret_cast(mem_) % alignment) \ + throw std::runtime_error("In " #CLASS "::" #CLASS ": misaligned buffer"); \ + auto curMem = mem_; \ + _ITERATE_ON_ALL(_ASSIGN_SOA_COLUMN_OR_SCALAR, ~, __VA_ARGS__) \ + /* Sanity check: we should have reached the computed size, only on host code */ \ + byteSize_ = computeDataSize(nElements_); \ + if (mem_ + byteSize_ != curMem) \ + throw std::runtime_error("In " #CLASS "::" #CLASS ": unexpected end pointer."); \ + } \ + \ + public: \ + /* Constructor relying on user provided storage */ \ + SOA_DEVICE_ONLY CLASS(bool devConstructor, std::byte* mem, size_type nElements) : \ + mem_(mem), \ + nElements_(nElements) \ + { \ + auto curMem = mem_; \ + _ITERATE_ON_ALL(_ASSIGN_SOA_COLUMN_OR_SCALAR, ~, __VA_ARGS__) \ + } \ + \ + /* ROOT read streamer */ \ + template \ + void ROOTReadStreamer(T & onfile) { \ + auto size = onfile.metadata().size(); \ + _ITERATE_ON_ALL(_STREAMER_READ_SOA_DATA_MEMBER, ~, __VA_ARGS__) \ + } \ + \ + /* dump the SoA internal structure */ \ + template \ + SOA_HOST_ONLY friend void dump(); \ + \ + private: \ + /* Range checker conditional to the macro _DO_RANGECHECK */ \ + SOA_HOST_DEVICE SOA_INLINE \ + void rangeCheck(size_type index) const { \ + if constexpr (_DO_RANGECHECK) { \ + if (index >= nElements_) { \ + printf("In " #CLASS "::rangeCheck(): index out of range: %zu with nElements: %zu\n", index, nElements_); \ + assert(false); \ + } \ + } \ + } \ + \ + /* data members */ \ + std::byte* mem_; \ + size_type nElements_; \ + byte_size_type byteSize_; \ + _ITERATE_ON_ALL(_DECLARE_SOA_DATA_MEMBER, ~, __VA_ARGS__) \ + /* Making the code conditional is problematic in macros as the commas will interfere with parameter lisings */ \ + /* So instead we make the code unconditional with paceholder names which are protected by a private protection. */ \ + /* This will be handled later as we handle the integration of the view as a subclass of the layout. */ \ + public: \ + _GENERATE_SOA_TRIVIAL_CONST_VIEW(CLASS, \ + SOA_VIEW_LAYOUT_LIST( \ + SOA_VIEW_LAYOUT(BOOST_PP_CAT(CLASS, _parametrized) , BOOST_PP_CAT(instance_, CLASS))), \ + SOA_VIEW_VALUE_LIST(_ITERATE_ON_ALL_COMMA( \ + _VIEW_FIELD_FROM_LAYOUT, BOOST_PP_CAT(instance_, CLASS), __VA_ARGS__))) \ + \ + template \ + using ConstViewTemplate = ConstViewTemplateFreeParams; \ + \ + _GENERATE_SOA_TRIVIAL_VIEW(CLASS, \ + SOA_VIEW_LAYOUT_LIST( \ + SOA_VIEW_LAYOUT(BOOST_PP_CAT(CLASS, _parametrized), BOOST_PP_CAT(instance_, CLASS))), \ + SOA_VIEW_VALUE_LIST(_ITERATE_ON_ALL_COMMA( \ + _VIEW_FIELD_FROM_LAYOUT, BOOST_PP_CAT(instance_, CLASS), __VA_ARGS__)), \ + __VA_ARGS__) \ + \ + template \ + using ViewTemplate = ViewTemplateFreeParams; \ + \ + using ConstView = ConstViewTemplate; \ + using View = ViewTemplate; \ + }; +// clang-format on + +#endif // DataFormats_SoATemplate_interface_SoALayout_h diff --git a/DataFormats/SoATemplate/interface/SoAView.h b/DataFormats/SoATemplate/interface/SoAView.h new file mode 100644 index 0000000000000..3e6423d5e83b8 --- /dev/null +++ b/DataFormats/SoATemplate/interface/SoAView.h @@ -0,0 +1,785 @@ +#ifndef DataFormats_SoATemplate_interface_SoAView_h +#define DataFormats_SoATemplate_interface_SoAView_h + +/* + * Structure-of-Arrays templates allowing access to a selection of scalars and columns from one + * or multiple SoA layouts or views. + * This template generator will allow handling subsets of columns from one or multiple SoA views or layouts. + */ + +#include "SoACommon.h" + +#define SOA_VIEW_LAYOUT(TYPE, NAME) (TYPE, NAME) + +#define SOA_VIEW_LAYOUT_LIST(...) __VA_ARGS__ + +#define SOA_VIEW_VALUE(LAYOUT_NAME, LAYOUT_MEMBER) (LAYOUT_NAME, LAYOUT_MEMBER, LAYOUT_MEMBER) + +#define SOA_VIEW_VALUE_RENAME(LAYOUT_NAME, LAYOUT_MEMBER, LOCAL_NAME) (LAYOUT_NAME, LAYOUT_MEMBER, LOCAL_NAME) + +#define SOA_VIEW_VALUE_LIST(...) __VA_ARGS__ + +/* + * A macro defining a SoA view (collection of columns from multiple layouts or views.) + * + * Usage: + * GENERATE_SOA_VIEW(PixelXYConstView, PixelXYView, + * SOA_VIEW_LAYOUT_LIST( + * SOA_VIEW_LAYOUT(PixelDigis, pixelDigis), + * SOA_VIEW_LAYOUT(PixelRecHitsLayout, pixelsRecHit) + * ), + * SOA_VIEW_VALUE_LIST( + * SOA_VIEW_VALUE_RENAME(pixelDigis, x, digisX), + * SOA_VIEW_VALUE_RENAME(pixelDigis, y, digisY), + * SOA_VIEW_VALUE_RENAME(pixelsRecHit, x, recHitsX), + * SOA_VIEW_VALUE_RENAME(pixelsRecHit, y, recHitsY) + * ) + * ); + * + */ + +namespace cms::soa { + + /* Traits for the different column type scenarios */ + /* Value traits passes the class as is in the case of column type and return + * an empty class with functions returning non-scalar as accessors. */ + template + struct ConstValueTraits : public C { + using C::C; + }; + + template + struct ConstValueTraits { + // Just take to SoAValue type to generate the right constructor. + SOA_HOST_DEVICE SOA_INLINE ConstValueTraits(size_type, const typename C::valueType*) {} + SOA_HOST_DEVICE SOA_INLINE ConstValueTraits(size_type, const typename C::Params&) {} + SOA_HOST_DEVICE SOA_INLINE ConstValueTraits(size_type, const typename C::ConstParams&) {} + // Any attempt to do anything with the "scalar" value a const element will fail. + }; + +} // namespace cms::soa + +/* + * Members definitions macros for views + */ + +/** + * Layout templates parametrization + */ +#define _DECLARE_VIEW_LAYOUT_PARAMETRIZED_TEMPLATE_IMPL(TYPE, NAME) \ + (using BOOST_PP_CAT(TYPE, _default) = BOOST_PP_CAT(TYPE, _StagedTemplates) < VIEW_ALIGNMENT, \ + VIEW_ALIGNMENT_ENFORCEMENT > ;) + +#define _DECLARE_VIEW_LAYOUT_PARAMETRIZED_TEMPLATE(R, DATA, TYPE_NAME) \ + BOOST_PP_EXPAND(_DECLARE_VIEW_LAYOUT_PARAMETRIZED_TEMPLATE_IMPL TYPE_NAME) + +/** + * Layout types aliasing for referencing by name + */ +#define _DECLARE_VIEW_LAYOUT_TYPE_ALIAS_IMPL(TYPE, NAME) using BOOST_PP_CAT(TypeOf_, NAME) = TYPE; + +#define _DECLARE_VIEW_LAYOUT_TYPE_ALIAS(R, DATA, TYPE_NAME) \ + BOOST_PP_EXPAND(_DECLARE_VIEW_LAYOUT_TYPE_ALIAS_IMPL TYPE_NAME) + +/** + * Member types aliasing for referencing by name + */ +// clang-format off +#define _DECLARE_VIEW_MEMBER_TYPE_ALIAS_IMPL(LAYOUT_NAME, LAYOUT_MEMBER, LOCAL_NAME, CAST) \ + using BOOST_PP_CAT(TypeOf_, LOCAL_NAME) = \ + typename BOOST_PP_CAT(TypeOf_, LAYOUT_NAME)::Metadata::BOOST_PP_CAT(TypeOf_, LAYOUT_MEMBER); \ + using BOOST_PP_CAT(ParametersTypeOf_, LOCAL_NAME) = \ + typename BOOST_PP_CAT(TypeOf_, LAYOUT_NAME)::Metadata::BOOST_PP_CAT(ParametersTypeOf_, LAYOUT_MEMBER); \ + constexpr static cms::soa::SoAColumnType BOOST_PP_CAT(ColumnTypeOf_, LOCAL_NAME) = \ + BOOST_PP_CAT(TypeOf_, LAYOUT_NAME)::Metadata::BOOST_PP_CAT(ColumnTypeOf_, LAYOUT_MEMBER); \ + SOA_HOST_DEVICE SOA_INLINE \ + const BOOST_PP_CAT(ParametersTypeOf_, LOCAL_NAME) BOOST_PP_CAT(parametersOf_, LOCAL_NAME)() const { \ + return CAST(parent_.BOOST_PP_CAT(LOCAL_NAME, Parameters_)); \ + }; +// clang-format on + +// DATA should be a function used to convert parent_.LOCAL_NAME ## Parameters_ to ParametersTypeOf_ ## LOCAL_NAME, or empty +#define _DECLARE_VIEW_MEMBER_TYPE_ALIAS(R, DATA, LAYOUT_MEMBER_NAME) \ + BOOST_PP_EXPAND(_DECLARE_VIEW_MEMBER_TYPE_ALIAS_IMPL BOOST_PP_TUPLE_PUSH_BACK(LAYOUT_MEMBER_NAME, DATA)) + +/** + * Member type pointers for referencing by name + */ +// clang-format off +#define _DECLARE_VIEW_MEMBER_POINTERS_IMPL(LAYOUT_NAME, LAYOUT_MEMBER, LOCAL_NAME) \ + SOA_HOST_DEVICE SOA_INLINE auto* BOOST_PP_CAT(addressOf_, LOCAL_NAME)() { \ + return BOOST_PP_CAT(parametersOf_, LOCAL_NAME)().addr_; \ + }; +// clang-format on + +#define _DECLARE_VIEW_MEMBER_POINTERS(R, DATA, LAYOUT_MEMBER_NAME) \ + BOOST_PP_EXPAND(_DECLARE_VIEW_MEMBER_POINTERS_IMPL LAYOUT_MEMBER_NAME) + +/** + * Member type const pointers for referencing by name + */ +// clang-format off +#define _DECLARE_VIEW_MEMBER_CONST_POINTERS_IMPL(LAYOUT_NAME, LAYOUT_MEMBER, LOCAL_NAME) \ + SOA_HOST_DEVICE SOA_INLINE auto const* BOOST_PP_CAT(addressOf_, LOCAL_NAME)() const { \ + return BOOST_PP_CAT(parametersOf_, LOCAL_NAME)().addr_; \ + }; +// clang-format on + +#define _DECLARE_VIEW_MEMBER_CONST_POINTERS(R, DATA, LAYOUT_MEMBER_NAME) \ + BOOST_PP_EXPAND(_DECLARE_VIEW_MEMBER_CONST_POINTERS_IMPL LAYOUT_MEMBER_NAME) + +/** + * Generator of parameters (layouts/views) for constructor by layouts/views. + */ +#define _DECLARE_VIEW_CONSTRUCTION_PARAMETERS_IMPL(LAYOUT_TYPE, LAYOUT_NAME, DATA) (DATA LAYOUT_TYPE & LAYOUT_NAME) + +#define _DECLARE_VIEW_CONSTRUCTION_PARAMETERS(R, DATA, TYPE_NAME) \ + BOOST_PP_EXPAND(_DECLARE_VIEW_CONSTRUCTION_PARAMETERS_IMPL BOOST_PP_TUPLE_PUSH_BACK(TYPE_NAME, DATA)) + +/** + * Generator of parameters for constructor by column. + */ +#define _DECLARE_VIEW_CONSTRUCTION_BYCOLUMN_PARAMETERS_IMPL(LAYOUT_NAME, LAYOUT_MEMBER, LOCAL_NAME, DATA) \ + (DATA typename BOOST_PP_CAT(Metadata::ParametersTypeOf_, LOCAL_NAME)::TupleOrPointerType LOCAL_NAME) + +#define _DECLARE_VIEW_CONSTRUCTION_BYCOLUMN_PARAMETERS(R, DATA, LAYOUT_MEMBER_NAME) \ + BOOST_PP_EXPAND( \ + _DECLARE_VIEW_CONSTRUCTION_BYCOLUMN_PARAMETERS_IMPL BOOST_PP_TUPLE_PUSH_BACK(LAYOUT_MEMBER_NAME, DATA)) + +/** + * Generator of member initialization from constructor. + * We use a lambda with auto return type to handle multiple possible return types. + */ +// clang-format off +#define _DECLARE_VIEW_MEMBER_INITIALIZERS_IMPL(LAYOUT, MEMBER, NAME) \ + (BOOST_PP_CAT(NAME, Parameters_)([&]() -> auto { \ + auto params = LAYOUT.metadata().BOOST_PP_CAT(parametersOf_, MEMBER)(); \ + if constexpr (alignmentEnforcement == AlignmentEnforcement::enforced) \ + if (reinterpret_cast(params.addr_) % alignment) \ + throw std::runtime_error("In constructor by layout: misaligned column: " #NAME); \ + return params; \ + }())) +// clang-format on + +#define _DECLARE_VIEW_MEMBER_INITIALIZERS(R, DATA, LAYOUT_MEMBER_NAME) \ + BOOST_PP_EXPAND(_DECLARE_VIEW_MEMBER_INITIALIZERS_IMPL LAYOUT_MEMBER_NAME) + +/** + * Generator of size computation for constructor. + * This is the per-layout part of the lambda checking they all have the same size. + */ +// clang-format off +#define _UPDATE_SIZE_OF_VIEW_IMPL(LAYOUT_TYPE, LAYOUT_NAME) \ + if (set) { \ + if (ret != LAYOUT_NAME.metadata().size()) \ + throw std::runtime_error("In constructor by layout: different sizes from layouts."); \ + } else { \ + ret = LAYOUT_NAME.metadata().size(); \ + set = true; \ + } +// clang-format on + +#define _UPDATE_SIZE_OF_VIEW(R, DATA, TYPE_NAME) BOOST_PP_EXPAND(_UPDATE_SIZE_OF_VIEW_IMPL TYPE_NAME) + +/** + * Generator of member initialization from constructor. + * We use a lambda with auto return type to handle multiple possible return types. + */ +// clang-format off +#define _DECLARE_VIEW_MEMBER_INITIALIZERS_BYCOLUMN_IMPL(LAYOUT, MEMBER, NAME) \ + ( \ + BOOST_PP_CAT(NAME, Parameters_)([&]() -> auto { \ + if constexpr (alignmentEnforcement == AlignmentEnforcement::enforced) \ + if (Metadata:: BOOST_PP_CAT(ParametersTypeOf_, NAME)::checkAlignment(NAME, alignment)) \ + throw std::runtime_error("In constructor by column: misaligned column: " #NAME); \ + return NAME; \ + }()) \ + ) +// clang-format on + +#define _DECLARE_VIEW_MEMBER_INITIALIZERS_BYCOLUMN(R, DATA, LAYOUT_MEMBER_NAME) \ + BOOST_PP_EXPAND(_DECLARE_VIEW_MEMBER_INITIALIZERS_BYCOLUMN_IMPL LAYOUT_MEMBER_NAME) + +/** + * Generator of layout list. + */ +#define _DECLARE_LAYOUT_LIST_IMPL(LAYOUT, NAME) (NAME) + +#define _DECLARE_LAYOUT_LIST(R, DATA, LAYOUT_MEMBER_NAME) BOOST_PP_EXPAND(_DECLARE_LAYOUT_LIST_IMPL LAYOUT_MEMBER_NAME) + +/** + * Generator of view member list. + */ +#define _DECLARE_VIEW_MEMBER_LIST_IMPL(LAYOUT, MEMBER, NAME) (NAME) + +#define _DECLARE_VIEW_MEMBER_LIST(R, DATA, LAYOUT_MEMBER_NAME) \ + BOOST_PP_EXPAND(_DECLARE_VIEW_MEMBER_LIST_IMPL LAYOUT_MEMBER_NAME) + +/** + * Generator of member initializer for copy constructor. + */ +#define _DECLARE_VIEW_MEMBER_INITIALIZERS_FROM_OTHER_IMPL(LAYOUT, MEMBER, LOCAL_NAME, DATA) \ + (BOOST_PP_CAT(MEMBER, Parameters_){DATA.BOOST_PP_CAT(MEMBER, Parameters_)}) + +#define _DECLARE_VIEW_MEMBER_INITIALIZERS_FROM_OTHER(R, DATA, LAYOUT_MEMBER_NAME) \ + BOOST_PP_EXPAND(_DECLARE_VIEW_MEMBER_INITIALIZERS_FROM_OTHER_IMPL BOOST_PP_TUPLE_PUSH_BACK(LAYOUT_MEMBER_NAME, DATA)) + +/** + * Generator of member assignment for assignment operator. + */ +#define _DECLARE_VIEW_MEMBER_ASSIGNMENT_FROM_OTHER_IMPL(LAYOUT, MEMBER, LOCAL_NAME, DATA) \ + BOOST_PP_CAT(MEMBER, Parameters_) = DATA.BOOST_PP_CAT(MEMBER, Parameters_); + +#define _DECLARE_VIEW_MEMBER_ASSIGNMENT_FROM_OTHER(R, DATA, LAYOUT_MEMBER_NAME) \ + BOOST_PP_EXPAND(_DECLARE_VIEW_MEMBER_ASSIGNMENT_FROM_OTHER_IMPL BOOST_PP_TUPLE_PUSH_BACK(LAYOUT_MEMBER_NAME, DATA)) + +/** + * Generator of element members initializer. + */ +#define _DECLARE_VIEW_ELEM_MEMBER_INIT_IMPL(LAYOUT, MEMBER, LOCAL_NAME, DATA) (LOCAL_NAME(DATA, LOCAL_NAME)) + +#define _DECLARE_VIEW_ELEM_MEMBER_INIT(R, DATA, LAYOUT_MEMBER_NAME) \ + BOOST_PP_EXPAND(_DECLARE_VIEW_ELEM_MEMBER_INIT_IMPL BOOST_PP_TUPLE_PUSH_BACK(LAYOUT_MEMBER_NAME, DATA)) + +/** + * Helper macro extracting the data type from metadata of a layout or view + */ +#define _COLUMN_TYPE(LAYOUT_NAME, LAYOUT_MEMBER) \ + typename std::remove_pointer::type + +/** + * Generator of parameters for (non-const) element subclass (expanded comma separated). + */ +#define _DECLARE_VIEW_ELEMENT_VALUE_ARG_IMPL(LAYOUT_NAME, LAYOUT_MEMBER, LOCAL_NAME, DATA) \ + (DATA typename BOOST_PP_CAT(Metadata::ParametersTypeOf_, LOCAL_NAME) LOCAL_NAME) + +#define _DECLARE_VIEW_ELEMENT_VALUE_ARG(R, DATA, LAYOUT_MEMBER_NAME) \ + _DECLARE_VIEW_ELEMENT_VALUE_ARG_IMPL BOOST_PP_TUPLE_PUSH_BACK(LAYOUT_MEMBER_NAME, DATA) + +/** + * Generator of parameters for (const) element subclass (expanded comma separated). + */ +#define _DECLARE_CONST_VIEW_ELEMENT_VALUE_ARG_IMPL(LAYOUT_NAME, LAYOUT_MEMBER, LOCAL_NAME, DATA) \ + (DATA typename BOOST_PP_CAT(Metadata::ParametersTypeOf_, LOCAL_NAME)::ConstType LOCAL_NAME) + +#define _DECLARE_CONST_VIEW_ELEMENT_VALUE_ARG(R, DATA, LAYOUT_MEMBER_NAME) \ + _DECLARE_CONST_VIEW_ELEMENT_VALUE_ARG_IMPL BOOST_PP_TUPLE_PUSH_BACK(LAYOUT_MEMBER_NAME, DATA) + +/** + * Generator of member initialization for constructor of element subclass + */ +#define _DECLARE_VIEW_CONST_ELEM_MEMBER_INIT_IMPL(LAYOUT_NAME, LAYOUT_MEMBER, LOCAL_NAME, DATA) \ + (BOOST_PP_CAT(LOCAL_NAME, _)(DATA, LOCAL_NAME)) + +/* declare AoS-like element value args for contructor; these should expand,for columns only */ +#define _DECLARE_VIEW_CONST_ELEM_MEMBER_INIT(R, DATA, LAYOUT_MEMBER_NAME) \ + BOOST_PP_EXPAND(_DECLARE_VIEW_CONST_ELEM_MEMBER_INIT_IMPL BOOST_PP_TUPLE_PUSH_BACK(LAYOUT_MEMBER_NAME, DATA)) + +/** + * Declaration of the members accessors of the const element subclass + */ +// clang-format off +#define _DECLARE_VIEW_CONST_ELEMENT_ACCESSOR_IMPL(LAYOUT_NAME, LAYOUT_MEMBER, LOCAL_NAME) \ + SOA_HOST_DEVICE SOA_INLINE \ + const typename SoAConstValueWithConf::RefToConst \ + LOCAL_NAME() const { \ + return BOOST_PP_CAT(LOCAL_NAME, _)(); \ + } +// clang-format on + +#define _DECLARE_VIEW_CONST_ELEMENT_ACCESSOR(R, DATA, LAYOUT_MEMBER_NAME) \ + _DECLARE_VIEW_CONST_ELEMENT_ACCESSOR_IMPL LAYOUT_MEMBER_NAME + +/** + * Declaration of the private members of the const element subclass + */ +// clang-format off +#define _DECLARE_VIEW_CONST_ELEMENT_VALUE_MEMBER_IMPL(LAYOUT_NAME, LAYOUT_MEMBER, LOCAL_NAME) \ + const cms::soa::ConstValueTraits, \ + BOOST_PP_CAT(Metadata::ColumnTypeOf_, LOCAL_NAME)> \ + BOOST_PP_CAT(LOCAL_NAME, _); +// clang-format on + +#define _DECLARE_VIEW_CONST_ELEMENT_VALUE_MEMBER(R, DATA, LAYOUT_MEMBER_NAME) \ + _DECLARE_VIEW_CONST_ELEMENT_VALUE_MEMBER_IMPL LAYOUT_MEMBER_NAME + +/** + * Generator of the member-by-member copy operator of the element subclass. + */ +#define _DECLARE_VIEW_ELEMENT_VALUE_COPY_IMPL(LAYOUT_NAME, LAYOUT_MEMBER, LOCAL_NAME) \ + if constexpr (Metadata::BOOST_PP_CAT(ColumnTypeOf_, LOCAL_NAME) != cms::soa::SoAColumnType::scalar) \ + LOCAL_NAME() = other.LOCAL_NAME(); + +#define _DECLARE_VIEW_ELEMENT_VALUE_COPY(R, DATA, LAYOUT_MEMBER_NAME) \ + BOOST_PP_EXPAND(_DECLARE_VIEW_ELEMENT_VALUE_COPY_IMPL LAYOUT_MEMBER_NAME) + +/** + * Declaration of the private members of the const element subclass + */ +// clang-format off +#define _DECLARE_VIEW_ELEMENT_VALUE_MEMBER_IMPL(LAYOUT_NAME, LAYOUT_MEMBER, LOCAL_NAME) \ + SoAValueWithConf \ + LOCAL_NAME; +// clang-format on + +#define _DECLARE_VIEW_ELEMENT_VALUE_MEMBER(R, DATA, LAYOUT_MEMBER_NAME) \ + _DECLARE_VIEW_ELEMENT_VALUE_MEMBER_IMPL LAYOUT_MEMBER_NAME + +/** + * Parameters passed to const element subclass constructor in operator[] + */ +#define _DECLARE_VIEW_CONST_ELEMENT_CONSTR_CALL_IMPL(LAYOUT_NAME, LAYOUT_MEMBER, LOCAL_NAME) \ + (BOOST_PP_CAT(LOCAL_NAME, Parameters_)) + +#define _DECLARE_VIEW_CONST_ELEMENT_CONSTR_CALL(R, DATA, LAYOUT_MEMBER_NAME) \ + BOOST_PP_EXPAND(_DECLARE_VIEW_CONST_ELEMENT_CONSTR_CALL_IMPL LAYOUT_MEMBER_NAME) + +/** + * Parameters passed to element subclass constructor in operator[] + * + * The use of const_cast (inside const_cast_SoAParametersImpl) is safe because the constructor of a View binds only to + * non-const arguments. + */ +#define _DECLARE_VIEW_ELEMENT_CONSTR_CALL_IMPL(LAYOUT_NAME, LAYOUT_MEMBER, LOCAL_NAME) \ + (const_cast_SoAParametersImpl(base_type::BOOST_PP_CAT(LOCAL_NAME, Parameters_))) + +#define _DECLARE_VIEW_ELEMENT_CONSTR_CALL(R, DATA, LAYOUT_MEMBER_NAME) \ + BOOST_PP_EXPAND(_DECLARE_VIEW_ELEMENT_CONSTR_CALL_IMPL LAYOUT_MEMBER_NAME) + +/** + * Direct access to column pointer and indexed access + */ +// clang-format off +#define _DECLARE_VIEW_SOA_ACCESSOR_IMPL(LAYOUT_NAME, LAYOUT_MEMBER, LOCAL_NAME) \ + /* Column or scalar */ \ + SOA_HOST_DEVICE SOA_INLINE \ + typename cms::soa::SoAAccessors:: \ + template ColumnType::template AccessType< \ + cms::soa::SoAAccessType::mutableAccess>::NoParamReturnType \ + LOCAL_NAME() { \ + return typename cms::soa::SoAAccessors:: \ + template ColumnType::template AccessType< \ + cms::soa::SoAAccessType::mutableAccess>(const_cast_SoAParametersImpl( \ + base_type:: BOOST_PP_CAT(LOCAL_NAME, Parameters_)))(); \ + } \ + SOA_HOST_DEVICE SOA_INLINE auto& LOCAL_NAME(size_type index) { \ + return typename cms::soa::SoAAccessors:: \ + template ColumnType::template AccessType< \ + cms::soa::SoAAccessType::mutableAccess>(const_cast_SoAParametersImpl( \ + base_type:: BOOST_PP_CAT(LOCAL_NAME, Parameters_)))(index); \ + } +// clang-format on + +#define _DECLARE_VIEW_SOA_ACCESSOR(R, DATA, LAYOUT_MEMBER_NAME) \ + BOOST_PP_EXPAND(_DECLARE_VIEW_SOA_ACCESSOR_IMPL LAYOUT_MEMBER_NAME) + +/** + * Direct access to column pointer (const) and indexed access. + */ +// clang-format off +#define _DECLARE_VIEW_SOA_CONST_ACCESSOR_IMPL(LAYOUT_NAME, LAYOUT_MEMBER, LOCAL_NAME) \ + /* Column or scalar */ \ + SOA_HOST_DEVICE SOA_INLINE auto LOCAL_NAME() const { \ + return typename cms::soa::SoAAccessors:: \ + template ColumnType::template AccessType< \ + cms::soa::SoAAccessType::constAccess>(BOOST_PP_CAT(LOCAL_NAME, Parameters_))(); \ + } \ + SOA_HOST_DEVICE SOA_INLINE auto LOCAL_NAME(size_type index) const { \ + return typename cms::soa::SoAAccessors:: \ + template ColumnType::template AccessType< \ + cms::soa::SoAAccessType::constAccess>(BOOST_PP_CAT(LOCAL_NAME, Parameters_))(index); \ + } +// clang-format on + +#define _DECLARE_VIEW_SOA_CONST_ACCESSOR(R, DATA, LAYOUT_MEMBER_NAME) \ + BOOST_PP_EXPAND(_DECLARE_VIEW_SOA_CONST_ACCESSOR_IMPL LAYOUT_MEMBER_NAME) + +/** + * SoA class member declaration (column pointers and parameters). + */ +#define _DECLARE_VIEW_SOA_MEMBER_IMPL(LAYOUT_NAME, LAYOUT_MEMBER, LOCAL_NAME, DATA) \ + typename BOOST_PP_CAT(Metadata::ParametersTypeOf_, LOCAL_NAME) BOOST_PP_CAT(LOCAL_NAME, Parameters_); + +#define _DECLARE_VIEW_SOA_MEMBER(R, DATA, LAYOUT_MEMBER_NAME) \ + BOOST_PP_EXPAND(_DECLARE_VIEW_SOA_MEMBER_IMPL BOOST_PP_TUPLE_PUSH_BACK(LAYOUT_MEMBER_NAME, DATA)) + +/** + * Const SoA class member declaration (column pointers and parameters). + */ +#define _DECLARE_CONST_VIEW_SOA_MEMBER_IMPL(LAYOUT_NAME, LAYOUT_MEMBER, LOCAL_NAME, DATA) \ + typename BOOST_PP_CAT(Metadata::ParametersTypeOf_, LOCAL_NAME)::ConstType BOOST_PP_CAT(LOCAL_NAME, Parameters_); + +#define _DECLARE_CONST_VIEW_SOA_MEMBER(R, DATA, LAYOUT_MEMBER_NAME) \ + BOOST_PP_EXPAND(_DECLARE_CONST_VIEW_SOA_MEMBER_IMPL BOOST_PP_TUPLE_PUSH_BACK(LAYOUT_MEMBER_NAME, DATA)) + +/** + * Assign the value of the view from the values in the value_element. + */ + +// clang-format off +#define _TRIVIAL_VIEW_ASSIGN_VALUE_ELEMENT_IMPL(VALUE_TYPE, CPP_TYPE, NAME) \ + _SWITCH_ON_TYPE(VALUE_TYPE, \ + /* Scalar (empty) */ \ + , \ + /* Column */ \ + NAME() = value.NAME; \ + , \ + /* Eigen column */ \ + NAME() = value.NAME; \ +) +// clang-format on + +#define _TRIVIAL_VIEW_ASSIGN_VALUE_ELEMENT(R, DATA, TYPE_NAME) _TRIVIAL_VIEW_ASSIGN_VALUE_ELEMENT_IMPL TYPE_NAME + +/* ---- MUTABLE VIEW ------------------------------------------------------------------------------------------------ */ +// clang-format off +#define _GENERATE_SOA_VIEW_PART_0(CONST_VIEW, VIEW, LAYOUTS_LIST, VALUE_LIST) \ + template \ + struct VIEW : public CONST_VIEW { \ + /* Declare the parametrized layouts as the default */ \ + /*BOOST_PP_SEQ_CAT(_ITERATE_ON_ALL(_DECLARE_VIEW_LAYOUT_PARAMETRIZED_TEMPLATE, ~, LAYOUTS_LIST)) */ \ + /* these could be moved to an external type trait to free up the symbol names */ \ + using self_type = VIEW; \ + using base_type = CONST_VIEW; +// clang-format on + +// clang-format off +#define _GENERATE_SOA_VIEW_PART_0_NO_DEFAULTS(CONST_VIEW, VIEW, LAYOUTS_LIST, VALUE_LIST) \ + template \ + struct VIEW : public CONST_VIEW { \ + /* Declare the parametrized layouts as the default */ \ + /*BOOST_PP_SEQ_CAT(_ITERATE_ON_ALL(_DECLARE_VIEW_LAYOUT_PARAMETRIZED_TEMPLATE, ~, LAYOUTS_LIST)) */ \ + /* these could be moved to an external type trait to free up the symbol names */ \ + using self_type = VIEW; \ + using base_type = CONST_VIEW; +// clang-format on + +/** + * Split of the const view definition where the parametrized template alias for the layout is defined for layout trivial view. + */ + +// clang-format off +#define _GENERATE_SOA_VIEW_PART_1(CONST_VIEW, VIEW, LAYOUTS_LIST, VALUE_LIST) \ + using size_type = cms::soa::size_type; \ + using byte_size_type = cms::soa::byte_size_type; \ + using AlignmentEnforcement = cms::soa::AlignmentEnforcement; \ + \ + /* For CUDA applications, we align to the 128 bytes of the cache lines. \ + * See https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#global-memory-3-0 this is still valid \ + * up to compute capability 8.X. \ + */ \ + constexpr static byte_size_type defaultAlignment = cms::soa::CacheLineSize::defaultSize; \ + constexpr static byte_size_type alignment = VIEW_ALIGNMENT; \ + constexpr static bool alignmentEnforcement = VIEW_ALIGNMENT_ENFORCEMENT; \ + constexpr static byte_size_type conditionalAlignment = \ + alignmentEnforcement == AlignmentEnforcement::enforced ? alignment : 0; \ + constexpr static bool restrictQualify = RESTRICT_QUALIFY; \ + constexpr static bool rangeChecking = RANGE_CHECKING; \ + /* Those typedefs avoid having commas in macros (which is problematic) */ \ + template \ + using SoAValueWithConf = cms::soa::SoAValue; \ + \ + template \ + using SoAConstValueWithConf = cms::soa::SoAConstValue; \ + \ + /** \ + * Helper/friend class allowing SoA introspection. \ + */ \ + struct Metadata { \ + friend VIEW; \ + SOA_HOST_DEVICE SOA_INLINE size_type size() const { return parent_.nElements_; } \ + /* Alias layout or view types to name-derived identifyer to allow simpler definitions */ \ + _ITERATE_ON_ALL(_DECLARE_VIEW_LAYOUT_TYPE_ALIAS, ~, LAYOUTS_LIST) \ + \ + /* Alias member types to name-derived identifyer to allow simpler definitions */ \ + _ITERATE_ON_ALL(_DECLARE_VIEW_MEMBER_TYPE_ALIAS, const_cast_SoAParametersImpl, VALUE_LIST) \ + _ITERATE_ON_ALL(_DECLARE_VIEW_MEMBER_POINTERS, ~, VALUE_LIST) \ + _ITERATE_ON_ALL(_DECLARE_VIEW_MEMBER_CONST_POINTERS, ~, VALUE_LIST) \ + \ + /* Forbid copying to avoid const correctness evasion */ \ + Metadata& operator=(const Metadata&) = delete; \ + Metadata(const Metadata&) = delete; \ + \ + private: \ + SOA_HOST_DEVICE SOA_INLINE Metadata(const VIEW& parent) : parent_(parent) {} \ + const VIEW& parent_; \ + }; \ + \ + friend Metadata; \ + SOA_HOST_DEVICE SOA_INLINE const Metadata metadata() const { return Metadata(*this); } \ + SOA_HOST_DEVICE SOA_INLINE Metadata metadata() { return Metadata(*this); } \ + \ + /* Trivial constuctor */ \ + VIEW() = default; \ + \ + /* Constructor relying on user provided layouts or views */ \ + SOA_HOST_ONLY VIEW(_ITERATE_ON_ALL_COMMA(_DECLARE_VIEW_CONSTRUCTION_PARAMETERS, BOOST_PP_EMPTY(), LAYOUTS_LIST)) \ + : base_type{_ITERATE_ON_ALL_COMMA(_DECLARE_LAYOUT_LIST, BOOST_PP_EMPTY(), LAYOUTS_LIST)} {} \ + \ + /* Constructor relying on individually provided column addresses */ \ + SOA_HOST_ONLY VIEW(size_type nElements, \ + _ITERATE_ON_ALL_COMMA(_DECLARE_VIEW_CONSTRUCTION_BYCOLUMN_PARAMETERS, \ + BOOST_PP_EMPTY(), \ + VALUE_LIST)) \ + : base_type{nElements, _ITERATE_ON_ALL_COMMA(_DECLARE_VIEW_MEMBER_LIST, BOOST_PP_EMPTY(), VALUE_LIST)} {} \ + \ + /* Copiable */ \ + VIEW(VIEW const&) = default; \ + VIEW& operator=(VIEW const&) = default; \ + \ + /* Movable */ \ + VIEW(VIEW &&) = default; \ + VIEW& operator=(VIEW &&) = default; \ + \ + /* Trivial destuctor */ \ + ~VIEW() = default; \ + \ + /* AoS-like accessor (const) */ \ + using const_element = typename base_type::const_element; \ + \ + using base_type::operator[]; \ + \ + /* AoS-like accessor (mutable) */ \ + struct element { \ + SOA_HOST_DEVICE SOA_INLINE \ + element(size_type index, /* Declare parameters */ \ + _ITERATE_ON_ALL_COMMA(_DECLARE_VIEW_ELEMENT_VALUE_ARG, BOOST_PP_EMPTY(), VALUE_LIST)) \ + : _ITERATE_ON_ALL_COMMA(_DECLARE_VIEW_ELEM_MEMBER_INIT, index, VALUE_LIST) {} \ + SOA_HOST_DEVICE SOA_INLINE \ + element& operator=(const element& other) { \ + _ITERATE_ON_ALL(_DECLARE_VIEW_ELEMENT_VALUE_COPY, ~, VALUE_LIST) \ + return *this; \ + } +// clang-format on + +// clang-format off +#define _GENERATE_SOA_VIEW_PART_2(CONST_VIEW, VIEW, LAYOUTS_LIST, VALUE_LIST) \ + _ITERATE_ON_ALL(_DECLARE_VIEW_ELEMENT_VALUE_MEMBER, ~, VALUE_LIST) \ + }; \ + \ + SOA_HOST_DEVICE SOA_INLINE \ + element operator[](size_type index) { \ + if constexpr (rangeChecking == cms::soa::RangeChecking::enabled) { \ + if (index >= base_type::nElements_) \ + SOA_THROW_OUT_OF_RANGE("Out of range index in " #VIEW "::operator[]") \ + } \ + return element{index, _ITERATE_ON_ALL_COMMA(_DECLARE_VIEW_ELEMENT_CONSTR_CALL, ~, VALUE_LIST)}; \ + } \ + \ + /* inherit const accessors from ConstView */ \ + \ + /* non-const accessors */ \ + _ITERATE_ON_ALL(_DECLARE_VIEW_SOA_ACCESSOR, ~, VALUE_LIST) \ + \ + /* dump the SoA internal structure */ \ + template \ + SOA_HOST_ONLY friend void dump(); \ + }; +// clang-format on + +/* ---- CONST VIEW -------------------------------------------------------------------------------------------------- */ +// clang-format off +#define _GENERATE_SOA_CONST_VIEW_PART_0(CONST_VIEW, VIEW, LAYOUTS_LIST, VALUE_LIST) \ + template \ + struct CONST_VIEW { \ + /* these could be moved to an external type trait to free up the symbol names */ \ + using self_type = CONST_VIEW; +// clang-format on + +// clang-format off +#define _GENERATE_SOA_CONST_VIEW_PART_0_NO_DEFAULTS(CONST_VIEW, VIEW, LAYOUTS_LIST, VALUE_LIST) \ + template \ + struct CONST_VIEW { \ + /* these could be moved to an external type trait to free up the symbol names */ \ + using self_type = CONST_VIEW; +// clang-format on + +/** + * Split of the const view definition where the parametrized template alias for the layout is defined for layout trivial view. + */ + +// clang-format off +#define _GENERATE_SOA_CONST_VIEW_PART_1(CONST_VIEW, VIEW, LAYOUTS_LIST, VALUE_LIST) \ + using size_type = cms::soa::size_type; \ + using byte_size_type = cms::soa::byte_size_type; \ + using AlignmentEnforcement = cms::soa::AlignmentEnforcement; \ + \ + template \ + friend struct VIEW; \ + \ + /* For CUDA applications, we align to the 128 bytes of the cache lines. \ + * See https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#global-memory-3-0 this is still valid \ + * up to compute capability 8.X. \ + */ \ + constexpr static byte_size_type defaultAlignment = cms::soa::CacheLineSize::defaultSize; \ + constexpr static byte_size_type alignment = VIEW_ALIGNMENT; \ + constexpr static bool alignmentEnforcement = VIEW_ALIGNMENT_ENFORCEMENT; \ + constexpr static byte_size_type conditionalAlignment = \ + alignmentEnforcement == AlignmentEnforcement::enforced ? alignment : 0; \ + constexpr static bool restrictQualify = RESTRICT_QUALIFY; \ + constexpr static bool rangeChecking = RANGE_CHECKING; \ + /* Those typedefs avoid having commas in macros (which is problematic) */ \ + template \ + using SoAValueWithConf = cms::soa::SoAValue; \ + \ + template \ + using SoAConstValueWithConf = cms::soa::SoAConstValue; \ + \ + /** \ + * Helper/friend class allowing SoA introspection. \ + */ \ + struct Metadata { \ + friend CONST_VIEW; \ + SOA_HOST_DEVICE SOA_INLINE size_type size() const { return parent_.nElements_; } \ + /* Alias layout or view types to name-derived identifyer to allow simpler definitions */ \ + _ITERATE_ON_ALL(_DECLARE_VIEW_LAYOUT_TYPE_ALIAS, ~, LAYOUTS_LIST) \ + \ + /* Alias member types to name-derived identifyer to allow simpler definitions */ \ + _ITERATE_ON_ALL(_DECLARE_VIEW_MEMBER_TYPE_ALIAS, BOOST_PP_EMPTY(), VALUE_LIST) \ + _ITERATE_ON_ALL(_DECLARE_VIEW_MEMBER_CONST_POINTERS, ~, VALUE_LIST) \ + \ + /* Forbid copying to avoid const correctness evasion */ \ + Metadata& operator=(const Metadata&) = delete; \ + Metadata(const Metadata&) = delete; \ + \ + private: \ + SOA_HOST_DEVICE SOA_INLINE Metadata(const CONST_VIEW& parent) : parent_(parent) {} \ + const CONST_VIEW& parent_; \ + }; \ + \ + friend Metadata; \ + SOA_HOST_DEVICE SOA_INLINE const Metadata metadata() const { return Metadata(*this); } \ + \ + /* Trivial constuctor */ \ + CONST_VIEW() = default; \ + \ + /* Constructor relying on user provided layouts or views */ \ + SOA_HOST_ONLY CONST_VIEW(_ITERATE_ON_ALL_COMMA(_DECLARE_VIEW_CONSTRUCTION_PARAMETERS, const, LAYOUTS_LIST)) \ + : nElements_([&]() -> size_type { \ + bool set = false; \ + size_type ret = 0; \ + _ITERATE_ON_ALL(_UPDATE_SIZE_OF_VIEW, BOOST_PP_EMPTY(), LAYOUTS_LIST) \ + return ret; \ + }()), \ + _ITERATE_ON_ALL_COMMA(_DECLARE_VIEW_MEMBER_INITIALIZERS, ~, VALUE_LIST) {} \ + \ + /* Constructor relying on individually provided column addresses */ \ + SOA_HOST_ONLY CONST_VIEW(size_type nElements, \ + _ITERATE_ON_ALL_COMMA(_DECLARE_VIEW_CONSTRUCTION_BYCOLUMN_PARAMETERS, const, VALUE_LIST)) \ + : nElements_(nElements), _ITERATE_ON_ALL_COMMA(_DECLARE_VIEW_MEMBER_INITIALIZERS_BYCOLUMN, ~, VALUE_LIST) {} \ + \ + /* Copiable */ \ + CONST_VIEW(CONST_VIEW const&) = default; \ + CONST_VIEW& operator=(CONST_VIEW const&) = default; \ + \ + /* Movable */ \ + CONST_VIEW(CONST_VIEW &&) = default; \ + CONST_VIEW& operator=(CONST_VIEW &&) = default; \ + \ + /* Trivial destuctor */ \ + ~CONST_VIEW() = default; \ + \ + /* AoS-like accessor (const) */ \ + struct const_element { \ + SOA_HOST_DEVICE SOA_INLINE \ + const_element(size_type index, /* Declare parameters */ \ + _ITERATE_ON_ALL_COMMA(_DECLARE_CONST_VIEW_ELEMENT_VALUE_ARG, const, VALUE_LIST)) \ + : _ITERATE_ON_ALL_COMMA(_DECLARE_VIEW_CONST_ELEM_MEMBER_INIT, index, VALUE_LIST) {} \ + _ITERATE_ON_ALL(_DECLARE_VIEW_CONST_ELEMENT_ACCESSOR, ~, VALUE_LIST) \ + \ + private: \ + _ITERATE_ON_ALL(_DECLARE_VIEW_CONST_ELEMENT_VALUE_MEMBER, ~, VALUE_LIST) \ + }; \ + \ + SOA_HOST_DEVICE SOA_INLINE \ + const_element operator[](size_type index) const { \ + if constexpr (rangeChecking == cms::soa::RangeChecking::enabled) { \ + if (index >= nElements_) \ + SOA_THROW_OUT_OF_RANGE("Out of range index in " #CONST_VIEW "::operator[]") \ + } \ + return const_element{index, _ITERATE_ON_ALL_COMMA(_DECLARE_VIEW_CONST_ELEMENT_CONSTR_CALL, ~, VALUE_LIST)}; \ + } \ + \ + /* const accessors */ \ + _ITERATE_ON_ALL(_DECLARE_VIEW_SOA_CONST_ACCESSOR, ~, VALUE_LIST) \ + \ + /* dump the SoA internal structure */ \ + template \ + SOA_HOST_ONLY friend void dump(); \ + \ + private: \ + size_type nElements_ = 0; \ + _ITERATE_ON_ALL(_DECLARE_CONST_VIEW_SOA_MEMBER, const, VALUE_LIST) \ +}; +// clang-format on + +// clang-format off +// MAJOR caveat: in order to propagate the LAYOUTS_LIST and VALUE_LIST +#define _GENERATE_SOA_CONST_VIEW(CONST_VIEW, VIEW, LAYOUTS_LIST, VALUE_LIST) \ + _GENERATE_SOA_CONST_VIEW_PART_0(CONST_VIEW, VIEW, \ + SOA_VIEW_LAYOUT_LIST(LAYOUTS_LIST), SOA_VIEW_VALUE_LIST(VALUE_LIST)) \ + _GENERATE_SOA_CONST_VIEW_PART_1(CONST_VIEW, VIEW, \ + SOA_VIEW_LAYOUT_LIST(LAYOUTS_LIST), SOA_VIEW_VALUE_LIST(VALUE_LIST)) + +#define GENERATE_SOA_CONST_VIEW(CONST_VIEW, VIEW, LAYOUTS_LIST, VALUE_LIST) \ + _GENERATE_SOA_CONST_VIEW(CONST_VIEW, BOOST_PP_CAT(CONST_VIEW, Unused_), \ + SOA_VIEW_LAYOUT_LIST(LAYOUTS_LIST), SOA_VIEW_VALUE_LIST(VALUE_LIST)) + +#define _GENERATE_SOA_TRIVIAL_CONST_VIEW(CLASS, LAYOUTS_LIST, VALUE_LIST) \ + _GENERATE_SOA_CONST_VIEW_PART_0_NO_DEFAULTS(ConstViewTemplateFreeParams, ViewTemplateFreeParams, \ + SOA_VIEW_LAYOUT_LIST(LAYOUTS_LIST), SOA_VIEW_VALUE_LIST(VALUE_LIST)) \ + using BOOST_PP_CAT(CLASS, _parametrized) = CLASS; \ + _GENERATE_SOA_CONST_VIEW_PART_1(ConstViewTemplateFreeParams, ViewTemplateFreeParams, \ + SOA_VIEW_LAYOUT_LIST(LAYOUTS_LIST), SOA_VIEW_VALUE_LIST(VALUE_LIST)) + +#define _GENERATE_SOA_VIEW(CONST_VIEW, VIEW, LAYOUTS_LIST, VALUE_LIST) \ + _GENERATE_SOA_VIEW_PART_0(CONST_VIEW, VIEW, SOA_VIEW_LAYOUT_LIST(LAYOUTS_LIST), SOA_VIEW_VALUE_LIST(VALUE_LIST)) \ + _GENERATE_SOA_VIEW_PART_1(CONST_VIEW, VIEW, SOA_VIEW_LAYOUT_LIST(LAYOUTS_LIST), SOA_VIEW_VALUE_LIST(VALUE_LIST)) \ + _GENERATE_SOA_VIEW_PART_2(CONST_VIEW, VIEW, SOA_VIEW_LAYOUT_LIST(LAYOUTS_LIST), SOA_VIEW_VALUE_LIST(VALUE_LIST)) + +#define GENERATE_SOA_VIEW(CONST_VIEW, VIEW, LAYOUTS_LIST, VALUE_LIST) \ + _GENERATE_SOA_CONST_VIEW(CONST_VIEW, VIEW, SOA_VIEW_LAYOUT_LIST(LAYOUTS_LIST), SOA_VIEW_VALUE_LIST(VALUE_LIST)) \ + _GENERATE_SOA_VIEW(CONST_VIEW, VIEW, SOA_VIEW_LAYOUT_LIST(LAYOUTS_LIST), SOA_VIEW_VALUE_LIST(VALUE_LIST)) + +#define _GENERATE_SOA_TRIVIAL_VIEW(CLASS, LAYOUTS_LIST, VALUE_LIST, ...) \ + _GENERATE_SOA_VIEW_PART_0_NO_DEFAULTS(ConstViewTemplateFreeParams, ViewTemplateFreeParams, \ + SOA_VIEW_LAYOUT_LIST(LAYOUTS_LIST), SOA_VIEW_VALUE_LIST(VALUE_LIST)) \ + using BOOST_PP_CAT(CLASS, _parametrized) = CLASS; \ + _GENERATE_SOA_VIEW_PART_1(ConstViewTemplateFreeParams, ViewTemplateFreeParams, \ + SOA_VIEW_LAYOUT_LIST(LAYOUTS_LIST), SOA_VIEW_VALUE_LIST(VALUE_LIST)) \ + \ + /* Extra operator=() for mutable element to emulate the aggregate initialisation syntax */ \ + SOA_HOST_DEVICE SOA_INLINE constexpr element & operator=(const typename \ + BOOST_PP_CAT(CLASS, _parametrized)::Metadata::value_element value) { \ + _ITERATE_ON_ALL(_TRIVIAL_VIEW_ASSIGN_VALUE_ELEMENT, ~, __VA_ARGS__) \ + return *this; \ + } \ + \ + _GENERATE_SOA_VIEW_PART_2(ConstViewTemplateFreeParams, ViewTemplateFreeParams, \ + SOA_VIEW_LAYOUT_LIST(LAYOUTS_LIST), SOA_VIEW_VALUE_LIST(VALUE_LIST)) +// clang-format on + +/** + * Helper macro turning layout field declaration into view field declaration. + */ +#define _VIEW_FIELD_FROM_LAYOUT_IMPL(VALUE_TYPE, CPP_TYPE, NAME, DATA) (DATA, NAME, NAME) + +#define _VIEW_FIELD_FROM_LAYOUT(R, DATA, VALUE_TYPE_NAME) \ + BOOST_PP_EXPAND((_VIEW_FIELD_FROM_LAYOUT_IMPL BOOST_PP_TUPLE_PUSH_BACK(VALUE_TYPE_NAME, DATA))) + +#endif // DataFormats_SoATemplate_interface_SoAView_h diff --git a/DataFormats/SoATemplate/test/BuildFile.xml b/DataFormats/SoATemplate/test/BuildFile.xml new file mode 100644 index 0000000000000..7c62e15bde402 --- /dev/null +++ b/DataFormats/SoATemplate/test/BuildFile.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + diff --git a/DataFormats/SoATemplate/test/FakeSoA.h b/DataFormats/SoATemplate/test/FakeSoA.h new file mode 100644 index 0000000000000..b0319d5a0bdca --- /dev/null +++ b/DataFormats/SoATemplate/test/FakeSoA.h @@ -0,0 +1,91 @@ +#ifndef DataFormats_SoATemplate_test_FakeSoA_h +#define DataFormats_SoATemplate_test_FakeSoA_h + +// A SoA-like class (with fake alignment (padding)) +#include +#include +#include + +#define myassert(A) \ + if (not(A)) { \ + std::cerr << "Failed assertion: " #A " at " __FILE__ "(" << __LINE__ << ")" << std::endl; \ + abort(); \ + } + +class FakeSoA { +public: + static constexpr size_t padding_ = 128; + + // A fake SoA with 2 columns of uint16_t and uin32_t, plus fake padding. + static size_t computeBufferSize(size_t nElements) { + return nElements * (sizeof(uint16_t) + sizeof(uint32_t)) + padding_ + 0x400; + } + + FakeSoA(std::byte *buffer, size_t nElements) { constFromBufferImpl(buffer, nElements); } + + FakeSoA() : size_(0) { std::cout << "At end of FakeSoA::FakeSoA()" << std::endl; } + + template + void allocateAndIoRead(T &onfile) { + std::cout << "allocateAndIoRead begin" << std::endl; + auto buffSize = FakeSoA::computeBufferSize(onfile.size_); + auto buffer = new std::byte[buffSize]; + std::cout << "Buffer first byte after (alloc) =" << buffer + buffSize << std::endl; + constFromBufferImpl(buffer, onfile.size_); + memcpy(a16_, onfile.a16_, sizeof(uint16_t) * onfile.size_); + memcpy(b32_, onfile.b32_, sizeof(uint32_t) * onfile.size_); + std::cout << "allocateAndIoRead end" << std::endl; + } + + void dump() { + std::cout << "size=" << size_ << " buffer=" << buffer_.get() << " a16=" << a16_ << " b32=" << b32_ + << " (b32 - a16)=" + << reinterpret_cast(reinterpret_cast(b32_) - reinterpret_cast(a16_)) + << " buffer size=" << computeBufferSize(size_) << "(" << std::hex << computeBufferSize(size_) << ")" + << std::endl; + } + + void dumpData() { std::cout << "a16_[0]=" << a16_[0] << " b32_[0]=" << b32_[0] << std::endl; } + + void fill() { + for (int i = 0; i < size_; i++) { + a16_[i] = 42 + i; + b32_[i] = 24 + i; + } + } + + bool check() { + bool result = true; + for (int i = 0; i < size_; i++) { + if (a16_[i] != 42 + i) { + std::cout << "a16 mismatch at i=" << i << "(" << a16_[i] << "/" << 42 + i << ")" << std::endl; + result = false; + } + if (b32_[i] != 24 + (uint32_t)i) { + std::cout << "b32 mismatch at i=" << i << "(" << b32_[i] << "/" << 24 + i << ")" << std::endl; + result = false; + } + } + return result; + } + +private: + void constFromBufferImpl(std::byte *buffer, size_t nElements) { + buffer_.reset(buffer); + size_ = nElements; + a16_ = reinterpret_cast(buffer); + buffer += nElements * sizeof(uint16_t) + padding_; + b32_ = reinterpret_cast(buffer); + buffer += nElements * sizeof(uint32_t); + std::cout << "Buffer first byte after (const) =" << buffer << std::endl; + std::cout << "At end of FakeSoA::constFromBufferImpl(std::byte * buffer, size_t nElements): "; + dump(); + } + + int size_; + uint16_t *a16_ = nullptr; //[size_] + uint32_t *b32_ = nullptr; //[size_] + std::unique_ptr buffer_ = nullptr; //! +}; + +#endif // DataFormats_SoATemplate_test_FakeSoA_h diff --git a/DataFormats/SoATemplate/test/SoALayoutAndView_t.cu b/DataFormats/SoATemplate/test/SoALayoutAndView_t.cu new file mode 100644 index 0000000000000..a4f9b0bc7d78f --- /dev/null +++ b/DataFormats/SoATemplate/test/SoALayoutAndView_t.cu @@ -0,0 +1,275 @@ +#include +#include + +#include +#include + +#include "DataFormats/SoATemplate/interface/SoALayout.h" +#include "DataFormats/SoATemplate/interface/SoAView.h" +#include "HeterogeneousCore/CUDAUtilities/interface/cudaCheck.h" +#include "HeterogeneousCore/CUDAUtilities/interface/requireDevices.h" + +// Test SoA stores and view. +// Use cases +// Multiple stores in a buffer +// Scalars, Columns of scalars and of Eigen vectors +// View to each of them, from one and multiple stores. + +GENERATE_SOA_LAYOUT(SoAHostDeviceLayoutTemplate, + /*SoAHostDeviceViewTemplate,*/ + // predefined static scalars + // size_t size; + // size_t alignment; + + // columns: one value per element + SOA_COLUMN(double, x), + SOA_COLUMN(double, y), + SOA_COLUMN(double, z), + SOA_EIGEN_COLUMN(Eigen::Vector3d, a), + SOA_EIGEN_COLUMN(Eigen::Vector3d, b), + SOA_EIGEN_COLUMN(Eigen::Vector3d, r), + // scalars: one value for the whole structure + SOA_SCALAR(const char*, description), + SOA_SCALAR(uint32_t, someNumber)) + +using SoAHostDeviceLayout = SoAHostDeviceLayoutTemplate<>; +using SoAHostDeviceView = SoAHostDeviceLayout::View; +using SoAHostDeviceConstView = SoAHostDeviceLayout::ConstView; + +GENERATE_SOA_LAYOUT(SoADeviceOnlyLayoutTemplate, + /*SoADeviceOnlyViewTemplate,*/ + SOA_COLUMN(uint16_t, color), + SOA_COLUMN(double, value), + SOA_COLUMN(double*, py), + SOA_COLUMN(uint32_t, count), + SOA_COLUMN(uint32_t, anotherCount)) + +using SoADeviceOnlyLayout = SoADeviceOnlyLayoutTemplate<>; +using SoADeviceOnlyView = SoADeviceOnlyLayout::View; + +// A 1 to 1 view of the store (except for unsupported types). +GENERATE_SOA_VIEW(SoAFullDeviceConstViewTemplate, + SoAFullDeviceViewTemplate, + SOA_VIEW_LAYOUT_LIST(SOA_VIEW_LAYOUT(SoAHostDeviceLayout, soaHD), + SOA_VIEW_LAYOUT(SoADeviceOnlyLayout, soaDO)), + SOA_VIEW_VALUE_LIST(SOA_VIEW_VALUE(soaHD, x), + SOA_VIEW_VALUE(soaHD, y), + SOA_VIEW_VALUE(soaHD, z), + SOA_VIEW_VALUE(soaDO, color), + SOA_VIEW_VALUE(soaDO, value), + SOA_VIEW_VALUE(soaDO, py), + SOA_VIEW_VALUE(soaDO, count), + SOA_VIEW_VALUE(soaDO, anotherCount), + SOA_VIEW_VALUE(soaHD, description), + SOA_VIEW_VALUE(soaHD, someNumber))) + +using SoAFullDeviceView = + SoAFullDeviceViewTemplate; + +// Eigen cross product kernel (on store) +__global__ void crossProduct(SoAHostDeviceView soa, const unsigned int numElements) { + int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= numElements) + return; + auto si = soa[i]; + si.r() = si.a().cross(si.b()); +} + +// Device-only producer kernel +__global__ void producerKernel(SoAFullDeviceView soa, const unsigned int numElements) { + int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= numElements) + return; + auto si = soa[i]; + si.color() &= 0x55 << i % (sizeof(si.color()) - sizeof(char)); + si.value() = sqrt(si.x() * si.x() + si.y() * si.y() + si.z() * si.z()); +} + +// Device-only consumer with result in host-device area +__global__ void consumerKernel(SoAFullDeviceView soa, const unsigned int numElements) { + int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= numElements) + return; + auto si = soa[i]; + si.x() = si.color() * si.value(); +} + +// Get a view like the default, except for range checking +using RangeCheckingHostDeviceView = + SoAHostDeviceLayout::ViewTemplate; + +// We expect to just run one thread. +__global__ void rangeCheckKernel(RangeCheckingHostDeviceView soa) { + printf("About to fail range-check in CUDA thread: %d\n", threadIdx.x); + [[maybe_unused]] auto si = soa[soa.metadata().size()]; + printf("Fail: range-check failure should have stopped the kernel.\n"); +} + +int main(void) { + cms::cudatest::requireDevices(); + + cudaStream_t stream; + cudaCheck(cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking)); + + // Non-aligned number of elements to check alignment features. + constexpr unsigned int numElements = 65537; + + // Allocate buffer and store on host + size_t hostDeviceSize = SoAHostDeviceLayout::computeDataSize(numElements); + std::byte* h_buf = nullptr; + cudaCheck(cudaMallocHost(&h_buf, hostDeviceSize)); + SoAHostDeviceLayout h_soahdLayout(h_buf, numElements); + SoAHostDeviceView h_soahd(h_soahdLayout); + SoAHostDeviceConstView h_soahd_c(h_soahdLayout); + + // Alocate buffer, stores and views on the device (single, shared buffer). + size_t deviceOnlySize = SoADeviceOnlyLayout::computeDataSize(numElements); + std::byte* d_buf = nullptr; + cudaCheck(cudaMallocHost(&d_buf, hostDeviceSize + deviceOnlySize)); + SoAHostDeviceLayout d_soahdLayout(d_buf, numElements); + SoADeviceOnlyLayout d_soadoLayout(d_soahdLayout.metadata().nextByte(), numElements); + SoAHostDeviceView d_soahdView(d_soahdLayout); + SoAFullDeviceView d_soaFullView(d_soahdLayout, d_soadoLayout); + + // Assert column alignments + assert(0 == reinterpret_cast(h_soahd.metadata().addressOf_x()) % decltype(h_soahd)::alignment); + assert(0 == reinterpret_cast(h_soahd.metadata().addressOf_y()) % decltype(h_soahd)::alignment); + assert(0 == reinterpret_cast(h_soahd.metadata().addressOf_z()) % decltype(h_soahd)::alignment); + assert(0 == reinterpret_cast(h_soahd.metadata().addressOf_a()) % decltype(h_soahd)::alignment); + assert(0 == reinterpret_cast(h_soahd.metadata().addressOf_b()) % decltype(h_soahd)::alignment); + assert(0 == reinterpret_cast(h_soahd.metadata().addressOf_r()) % decltype(h_soahd)::alignment); + assert(0 == reinterpret_cast(h_soahd.metadata().addressOf_description()) % decltype(h_soahd)::alignment); + assert(0 == reinterpret_cast(h_soahd.metadata().addressOf_someNumber()) % decltype(h_soahd)::alignment); + + assert(0 == reinterpret_cast(d_soahdLayout.metadata().addressOf_x()) % decltype(d_soahdLayout)::alignment); + assert(0 == reinterpret_cast(d_soahdLayout.metadata().addressOf_y()) % decltype(d_soahdLayout)::alignment); + assert(0 == reinterpret_cast(d_soahdLayout.metadata().addressOf_z()) % decltype(d_soahdLayout)::alignment); + assert(0 == reinterpret_cast(d_soahdLayout.metadata().addressOf_a()) % decltype(d_soahdLayout)::alignment); + assert(0 == reinterpret_cast(d_soahdLayout.metadata().addressOf_b()) % decltype(d_soahdLayout)::alignment); + assert(0 == reinterpret_cast(d_soahdLayout.metadata().addressOf_r()) % decltype(d_soahdLayout)::alignment); + assert(0 == reinterpret_cast(d_soahdLayout.metadata().addressOf_description()) % + decltype(d_soahdLayout)::alignment); + assert(0 == reinterpret_cast(d_soahdLayout.metadata().addressOf_someNumber()) % + decltype(d_soahdLayout)::alignment); + + assert(0 == + reinterpret_cast(d_soadoLayout.metadata().addressOf_color()) % decltype(d_soadoLayout)::alignment); + assert(0 == + reinterpret_cast(d_soadoLayout.metadata().addressOf_value()) % decltype(d_soadoLayout)::alignment); + assert(0 == + reinterpret_cast(d_soadoLayout.metadata().addressOf_py()) % decltype(d_soadoLayout)::alignment); + assert(0 == + reinterpret_cast(d_soadoLayout.metadata().addressOf_count()) % decltype(d_soadoLayout)::alignment); + assert(0 == reinterpret_cast(d_soadoLayout.metadata().addressOf_anotherCount()) % + decltype(d_soadoLayout)::alignment); + + // Views should get the same alignment as the stores they refer to + assert(0 == reinterpret_cast(d_soaFullView.metadata().addressOf_x()) % decltype(d_soaFullView)::alignment); + assert(0 == reinterpret_cast(d_soaFullView.metadata().addressOf_y()) % decltype(d_soaFullView)::alignment); + assert(0 == reinterpret_cast(d_soaFullView.metadata().addressOf_z()) % decltype(d_soaFullView)::alignment); + // Limitation of views: we have to get scalar member addresses via metadata. + assert(0 == reinterpret_cast(d_soaFullView.metadata().addressOf_description()) % + decltype(d_soaFullView)::alignment); + assert(0 == reinterpret_cast(d_soaFullView.metadata().addressOf_someNumber()) % + decltype(d_soaFullView)::alignment); + assert(0 == + reinterpret_cast(d_soaFullView.metadata().addressOf_color()) % decltype(d_soaFullView)::alignment); + assert(0 == + reinterpret_cast(d_soaFullView.metadata().addressOf_value()) % decltype(d_soaFullView)::alignment); + assert(0 == + reinterpret_cast(d_soaFullView.metadata().addressOf_py()) % decltype(d_soaFullView)::alignment); + assert(0 == + reinterpret_cast(d_soaFullView.metadata().addressOf_count()) % decltype(d_soaFullView)::alignment); + assert(0 == reinterpret_cast(d_soaFullView.metadata().addressOf_anotherCount()) % + decltype(d_soaFullView)::alignment); + + // Initialize and fill the host buffer + std::memset(h_soahdLayout.metadata().data(), 0, hostDeviceSize); + for (size_t i = 0; i < numElements; ++i) { + auto si = h_soahd[i]; + // Tuple assignment... + // elements are: x, y, z, a, b, r + auto v1 = 1.0 * i + 1.0; + auto v2 = 2.0 * i; + auto v3 = 3.0 * i - 1.0; + if (i % 2) { + si = {v1, v2, v3, {v1, v2, v3}, {v3, v2, v1}, {0, 0, 0}}; + } else { + si.x() = si.a()(0) = si.b()(2) = v1; + si.y() = si.a()(1) = si.b()(1) = v2; + si.z() = si.a()(2) = si.b()(0) = v3; + } + } + auto& sn = h_soahd.someNumber(); + sn = numElements + 2; + + // Push to device + cudaCheck(cudaMemcpyAsync(d_buf, h_buf, hostDeviceSize, cudaMemcpyDefault, stream)); + + // Process on device + crossProduct<<<(numElements + 255) / 256, 256, 0, stream>>>(d_soahdView, numElements); + + // Paint the device only with 0xFF initially + cudaCheck(cudaMemsetAsync(d_soadoLayout.metadata().data(), 0xFF, d_soadoLayout.metadata().byteSize(), stream)); + + // Produce to the device only area + producerKernel<<<(numElements + 255) / 256, 256, 0, stream>>>(d_soaFullView, numElements); + + // Consume the device only area and generate a result on the host-device area + consumerKernel<<<(numElements + 255) / 256, 256, 0, stream>>>(d_soaFullView, numElements); + + // Get result back + cudaCheck(cudaMemcpyAsync(h_buf, d_buf, hostDeviceSize, cudaMemcpyDefault, stream)); + + // Wait and validate. + cudaCheck(cudaStreamSynchronize(stream)); + for (size_t i = 0; i < numElements; ++i) { + auto si = h_soahd_c[i]; + assert(si.r() == si.a().cross(si.b())); + double initialX = 1.0 * i + 1.0; + double initialY = 2.0 * i; + double initialZ = 3.0 * i - 1.0; + uint16_t expectedColor = 0x55 << i % (sizeof(uint16_t) - sizeof(char)); + double expectedX = expectedColor * sqrt(initialX * initialX + initialY * initialY + initialZ * initialZ); + if (abs(si.x() - expectedX) / expectedX >= 2 * std::numeric_limits::epsilon()) { + std::cout << "X failed: for i=" << i << std::endl + << "initialX=" << initialX << " initialY=" << initialY << " initialZ=" << initialZ << std::endl + << "expectedX=" << expectedX << std::endl + << "resultX=" << si.x() << " resultY=" << si.y() << " resultZ=" << si.z() << std::endl + << "relativeDiff=" << abs(si.x() - expectedX) / expectedX + << " epsilon=" << std::numeric_limits::epsilon() << std::endl; + assert(false); + } + } + + // Validation of range checking + try { + // Get a view like the default, except for range checking + SoAHostDeviceLayout::ViewTemplate + soa1viewRangeChecking(h_soahdLayout); + // This should throw an exception + [[maybe_unused]] auto si = soa1viewRangeChecking[soa1viewRangeChecking.metadata().size()]; + std::cout << "Fail: expected range-check exception not caught on the host." << std::endl; + assert(false); + } catch (const std::out_of_range&) { + std::cout << "Pass: expected range-check exception successfully caught on the host." << std::endl; + } + + // Validation of range checking in a kernel + // Get a view like the default one, except for range checking + RangeCheckingHostDeviceView soa1viewRangeChecking(d_soahdLayout); + + // This should throw an exception in the kernel + rangeCheckKernel<<<1, 1, 0, stream>>>(soa1viewRangeChecking); + + // Wait and confirm that the CUDA kernel failed + try { + cudaCheck(cudaStreamSynchronize(stream)); + std::cout << "Fail: expected range-check exception not caught while executing the kernel." << std::endl; + assert(false); + } catch (const std::runtime_error&) { + std::cout << "Pass: expected range-check exception caught while executing the kernel." << std::endl; + } + + std::cout << "OK" << std::endl; +} diff --git a/DataFormats/SoATemplate/test/SoAStreamer_t.cpp b/DataFormats/SoATemplate/test/SoAStreamer_t.cpp new file mode 100644 index 0000000000000..08b67506051a3 --- /dev/null +++ b/DataFormats/SoATemplate/test/SoAStreamer_t.cpp @@ -0,0 +1,69 @@ +/* + * SoAStreamer_t.cpp + * + * A test validating and the serialization of SoA Layouts to a ROOT file + */ + +#include +#include + +#include +#include + +#include "FakeSoA.h" + +void writeSoA() { + std::cout << "write begin" << std::endl; + constexpr size_t nElements = 128; + + auto buffer = std::make_unique(FakeSoA::computeBufferSize(nElements)); + FakeSoA fsoa(buffer.get(), nElements); + fsoa.dump(); + fsoa.fill(); + if (not fsoa.check()) { + exit(EXIT_FAILURE); + } + + std::unique_ptr myFile(TFile::Open("serializerNoTObj.root", "RECREATE")); + TTree tt("serializerNoTObjTree", "A SoA TTree"); + // In CMSSW, we will get a branch of objects (each row from the branched corresponding to an event) + // So we have a branch with one element for the moment. + [[maybe_unused]] auto Branch = tt.Branch("FakeSoA", &fsoa); + std::cout << "In writeFile(), about to Fill()" << std::endl; + fsoa.dump(); + auto prevGDebug = gDebug; + gDebug = 5; + tt.Fill(); + gDebug = prevGDebug; + tt.Write(); + myFile->Close(); + std::cout << "write end" << std::endl; +} + +void readSoA() { + std::cout << "read begin" << std::endl; + std::unique_ptr myFile(TFile::Open("serializerNoTObj.root", "READ")); + myFile->ls(); + std::unique_ptr fakeSoATree((TTree *)myFile->Get("serializerNoTObjTree")); + fakeSoATree->ls(); + auto prevGDebug = gDebug; + //gDebug = 3; + FakeSoA *fakeSoA = nullptr; + fakeSoATree->SetBranchAddress("FakeSoA", &fakeSoA); + fakeSoATree->GetEntry(0); + gDebug = prevGDebug; + std::cout << "fakeSoAAddress=" << fakeSoA << std::endl; + fakeSoA->dump(); + fakeSoA->dumpData(); + std::cout << "Checking SoA readback..."; + if (not fakeSoA->check()) { + exit(EXIT_FAILURE); + } + std::cout << " OK" << std::endl; +} + +int main() { + writeSoA(); + readSoA(); + return EXIT_SUCCESS; +} diff --git a/DataFormats/SoATemplate/test/classes.h b/DataFormats/SoATemplate/test/classes.h new file mode 100644 index 0000000000000..bba9150237d88 --- /dev/null +++ b/DataFormats/SoATemplate/test/classes.h @@ -0,0 +1 @@ +#include "DataFormats/SoATemplate/test/FakeSoA.h" \ No newline at end of file diff --git a/DataFormats/SoATemplate/test/classes_def.xml b/DataFormats/SoATemplate/test/classes_def.xml new file mode 100644 index 0000000000000..23695971e87e1 --- /dev/null +++ b/DataFormats/SoATemplate/test/classes_def.xml @@ -0,0 +1,14 @@ + + + + allocateAndIoRead(onfile); + ]]> + + diff --git a/EventFilter/RPCRawToDigi/plugins/RPCCPPFUnpacker.cc b/EventFilter/RPCRawToDigi/plugins/RPCCPPFUnpacker.cc index a86f3662412e4..ab893d3c55783 100644 --- a/EventFilter/RPCRawToDigi/plugins/RPCCPPFUnpacker.cc +++ b/EventFilter/RPCRawToDigi/plugins/RPCCPPFUnpacker.cc @@ -257,12 +257,14 @@ void RPCCPPFUnpacker::processTXRecord(RPCAMCLink link, static int const station[6] = {1, 2, 3, 3, 4, 4}; int region(link.getAMCNumber() < 7 ? 1 : -1); unsigned int endcap_sector((35 + (link.getAMCNumber() - (region > 0 ? 3 : 7)) * 9 + (block >> 1)) % 36 + 1); + unsigned int emtf_link(((34 + (link.getAMCNumber() - (region > 0 ? 3 : 7)) * 9 + (block >> 1)) % 36) % 6 + 1); + unsigned int emtf_sector(((34 + (link.getAMCNumber() - (region > 0 ? 3 : 7)) * 9 + (block >> 1)) % 36) / 6 + 1); RPCDetId rpc_id(region, ring[word] // ring , station[word] // station , - (endcap_sector / 6) + 1 // sector + ((endcap_sector - 1) / 6) + 1 // sector , 1 // layer , @@ -271,10 +273,12 @@ void RPCCPPFUnpacker::processTXRecord(RPCAMCLink link, 0); // roll if (record.isValid(0)) { - rpc_cppf_digis.push_back(l1t::CPPFDigi(rpc_id, 0, record.getTheta(0), record.getPhi(0))); + rpc_cppf_digis.push_back( + l1t::CPPFDigi(rpc_id, 0, record.getPhi(0), record.getTheta(0), 0, 0, 0, emtf_sector, emtf_link, 0, 0, 0, 0)); } if (record.isValid(1)) { - rpc_cppf_digis.push_back(l1t::CPPFDigi(rpc_id, 0, record.getTheta(1), record.getPhi(1))); + rpc_cppf_digis.push_back( + l1t::CPPFDigi(rpc_id, 0, record.getPhi(1), record.getTheta(1), 1, 0, 0, emtf_sector, emtf_link, 0, 0, 0, 0)); } } diff --git a/FWCore/Framework/src/EventPrincipal.cc b/FWCore/Framework/src/EventPrincipal.cc index 42df363c064b7..8e25e00bd5063 100644 --- a/FWCore/Framework/src/EventPrincipal.cc +++ b/FWCore/Framework/src/EventPrincipal.cc @@ -8,6 +8,7 @@ #include "DataFormats/Provenance/interface/BranchIDList.h" #include "DataFormats/Provenance/interface/BranchIDListHelper.h" #include "DataFormats/Provenance/interface/BranchListIndex.h" +#include "DataFormats/Provenance/interface/branchIDToProductID.h" #include "DataFormats/Provenance/interface/RunLumiEventNumber.h" #include "DataFormats/Provenance/interface/ProductIDToBranchID.h" #include "DataFormats/Provenance/interface/ProductRegistry.h" @@ -149,13 +150,7 @@ namespace edm { branchListIndexToProcessIndex_.clear(); // Fill in helper map for Branch to ProductID mapping if (not branchListIndexes_.empty()) { - ProcessIndex pix = 0; - branchListIndexToProcessIndex_.resize(1 + *std::max_element(branchListIndexes_.begin(), branchListIndexes_.end()), - std::numeric_limits::max()); - for (auto const& blindex : branchListIndexes_) { - branchListIndexToProcessIndex_[blindex] = pix; - ++pix; - } + branchListIndexToProcessIndex_ = makeBranchListIndexToProcessIndex(branchListIndexes_); } // Fill in the product ID's in the product holders. @@ -235,27 +230,7 @@ namespace edm { } ProductID EventPrincipal::branchIDToProductID(BranchID const& bid) const { - if (!bid.isValid()) { - throw Exception(errors::NotFound, "InvalidID") << "branchIDToProductID: invalid BranchID supplied\n"; - } - typedef BranchIDListHelper::BranchIDToIndexMap BIDToIndexMap; - typedef BIDToIndexMap::const_iterator Iter; - typedef std::pair IndexRange; - - IndexRange range = branchIDListHelper_->branchIDToIndexMap().equal_range(bid); - for (Iter it = range.first; it != range.second; ++it) { - BranchListIndex blix = it->second.first; - if (blix < branchListIndexToProcessIndex_.size()) { - auto v = branchListIndexToProcessIndex_[blix]; - if (v != std::numeric_limits::max()) { - ProductIndex productIndex = it->second.second; - ProcessIndex processIndex = v; - return ProductID(processIndex + 1, productIndex + 1); - } - } - } - // cannot throw, because some products may legitimately not have product ID's (e.g. pile-up). - return ProductID(); + return edm::branchIDToProductID(bid, *branchIDListHelper_, branchListIndexToProcessIndex_); } unsigned int EventPrincipal::processBlockIndex(std::string const& processName) const { diff --git a/GeneratorInterface/Core/bin/externalGenerator.cc b/GeneratorInterface/Core/bin/externalGenerator.cc index 0c14a763ff2d6..b35d54479b325 100644 --- a/GeneratorInterface/Core/bin/externalGenerator.cc +++ b/GeneratorInterface/Core/bin/externalGenerator.cc @@ -7,6 +7,7 @@ #include #include #include +#include #include "FWCore/TestProcessor/interface/TestProcessor.h" @@ -43,6 +44,20 @@ CMS_THREAD_SAFE static std::string s_uniqueID; //NOTE: Can use TestProcessor as the harness for the worker +namespace { + //Based on MessageLogger time handling + constexpr char timeFormat[] = "dd-Mon-yyyy hh:mm:ss TZN "; + constexpr size_t kTimeSize = sizeof(timeFormat); + std::array formattedTime() { + auto t = time(nullptr); + std::array ts; + + struct tm timebuf; + std::strftime(ts.data(), ts.size(), "%d-%b-%Y %H:%M:%S %Z", localtime_r(&t, &timebuf)); + return ts; + } +} // namespace + using namespace edm::shared_memory; class Harness { public: @@ -88,7 +103,7 @@ namespace { void atexit_handler() { if (s_sharedLock) { - std::cerr << s_uniqueID << " process: early exit called: unlock\n"; + std::cerr << s_uniqueID << " process: early exit called: unlock " << formattedTime().data() << "\n"; s_sharedLock->unlock(); } } @@ -175,7 +190,7 @@ int main(int argc, char* argv[]) { monitorThread.setAction([lockPtr]() { if (lockPtr) { - std::cerr << s_uniqueID << " process: SIGNAL CAUGHT: unlock\n"; + std::cerr << s_uniqueID << " process: SIGNAL CAUGHT: unlock " << formattedTime().data() << "\n"; lockPtr->unlock(); } }); @@ -188,7 +203,7 @@ int main(int argc, char* argv[]) { std::atexit(atexit_handler); auto releaseLock = []() { if (s_sharedLock) { - std::cerr << s_uniqueID << " process: terminate called: unlock\n"; + std::cerr << s_uniqueID << " process: terminate called: unlock " << formattedTime().data() << "\n"; s_sharedLock->unlock(); s_sharedLock = nullptr; //deactivate the abort signal @@ -212,7 +227,7 @@ int main(int argc, char* argv[]) { ROOTDeserializer random_deserializer(sm_readbuffer); presentState = "reading configuration"; - std::cerr << uniqueID << " process: initializing " << std::endl; + std::cerr << uniqueID << " process: initializing " << formattedTime().data() << std::endl; int nlines; std::cin >> nlines; @@ -237,30 +252,30 @@ int main(int argc, char* argv[]) { std::set_terminate(releaseLock); if (verbose) { - std::cerr << uniqueID << " process: done initializing" << std::endl; + std::cerr << uniqueID << " process: done initializing " << formattedTime().data() << std::endl; } presentState = "finished initialization"; communicationChannel.workerSetupDone(); presentState = "waiting for transition"; if (verbose) - std::cerr << uniqueID << " process: waiting " << counter << std::endl; + std::cerr << uniqueID << " process: waiting " << counter << " " << formattedTime().data() << std::endl; communicationChannel.handleTransitions([&](edm::Transition iTransition, unsigned long long iTransitionID) { ++counter; switch (iTransition) { case edm::Transition::BeginRun: { presentState = "beginRun transition"; if (verbose) - std::cerr << uniqueID << " process: start beginRun " << std::endl; + std::cerr << uniqueID << " process: start beginRun " << formattedTime().data() << std::endl; if (verbose) - std::cerr << uniqueID << " process: end beginRun " << std::endl; + std::cerr << uniqueID << " process: end beginRun " << formattedTime().data() << std::endl; break; } case edm::Transition::BeginLuminosityBlock: { presentState = "begin lumi"; if (verbose) - std::cerr << uniqueID << " process: start beginLumi " << std::endl; + std::cerr << uniqueID << " process: start beginLumi " << formattedTime().data() << std::endl; auto randState = random_deserializer.deserialize(); presentState = "deserialized random state in begin lumi"; if (verbose) @@ -274,7 +289,7 @@ int main(int argc, char* argv[]) { presentState = "serialize lumi"; bl_serializer.serialize(value); if (verbose) - std::cerr << uniqueID << " process: end beginLumi " << std::endl; + std::cerr << uniqueID << " process: end beginLumi " << formattedTime().data() << std::endl; if (verbose) std::cerr << uniqueID << " rand " << value.randomState_.state_.size() << " " << value.randomState_.seed_ << std::endl; @@ -283,7 +298,7 @@ int main(int argc, char* argv[]) { case edm::Transition::Event: { presentState = "begin event"; if (verbose) - std::cerr << uniqueID << " process: event " << counter << std::endl; + std::cerr << uniqueID << " process: event " << counter << " " << formattedTime().data() << std::endl; presentState = "deserialized random state in event"; auto randState = random_deserializer.deserialize(); randomService->setState(randState.state_, randState.seed_); @@ -293,7 +308,7 @@ int main(int argc, char* argv[]) { value.randomState_.seed_ = randomService->mySeed(); if (verbose) - std::cerr << uniqueID << " process: event " << counter << std::endl; + std::cerr << uniqueID << " process: event " << counter << " " << formattedTime().data() << std::endl; presentState = "serialize event"; serializer.serialize(value); @@ -306,28 +321,28 @@ int main(int argc, char* argv[]) { case edm::Transition::EndLuminosityBlock: { presentState = "begin end lumi"; if (verbose) - std::cerr << uniqueID << " process: start endLumi " << std::endl; + std::cerr << uniqueID << " process: start endLumi " << formattedTime().data() << std::endl; presentState = "processing end lumi"; auto value = harness.getEndLumiValue(); presentState = "serialize end lumi"; el_serializer.serialize(value); if (verbose) - std::cerr << uniqueID << " process: end endLumi " << std::endl; + std::cerr << uniqueID << " process: end endLumi " << formattedTime().data() << std::endl; break; } case edm::Transition::EndRun: { presentState = "begin end run"; if (verbose) - std::cerr << uniqueID << " process: start endRun " << std::endl; + std::cerr << uniqueID << " process: start endRun " << formattedTime().data() << std::endl; presentState = "process end run"; auto value = harness.getEndRunValue(); presentState = "serialize end run"; er_serializer.serialize(value); if (verbose) - std::cerr << uniqueID << " process: end endRun " << std::endl; + std::cerr << uniqueID << " process: end endRun " << formattedTime().data() << std::endl; break; } @@ -337,19 +352,20 @@ int main(int argc, char* argv[]) { } presentState = "notifying and waiting after " + presentState; if (verbose) - std::cerr << uniqueID << " process: notifying and waiting " << counter << std::endl; + std::cerr << uniqueID << " process: notifying and waiting " << counter << " " << std::endl; }); } } catch (std::exception const& iExcept) { std::cerr << "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n" << s_uniqueID << " process: caught exception \n" - << iExcept.what() << "\n" + << iExcept.what() << " " << formattedTime().data() << "\n" << " while " << presentState << "\n" << "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n"; return 1; } catch (...) { std::cerr << "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n" - << s_uniqueID << " process: caught unknown exception\n while " << presentState << "\n" + << s_uniqueID << " process: caught unknown exception " << formattedTime().data() << "\n while " + << presentState << "\n" << "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n"; return 1; } diff --git a/Geometry/HGCalCommonData/src/HGCalGeomRotation.cc b/Geometry/HGCalCommonData/src/HGCalGeomRotation.cc index 49ae8e3c1a6ec..e7f51cf17b91c 100644 --- a/Geometry/HGCalCommonData/src/HGCalGeomRotation.cc +++ b/Geometry/HGCalCommonData/src/HGCalGeomRotation.cc @@ -128,7 +128,7 @@ unsigned HGCalGeomRotation::uvMappingTo60DegreeSector0(WaferCentring waferCentri } if (moduleU > 0 && moduleV >= 0) { - if (moduleV <= moduleU) { + if (moduleV < moduleU) { return sector; } else { sector = 1; diff --git a/Geometry/HGCalGeometry/test/python/testHGCalCorner_cfg.py b/Geometry/HGCalGeometry/test/python/testHGCalCorner_cfg.py index b04ab1ade1098..45e7a15b654e8 100644 --- a/Geometry/HGCalGeometry/test/python/testHGCalCorner_cfg.py +++ b/Geometry/HGCalGeometry/test/python/testHGCalCorner_cfg.py @@ -1,9 +1,41 @@ +############################################################################### +# Way to use this: +# cmsRun testHGCalCorner_cfg.py geometry=D88 +# +# Options for type D88, D92, D93 +# +############################################################################### import FWCore.ParameterSet.Config as cms +import os, sys, imp, re +import FWCore.ParameterSet.VarParsing as VarParsing + +#################################################################### +### SETUP OPTIONS +options = VarParsing.VarParsing('standard') +options.register('geometry', + "D92", + VarParsing.VarParsing.multiplicity.singleton, + VarParsing.VarParsing.varType.string, + "type of operations: D88, D92, D93") + +### get and parse the command line arguments +options.parseArguments() +print(options) + +from Configuration.Eras.Era_Phase2C11I13M9_cff import Phase2C11I13M9 + +process = cms.Process("HGCalCornerTest",Phase2C11I13M9) + +#################################################################### +# Use the options +if (options.geometry == "D88"): + process.load('Configuration.Geometry.GeometryExtended2026D88Reco_cff') +elif (options.geometry == "D93"): + process.load('Configuration.Geometry.GeometryExtended2026D93Reco_cff') +else: + process.load('Configuration.Geometry.GeometryExtended2026D92Reco_cff') -from Configuration.Eras.Era_Phase2C11_cff import Phase2C11 -process = cms.Process("PROD",Phase2C11) process.load("SimGeneral.HepPDTESSource.pdt_cfi") -process.load('Configuration.Geometry.GeometryExtended2026D86Reco_cff') process.load('FWCore.MessageService.MessageLogger_cfi') if hasattr(process,'MessageLogger'): diff --git a/Geometry/HGCalGeometry/test/python/testHGCalGeomLocatorSc_cfg.py b/Geometry/HGCalGeometry/test/python/testHGCalGeomLocatorSc_cfg.py index 4d82686621309..d2f215d396292 100644 --- a/Geometry/HGCalGeometry/test/python/testHGCalGeomLocatorSc_cfg.py +++ b/Geometry/HGCalGeometry/test/python/testHGCalGeomLocatorSc_cfg.py @@ -1,10 +1,40 @@ +############################################################################### +# Way to use this: +# cmsRun testHGCalGeomLocatorSc_cfg.py geometry=D88 +# +# Options for type D88, D92, D93 +# +############################################################################### import FWCore.ParameterSet.Config as cms +import os, sys, imp, re +import FWCore.ParameterSet.VarParsing as VarParsing -process = cms.Process("PROD") -process.load("SimGeneral.HepPDTESSource.pdt_cfi") +#################################################################### +### SETUP OPTIONS +options = VarParsing.VarParsing('standard') +options.register('geometry', + "D92", + VarParsing.VarParsing.multiplicity.singleton, + VarParsing.VarParsing.varType.string, + "type of operations: D88, D92, D93") + +### get and parse the command line arguments +options.parseArguments() +print(options) + +from Configuration.Eras.Era_Phase2C11I13M9_cff import Phase2C11I13M9 +process = cms.Process("HGCalGeomLocatorSc",Phase2C11I13M9) -process.load("Configuration.Geometry.GeometryExtended2026D71Reco_cff") -#process.load("Configuration.Geometry.GeometryExtended2026D49Reco_cff") +#################################################################### +# Use the options +if (options.geometry == "D88"): + process.load('Configuration.Geometry.GeometryExtended2026D88Reco_cff') +elif (options.geometry == "D93"): + process.load('Configuration.Geometry.GeometryExtended2026D93Reco_cff') +else: + process.load('Configuration.Geometry.GeometryExtended2026D92Reco_cff') + +process.load("SimGeneral.HepPDTESSource.pdt_cfi") process.load('FWCore.MessageService.MessageLogger_cfi') if hasattr(process,'MessageLogger'): diff --git a/Geometry/HGCalGeometry/test/python/testHGCalGeomLocator_cfg.py b/Geometry/HGCalGeometry/test/python/testHGCalGeomLocator_cfg.py index 41a77fe09befa..4fe0ce23da84f 100644 --- a/Geometry/HGCalGeometry/test/python/testHGCalGeomLocator_cfg.py +++ b/Geometry/HGCalGeometry/test/python/testHGCalGeomLocator_cfg.py @@ -1,10 +1,40 @@ +############################################################################### +# Way to use this: +# cmsRun testHGCalGeomLocator_cfg.py geometry=D88 +# +# Options for type D88, D92, D93 +# +############################################################################### import FWCore.ParameterSet.Config as cms +import os, sys, imp, re +import FWCore.ParameterSet.VarParsing as VarParsing -process = cms.Process("PROD") -process.load("SimGeneral.HepPDTESSource.pdt_cfi") +#################################################################### +### SETUP OPTIONS +options = VarParsing.VarParsing('standard') +options.register('geometry', + "D92", + VarParsing.VarParsing.multiplicity.singleton, + VarParsing.VarParsing.varType.string, + "type of operations: D88, D92, D93") + +### get and parse the command line arguments +options.parseArguments() +print(options) + +from Configuration.Eras.Era_Phase2C11I13M9_cff import Phase2C11I13M9 +process = cms.Process("HGCalGeomLocator",Phase2C11I13M9) -process.load("Configuration.Geometry.GeometryExtended2026D71Reco_cff") -#process.load("Configuration.Geometry.GeometryExtended2026D49Reco_cff") +#################################################################### +# Use the options +if (options.geometry == "D88"): + process.load('Configuration.Geometry.GeometryExtended2026D88Reco_cff') +elif (options.geometry == "D93"): + process.load('Configuration.Geometry.GeometryExtended2026D93Reco_cff') +else: + process.load('Configuration.Geometry.GeometryExtended2026D92Reco_cff') + +process.load("SimGeneral.HepPDTESSource.pdt_cfi") process.load('FWCore.MessageService.MessageLogger_cfi') if hasattr(process,'MessageLogger'): diff --git a/Geometry/HGCalGeometry/test/python/testHGCalGeometryMouseBite_cfg.py b/Geometry/HGCalGeometry/test/python/testHGCalGeometryMouseBite_cfg.py index e59f4ad1e25e0..16cb78700efdb 100644 --- a/Geometry/HGCalGeometry/test/python/testHGCalGeometryMouseBite_cfg.py +++ b/Geometry/HGCalGeometry/test/python/testHGCalGeometryMouseBite_cfg.py @@ -1,10 +1,42 @@ +############################################################################### +# Way to use this: +# cmsRun testHGCalGeometryMouseBite_cfg.py geometry=D88 +# +# Options for type D88, D92, D93, D94 +# +############################################################################### import FWCore.ParameterSet.Config as cms -from Configuration.Eras.Era_Phase2C11_cff import Phase2C11 +import os, sys, imp, re +import FWCore.ParameterSet.VarParsing as VarParsing -process = cms.Process("PROD",Phase2C11) -process.load("SimGeneral.HepPDTESSource.pdt_cfi") +#################################################################### +### SETUP OPTIONS +options = VarParsing.VarParsing('standard') +options.register('geometry', + "D92", + VarParsing.VarParsing.multiplicity.singleton, + VarParsing.VarParsing.varType.string, + "type of operations: D88, D92, D93, D94") + +### get and parse the command line arguments +options.parseArguments() +print(options) + +from Configuration.Eras.Era_Phase2C11I13M9_cff import Phase2C11I13M9 +process = cms.Process("HGCalGeometryMouseBite",Phase2C11I13M9) -process.load("Configuration.Geometry.GeometryExtended2026D86Reco_cff") +#################################################################### +# Use the options +if (options.geometry == "D88"): + process.load('Configuration.Geometry.GeometryExtended2026D88Reco_cff') +elif (options.geometry == "D93"): + process.load('Configuration.Geometry.GeometryExtended2026D93Reco_cff') +elif (options.geometry == "D94"): + process.load('Configuration.Geometry.GeometryExtended2026D94Reco_cff') +else: + process.load('Configuration.Geometry.GeometryExtended2026D92Reco_cff') + +process.load("SimGeneral.HepPDTESSource.pdt_cfi") process.load('FWCore.MessageService.MessageLogger_cfi') if hasattr(process,'MessageLogger'): @@ -50,4 +82,7 @@ NameDevice = "HGCal HF Nose" ) -process.p1 = cms.Path(process.generator*process.prodEE*process.prodHEF*process.prodHFN) +if (options.geometry == "D94"): + process.p1 = cms.Path(process.generator*process.prodEE*process.prodHEF*process.prodHFN) +else: + process.p1 = cms.Path(process.generator*process.prodEE*process.prodHEF) diff --git a/Geometry/HGCalGeometry/test/python/testHGCalGeometryNewCorners_cfg.py b/Geometry/HGCalGeometry/test/python/testHGCalGeometryNewCorners_cfg.py index 7e1a74289a41b..bf857f57861b0 100644 --- a/Geometry/HGCalGeometry/test/python/testHGCalGeometryNewCorners_cfg.py +++ b/Geometry/HGCalGeometry/test/python/testHGCalGeometryNewCorners_cfg.py @@ -1,8 +1,38 @@ +############################################################################### +# Way to use this: +# cmsRun testHGCalGeometryNewCorners_cfg.py geometry=D88 +# +# Options for type D88, D92, D93 +# +############################################################################### import FWCore.ParameterSet.Config as cms +import os, sys, imp, re +import FWCore.ParameterSet.VarParsing as VarParsing + +#################################################################### +### SETUP OPTIONS +options = VarParsing.VarParsing('standard') +options.register('geometry', + "D92", + VarParsing.VarParsing.multiplicity.singleton, + VarParsing.VarParsing.varType.string, + "type of operations: D88, D92, D93") + +### get and parse the command line arguments +options.parseArguments() +print(options) from Configuration.Eras.Era_Phase2C11I13M9_cff import Phase2C11I13M9 -process = cms.Process('PROD',Phase2C11I13M9) -process.load('Configuration.Geometry.GeometryExtended2026D86Reco_cff') +process = cms.Process("HGCalGeometryNewCorners",Phase2C11I13M9) + +#################################################################### +# Use the options +if (options.geometry == "D88"): + process.load('Configuration.Geometry.GeometryExtended2026D88Reco_cff') +elif (options.geometry == "D93"): + process.load('Configuration.Geometry.GeometryExtended2026D93Reco_cff') +else: + process.load('Configuration.Geometry.GeometryExtended2026D92Reco_cff') process.load("SimGeneral.HepPDTESSource.pdt_cfi") process.load('Geometry.HGCalGeometry.hgcalGeometryNewCornersTest_cfi') diff --git a/Geometry/HGCalGeometry/test/python/testHGCalGeometryRotCheck_cfg.py b/Geometry/HGCalGeometry/test/python/testHGCalGeometryRotCheck_cfg.py index 525a0fc3ec5a2..dc097c8d5ea5d 100644 --- a/Geometry/HGCalGeometry/test/python/testHGCalGeometryRotCheck_cfg.py +++ b/Geometry/HGCalGeometry/test/python/testHGCalGeometryRotCheck_cfg.py @@ -1,8 +1,38 @@ +############################################################################### +# Way to use this: +# cmsRun testHGCalGeometryRotCheck_cfg.py geometry=D88 +# +# Options for type D88, D92, D93 +# +############################################################################### import FWCore.ParameterSet.Config as cms +import os, sys, imp, re +import FWCore.ParameterSet.VarParsing as VarParsing + +#################################################################### +### SETUP OPTIONS +options = VarParsing.VarParsing('standard') +options.register('geometry', + "D92", + VarParsing.VarParsing.multiplicity.singleton, + VarParsing.VarParsing.varType.string, + "type of operations: D88, D92, D93") + +### get and parse the command line arguments +options.parseArguments() +print(options) from Configuration.Eras.Era_Phase2C11I13M9_cff import Phase2C11I13M9 -process = cms.Process('PROD',Phase2C11I13M9) -process.load('Configuration.Geometry.GeometryExtended2026D86Reco_cff') +process = cms.Process("HGCalGeometryRotCheck",Phase2C11I13M9) + +#################################################################### +# Use the options +if (options.geometry == "D88"): + process.load('Configuration.Geometry.GeometryExtended2026D88Reco_cff') +elif (options.geometry == "D93"): + process.load('Configuration.Geometry.GeometryExtended2026D93Reco_cff') +else: + process.load('Configuration.Geometry.GeometryExtended2026D92Reco_cff') process.load("SimGeneral.HepPDTESSource.pdt_cfi") process.load('Geometry.HGCalGeometry.hgcalGeometryRotCheck_cfi') diff --git a/Geometry/HGCalGeometry/test/python/testHGCalGeometryRotTest_cfg.py b/Geometry/HGCalGeometry/test/python/testHGCalGeometryRotTest_cfg.py index c113e6108c6dc..3fb17f8599061 100644 --- a/Geometry/HGCalGeometry/test/python/testHGCalGeometryRotTest_cfg.py +++ b/Geometry/HGCalGeometry/test/python/testHGCalGeometryRotTest_cfg.py @@ -1,8 +1,38 @@ +############################################################################### +# Way to use this: +# cmsRun testHGCalGeometryRotTest_cfg.py geometry=D88 +# +# Options for type D88, D92, D93 +# +############################################################################### import FWCore.ParameterSet.Config as cms +import os, sys, imp, re +import FWCore.ParameterSet.VarParsing as VarParsing + +#################################################################### +### SETUP OPTIONS +options = VarParsing.VarParsing('standard') +options.register('geometry', + "D92", + VarParsing.VarParsing.multiplicity.singleton, + VarParsing.VarParsing.varType.string, + "type of operations: D88, D92, D93") + +### get and parse the command line arguments +options.parseArguments() +print(options) from Configuration.Eras.Era_Phase2C11I13M9_cff import Phase2C11I13M9 -process = cms.Process('PROD',Phase2C11I13M9) -process.load('Configuration.Geometry.GeometryExtended2026D86Reco_cff') +process = cms.Process("HGCalGeometryRotCheck",Phase2C11I13M9) + +#################################################################### +# Use the options +if (options.geometry == "D88"): + process.load('Configuration.Geometry.GeometryExtended2026D88Reco_cff') +elif (options.geometry == "D93"): + process.load('Configuration.Geometry.GeometryExtended2026D93Reco_cff') +else: + process.load('Configuration.Geometry.GeometryExtended2026D92Reco_cff') process.load("SimGeneral.HepPDTESSource.pdt_cfi") process.load('Geometry.HGCalGeometry.hgcalGeometryRotTest_cfi') diff --git a/HeterogeneousCore/AlpakaCore/BuildFile.xml b/HeterogeneousCore/AlpakaCore/BuildFile.xml new file mode 100644 index 0000000000000..786446de87dce --- /dev/null +++ b/HeterogeneousCore/AlpakaCore/BuildFile.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/HeterogeneousCore/AlpakaCore/interface/MakerMacros.h b/HeterogeneousCore/AlpakaCore/interface/MakerMacros.h new file mode 100644 index 0000000000000..71fece04e7e38 --- /dev/null +++ b/HeterogeneousCore/AlpakaCore/interface/MakerMacros.h @@ -0,0 +1,11 @@ +#ifndef HeterogeneousCore_AlpakaCore_interface_MakerMacros_h +#define HeterogeneousCore_AlpakaCore_interface_MakerMacros_h + +#include "FWCore/Framework/interface/MakerMacros.h" +#include "HeterogeneousCore/AlpakaInterface/interface/config.h" + +// force expanding ALPAKA_ACCELERATOR_NAMESPACE before stringification inside DEFINE_FWK_MODULE +#define DEFINE_FWK_ALPAKA_MODULE2(name) DEFINE_FWK_MODULE(name) +#define DEFINE_FWK_ALPAKA_MODULE(name) DEFINE_FWK_ALPAKA_MODULE2(ALPAKA_ACCELERATOR_NAMESPACE::name) + +#endif // HeterogeneousCore_AlpakaCore_interface_MakerMacros_h diff --git a/HeterogeneousCore/AlpakaInterface/BuildFile.xml b/HeterogeneousCore/AlpakaInterface/BuildFile.xml new file mode 100644 index 0000000000000..6287a9a38a31f --- /dev/null +++ b/HeterogeneousCore/AlpakaInterface/BuildFile.xml @@ -0,0 +1,2 @@ + + diff --git a/HeterogeneousCore/AlpakaInterface/README.md b/HeterogeneousCore/AlpakaInterface/README.md new file mode 100644 index 0000000000000..709098b772665 --- /dev/null +++ b/HeterogeneousCore/AlpakaInterface/README.md @@ -0,0 +1,6 @@ +## HeterogeneousCore/AlpakaInterface + +This package only depends on the `alpaka` header-only external library, and +provides the interface used by other packages in CMSSW. + +It is safe to be used inside DataFormats packages. diff --git a/HeterogeneousCore/AlpakaInterface/interface/config.h b/HeterogeneousCore/AlpakaInterface/interface/config.h new file mode 100644 index 0000000000000..2ad630440bda4 --- /dev/null +++ b/HeterogeneousCore/AlpakaInterface/interface/config.h @@ -0,0 +1,164 @@ +#ifndef HeterogeneousCore_AlpakaInterface_interface_config_h +#define HeterogeneousCore_AlpakaInterface_interface_config_h + +#include + +#include + +#include "FWCore/Utilities/interface/stringize.h" + +namespace alpaka_common { + + // common types and dimensions + using Idx = uint32_t; + using Extent = uint32_t; + using Offsets = Extent; + + using Dim0D = alpaka::DimInt<0u>; + using Dim1D = alpaka::DimInt<1u>; + using Dim2D = alpaka::DimInt<2u>; + using Dim3D = alpaka::DimInt<3u>; + + template + using Vec = alpaka::Vec; + using Vec1D = Vec; + using Vec2D = Vec; + using Vec3D = Vec; + using Scalar = Vec; + + template + using WorkDiv = alpaka::WorkDivMembers; + using WorkDiv1D = WorkDiv; + using WorkDiv2D = WorkDiv; + using WorkDiv3D = WorkDiv; + + // host types + using DevHost = alpaka::DevCpu; + using PltfHost = alpaka::Pltf; + +} // namespace alpaka_common + +#ifdef ALPAKA_ACC_GPU_CUDA_ENABLED +namespace alpaka_cuda_async { + using namespace alpaka_common; + + using Platform = alpaka::PltfCudaRt; + using Device = alpaka::DevCudaRt; + using Queue = alpaka::QueueCudaRtNonBlocking; + using Event = alpaka::EventCudaRt; + + template + using Acc = alpaka::AccGpuCudaRt; + using Acc1D = Acc; + using Acc2D = Acc; + using Acc3D = Acc; + +} // namespace alpaka_cuda_async + +#ifdef ALPAKA_ACCELERATOR_NAMESPACE +#define ALPAKA_DUPLICATE_NAMESPACE +#else +#define ALPAKA_ACCELERATOR_NAMESPACE alpaka_cuda_async +#define ALPAKA_TYPE_SUFFIX CudaAsync +#endif + +#endif // ALPAKA_ACC_GPU_CUDA_ENABLED + +#ifdef ALPAKA_ACC_GPU_HIP_ENABLED +namespace alpaka_hip_async { + using namespace alpaka_common; + + using Platform = alpaka::PltfHipRt; + using Device = alpaka::DevHipRt; + using Queue = alpaka::QueueHipRtNonBlocking; + using Event = alpaka::EventHipRt; + + template + using Acc = alpaka::AccGpuHipRt; + using Acc1D = Acc; + using Acc2D = Acc; + using Acc3D = Acc; + +} // namespace alpaka_hip_async + +#ifdef ALPAKA_ACCELERATOR_NAMESPACE +#define ALPAKA_DUPLICATE_NAMESPACE +#else +#define ALPAKA_ACCELERATOR_NAMESPACE alpaka_hip_async +#define ALPAKA_TYPE_SUFFIX HipAsync +#endif + +#endif // ALPAKA_ACC_GPU_HIP_ENABLED + +#ifdef ALPAKA_ACC_CPU_B_SEQ_T_SEQ_ENABLED +namespace alpaka_serial_sync { + using namespace alpaka_common; + + using Platform = alpaka::PltfCpu; + using Device = alpaka::DevCpu; + using Queue = alpaka::QueueCpuBlocking; + using Event = alpaka::EventCpu; + + template + using Acc = alpaka::AccCpuSerial; + using Acc1D = Acc; + using Acc2D = Acc; + using Acc3D = Acc; + +} // namespace alpaka_serial_sync + +#ifdef ALPAKA_ACCELERATOR_NAMESPACE +#define ALPAKA_DUPLICATE_NAMESPACE +#else +#define ALPAKA_ACCELERATOR_NAMESPACE alpaka_serial_sync +#define ALPAKA_TYPE_SUFFIX SerialSync +#endif + +#endif // ALPAKA_ACC_CPU_B_SEQ_T_SEQ_ENABLED + +#ifdef ALPAKA_ACC_CPU_B_TBB_T_SEQ_ENABLED +namespace alpaka_tbb_async { + using namespace alpaka_common; + + using Platform = alpaka::PltfCpu; + using Device = alpaka::DevCpu; + using Queue = alpaka::QueueCpuNonBlocking; + using Event = alpaka::EventCpu; + + template + using Acc = alpaka::AccCpuTbbBlocks; + using Acc1D = Acc; + using Acc2D = Acc; + using Acc3D = Acc; + +} // namespace alpaka_tbb_async + +#ifdef ALPAKA_ACCELERATOR_NAMESPACE +#define ALPAKA_DUPLICATE_NAMESPACE +#else +#define ALPAKA_ACCELERATOR_NAMESPACE alpaka_tbb_async +#define ALPAKA_TYPE_SUFFIX TbbAsync +#endif + +#endif // ALPAKA_ACC_CPU_B_TBB_T_SEQ_ENABLED + +#if defined ALPAKA_DUPLICATE_NAMESPACE +#error Only one alpaka backend symbol can be defined at the same time: ALPAKA_ACC_GPU_CUDA_ENABLED, ALPAKA_ACC_GPU_HIP_ENABLED, ALPAKA_ACC_CPU_B_SEQ_T_SEQ_ENABLED, ALPAKA_ACC_CPU_B_TBB_T_SEQ_ENABLED. +#endif + +#if defined ALPAKA_ACCELERATOR_NAMESPACE + +// create a new backend-specific identifier based on the original type name and a backend-specific suffix +#define ALPAKA_TYPE_ALIAS__(TYPE, SUFFIX) TYPE##SUFFIX +#define ALPAKA_TYPE_ALIAS_(TYPE, SUFFIX) ALPAKA_TYPE_ALIAS__(TYPE, SUFFIX) +#define ALPAKA_TYPE_ALIAS(TYPE) ALPAKA_TYPE_ALIAS_(TYPE, ALPAKA_TYPE_SUFFIX) + +// declare the backend-specific identifier as an alias for the namespace-based type name +#define DECLARE_ALPAKA_TYPE_ALIAS(TYPE) using ALPAKA_TYPE_ALIAS(TYPE) = ALPAKA_ACCELERATOR_NAMESPACE::TYPE + +// define a null-terminated string containing the backend-specific identifier +#define ALPAKA_TYPE_ALIAS_NAME(TYPE) EDM_STRINGIZE(ALPAKA_TYPE_ALIAS(TYPE)) + +#endif // ALPAKA_ACCELERATOR_NAMESPACE + +#endif // HeterogeneousCore_AlpakaInterface_interface_config_h diff --git a/HeterogeneousCore/AlpakaInterface/interface/host.h b/HeterogeneousCore/AlpakaInterface/interface/host.h new file mode 100644 index 0000000000000..147efd9a819a8 --- /dev/null +++ b/HeterogeneousCore/AlpakaInterface/interface/host.h @@ -0,0 +1,16 @@ +#ifndef HeterogeneousCore_AlpakaInterface_interface_host_h +#define HeterogeneousCore_AlpakaInterface_interface_host_h + +#include "HeterogeneousCore/AlpakaInterface/interface/config.h" + +namespace alpaka_common { + + // alpaka host device + static inline DevHost const& host() { + static const auto host = alpaka::getDevByIdx(0u); + return host; + } + +} // namespace alpaka_common + +#endif // HeterogeneousCore_AlpakaInterface_interface_host_h diff --git a/HeterogeneousCore/AlpakaServices/BuildFile.xml b/HeterogeneousCore/AlpakaServices/BuildFile.xml new file mode 100644 index 0000000000000..e165ce9200bbc --- /dev/null +++ b/HeterogeneousCore/AlpakaServices/BuildFile.xml @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/HeterogeneousCore/AlpakaServices/interface/alpaka/AlpakaService.h b/HeterogeneousCore/AlpakaServices/interface/alpaka/AlpakaService.h new file mode 100644 index 0000000000000..df9e1bcd38f93 --- /dev/null +++ b/HeterogeneousCore/AlpakaServices/interface/alpaka/AlpakaService.h @@ -0,0 +1,41 @@ +#ifndef HeterogeneousCore_AlpakaServices_interface_AlpakaService_h +#define HeterogeneousCore_AlpakaServices_interface_AlpakaService_h + +#include + +#include + +#include "HeterogeneousCore/AlpakaInterface/interface/config.h" + +namespace edm { + class ActivityRegistry; + class ConfigurationDescriptions; + class ParameterSet; +} // namespace edm + +namespace ALPAKA_ACCELERATOR_NAMESPACE { + + class AlpakaService { + public: + AlpakaService(edm::ParameterSet const& config, edm::ActivityRegistry&); + ~AlpakaService() = default; + + static void fillDescriptions(edm::ConfigurationDescriptions& descriptions); + + bool enabled() const { return enabled_; } + + std::vector const& devices() const { return devices_; } + + Device const& device(uint32_t index) const { return devices_.at(index); } + + private: + bool enabled_ = false; + bool verbose_ = false; + std::vector devices_; + }; + +} // namespace ALPAKA_ACCELERATOR_NAMESPACE + +DECLARE_ALPAKA_TYPE_ALIAS(AlpakaService); + +#endif // HeterogeneousCore_AlpakaServices_interface_AlpakaService_h diff --git a/HeterogeneousCore/AlpakaServices/plugins/BuildFile.xml b/HeterogeneousCore/AlpakaServices/plugins/BuildFile.xml new file mode 100644 index 0000000000000..0da58dae89970 --- /dev/null +++ b/HeterogeneousCore/AlpakaServices/plugins/BuildFile.xml @@ -0,0 +1,16 @@ + + + + + + + + + + + + + diff --git a/HeterogeneousCore/AlpakaServices/plugins/alpaka/plugins.cc b/HeterogeneousCore/AlpakaServices/plugins/alpaka/plugins.cc new file mode 100644 index 0000000000000..4c3e3da3ff3a2 --- /dev/null +++ b/HeterogeneousCore/AlpakaServices/plugins/alpaka/plugins.cc @@ -0,0 +1,5 @@ +#include "FWCore/ServiceRegistry/interface/ServiceMaker.h" +#include "HeterogeneousCore/AlpakaInterface/interface/config.h" +#include "HeterogeneousCore/AlpakaServices/interface/alpaka/AlpakaService.h" + +DEFINE_FWK_SERVICE(ALPAKA_TYPE_ALIAS(AlpakaService)); diff --git a/HeterogeneousCore/AlpakaServices/src/alpaka/AlpakaService.cc b/HeterogeneousCore/AlpakaServices/src/alpaka/AlpakaService.cc new file mode 100644 index 0000000000000..bc59c755137e8 --- /dev/null +++ b/HeterogeneousCore/AlpakaServices/src/alpaka/AlpakaService.cc @@ -0,0 +1,78 @@ +#include + +#include + +#include "FWCore/MessageLogger/interface/MessageLogger.h" +#include "FWCore/ParameterSet/interface/ConfigurationDescriptions.h" +#include "FWCore/ParameterSet/interface/ParameterSet.h" +#include "FWCore/ParameterSet/interface/ParameterSetDescription.h" +#include "HeterogeneousCore/AlpakaServices/interface/alpaka/AlpakaService.h" + +#ifdef ALPAKA_ACC_GPU_CUDA_ENABLED +#include "FWCore/ServiceRegistry/interface/Service.h" +#include "HeterogeneousCore/CUDAServices/interface/CUDAService.h" +#endif // ALPAKA_ACC_GPU_CUDA_ENABLED + +namespace ALPAKA_ACCELERATOR_NAMESPACE { + + AlpakaService::AlpakaService(edm::ParameterSet const& config, edm::ActivityRegistry&) + : enabled_(config.getUntrackedParameter("enabled")), + verbose_(config.getUntrackedParameter("verbose")) { +#ifdef ALPAKA_ACC_GPU_CUDA_ENABLED + // rely on the CUDAService to initialise the CUDA devices + edm::Service cudaService; +#endif // ALPAKA_ACC_GPU_CUDA_ENABLED + + // TODO from Andrea Bocci: + // - handle alpaka caching allocators ? + // - extract and print more information about the platform and devices + + if (not enabled_) { + edm::LogInfo("AlpakaService") << ALPAKA_TYPE_ALIAS_NAME(AlpakaService) << " disabled by configuration"; + return; + } + +#ifdef ALPAKA_ACC_GPU_CUDA_ENABLED + if (not cudaService->enabled()) { + enabled_ = false; + edm::LogInfo("AlpakaService") << ALPAKA_TYPE_ALIAS_NAME(AlpakaService) << " disabled by CUDAService"; + return; + } +#endif // ALPAKA_ACC_GPU_CUDA_ENABLED + + // enumerate all devices on this platform + uint32_t n = alpaka::getDevCount(); + if (n == 0) { + const std::string platform = boost::core::demangle(typeid(Platform).name()); + edm::LogWarning("AlpakaService") << "Could not find any devices on platform " << platform << ".\n" + << "Disabling " << ALPAKA_TYPE_ALIAS_NAME(AlpakaService) << "."; + enabled_ = false; + return; + } + + devices_.reserve(n); + for (uint32_t i = 0; i < n; ++i) { + devices_.push_back(alpaka::getDevByIdx(i)); + //assert(getDeviceIndex(devices_.back()) == static_cast(i)); + } + + { + const char* suffix[] = {"s.", ":", "s:"}; + edm::LogInfo out("AlpakaService"); + out << ALPAKA_TYPE_ALIAS_NAME(AlpakaService) << " succesfully initialised.\n"; + out << "Found " << n << " device" << suffix[n < 2 ? n : 2]; + for (auto const& device : devices_) { + out << "\n - " << alpaka::getName(device); + } + } + } + + void AlpakaService::fillDescriptions(edm::ConfigurationDescriptions& descriptions) { + edm::ParameterSetDescription desc; + desc.addUntracked("enabled", true); + desc.addUntracked("verbose", false); + + descriptions.add(ALPAKA_TYPE_ALIAS_NAME(AlpakaService), desc); + } + +} // namespace ALPAKA_ACCELERATOR_NAMESPACE diff --git a/HeterogeneousCore/AlpakaTest/plugins/BuildFile.xml b/HeterogeneousCore/AlpakaTest/plugins/BuildFile.xml new file mode 100644 index 0000000000000..82a5b499f9d85 --- /dev/null +++ b/HeterogeneousCore/AlpakaTest/plugins/BuildFile.xml @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/HeterogeneousCore/AlpakaTest/plugins/TestAlpakaAnalyzer.cc b/HeterogeneousCore/AlpakaTest/plugins/TestAlpakaAnalyzer.cc new file mode 100644 index 0000000000000..8b1779e9e4e6e --- /dev/null +++ b/HeterogeneousCore/AlpakaTest/plugins/TestAlpakaAnalyzer.cc @@ -0,0 +1,50 @@ +#include +#include + +#include "DataFormats/PortableTestObjects/interface/TestHostCollection.h" +#include "FWCore/Framework/interface/Event.h" +#include "FWCore/Framework/interface/EventSetup.h" +#include "FWCore/Framework/interface/Frameworkfwd.h" +#include "FWCore/Framework/interface/stream/EDAnalyzer.h" +#include "FWCore/MessageLogger/interface/MessageLogger.h" +#include "FWCore/ParameterSet/interface/ConfigurationDescriptions.h" +#include "FWCore/ParameterSet/interface/ParameterSet.h" +#include "FWCore/ParameterSet/interface/ParameterSetDescription.h" +#include "FWCore/Utilities/interface/EDGetToken.h" +#include "FWCore/Utilities/interface/InputTag.h" + +class TestAlpakaAnalyzer : public edm::stream::EDAnalyzer<> { +public: + TestAlpakaAnalyzer(edm::ParameterSet const& config) + : source_{config.getParameter("source")}, token_{consumes(source_)} {} + + void analyze(edm::Event const& event, edm::EventSetup const&) override { + portabletest::TestHostCollection const& product = event.get(token_); + + auto const& view = product.const_view(); + for (int32_t i = 0; i < view.metadata().size(); ++i) { + assert(view[i].id() == i); + } + + edm::LogInfo msg("TestAlpakaAnalyzer"); + msg << source_.encode() << ".size() = " << view.metadata().size() << '\n'; + msg << "data = " << product.buffer().data() << " x = " << view.x() << " y = " << view.y() << " z = " << view.z() + << " id = " << view.id() << '\n'; + msg << std::hex << "[y - x] = 0x" << reinterpret_cast(view.y()) - reinterpret_cast(view.x()) + << " [z - y] = 0x" << reinterpret_cast(view.z()) - reinterpret_cast(view.y()) + << " [id - z] = 0x" << reinterpret_cast(view.id()) - reinterpret_cast(view.z()); + } + + static void fillDescriptions(edm::ConfigurationDescriptions& descriptions) { + edm::ParameterSetDescription desc; + desc.add("source"); + descriptions.addWithDefaultLabel(desc); + } + +private: + const edm::InputTag source_; + const edm::EDGetTokenT token_; +}; + +#include "FWCore/Framework/interface/MakerMacros.h" +DEFINE_FWK_MODULE(TestAlpakaAnalyzer); diff --git a/HeterogeneousCore/AlpakaTest/plugins/alpaka/TestAlgo.dev.cc b/HeterogeneousCore/AlpakaTest/plugins/alpaka/TestAlgo.dev.cc new file mode 100644 index 0000000000000..797125d5f330f --- /dev/null +++ b/HeterogeneousCore/AlpakaTest/plugins/alpaka/TestAlgo.dev.cc @@ -0,0 +1,40 @@ +// Check that ALPAKA_HOST_ONLY is not defined during device compilation: +#ifdef ALPAKA_HOST_ONLY +#error ALPAKA_HOST_ONLY defined in device compilation +#endif + +#include + +#include "DataFormats/PortableTestObjects/interface/alpaka/TestDeviceCollection.h" +#include "HeterogeneousCore/AlpakaInterface/interface/config.h" + +#include "TestAlgo.h" + +namespace ALPAKA_ACCELERATOR_NAMESPACE { + + class TestAlgoKernel { + public: + template + ALPAKA_FN_ACC void operator()(TAcc const& acc, portabletest::TestDeviceCollection::View view, int32_t size) const { + // this example accepts an arbitrary number of blocks and threads, and always uses 1 element per thread + const int32_t thread = alpaka::getIdx(acc)[0u]; + const int32_t stride = alpaka::getWorkDiv(acc)[0u]; + for (auto i = thread; i < size; i += stride) { + view[i] = {0., 0., 0., i}; + } + } + }; + + void TestAlgo::fill(Queue& queue, portabletest::TestDeviceCollection& collection) const { + auto const& deviceProperties = alpaka::getAccDevProps(alpaka::getDev(queue)); + uint32_t maxThreadsPerBlock = deviceProperties.m_blockThreadExtentMax[0]; + + uint32_t threadsPerBlock = maxThreadsPerBlock; + uint32_t blocksPerGrid = (collection->metadata().size() + threadsPerBlock - 1) / threadsPerBlock; + uint32_t elementsPerThread = 1; + auto workDiv = WorkDiv1D{blocksPerGrid, threadsPerBlock, elementsPerThread}; + + alpaka::exec(queue, workDiv, TestAlgoKernel{}, collection.view(), collection->metadata().size()); + } + +} // namespace ALPAKA_ACCELERATOR_NAMESPACE diff --git a/HeterogeneousCore/AlpakaTest/plugins/alpaka/TestAlgo.h b/HeterogeneousCore/AlpakaTest/plugins/alpaka/TestAlgo.h new file mode 100644 index 0000000000000..64ed9421121b4 --- /dev/null +++ b/HeterogeneousCore/AlpakaTest/plugins/alpaka/TestAlgo.h @@ -0,0 +1,16 @@ +#ifndef HeterogeneousCore_AlpakaTest_plugins_alpaka_TestAlgo_h +#define HeterogeneousCore_AlpakaTest_plugins_alpaka_TestAlgo_h + +#include "DataFormats/PortableTestObjects/interface/alpaka/TestDeviceCollection.h" +#include "HeterogeneousCore/AlpakaInterface/interface/config.h" + +namespace ALPAKA_ACCELERATOR_NAMESPACE { + + class TestAlgo { + public: + void fill(Queue& queue, portabletest::TestDeviceCollection& collection) const; + }; + +} // namespace ALPAKA_ACCELERATOR_NAMESPACE + +#endif // HeterogeneousCore_AlpakaTest_plugins_alpaka_TestAlgo_h diff --git a/HeterogeneousCore/AlpakaTest/plugins/alpaka/TestAlpakaProducer.cc b/HeterogeneousCore/AlpakaTest/plugins/alpaka/TestAlpakaProducer.cc new file mode 100644 index 0000000000000..00770e3cc974e --- /dev/null +++ b/HeterogeneousCore/AlpakaTest/plugins/alpaka/TestAlpakaProducer.cc @@ -0,0 +1,75 @@ +#include +#include + +#include + +#include "DataFormats/PortableTestObjects/interface/alpaka/TestDeviceCollection.h" +#include "FWCore/Framework/interface/Event.h" +#include "FWCore/Framework/interface/EventSetup.h" +#include "FWCore/Framework/interface/Frameworkfwd.h" +#include "FWCore/Framework/interface/stream/EDProducer.h" +#include "FWCore/ParameterSet/interface/ConfigurationDescriptions.h" +#include "FWCore/ParameterSet/interface/ParameterSet.h" +#include "FWCore/ParameterSet/interface/ParameterSetDescription.h" +#include "FWCore/ServiceRegistry/interface/Service.h" +#include "FWCore/Utilities/interface/EDGetToken.h" +#include "FWCore/Utilities/interface/InputTag.h" +#include "FWCore/Utilities/interface/StreamID.h" +#include "HeterogeneousCore/AlpakaInterface/interface/config.h" +#include "HeterogeneousCore/AlpakaServices/interface/alpaka/AlpakaService.h" + +#include "TestAlgo.h" + +namespace ALPAKA_ACCELERATOR_NAMESPACE { + + class TestAlpakaProducer : public edm::stream::EDProducer<> { + public: + TestAlpakaProducer(edm::ParameterSet const& config) + : deviceToken_{produces()}, size_{config.getParameter("size")} {} + + void beginStream(edm::StreamID sid) override { + // choose a device based on the EDM stream number + edm::Service service; + if (not service->enabled()) { + throw cms::Exception("Configuration") << ALPAKA_TYPE_ALIAS_NAME(AlpakaService) << " is disabled."; + } + auto& devices = service->devices(); + unsigned int index = sid.value() % devices.size(); + device_ = devices[index]; + } + + void produce(edm::Event& event, edm::EventSetup const&) override { + // create a queue to submit async work + Queue queue{*device_}; + portabletest::TestDeviceCollection deviceProduct{size_, *device_}; + + // run the algorithm, potentially asynchronously + algo_.fill(queue, deviceProduct); + + // wait for any asynchronous work to complete + alpaka::wait(queue); + + event.emplace(deviceToken_, std::move(deviceProduct)); + } + + static void fillDescriptions(edm::ConfigurationDescriptions& descriptions) { + edm::ParameterSetDescription desc; + desc.add("size"); + descriptions.addWithDefaultLabel(desc); + } + + private: + const edm::EDPutTokenT deviceToken_; + const int32_t size_; + + // device associated to the EDM stream + std::optional device_; + + // implementation of the algorithm + TestAlgo algo_; + }; + +} // namespace ALPAKA_ACCELERATOR_NAMESPACE + +#include "HeterogeneousCore/AlpakaCore/interface/MakerMacros.h" +DEFINE_FWK_ALPAKA_MODULE(TestAlpakaProducer); diff --git a/HeterogeneousCore/AlpakaTest/plugins/alpaka/TestAlpakaTranscriber.cc b/HeterogeneousCore/AlpakaTest/plugins/alpaka/TestAlpakaTranscriber.cc new file mode 100644 index 0000000000000..d9cea435bbcd5 --- /dev/null +++ b/HeterogeneousCore/AlpakaTest/plugins/alpaka/TestAlpakaTranscriber.cc @@ -0,0 +1,77 @@ +// The "Transcriber" makes sense only across different memory spaces +#if defined(ALPAKA_ACC_GPU_CUDA_ENABLED) or defined(ALPAKA_ACC_GPU_HIP_ENABLED) + +#include +#include + +#include + +#include "DataFormats/PortableTestObjects/interface/TestHostCollection.h" +#include "DataFormats/PortableTestObjects/interface/alpaka/TestDeviceCollection.h" +#include "FWCore/Framework/interface/Event.h" +#include "FWCore/Framework/interface/EventSetup.h" +#include "FWCore/Framework/interface/Frameworkfwd.h" +#include "FWCore/Framework/interface/stream/EDProducer.h" +#include "FWCore/ParameterSet/interface/ConfigurationDescriptions.h" +#include "FWCore/ParameterSet/interface/ParameterSet.h" +#include "FWCore/ParameterSet/interface/ParameterSetDescription.h" +#include "FWCore/ServiceRegistry/interface/Service.h" +#include "FWCore/Utilities/interface/EDGetToken.h" +#include "FWCore/Utilities/interface/InputTag.h" +#include "FWCore/Utilities/interface/StreamID.h" +#include "HeterogeneousCore/AlpakaInterface/interface/config.h" +#include "HeterogeneousCore/AlpakaInterface/interface/host.h" +#include "HeterogeneousCore/AlpakaServices/interface/alpaka/AlpakaService.h" + +namespace ALPAKA_ACCELERATOR_NAMESPACE { + + class TestAlpakaTranscriber : public edm::stream::EDProducer<> { + public: + TestAlpakaTranscriber(edm::ParameterSet const& config) + : deviceToken_{consumes(config.getParameter("source"))}, hostToken_{produces()} {} + + void beginStream(edm::StreamID sid) override { + // choose a device based on the EDM stream number + edm::Service service; + if (not service->enabled()) { + throw cms::Exception("Configuration") << ALPAKA_TYPE_ALIAS_NAME(AlpakaService) << " is disabled."; + } + auto& devices = service->devices(); + unsigned int index = sid.value() % devices.size(); + device_ = devices[index]; + } + + void produce(edm::Event& event, edm::EventSetup const&) override { + // create a queue to submit async work + Queue queue{*device_}; + portabletest::TestDeviceCollection const& deviceProduct = event.get(deviceToken_); + + portabletest::TestHostCollection hostProduct{deviceProduct->metadata().size(), alpaka_common::host(), *device_}; + alpaka::memcpy(queue, hostProduct.buffer(), deviceProduct.const_buffer()); + + // wait for any async work to complete + alpaka::wait(queue); + + event.emplace(hostToken_, std::move(hostProduct)); + } + + static void fillDescriptions(edm::ConfigurationDescriptions& descriptions) { + edm::ParameterSetDescription desc; + desc.add("source"); + descriptions.addWithDefaultLabel(desc); + } + + private: + const edm::EDGetTokenT deviceToken_; + const edm::EDPutTokenT hostToken_; + + // device associated to the EDM stream + std::optional device_; + }; + +} // namespace ALPAKA_ACCELERATOR_NAMESPACE + +#include "HeterogeneousCore/AlpakaCore/interface/MakerMacros.h" +DEFINE_FWK_ALPAKA_MODULE(TestAlpakaTranscriber); + +#endif // defined(ALPAKA_ACC_GPU_CUDA_ENABLED) or defined(ALPAKA_ACC_GPU_HIP_ENABLED) diff --git a/HeterogeneousCore/AlpakaTest/test/BuildFile.xml b/HeterogeneousCore/AlpakaTest/test/BuildFile.xml new file mode 100644 index 0000000000000..c53ee8acdb820 --- /dev/null +++ b/HeterogeneousCore/AlpakaTest/test/BuildFile.xml @@ -0,0 +1,4 @@ + diff --git a/HeterogeneousCore/AlpakaTest/test/reader.py b/HeterogeneousCore/AlpakaTest/test/reader.py new file mode 100644 index 0000000000000..8ad854082d38f --- /dev/null +++ b/HeterogeneousCore/AlpakaTest/test/reader.py @@ -0,0 +1,27 @@ +import FWCore.ParameterSet.Config as cms + +process = cms.Process('Reader') + +# read the products from a 'test.root' file +process.source = cms.Source('PoolSource', + fileNames = cms.untracked.vstring('file:test.root') +) + +# enable logging for the TestAlpakaAnalyzer +process.MessageLogger.TestAlpakaAnalyzer = cms.untracked.PSet() + +# analyse the first product +process.testAnalyzer = cms.EDAnalyzer('TestAlpakaAnalyzer', + source = cms.InputTag('testProducer') +) + +# analyse the second product +process.testAnalyzerSerial = cms.EDAnalyzer('TestAlpakaAnalyzer', + source = cms.InputTag('testProducerSerial') +) + +process.cuda_path = cms.Path(process.testAnalyzer) + +process.serial_path = cms.Path(process.testAnalyzerSerial) + +process.maxEvents.input = 10 diff --git a/HeterogeneousCore/AlpakaTest/test/writer.py b/HeterogeneousCore/AlpakaTest/test/writer.py new file mode 100644 index 0000000000000..57fcb51a376f2 --- /dev/null +++ b/HeterogeneousCore/AlpakaTest/test/writer.py @@ -0,0 +1,81 @@ +import FWCore.ParameterSet.Config as cms +from HeterogeneousCore.CUDACore.SwitchProducerCUDA import SwitchProducerCUDA + +process = cms.Process('Writer') + +process.source = cms.Source('EmptySource') + +process.load('Configuration.StandardSequences.Accelerators_cff') + +# enable logging for the AlpakaService and TestAlpakaAnalyzer +process.MessageLogger.TestAlpakaAnalyzer = cms.untracked.PSet() +process.MessageLogger.AlpakaService = cms.untracked.PSet() + +# enable alpaka-based heterogeneous modules +process.AlpakaServiceCudaAsync = cms.Service('AlpakaServiceCudaAsync') +process.AlpakaServiceSerialSync = cms.Service('AlpakaServiceSerialSync') + +# run the producer on a CUDA gpu (if available) +process.testProducerCuda = cms.EDProducer('alpaka_cuda_async::TestAlpakaProducer', + size = cms.int32(42) +) + +# copy the product from the gpu (if available) to the host +process.testTranscriberFromCuda = cms.EDProducer('alpaka_cuda_async::TestAlpakaTranscriber', + source = cms.InputTag('testProducerCuda') +) + +# run the producer on the cpu +process.testProducerCpu = cms.EDProducer('alpaka_serial_sync::TestAlpakaProducer', + size = cms.int32(42) +) + +# either run the producer on a CUDA gpu (if available) and copy the product to the cpu, or run the producer directly on the cpu +process.testProducer = SwitchProducerCUDA( + cpu = cms.EDAlias( + testProducerCpu = cms.VPSet(cms.PSet(type = cms.string('*'))) + ), + cuda = cms.EDAlias( + testTranscriberFromCuda = cms.VPSet(cms.PSet(type = cms.string('*'))) + ) +) + +# analyse the product +process.testAnalyzer = cms.EDAnalyzer('TestAlpakaAnalyzer', + source = cms.InputTag('testProducer') +) + +# run a second producer explicitly on the cpu +process.testProducerSerial = cms.EDProducer('alpaka_serial_sync::TestAlpakaProducer', + size = cms.int32(99) +) + +# analyse the second product +process.testAnalyzerSerial = cms.EDAnalyzer('TestAlpakaAnalyzer', + source = cms.InputTag('testProducerSerial') +) + +# write the two products to a 'test.root' file +process.output = cms.OutputModule('PoolOutputModule', + fileName = cms.untracked.string('test.root'), + outputCommands = cms.untracked.vstring( + 'drop *', + 'keep *_testProducer_*_*', + 'keep *_testProducerSerial_*_*', + ) +) + +process.producer_task = cms.Task(process.testProducerCuda, process.testTranscriberFromCuda, process.testProducerCpu) + +process.process_path = cms.Path( + process.testProducer + + process.testAnalyzer, + process.producer_task) + +process.serial_path = cms.Path( + process.testProducerSerial + + process.testAnalyzerSerial) + +process.output_path = cms.EndPath(process.output) + +process.maxEvents.input = 10 diff --git a/IOPool/Common/bin/EdmProvDump.cc b/IOPool/Common/bin/EdmProvDump.cc index e837709b8cfea..3a1dae6a36ae7 100644 --- a/IOPool/Common/bin/EdmProvDump.cc +++ b/IOPool/Common/bin/EdmProvDump.cc @@ -1,5 +1,7 @@ #include "DataFormats/Common/interface/setIsMergeable.h" +#include "DataFormats/Provenance/interface/BranchIDListHelper.h" #include "DataFormats/Provenance/interface/BranchType.h" +#include "DataFormats/Provenance/interface/branchIDToProductID.h" #include "DataFormats/Provenance/interface/EventSelectionID.h" #include "DataFormats/Provenance/interface/History.h" #include "DataFormats/Provenance/interface/ParameterSetBlob.h" @@ -29,6 +31,7 @@ #include #include #include +#include #include #include #include @@ -441,7 +444,8 @@ class ProvenanceDumper { bool showTopLevelPSets, std::vector const& findMatch, bool dontPrintProducts, - std::string const& dumpPSetID); + std::string const& dumpPSetID, + int productIDEntry); ProvenanceDumper(ProvenanceDumper const&) = delete; // Disallow copying and moving ProvenanceDumper& operator=(ProvenanceDumper const&) = delete; // Disallow copying and moving @@ -482,12 +486,14 @@ class ProvenanceDumper { std::vector findMatch_; bool dontPrintProducts_; std::string dumpPSetID_; + int const productIDEntry_; void work_(); void dumpProcessHistory_(); void dumpEventFilteringParameterSets_(TFile* file); void dumpEventFilteringParameterSets(edm::EventSelectionIDVector const& ids); void dumpParameterSetForID_(edm::ParameterSetID const& id); + std::optional>> makeBranchIDListHelper(); }; ProvenanceDumper::ProvenanceDumper(std::string const& filename, @@ -499,7 +505,8 @@ ProvenanceDumper::ProvenanceDumper(std::string const& filename, bool showTopLevelPSets, std::vector const& findMatch, bool dontPrintProducts, - std::string const& dumpPSetID) + std::string const& dumpPSetID, + int productIDEntry) : filename_(filename), inputFile_(makeTFile(filename)), exitCode_(0), @@ -514,7 +521,8 @@ ProvenanceDumper::ProvenanceDumper(std::string const& filename, showTopLevelPSets_(showTopLevelPSets), findMatch_(findMatch), dontPrintProducts_(dontPrintProducts), - dumpPSetID_(dumpPSetID) {} + dumpPSetID_(dumpPSetID), + productIDEntry_(productIDEntry) {} void ProvenanceDumper::dump() { work_(); } @@ -627,6 +635,71 @@ void ProvenanceDumper::dumpProcessHistory_() { historyGraph_.printHistory(); } +std::optional>> +ProvenanceDumper::makeBranchIDListHelper() { + // BranchID-to-ProductID mapping disabled + if (productIDEntry_ < 0) { + return {}; + } + + TTree* metaTree = dynamic_cast(inputFile_->Get(edm::poolNames::metaDataTreeName().c_str())); + if (nullptr == metaTree) { + //std::cerr << "Did not find " << edm::poolNames::metaDataTreeName() << " tree" << std::endl; + return {}; + } + + TBranch* branchIDListsBranch = metaTree->GetBranch(edm::poolNames::branchIDListBranchName().c_str()); + if (nullptr == branchIDListsBranch) { + /* + std::cerr << "Did not find " << edm::poolNames::branchIDListBranchName() << " from " + << edm::poolNames::metaDataTreeName() << " tree" << std::endl; + */ + return {}; + } + + edm::BranchIDLists branchIDLists; + edm::BranchIDLists* branchIDListsPtr = &branchIDLists; + branchIDListsBranch->SetAddress(&branchIDListsPtr); + if (branchIDListsBranch->GetEntry(0) <= 0) { + //std::cerr << "Failed to read an entry from " << edm::poolNames::branchIDListBranchName() << std::endl; + return {}; + } + + edm::BranchIDListHelper branchIDListHelper; + branchIDListHelper.updateFromInput(branchIDLists); + + TTree* events = dynamic_cast(inputFile_->Get(edm::poolNames::eventTreeName().c_str())); + assert(events != nullptr); + TBranch* branchListIndexesBranch = events->GetBranch(edm::poolNames::branchListIndexesBranchName().c_str()); + if (nullptr == branchListIndexesBranch) { + /* + std::cerr << "Did not find " << edm::poolNames::branchListIndexesBranchName() << " from " + << edm::poolNames::eventTreeName() << " tree" << std::endl; + */ + return {}; + } + edm::BranchListIndexes branchListIndexes; + edm::BranchListIndexes* pbranchListIndexes = &branchListIndexes; + branchListIndexesBranch->SetAddress(&pbranchListIndexes); + if (branchListIndexesBranch->GetEntry(productIDEntry_) <= 0 or branchListIndexes.empty()) { + /* + std::cerr << "Failed to read entry from " << edm::poolNames::branchListIndexesBranchName() << ", or it is empty" + << std::endl; + */ + return {}; + } + + if (not branchIDListHelper.fixBranchListIndexes(branchListIndexes)) { + //std::cerr << "Call to branchIDListHelper.fixBranchListIndexes() failed" << std::endl; + return {}; + } + + // Fill in helper map for Branch to ProductID mapping + auto branchListIndexToProcessIndex = edm::makeBranchListIndexToProcessIndex(branchListIndexes); + + return std::tuple(std::move(branchIDListHelper), std::move(branchListIndexToProcessIndex)); +} + void ProvenanceDumper::work_() { TTree* meta = dynamic_cast(inputFile_->Get(edm::poolNames::metaDataTreeName().c_str())); assert(nullptr != meta); @@ -717,6 +790,9 @@ void ProvenanceDumper::work_() { return; } + // Helper to map BranchID to ProductID (metadata tree needed also for parentage information) + auto branchIDListHelperAndToProcessIndex = makeBranchIDListHelper(); + //Prepare the parentage information if requested std::map> perProductParentage; @@ -887,7 +963,17 @@ void ProvenanceDumper::work_() { std::set branchIDs; for (auto const& branch : idBranch.second) { if (!dontPrintProducts_) { - sout << " " << branch.branchName() << std::endl; + sout << " " << branch.branchName(); + edm::ProductID id; + if (branchIDListHelperAndToProcessIndex) { + sout << " ProductID " + << edm::branchIDToProductID(branch.branchID(), + std::get<0>(*branchIDListHelperAndToProcessIndex), + std::get<1>(*branchIDListHelperAndToProcessIndex)); + } else { + sout << " BranchID " << branch.branchID(); + } + sout << std::endl; } branchIDs.insert(branch.branchID()); allBranchIDsForLabelAndProcess.insert(branch.branchID()); @@ -1042,6 +1128,7 @@ static char const* const kHelpCommandOpt = "help,h"; static char const* const kFileNameOpt = "input-file"; static char const* const kDumpPSetIDOpt = "dumpPSetID"; static char const* const kDumpPSetIDCommandOpt = "dumpPSetID,i"; +static char const* const kProductIDEntryOpt = "productIDEntry"; int main(int argc, char* argv[]) { using namespace boost::program_options; @@ -1066,7 +1153,10 @@ int main(int argc, char* argv[]) { "be repeated with different strings)")(kDontPrintProductsCommandOpt, "do not print products produced by module")( kDumpPSetIDCommandOpt, value(), - "print the parameter set associated with the parameter set ID string (and print nothing else)"); + "print the parameter set associated with the parameter set ID string (and print nothing else)")( + kProductIDEntryOpt, + value(), + "show ProductID instead of BranchID using the specified entry in the Events tree"); // clang-format on //we don't want users to see these in the help messages since this @@ -1168,6 +1258,16 @@ int main(int argc, char* argv[]) { dontPrintProducts = true; } + int productIDEntry = -1; + if (vm.count(kProductIDEntryOpt)) { + try { + productIDEntry = vm[kProductIDEntryOpt].as(); + } catch (boost::bad_any_cast const& e) { + std::cout << e.what() << std::endl; + return 2; + } + } + //silence ROOT warnings about missing dictionaries gErrorIgnoreLevel = kError; @@ -1180,7 +1280,8 @@ int main(int argc, char* argv[]) { showTopLevelPSets, findMatch, dontPrintProducts, - dumpPSetID); + dumpPSetID, + productIDEntry); int exitCode(0); try { dumper.dump(); diff --git a/IOPool/Common/test/unit_test_outputs/provdump.log b/IOPool/Common/test/unit_test_outputs/provdump.log index b8f17e3e9a769..a2ead2f9a5875 100644 --- a/IOPool/Common/test/unit_test_outputs/provdump.log +++ b/IOPool/Common/test/unit_test_outputs/provdump.log @@ -14,7 +14,7 @@ Processing History: Module: TriggerResults PROD1 PSet id:1d569bb732972ed5978f283a32c90565 products: { - edmTriggerResults_TriggerResults__PROD1. + edmTriggerResults_TriggerResults__PROD1. BranchID 3548090599 } parameters: { @trigger_paths: vstring tracked = {'p'} @@ -23,7 +23,7 @@ Module: TriggerResults PROD1 Module: aliasForInt PROD1 PSet id:6629013372178d257799a6e9fc9aa2cd products: { - edmtestIntProduct_aliasForInt__PROD1. + edmtestIntProduct_aliasForInt__PROD1. BranchID 3673681161 } parameters: { @module_edm_type: string tracked = 'EDAlias' @@ -39,7 +39,7 @@ Module: aliasForInt PROD1 Module: intProducer PROD1 PSet id:3df1a82d54b59acbefd683a0491cddcf products: { - edmtestIntProduct_intProducer__PROD1. + edmtestIntProduct_intProducer__PROD1. BranchID 709634656 } parameters: { @module_edm_type: string tracked = 'EDProducer' @@ -51,7 +51,7 @@ Module: intProducer PROD1 Module: intProducerA PROD1 PSet id:38971365e8174cb2ccc12430661ba6d4 products: { - edmtestIntProduct_intProducerA__PROD1. + edmtestIntProduct_intProducerA__PROD1. BranchID 1289746214 } parameters: { @module_edm_type: string tracked = 'EDProducer' @@ -63,7 +63,7 @@ Module: intProducerA PROD1 Module: intProducerU PROD1 PSet id:4af95ea04257c4d5af7a39a5d880e879 products: { - edmtestIntProduct_intProducerU__PROD1. + edmtestIntProduct_intProducerU__PROD1. BranchID 3186877531 } parameters: { @module_edm_type: string tracked = 'EDProducer' @@ -75,7 +75,7 @@ Module: intProducerU PROD1 Module: intVectorProducer PROD1 PSet id:c016fa1f72fbfead00d09bc2e8e8a3c4 products: { - ints_intVectorProducer__PROD1. + ints_intVectorProducer__PROD1. BranchID 315054627 } parameters: { @module_edm_type: string tracked = 'EDProducer' @@ -89,7 +89,7 @@ Module: intVectorProducer PROD1 Module: source PROD1 PSet id:031810a3ee2992e7936b85708f83a8b2 products: { - edmtestIntProduct_source__PROD1. + edmtestIntProduct_source__PROD1. BranchID 3765011715 } parameters: { @module_edm_type: string tracked = 'Source' diff --git a/L1Trigger/Configuration/python/L1TRawToDigi_cff.py b/L1Trigger/Configuration/python/L1TRawToDigi_cff.py index 5d163257adde2..aaf600b1410f9 100644 --- a/L1Trigger/Configuration/python/L1TRawToDigi_cff.py +++ b/L1Trigger/Configuration/python/L1TRawToDigi_cff.py @@ -43,6 +43,7 @@ # Stage-2 Trigger: fow now, unpack Stage 1 and Stage 2 (in case both available) # from EventFilter.RPCRawToDigi.rpcTwinMuxRawToDigi_cfi import rpcTwinMuxRawToDigi +from EventFilter.RPCRawToDigi.rpcUnpacker_cfi import rpcunpacker from EventFilter.RPCRawToDigi.RPCCPPFRawToDigi_cfi import rpcCPPFRawToDigi from EventFilter.L1TRawToDigi.bmtfDigis_cfi import bmtfDigis from EventFilter.L1TRawToDigi.omtfStage2Digis_cfi import omtfStage2Digis @@ -56,7 +57,7 @@ stage2L1Trigger.toModify(caloStage2Digis, MinFeds = cms.uint32(1)) stage2L1Trigger.toModify(gmtStage2Digis, MinFeds = cms.uint32(1)) stage2L1Trigger.toModify(gtStage2Digis, MinFeds = cms.uint32(1)) -L1TRawToDigi_Stage2 = cms.Task(rpcTwinMuxRawToDigi, twinMuxStage2Digis, bmtfDigis, omtfStage2Digis, rpcCPPFRawToDigi, emtfStage2Digis, caloLayer1Digis, caloStage2Digis, gmtStage2Digis, gtStage2Digis) +L1TRawToDigi_Stage2 = cms.Task(rpcunpacker, rpcTwinMuxRawToDigi, twinMuxStage2Digis, bmtfDigis, omtfStage2Digis, rpcCPPFRawToDigi, emtfStage2Digis, caloLayer1Digis, caloStage2Digis, gmtStage2Digis, gtStage2Digis) stage2L1Trigger.toReplaceWith(L1TRawToDigiTask, cms.Task(L1TRawToDigi_Stage1,L1TRawToDigi_Stage2)) L1TRawToDigi = cms.Sequence(L1TRawToDigiTask) diff --git a/L1Trigger/L1TMuonCPPF/interface/EmulateCPPF.h b/L1Trigger/L1TMuonCPPF/interface/EmulateCPPF.h index a1613d5503f83..8b62459bcd31b 100644 --- a/L1Trigger/L1TMuonCPPF/interface/EmulateCPPF.h +++ b/L1Trigger/L1TMuonCPPF/interface/EmulateCPPF.h @@ -28,6 +28,7 @@ class EmulateCPPF { const edm::EDGetToken rpcDigiToken_; const edm::EDGetToken recHitToken_; const edm::EDGetToken rpcDigiSimLinkToken_; + const edm::ESGetToken rpcGeomToken_; enum class CppfSource { File, EventSetup } cppfSource_; std::vector CppfVec_1; diff --git a/L1Trigger/L1TMuonCPPF/interface/RecHitProcessor.h b/L1Trigger/L1TMuonCPPF/interface/RecHitProcessor.h index fbaca0821f342..6eea898982ef8 100644 --- a/L1Trigger/L1TMuonCPPF/interface/RecHitProcessor.h +++ b/L1Trigger/L1TMuonCPPF/interface/RecHitProcessor.h @@ -55,6 +55,7 @@ class RecHitProcessor { const edm::EDGetToken &recHitToken, const edm::EDGetToken &rpcDigiToken, const edm::EDGetToken &rpcDigiSimLinkToken, + const edm::ESGetToken &rpcGeomToken, std::vector &CppfVec1, // Output l1t::CPPFDigiCollection &cppfDigis, @@ -67,6 +68,7 @@ class RecHitProcessor { const edm::EDGetToken &recHitToken, const edm::EDGetToken &rpcDigiToken, const edm::EDGetToken &rpcDigiSimLinkToken, + const edm::ESGetToken &rpcGeomToken, // Output l1t::CPPFDigiCollection &cppfDigis) const; diff --git a/L1Trigger/L1TMuonCPPF/python/emulatorCppfDigis_cfi.py b/L1Trigger/L1TMuonCPPF/python/emulatorCppfDigis_cfi.py index ad2093a5531a1..ff30ef5511a6d 100644 --- a/L1Trigger/L1TMuonCPPF/python/emulatorCppfDigis_cfi.py +++ b/L1Trigger/L1TMuonCPPF/python/emulatorCppfDigis_cfi.py @@ -3,7 +3,7 @@ emulatorCppfDigis = cms.EDProducer("L1TMuonCPPFDigiProducer", ## Input collection recHitLabel = cms.InputTag("rpcRecHits"), - rpcDigiLabel = cms.InputTag("simMuonRPCDigis"), + rpcDigiLabel = cms.InputTag("muonRPCDigis"), rpcDigiSimLinkLabel = cms.InputTag("simMuonRPCDigis", "RPCDigiSimLink"), MaxClusterSize = cms.int32(3), # cppfSource = cms.string('Geo'), #'File' for Look up table and 'Geo' for CMSSW Geometry diff --git a/L1Trigger/L1TMuonCPPF/src/EmulateCPPF.cc b/L1Trigger/L1TMuonCPPF/src/EmulateCPPF.cc index 404416aafb04a..59f141d131c1c 100644 --- a/L1Trigger/L1TMuonCPPF/src/EmulateCPPF.cc +++ b/L1Trigger/L1TMuonCPPF/src/EmulateCPPF.cc @@ -17,6 +17,7 @@ EmulateCPPF::EmulateCPPF(const edm::ParameterSet &iConfig, edm::ConsumesCollecto recHitToken_(iConsumes.consumes(iConfig.getParameter("recHitLabel"))), rpcDigiSimLinkToken_(iConsumes.consumes >( iConfig.getParameter("rpcDigiSimLinkLabel"))), + rpcGeomToken_(iConsumes.esConsumes()), cppfSource_(CppfSource::EventSetup), MaxClusterSize_(0) { MaxClusterSize_ = iConfig.getParameter("MaxClusterSize"); @@ -58,8 +59,15 @@ void EmulateCPPF::process(const edm::Event &iEvent, if (cppfSource_ == CppfSource::File) { // Using the look up table to fill the information cppf_recHit.clear(); for (auto &recHit_processor : recHit_processors_) { - recHit_processor.processLook( - iEvent, iSetup, recHitToken_, rpcDigiToken_, rpcDigiSimLinkToken_, CppfVec_1, cppf_recHit, MaxClusterSize_); + recHit_processor.processLook(iEvent, + iSetup, + recHitToken_, + rpcDigiToken_, + rpcDigiSimLinkToken_, + rpcGeomToken_, + CppfVec_1, + cppf_recHit, + MaxClusterSize_); } } else if (cppfSource_ == CppfSource::EventSetup) { // Clear output collections @@ -79,7 +87,8 @@ void EmulateCPPF::process(const edm::Event &iEvent, // cppf_rpcDigi ); // } for (auto &recHit_processor : recHit_processors_) { - recHit_processor.process(iEvent, iSetup, recHitToken_, rpcDigiToken_, rpcDigiSimLinkToken_, cppf_recHit); + recHit_processor.process( + iEvent, iSetup, recHitToken_, rpcDigiToken_, rpcDigiSimLinkToken_, rpcGeomToken_, cppf_recHit); } } } // End void EmulateCPPF::process() diff --git a/L1Trigger/L1TMuonCPPF/src/RecHitProcessor.cc b/L1Trigger/L1TMuonCPPF/src/RecHitProcessor.cc index 871ec246c9c1b..e14b99d883744 100644 --- a/L1Trigger/L1TMuonCPPF/src/RecHitProcessor.cc +++ b/L1Trigger/L1TMuonCPPF/src/RecHitProcessor.cc @@ -1,3 +1,4 @@ +#include "FWCore/Framework/interface/ConsumesCollector.h" #include "L1Trigger/L1TMuonCPPF/interface/RecHitProcessor.h" #include "Geometry/RPCGeometry/interface/RPCRoll.h" #include "DataFormats/Common/interface/DetSetVector.h" @@ -16,6 +17,7 @@ void RecHitProcessor::processLook(const edm::Event &iEvent, const edm::EDGetToken &recHitToken, const edm::EDGetToken &rpcDigiToken, const edm::EDGetToken &rpcDigiSimLinkToken, + const edm::ESGetToken &rpcGeomToken, std::vector &CppfVec1, l1t::CPPFDigiCollection &cppfDigis, const int MaxClusterSize) const { @@ -28,8 +30,7 @@ void RecHitProcessor::processLook(const edm::Event &iEvent, edm::Handle> theSimlinkDigis; iEvent.getByToken(rpcDigiSimLinkToken, theSimlinkDigis); - edm::ESHandle rpcGeom; - iSetup.get().get(rpcGeom); + const auto &rpcGeom = iSetup.getData(rpcGeomToken); for (const auto &&rpcdgIt : (*rpcDigis)) { const RPCDetId &rpcId = rpcdgIt.first; @@ -50,7 +51,7 @@ void RecHitProcessor::processLook(const edm::Event &iEvent, const int firststrip = cl.firstStrip(); const int clustersize = cl.clusterSize(); const int laststrip = cl.lastStrip(); - const RPCRoll *roll = rpcGeom->roll(rpcId); + const RPCRoll *roll = rpcGeom.roll(rpcId); // Get Average Strip position const float fstrip = (roll->centreOfStrip(firststrip)).x(); const float lstrip = (roll->centreOfStrip(laststrip)).x(); @@ -283,10 +284,10 @@ void RecHitProcessor::process(const edm::Event &iEvent, const edm::EDGetToken &recHitToken, const edm::EDGetToken &rpcDigiToken, const edm::EDGetToken &rpcDigiSimLinkToken, + const edm::ESGetToken &rpcGeomToken, l1t::CPPFDigiCollection &cppfDigis) const { // Get the RPC Geometry - edm::ESHandle rpcGeom; - iSetup.get().get(rpcGeom); + const auto &rpcGeom = iSetup.getData(rpcGeomToken); edm::Handle rpcDigis; iEvent.getByToken(rpcDigiToken, rpcDigis); @@ -315,7 +316,7 @@ void RecHitProcessor::process(const edm::Event &iEvent, const int firststrip = cl.firstStrip(); const int clustersize = cl.clusterSize(); const int laststrip = cl.lastStrip(); - const RPCRoll *roll = rpcGeom->roll(rpcId); + const RPCRoll *roll = rpcGeom.roll(rpcId); // Get Average Strip position const float fstrip = (roll->centreOfStrip(firststrip)).x(); const float lstrip = (roll->centreOfStrip(laststrip)).x(); diff --git a/L1Trigger/L1TNtuples/plugins/L1ElectronRecoTreeProducer.cc b/L1Trigger/L1TNtuples/plugins/L1ElectronRecoTreeProducer.cc index bb505c962ad20..626409501586d 100644 --- a/L1Trigger/L1TNtuples/plugins/L1ElectronRecoTreeProducer.cc +++ b/L1Trigger/L1TNtuples/plugins/L1ElectronRecoTreeProducer.cc @@ -15,7 +15,7 @@ // framework #include "FWCore/Framework/interface/Frameworkfwd.h" -#include "FWCore/Framework/interface/EDAnalyzer.h" +#include "FWCore/Framework/interface/one/EDAnalyzer.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/EventSetup.h" #include "FWCore/Framework/interface/MakerMacros.h" @@ -40,7 +40,7 @@ // class declaration // -class L1ElectronRecoTreeProducer : public edm::EDAnalyzer { +class L1ElectronRecoTreeProducer : public edm::one::EDAnalyzer { public: explicit L1ElectronRecoTreeProducer(const edm::ParameterSet&); ~L1ElectronRecoTreeProducer() override; @@ -99,6 +99,7 @@ L1ElectronRecoTreeProducer::L1ElectronRecoTreeProducer(const edm::ParameterSet& electron = new L1Analysis::L1AnalysisRecoElectron(); electron_data = electron->getData(); + usesResource(TFileService::kSharedResource); tree_ = fs_->make("ElectronRecoTree", "ElectronRecoTree"); tree_->Branch("Electron", "L1Analysis::L1AnalysisRecoElectronDataFormat", &electron_data, 32000, 3); } diff --git a/L1Trigger/L1TNtuples/plugins/L1ExtraTreeProducer.cc b/L1Trigger/L1TNtuples/plugins/L1ExtraTreeProducer.cc index c43183e12de1a..ccd81eb694f18 100644 --- a/L1Trigger/L1TNtuples/plugins/L1ExtraTreeProducer.cc +++ b/L1Trigger/L1TNtuples/plugins/L1ExtraTreeProducer.cc @@ -22,7 +22,7 @@ Description: Produce L1 Extra tree // framework #include "FWCore/Framework/interface/Frameworkfwd.h" -#include "FWCore/Framework/interface/EDAnalyzer.h" +#include "FWCore/Framework/interface/one/EDAnalyzer.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" @@ -52,7 +52,7 @@ Description: Produce L1 Extra tree // class declaration // -class L1ExtraTreeProducer : public edm::EDAnalyzer { +class L1ExtraTreeProducer : public edm::one::EDAnalyzer { public: explicit L1ExtraTreeProducer(const edm::ParameterSet&); ~L1ExtraTreeProducer() override; @@ -115,6 +115,7 @@ L1ExtraTreeProducer::L1ExtraTreeProducer(const edm::ParameterSet& iConfig) { l1Extra = new L1Analysis::L1AnalysisL1Extra(); l1ExtraData = l1Extra->getData(); + usesResource(TFileService::kSharedResource); // set up output tree_ = fs_->make("L1ExtraTree", "L1ExtraTree"); tree_->Branch("L1Extra", "L1Analysis::L1AnalysisL1ExtraDataFormat", &l1ExtraData, 32000, 3); diff --git a/L1Trigger/L1TNtuples/plugins/L1GenTreeProducer.cc b/L1Trigger/L1TNtuples/plugins/L1GenTreeProducer.cc index 7b5d34c06704a..6959701923ed7 100644 --- a/L1Trigger/L1TNtuples/plugins/L1GenTreeProducer.cc +++ b/L1Trigger/L1TNtuples/plugins/L1GenTreeProducer.cc @@ -22,7 +22,7 @@ Description: Produce L1 Extra tree // framework #include "FWCore/Framework/interface/Frameworkfwd.h" -#include "FWCore/Framework/interface/EDAnalyzer.h" +#include "FWCore/Framework/interface/one/EDAnalyzer.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" @@ -51,7 +51,7 @@ Description: Produce L1 Extra tree // class declaration // -class L1GenTreeProducer : public edm::EDAnalyzer { +class L1GenTreeProducer : public edm::one::EDAnalyzer { public: explicit L1GenTreeProducer(const edm::ParameterSet&); ~L1GenTreeProducer() override; @@ -90,6 +90,7 @@ L1GenTreeProducer::L1GenTreeProducer(const edm::ParameterSet& iConfig) { l1GenData_ = std::make_unique(); + usesResource(TFileService::kSharedResource); // set up output tree_ = fs_->make("L1GenTree", "L1GenTree"); tree_->Branch("Generator", "L1Analysis::L1AnalysisGeneratorDataFormat", l1GenData_.get(), 32000, 3); diff --git a/L1Trigger/L1TNtuples/plugins/L1MenuTreeProducer.cc b/L1Trigger/L1TNtuples/plugins/L1MenuTreeProducer.cc index 071733c74dc00..97567aac94c6b 100644 --- a/L1Trigger/L1TNtuples/plugins/L1MenuTreeProducer.cc +++ b/L1Trigger/L1TNtuples/plugins/L1MenuTreeProducer.cc @@ -22,7 +22,7 @@ Description: Produce L1 Extra tree // framework #include "FWCore/Framework/interface/Frameworkfwd.h" -#include "FWCore/Framework/interface/EDAnalyzer.h" +#include "FWCore/Framework/interface/one/EDAnalyzer.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" @@ -42,17 +42,13 @@ Description: Produce L1 Extra tree // class declaration // -class L1MenuTreeProducer : public edm::EDAnalyzer { +class L1MenuTreeProducer : public edm::one::EDAnalyzer { public: explicit L1MenuTreeProducer(const edm::ParameterSet&); ~L1MenuTreeProducer() override; private: - void beginJob(void) override; - void beginRun(const edm::Run&, const edm::EventSetup&) override; void analyze(const edm::Event&, const edm::EventSetup&) override; - void endRun(const edm::Run&, const edm::EventSetup&) override {} - void endJob() override; public: L1Analysis::L1AnalysisL1Menu* l1Menu; @@ -73,6 +69,8 @@ class L1MenuTreeProducer : public edm::EDAnalyzer { L1MenuTreeProducer::L1MenuTreeProducer(const edm::ParameterSet& iConfig) : // l1MenuInputTag_(iConfig.getParameter("L1MenuInputTag")), l1GtUtils_(iConfig, consumesCollector(), true, L1GtUtils::UseEventSetupIn::Event) { + usesResource(TFileService::kSharedResource); + l1Menu = new L1Analysis::L1AnalysisL1Menu(); l1MenuData = l1Menu->getData(); @@ -107,16 +105,5 @@ void L1MenuTreeProducer::analyze(const edm::Event& iEvent, const edm::EventSetup tree_->Fill(); } -// ------------ method called once each job just before starting event loop ------------ -void L1MenuTreeProducer::beginJob(void) {} - -void L1MenuTreeProducer::beginRun(const edm::Run& iRun, const edm::EventSetup& evSetup) { - // L1GtTriggerMenuLite input tag from provenance - //l1GtUtils_.getL1GtRunCache(iRun, evSetup, true, true); -} - -// ------------ method called once each job just after ending the event loop ------------ -void L1MenuTreeProducer::endJob() {} - //define this as a plug-in DEFINE_FWK_MODULE(L1MenuTreeProducer); diff --git a/L1Trigger/L1TNtuples/plugins/L1MetFilterRecoTreeProducer.cc b/L1Trigger/L1TNtuples/plugins/L1MetFilterRecoTreeProducer.cc index 1e1af5cb53398..d14046e9a6082 100644 --- a/L1Trigger/L1TNtuples/plugins/L1MetFilterRecoTreeProducer.cc +++ b/L1Trigger/L1TNtuples/plugins/L1MetFilterRecoTreeProducer.cc @@ -15,7 +15,7 @@ // framework #include "FWCore/Framework/interface/Frameworkfwd.h" -#include "FWCore/Framework/interface/EDAnalyzer.h" +#include "FWCore/Framework/interface/one/EDAnalyzer.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/EventSetup.h" #include "FWCore/Framework/interface/MakerMacros.h" @@ -45,7 +45,7 @@ // class declaration // -class L1MetFilterRecoTreeProducer : public edm::EDAnalyzer { +class L1MetFilterRecoTreeProducer : public edm::one::EDAnalyzer { public: explicit L1MetFilterRecoTreeProducer(const edm::ParameterSet&); ~L1MetFilterRecoTreeProducer() override; @@ -87,6 +87,8 @@ L1MetFilterRecoTreeProducer::L1MetFilterRecoTreeProducer(const edm::ParameterSet : triggerResultsMissing_(false) //hbheNoiseFilterResultMissing_(false) { + usesResource(TFileService::kSharedResource); + triggerResultsToken_ = consumes( iConfig.getUntrackedParameter("triggerResultsToken", edm::InputTag("TriggerResults"))); diff --git a/L1Trigger/L1TNtuples/plugins/L1RecoTreeProducer.cc b/L1Trigger/L1TNtuples/plugins/L1RecoTreeProducer.cc index 7c121e87217fc..4c8f24cbd4621 100644 --- a/L1Trigger/L1TNtuples/plugins/L1RecoTreeProducer.cc +++ b/L1Trigger/L1TNtuples/plugins/L1RecoTreeProducer.cc @@ -12,7 +12,7 @@ // framework #include "FWCore/Framework/interface/Frameworkfwd.h" -#include "FWCore/Framework/interface/EDAnalyzer.h" +#include "FWCore/Framework/interface/one/EDAnalyzer.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/EventSetup.h" #include "FWCore/Framework/interface/MakerMacros.h" @@ -38,7 +38,7 @@ // class declaration // -class L1RecoTreeProducer : public edm::EDAnalyzer { +class L1RecoTreeProducer : public edm::one::EDAnalyzer { public: explicit L1RecoTreeProducer(const edm::ParameterSet&); ~L1RecoTreeProducer() override; @@ -72,6 +72,7 @@ L1RecoTreeProducer::L1RecoTreeProducer(const edm::ParameterSet& iConfig) { vtxData_ = new L1Analysis::L1AnalysisRecoVertexDataFormat(); + usesResource(TFileService::kSharedResource); // set up output tree_ = fs_->make("RecoTree", "RecoTree"); tree_->Branch("Vertex", "L1Analysis::L1AnalysisRecoVertexDataFormat", &vtxData_, 32000, 3); diff --git a/L1Trigger/L1TNtuples/plugins/L1TauRecoTreeProducer.cc b/L1Trigger/L1TNtuples/plugins/L1TauRecoTreeProducer.cc index 0e3bf59998c27..2fb3ad90e23ad 100644 --- a/L1Trigger/L1TNtuples/plugins/L1TauRecoTreeProducer.cc +++ b/L1Trigger/L1TNtuples/plugins/L1TauRecoTreeProducer.cc @@ -15,7 +15,7 @@ // framework #include "FWCore/Framework/interface/Frameworkfwd.h" -#include "FWCore/Framework/interface/EDAnalyzer.h" +#include "FWCore/Framework/interface/one/EDAnalyzer.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/EventSetup.h" #include "FWCore/Framework/interface/MakerMacros.h" @@ -59,7 +59,7 @@ // class declaration // -class L1TauRecoTreeProducer : public edm::EDAnalyzer { +class L1TauRecoTreeProducer : public edm::one::EDAnalyzer { public: explicit L1TauRecoTreeProducer(const edm::ParameterSet&); ~L1TauRecoTreeProducer() override; @@ -173,6 +173,7 @@ L1TauRecoTreeProducer::L1TauRecoTreeProducer(const edm::ParameterSet& iConfig) : tau = new L1Analysis::L1AnalysisRecoTau(); tau_data = tau->getData(); + usesResource(TFileService::kSharedResource); /* // set up output */ diff --git a/L1Trigger/RegionalCaloTrigger/interface/L1RCTInputProducer.h b/L1Trigger/RegionalCaloTrigger/interface/L1RCTInputProducer.h index da2a4afe3e3a6..b75422c6e0fd2 100644 --- a/L1Trigger/RegionalCaloTrigger/interface/L1RCTInputProducer.h +++ b/L1Trigger/RegionalCaloTrigger/interface/L1RCTInputProducer.h @@ -1,7 +1,7 @@ #ifndef L1RCTInputProducer_h #define L1RCTInputProducer_h -#include "FWCore/Framework/interface/EDProducer.h" +#include "FWCore/Framework/interface/stream/EDProducer.h" #include "DataFormats/Common/interface/Handle.h" #include "FWCore/Framework/interface/ESHandle.h" @@ -27,7 +27,7 @@ class L1RCT; class L1RCTLookupTables; -class L1RCTInputProducer : public edm::EDProducer { +class L1RCTInputProducer : public edm::stream::EDProducer<> { public: explicit L1RCTInputProducer(const edm::ParameterSet &ps); ~L1RCTInputProducer() override; diff --git a/L1Trigger/RegionalCaloTrigger/interface/L1RCTLutWriter.h b/L1Trigger/RegionalCaloTrigger/interface/L1RCTLutWriter.h index 6c156959db005..fa4abea30b7d0 100644 --- a/L1Trigger/RegionalCaloTrigger/interface/L1RCTLutWriter.h +++ b/L1Trigger/RegionalCaloTrigger/interface/L1RCTLutWriter.h @@ -27,7 +27,7 @@ #include // user include files -#include "FWCore/Framework/interface/EDAnalyzer.h" +#include "FWCore/Framework/interface/one/EDAnalyzer.h" #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/Event.h" @@ -56,7 +56,7 @@ class L1RCTParameters; // class declaration // -class L1RCTLutWriter : public edm::EDAnalyzer { +class L1RCTLutWriter : public edm::one::EDAnalyzer<> { public: explicit L1RCTLutWriter(const edm::ParameterSet &); ~L1RCTLutWriter() override; diff --git a/L1Trigger/RegionalCaloTrigger/interface/L1RCTRelValAnalyzer.h b/L1Trigger/RegionalCaloTrigger/interface/L1RCTRelValAnalyzer.h index 12c1864306706..ec085cde561d7 100644 --- a/L1Trigger/RegionalCaloTrigger/interface/L1RCTRelValAnalyzer.h +++ b/L1Trigger/RegionalCaloTrigger/interface/L1RCTRelValAnalyzer.h @@ -22,7 +22,7 @@ #include #include // user include files -#include "FWCore/Framework/interface/EDAnalyzer.h" +#include "FWCore/Framework/interface/one/EDAnalyzer.h" #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/Event.h" @@ -42,7 +42,7 @@ // class declaration // -class L1RCTRelValAnalyzer : public edm::EDAnalyzer { +class L1RCTRelValAnalyzer : public edm::one::EDAnalyzer { public: explicit L1RCTRelValAnalyzer(const edm::ParameterSet &); ~L1RCTRelValAnalyzer() override; @@ -51,8 +51,8 @@ class L1RCTRelValAnalyzer : public edm::EDAnalyzer { private: // ----------member data --------------------------- - edm::InputTag rctEmCandsLabel; - edm::InputTag rctRegionsLabel; + edm::EDGetTokenT m_rctEmCands; + edm::EDGetTokenT m_rctRegions; TH1F *h_emRank; TH1F *h_emIeta; diff --git a/L1Trigger/RegionalCaloTrigger/interface/L1RCTSaveInput.h b/L1Trigger/RegionalCaloTrigger/interface/L1RCTSaveInput.h index f427111ac1e0c..688b17719cfd4 100644 --- a/L1Trigger/RegionalCaloTrigger/interface/L1RCTSaveInput.h +++ b/L1Trigger/RegionalCaloTrigger/interface/L1RCTSaveInput.h @@ -24,7 +24,7 @@ #include "DataFormats/Common/interface/Handle.h" -#include "FWCore/Framework/interface/EDAnalyzer.h" +#include "FWCore/Framework/interface/one/EDAnalyzer.h" #include "FWCore/Framework/interface/ESHandle.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/EventSetup.h" @@ -46,11 +46,13 @@ #include "CondFormats/DataRecord/interface/L1EmEtScaleRcd.h" #include "CondFormats/L1TObjects/interface/L1CaloEtScale.h" #include "CalibCalorimetry/EcalTPGTools/interface/EcalTPGScale.h" +#include "DataFormats/EcalDigi/interface/EcalDigiCollections.h" +#include "DataFormats/HcalDigi/interface/HcalDigiCollections.h" class L1RCTLookupTables; class L1RCT; -class L1RCTSaveInput : public edm::EDAnalyzer { +class L1RCTSaveInput : public edm::one::EDAnalyzer<> { public: explicit L1RCTSaveInput(const edm::ParameterSet &); ~L1RCTSaveInput() override; @@ -62,8 +64,8 @@ class L1RCTSaveInput : public edm::EDAnalyzer { L1RCT *rct; bool useEcal; bool useHcal; - edm::InputTag ecalDigisLabel; - edm::InputTag hcalDigisLabel; + edm::EDGetTokenT ecalDigisToken_; + edm::EDGetTokenT hcalDigisToken_; edm::ESGetToken rctParametersToken_; edm::ESGetToken channelMaskToken_; edm::ESGetToken emScaleToken_; diff --git a/L1Trigger/RegionalCaloTrigger/interface/L1RCTTPGProvider.h b/L1Trigger/RegionalCaloTrigger/interface/L1RCTTPGProvider.h index 7412856d9e8ec..9d0ee2da45f3b 100644 --- a/L1Trigger/RegionalCaloTrigger/interface/L1RCTTPGProvider.h +++ b/L1Trigger/RegionalCaloTrigger/interface/L1RCTTPGProvider.h @@ -19,33 +19,36 @@ // system include files #include +#include // user include files -#include "FWCore/Framework/interface/EDProducer.h" +#include "FWCore/Framework/interface/global/EDProducer.h" #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" +#include "DataFormats/EcalDigi/interface/EcalDigiCollections.h" +#include "DataFormats/HcalDigi/interface/HcalDigiCollections.h" + // // class decleration // -class L1RCTTPGProvider : public edm::EDProducer { +class L1RCTTPGProvider : public edm::global::EDProducer<> { public: explicit L1RCTTPGProvider(const edm::ParameterSet &); ~L1RCTTPGProvider() override; private: - void produce(edm::Event &, const edm::EventSetup &) override; - void endJob() override; + void produce(edm::StreamID, edm::Event &, const edm::EventSetup &) const override; // ----------member data --------------------------- - edm::InputTag ecalTPG_; - edm::InputTag hcalTPG_; - bool useHcalCosmicTiming; - bool useEcalCosmicTiming; + edm::EDGetTokenT ecalTPG_; + edm::EDGetTokenT hcalTPG_; + mutable std::atomic useHcalCosmicTiming; + mutable std::atomic useEcalCosmicTiming; int preSamples; int postSamples; int hfShift; diff --git a/L1Trigger/RegionalCaloTrigger/interface/L1RCTTestAnalyzer.h b/L1Trigger/RegionalCaloTrigger/interface/L1RCTTestAnalyzer.h index fcdc9056c65bd..085bf9e47755c 100644 --- a/L1Trigger/RegionalCaloTrigger/interface/L1RCTTestAnalyzer.h +++ b/L1Trigger/RegionalCaloTrigger/interface/L1RCTTestAnalyzer.h @@ -21,7 +21,7 @@ #include #include // user include files -#include "FWCore/Framework/interface/EDAnalyzer.h" +#include "FWCore/Framework/interface/one/EDAnalyzer.h" #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/Event.h" @@ -50,7 +50,7 @@ // class declaration // -class L1RCTTestAnalyzer : public edm::EDAnalyzer { +class L1RCTTestAnalyzer : public edm::one::EDAnalyzer { public: explicit L1RCTTestAnalyzer(const edm::ParameterSet &); ~L1RCTTestAnalyzer() override; diff --git a/L1Trigger/RegionalCaloTrigger/interface/MaskedRctInputDigiProducer.h b/L1Trigger/RegionalCaloTrigger/interface/MaskedRctInputDigiProducer.h index d928488def585..f59f5c21cf877 100644 --- a/L1Trigger/RegionalCaloTrigger/interface/MaskedRctInputDigiProducer.h +++ b/L1Trigger/RegionalCaloTrigger/interface/MaskedRctInputDigiProducer.h @@ -26,7 +26,7 @@ RCT. #include // user include files -#include "FWCore/Framework/interface/EDProducer.h" +#include "FWCore/Framework/interface/global/EDProducer.h" #include "FWCore/Framework/interface/ESHandle.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/EventSetup.h" @@ -42,21 +42,20 @@ RCT. // class declaration // -class MaskedRctInputDigiProducer : public edm::EDProducer { +class MaskedRctInputDigiProducer : public edm::global::EDProducer<> { public: explicit MaskedRctInputDigiProducer(const edm::ParameterSet &); ~MaskedRctInputDigiProducer() override; private: - void produce(edm::Event &, const edm::EventSetup &) override; - void endJob() override; + void produce(edm::StreamID, edm::Event &, const edm::EventSetup &) const override; // ----------member data --------------------------- bool useEcal_; bool useHcal_; - edm::InputTag ecalDigisLabel_; - edm::InputTag hcalDigisLabel_; + edm::EDGetTokenT ecalDigisToken_; + edm::EDGetTokenT hcalDigisToken_; edm::FileInPath maskFile_; }; #endif diff --git a/L1Trigger/RegionalCaloTrigger/plugins/L1RCTRelValAnalyzer.cc b/L1Trigger/RegionalCaloTrigger/plugins/L1RCTRelValAnalyzer.cc index cab6f630c4fbb..1a92e3bac2e1e 100644 --- a/L1Trigger/RegionalCaloTrigger/plugins/L1RCTRelValAnalyzer.cc +++ b/L1Trigger/RegionalCaloTrigger/plugins/L1RCTRelValAnalyzer.cc @@ -24,10 +24,11 @@ using std::string; // constructors and destructor // L1RCTRelValAnalyzer::L1RCTRelValAnalyzer(const edm::ParameterSet &iConfig) - : rctEmCandsLabel(iConfig.getParameter("rctEmCandsLabel")), - rctRegionsLabel(iConfig.getParameter("rctRegionsLabel")) { + : m_rctEmCands(consumes(iConfig.getParameter("rctEmCandsLabel"))), + m_rctRegions(consumes(iConfig.getParameter("rctRegionsLabel"))) { // now do what ever initialization is needed + usesResource(TFileService::kSharedResource); edm::Service fs; h_emRank = fs->make("emRank", "emRank", 64, 0., 64.); h_emIeta = fs->make("emOccupancyIeta", "emOccupancyIeta", 22, 0., 22.); @@ -52,27 +53,12 @@ L1RCTRelValAnalyzer::~L1RCTRelValAnalyzer() { // ------------ method called to produce the data ------------ void L1RCTRelValAnalyzer::analyze(const edm::Event &iEvent, const edm::EventSetup &iSetup) { using namespace edm; -#ifdef THIS_IS_AN_EVENT_EXAMPLE - Handle pIn; - iEvent.getByLabel("example", pIn); -#endif - -#ifdef THIS_IS_AN_EVENTSETUP_EXAMPLE - ESHandle pSetup; - iSetup.get().get(pSetup); -#endif // as in L1GctTestAnalyzer.cc - Handle rctEmCands; - Handle rctRegions; - - L1CaloEmCollection::const_iterator em; - L1CaloRegionCollection::const_iterator rgn; - - iEvent.getByLabel(rctEmCandsLabel, rctEmCands); - iEvent.getByLabel(rctRegionsLabel, rctRegions); + Handle rctEmCands = iEvent.getHandle(m_rctEmCands); + Handle rctRegions = iEvent.getHandle(m_rctRegions); - for (em = rctEmCands->begin(); em != rctEmCands->end(); em++) { + for (auto em = rctEmCands->begin(); em != rctEmCands->end(); em++) { if ((*em).rank() > 0) { h_emRank->Fill((*em).rank()); h_emIeta->Fill((*em).regionId().ieta()); @@ -85,7 +71,7 @@ void L1RCTRelValAnalyzer::analyze(const edm::Event &iEvent, const edm::EventSetu } } - for (rgn = rctRegions->begin(); rgn != rctRegions->end(); rgn++) { + for (auto rgn = rctRegions->begin(); rgn != rctRegions->end(); rgn++) { if ((*rgn).et() > 0) { h_regionSum->Fill((*rgn).et()); h_regionSumIetaIphi->Fill((*rgn).gctEta(), (*rgn).gctPhi(), (*rgn).et()); diff --git a/L1Trigger/RegionalCaloTrigger/plugins/L1RCTSaveInput.cc b/L1Trigger/RegionalCaloTrigger/plugins/L1RCTSaveInput.cc index b7eac77982f7b..469e2ae81636e 100644 --- a/L1Trigger/RegionalCaloTrigger/plugins/L1RCTSaveInput.cc +++ b/L1Trigger/RegionalCaloTrigger/plugins/L1RCTSaveInput.cc @@ -30,8 +30,8 @@ L1RCTSaveInput::L1RCTSaveInput(const edm::ParameterSet &conf) rct(new L1RCT(rctLookupTables)), useEcal(conf.getParameter("useEcal")), useHcal(conf.getParameter("useHcal")), - ecalDigisLabel(conf.getParameter("ecalDigisLabel")), - hcalDigisLabel(conf.getParameter("hcalDigisLabel")), + ecalDigisToken_(consumes(conf.getParameter("ecalDigisLabel"))), + hcalDigisToken_(consumes(conf.getParameter("hcalDigisLabel"))), rctParametersToken_(esConsumes()), channelMaskToken_(esConsumes()), emScaleToken_(esConsumes()), @@ -42,8 +42,7 @@ L1RCTSaveInput::L1RCTSaveInput(const edm::ParameterSet &conf) tokens_(consumesCollector()) { ofs.open(fileName.c_str(), std::ios::app); if (!ofs) { - std::cerr << "Could not create " << fileName << std::endl; - exit(1); + throw cms::Exception("FailedFileOpen") << "Could not create " << fileName << std::endl; } } @@ -141,10 +140,8 @@ void L1RCTSaveInput::analyze(const edm::Event &event, const edm::EventSetup &eve rctLookupTables->setEcalScale(e); } - edm::Handle ecal; - edm::Handle hcal; - event.getByLabel(ecalDigisLabel, ecal); - event.getByLabel(hcalDigisLabel, hcal); + edm::Handle ecal = event.getHandle(ecalDigisToken_); + edm::Handle hcal = event.getHandle(hcalDigisToken_); EcalTrigPrimDigiCollection ecalColl; HcalTrigPrimDigiCollection hcalColl; if (ecal.isValid()) { diff --git a/L1Trigger/RegionalCaloTrigger/plugins/L1RCTTPGProvider.cc b/L1Trigger/RegionalCaloTrigger/plugins/L1RCTTPGProvider.cc index 26d0918634a5c..47c1093dad232 100644 --- a/L1Trigger/RegionalCaloTrigger/plugins/L1RCTTPGProvider.cc +++ b/L1Trigger/RegionalCaloTrigger/plugins/L1RCTTPGProvider.cc @@ -3,8 +3,8 @@ #include "L1Trigger/RegionalCaloTrigger/interface/L1RCTTPGProvider.h" L1RCTTPGProvider::L1RCTTPGProvider(const edm::ParameterSet &iConfig) - : ecalTPG_(iConfig.getParameter("ecalTPGs")), - hcalTPG_(iConfig.getParameter("hcalTPGs")), + : ecalTPG_(consumes(iConfig.getParameter("ecalTPGs"))), + hcalTPG_(consumes(iConfig.getParameter("hcalTPGs"))), useHcalCosmicTiming(iConfig.getParameter("useHCALCosmicTiming")), useEcalCosmicTiming(iConfig.getParameter("useECALCosmicTiming")), preSamples(iConfig.getParameter("preSamples")), @@ -45,7 +45,7 @@ L1RCTTPGProvider::~L1RCTTPGProvider() { // // ------------ method called to produce the data ------------ -void L1RCTTPGProvider::produce(edm::Event &iEvent, const edm::EventSetup &iSetup) { +void L1RCTTPGProvider::produce(edm::StreamID, edm::Event &iEvent, const edm::EventSetup &iSetup) const { using namespace edm; // Declare handles Handle ecal; @@ -58,7 +58,7 @@ void L1RCTTPGProvider::produce(edm::Event &iEvent, const edm::EventSetup &iSetup unsigned nSamples = preSamples + postSamples + 1; - if (iEvent.getByLabel(ecalTPG_, ecal)) + if ((ecal = iEvent.getHandle(ecalTPG_))) if (ecal.isValid()) { // loop through all ecal digis for (EcalTrigPrimDigiCollection::const_iterator ecal_it = ecal->begin(); ecal_it != ecal->end(); ecal_it++) { @@ -152,7 +152,7 @@ void L1RCTTPGProvider::produce(edm::Event &iEvent, const edm::EventSetup &iSetup } } - if (iEvent.getByLabel(hcalTPG_, hcal)) + if ((hcal = iEvent.getHandle(hcalTPG_))) if (hcal.isValid()) { // loop through all hcal digis for (HcalTrigPrimDigiCollection::const_iterator hcal_it = hcal->begin(); hcal_it != hcal->end(); hcal_it++) { @@ -301,10 +301,3 @@ void L1RCTTPGProvider::produce(edm::Event &iEvent, const edm::EventSetup &iSetup iEvent.put(std::move(hcalIn2), hcal_label); } } - -// ------------ method called once each job just before starting event loop -// ------------ - -// ------------ method called once each job just after ending the event loop -// ------------ -void L1RCTTPGProvider::endJob() {} diff --git a/L1Trigger/RegionalCaloTrigger/plugins/L1RCTTestAnalyzer.cc b/L1Trigger/RegionalCaloTrigger/plugins/L1RCTTestAnalyzer.cc index 4693bd22eb366..b16d70c38a1b2 100644 --- a/L1Trigger/RegionalCaloTrigger/plugins/L1RCTTestAnalyzer.cc +++ b/L1Trigger/RegionalCaloTrigger/plugins/L1RCTTestAnalyzer.cc @@ -32,6 +32,7 @@ L1RCTTestAnalyzer::L1RCTTestAnalyzer(const edm::ParameterSet &iConfig) rctDigisLabel(iConfig.getParameter("rctDigisLabel")) { // now do what ever initialization is needed + usesResource(TFileService::kSharedResource); edm::Service fs; emTree = fs->make("emTree", "L1 RCT EM tree"); diff --git a/L1Trigger/RegionalCaloTrigger/plugins/MaskedRctInputDigiProducer.cc b/L1Trigger/RegionalCaloTrigger/plugins/MaskedRctInputDigiProducer.cc index ad539d61cb530..58adfffb1ce2b 100644 --- a/L1Trigger/RegionalCaloTrigger/plugins/MaskedRctInputDigiProducer.cc +++ b/L1Trigger/RegionalCaloTrigger/plugins/MaskedRctInputDigiProducer.cc @@ -15,9 +15,13 @@ using std::vector; MaskedRctInputDigiProducer::MaskedRctInputDigiProducer(const edm::ParameterSet &iConfig) : useEcal_(iConfig.getParameter("useEcal")), useHcal_(iConfig.getParameter("useHcal")), - ecalDigisLabel_(iConfig.getParameter("ecalDigisLabel")), - hcalDigisLabel_(iConfig.getParameter("hcalDigisLabel")), maskFile_(iConfig.getParameter("maskFile")) { + if (useEcal_) { + ecalDigisToken_ = consumes(iConfig.getParameter("ecalDigisLabel")); + } + if (useHcal_) { + hcalDigisToken_ = consumes(iConfig.getParameter("hcalDigisLabel")); + } // register your products /* Examples produces(); @@ -42,27 +46,17 @@ MaskedRctInputDigiProducer::~MaskedRctInputDigiProducer() { // // ------------ method called to produce the data ------------ -void MaskedRctInputDigiProducer::produce(edm::Event &iEvent, const edm::EventSetup &iSetup) { +void MaskedRctInputDigiProducer::produce(edm::StreamID, edm::Event &iEvent, const edm::EventSetup &iSetup) const { using namespace edm; - /* This is an event example - //Read 'ExampleData' from the Event - Handle pIn; - iEvent.getByLabel("example",pIn); - - //Use the ExampleData to create an ExampleData2 which - // is put into the Event - std::unique_ptr pOut(new ExampleData2(*pIn)); - iEvent.put(std::move(pOut)); - */ edm::Handle ecal; edm::Handle hcal; if (useEcal_) { - iEvent.getByLabel(ecalDigisLabel_, ecal); + ecal = iEvent.getHandle(ecalDigisToken_); } if (useHcal_) { - iEvent.getByLabel(hcalDigisLabel_, hcal); + hcal = iEvent.getHandle(hcalDigisToken_); } EcalTrigPrimDigiCollection ecalColl; @@ -74,12 +68,6 @@ void MaskedRctInputDigiProducer::produce(edm::Event &iEvent, const edm::EventSet hcalColl = *hcal; } - /* this is an EventSetup example - //Read SetupData from the SetupRecord in the EventSetup - ESHandle pSetup; - iSetup.get().get(pSetup); - */ - ifstream maskFileStream(maskFile_.fullPath().c_str()); if (!maskFileStream.is_open()) { throw cms::Exception("FileInPathError") << "RCT mask file not opened" << std::endl; @@ -333,12 +321,5 @@ void MaskedRctInputDigiProducer::produce(edm::Event &iEvent, const edm::EventSet iEvent.put(std::move(maskedHcalTPs)); } -// ------------ method called once each job just before starting event loop -// ------------ - -// ------------ method called once each job just after ending the event loop -// ------------ -void MaskedRctInputDigiProducer::endJob() {} - // define this as a plug-in DEFINE_FWK_MODULE(MaskedRctInputDigiProducer); diff --git a/MagneticField/Engine/test/regression.py b/MagneticField/Engine/test/regression.py index 650b314b77863..b6c703e9f1934 100644 --- a/MagneticField/Engine/test/regression.py +++ b/MagneticField/Engine/test/regression.py @@ -22,7 +22,7 @@ 18000, #default value VarParsing.VarParsing.multiplicity.singleton, VarParsing.VarParsing.varType.float, - "Magnet current (nominal values: 18164=3.8T; 16730=3.5T; 14340=3T; 9500=2T; -1=loop in different IOV") + "Magnet current (nominal values: 18164=3.8T; 16730=3.5T; 14340=3T; 9500=2T; -1=loop in different IOVs, to test switching currents in the same job") options.parseArguments() @@ -37,12 +37,15 @@ REFERENCEFILE = 'none' -if options.current < 0 : # Test all currents, simulating different IOVs with different values runInfo - # FIXME: currents are set all equal for the time being because we need to set up a way to specify the correct - # reference file file to be picked for each at runtime. +if options.current < 0 : # Test switching of maps in the same job, simulating different IOVs with different currents in runInfo + # Note that this currently crashes with producerType='fromDB_DD4hep' when a different geometry has to be created in the switch, due a limitation of DD4hep. + + # FIXME: Only build the map and print the field at IP - no regression is actually run. To do that we would need to set up a mechanism to specify the + # reference file file to be picked for each current at runtime. + REFERENCEFILE = '' + if options.producerType == 'static_DDD' or options.producerType == 'static_DD4hep' : sys.exit('Invalid configuration: current=-1 mode is not supported with static prouducers') - process.maxEvents.input = 4 process.source.numberEventsInLuminosityBlock =cms.untracked.uint32(1) if options.era=='RunI': @@ -51,12 +54,19 @@ cms.LuminosityBlockID(20,2), cms.LuminosityBlockID(30,3), cms.LuminosityBlockID(40,4), + cms.LuminosityBlockID(50,5), ) + + process.riSource = cms.ESSource("EmptyESSource", recordName = cms.string("RunInfoRcd"), + iovIsRunNotTime = cms.bool(True), + firstValid = cms.vuint32(10,20,30,40,50)) + process.add_( cms.ESProducer("RunInfoTestESProducer", runInfos = cms.VPSet(cms.PSet(run = cms.int32(10), avg_current = cms.double(18000.)), - cms.PSet(run = cms.int32(20), avg_current = cms.double(18000.)), - cms.PSet(run = cms.int32(30), avg_current = cms.double(18000.)), - cms.PSet(run = cms.int32(40), avg_current = cms.double(18000.)), + cms.PSet(run = cms.int32(20), avg_current = cms.double(16000.)), + cms.PSet(run = cms.int32(30), avg_current = cms.double(14000.)), + cms.PSet(run = cms.int32(40), avg_current = cms.double(10000.)), + cms.PSet(run = cms.int32(50), avg_current = cms.double(0.)), ) ) ) else : process.source.firstLuminosityBlockForEachRun = cms.untracked.VLuminosityBlockID( @@ -64,20 +74,19 @@ cms.LuminosityBlockID(300002,2), cms.LuminosityBlockID(300003,3), cms.LuminosityBlockID(300004,4), + cms.LuminosityBlockID(300005,5), ) process.add_( cms.ESProducer("RunInfoTestESProducer", runInfos = cms.VPSet(cms.PSet(run = cms.int32(300001), avg_current = cms.double(18000.)), - cms.PSet(run = cms.int32(300002), avg_current = cms.double(18000.)), - cms.PSet(run = cms.int32(300003), avg_current = cms.double(18000.)), - cms.PSet(run = cms.int32(300004), avg_current = cms.double(18000.)), + cms.PSet(run = cms.int32(300002), avg_current = cms.double(16000.)), + cms.PSet(run = cms.int32(300003), avg_current = cms.double(14000.)), + cms.PSet(run = cms.int32(300004), avg_current = cms.double(10000.)), + cms.PSet(run = cms.int32(300005), avg_current = cms.double(0.)), ) ) ) - process.riSource = cms.ESSource("EmptyESSource", recordName = cms.string("RunInfoRcd"), - iovIsRunNotTime = cms.bool(True), - firstValid = cms.vuint32(10,20,30,40)) + process.maxEvents.input = len(process.source.firstLuminosityBlockForEachRun) - REFERENCEFILE = 'MagneticField/Engine/data/Regression/referenceField_160812_RII_3_8T.bin' #FIXME cf. comment above. if options.current > 18765 or (options.current <= 4779 and options.current>0) : sys.exit('ERROR: invalid current value: ' + str(options.current)) diff --git a/MagneticField/GeomBuilder/plugins/dd4hep/DD4hep_VolumeBasedMagneticFieldESProducerFromDB.cc b/MagneticField/GeomBuilder/plugins/dd4hep/DD4hep_VolumeBasedMagneticFieldESProducerFromDB.cc index e21f52421ad54..4a3c8dc070019 100644 --- a/MagneticField/GeomBuilder/plugins/dd4hep/DD4hep_VolumeBasedMagneticFieldESProducerFromDB.cc +++ b/MagneticField/GeomBuilder/plugins/dd4hep/DD4hep_VolumeBasedMagneticFieldESProducerFromDB.cc @@ -75,6 +75,7 @@ namespace magneticfield { edm::ESGetToken mayConsumeBlobToken_; cms::DDDetector* detector_{nullptr}; + int cachedGeometryVersion_{-1}; const bool debug_; const bool useMergeFileIfAvailable_; @@ -183,19 +184,26 @@ std::unique_ptr DD4hep_VolumeBasedMagneticFieldESProducerFromDB:: builder.setGridFiles(conf->gridFiles); } - // Build the geometry from the DB blob + // Build the geometry from the DB blob and cache it + if (cachedGeometryVersion_ != conf->geometryVersion) { + if (nullptr != detector_) { + edm::LogError("MagneticField") << "MF Geometry needs to be re-created since current changed (cached: " + << cachedGeometryVersion_ << " requested: " << conf->geometryVersion + << "), which is not supported by dd4hep" << endl; + } - auto const& blob = iRecord.getTransientHandle(mayConsumeBlobToken_); - std::unique_ptr > tb = blob->getUncompressedBlob(); + auto const& blob = iRecord.getTransientHandle(mayConsumeBlobToken_); + std::unique_ptr > tb = blob->getUncompressedBlob(); - string sblob(tb->begin(), tb->end()); - sblob.insert( - sblob.rfind(""), - ""); + string sblob(tb->begin(), tb->end()); + sblob.insert(sblob.rfind(""), + ""); - if (nullptr == detector_) detector_ = new cms::DDDetector("cmsMagneticField:MAGF", sblob, true); + cachedGeometryVersion_ = conf->geometryVersion; + } builder.build(detector_); diff --git a/PhysicsTools/NanoAOD/python/photons_cff.py b/PhysicsTools/NanoAOD/python/photons_cff.py index 3ffa66cadc50d..c10ba88ed1dec 100644 --- a/PhysicsTools/NanoAOD/python/photons_cff.py +++ b/PhysicsTools/NanoAOD/python/photons_cff.py @@ -223,6 +223,7 @@ def make_bitmapVID_docstring(id_modules_working_points_pset): # ES variables esEffSigmaRR = Var("full5x5_showerShapeVariables().effSigmaRR()", float, doc="preshower sigmaRR"), esEnergyOverRawE = Var("superCluster().preshowerEnergy()/superCluster().rawEnergy()", float, doc="ratio of preshower energy to raw supercluster energy"), + haloTaggerMVAVal = Var("haloTaggerMVAVal()",float,doc="Value of MVA based BDT based beam halo tagger in the Ecal endcap (valid for pT > 200 GeV)",precision=8), ) ) diff --git a/PhysicsTools/PatAlgos/python/producersHeavyIons/heavyIonJets_cff.py b/PhysicsTools/PatAlgos/python/producersHeavyIons/heavyIonJets_cff.py index c367b4413e2cd..f3f1f4f7788a5 100644 --- a/PhysicsTools/PatAlgos/python/producersHeavyIons/heavyIonJets_cff.py +++ b/PhysicsTools/PatAlgos/python/producersHeavyIons/heavyIonJets_cff.py @@ -79,8 +79,7 @@ run2_miniAOD_pp_on_AA_103X.toReplaceWith(recoPFJetsHIpostAODTask, _recoPFJetsHIpostAODTask) -recoJetsHIpostAODTask = cms.Task( - recoPFJetsHIpostAODTask, +recoGenJetsHIpostAODTask = cms.Task( allPartons, hiGenJetsTask, ) diff --git a/PhysicsTools/PatAlgos/python/producersLayer1/jetProducer_cff.py b/PhysicsTools/PatAlgos/python/producersLayer1/jetProducer_cff.py index 4a6febc4257e1..43ccc60a6881f 100644 --- a/PhysicsTools/PatAlgos/python/producersLayer1/jetProducer_cff.py +++ b/PhysicsTools/PatAlgos/python/producersLayer1/jetProducer_cff.py @@ -19,13 +19,19 @@ ) from PhysicsTools.PatAlgos.producersHeavyIons.heavyIonJets_cff import * +_makePatJetsTaskHI2018 = cms.Task( + recoPFJetsHIpostAODTask, + recoGenJetsHIpostAODTask, + makePatJetsTask.copy() +) _makePatJetsTaskHI = cms.Task( - recoJetsHIpostAODTask, + recoGenJetsHIpostAODTask, makePatJetsTask.copy() ) - -from Configuration.ProcessModifiers.pp_on_AA_cff import pp_on_AA -pp_on_AA.toReplaceWith(makePatJetsTask, _makePatJetsTaskHI) +from Configuration.Eras.Modifier_pp_on_AA_2018_cff import pp_on_AA_2018 +pp_on_AA_2018.toReplaceWith(makePatJetsTask, _makePatJetsTaskHI2018) +from Configuration.Eras.Modifier_pp_on_PbPb_run3_cff import pp_on_PbPb_run3 +pp_on_PbPb_run3.toReplaceWith(makePatJetsTask, _makePatJetsTaskHI) makePatJets = cms.Sequence(makePatJetsTask) diff --git a/PhysicsTools/PatAlgos/python/producersLayer1/jetProducer_cfi.py b/PhysicsTools/PatAlgos/python/producersLayer1/jetProducer_cfi.py index f8445c5f87e9f..12cb04bd8c32e 100644 --- a/PhysicsTools/PatAlgos/python/producersLayer1/jetProducer_cfi.py +++ b/PhysicsTools/PatAlgos/python/producersLayer1/jetProducer_cfi.py @@ -99,26 +99,44 @@ resolutions = dict() ) -from Configuration.ProcessModifiers.pp_on_AA_cff import pp_on_AA -pp_on_AA.toModify(_patJets, - jetSource = "akCs4PFJets", - genJetMatch = "patJetGenJetMatch", - genPartonMatch = "patJetPartonMatch", - JetFlavourInfoSource = "patJetFlavourAssociation", - JetPartonMapSource = "patJetFlavourAssociationLegacy", - jetCorrFactorsSource = ["patJetCorrFactors"], - trackAssociationSource = "ak5JetTracksAssociatorAtVertex", - useLegacyJetMCFlavour = True, - discriminatorSources = [ - "simpleSecondaryVertexHighEffBJetTags", - "simpleSecondaryVertexHighPurBJetTags", - "combinedSecondaryVertexV2BJetTags", - "jetBProbabilityBJetTags", - "jetProbabilityBJetTags", - "trackCountingHighEffBJetTags", - "trackCountingHighPurBJetTags", - ], - addJetCharge = False, +from Configuration.Eras.Modifier_pp_on_AA_2018_cff import pp_on_AA_2018 +pp_on_AA_2018.toModify(_patJets, + jetSource = "akCs4PFJets", + genJetMatch = "patJetGenJetMatch", + genPartonMatch = "patJetPartonMatch", + JetFlavourInfoSource = "patJetFlavourAssociation", + JetPartonMapSource = "patJetFlavourAssociationLegacy", + jetCorrFactorsSource = ["patJetCorrFactors"], + trackAssociationSource = "ak5JetTracksAssociatorAtVertex", + useLegacyJetMCFlavour = True, + discriminatorSources = [ + "simpleSecondaryVertexHighEffBJetTags", + "simpleSecondaryVertexHighPurBJetTags", + "combinedSecondaryVertexV2BJetTags", + "jetBProbabilityBJetTags", + "jetProbabilityBJetTags", + "trackCountingHighEffBJetTags", + "trackCountingHighPurBJetTags", + ], + addJetCharge = False, +) + +from Configuration.Eras.Modifier_pp_on_PbPb_run3_cff import pp_on_PbPb_run3 +pp_on_PbPb_run3.toModify(_patJets, + jetSource = "akCs4PFJets", + genJetMatch = "patJetGenJetMatch", + genPartonMatch = "patJetPartonMatch", + JetFlavourInfoSource = "patJetFlavourAssociation", + JetPartonMapSource = "patJetFlavourAssociationLegacy", + jetCorrFactorsSource = ["patJetCorrFactors"], + trackAssociationSource = "", + useLegacyJetMCFlavour = True, + discriminatorSources = [], + tagInfoSources = [], + addJetCharge = False, + addTagInfos = False, + addDiscriminators = False, + addAssociatedTracks = False, ) patJets = _patJets.clone() diff --git a/PhysicsTools/PatAlgos/python/slimming/miniAOD_tools.py b/PhysicsTools/PatAlgos/python/slimming/miniAOD_tools.py index d5cc380ab8135..43067e68b4ca6 100644 --- a/PhysicsTools/PatAlgos/python/slimming/miniAOD_tools.py +++ b/PhysicsTools/PatAlgos/python/slimming/miniAOD_tools.py @@ -261,7 +261,8 @@ def _add_deepFlavour(process): 'pfDeepCSVDiscriminatorsJetTags:CvsB', 'pfDeepCSVDiscriminatorsJetTags:CvsL', ]) - (~pp_on_AA).toModify(process, _add_deepFlavour) + from Configuration.Eras.Modifier_pp_on_AA_2018_cff import pp_on_AA_2018 + (~pp_on_AA_2018).toModify(process, _add_deepFlavour) ## CaloJets process.caloJetMap = cms.EDProducer("RecoJetDeltaRValueMapProducer", @@ -322,11 +323,11 @@ def _add_deepFlavour(process): keysForValueMaps = cms.InputTag('reducedEgamma','reducedGedGsfElectrons'), src = cms.InputTag("gedGsfElectronsFrom94XTo106X")) - from Configuration.ProcessModifiers.pp_on_AA_cff import pp_on_AA - pp_on_AA.toModify(task, func=lambda t: t.add(process.gedGsfElectronsFrom94XTo106XTask)) - pp_on_AA.toModify(process.electronMVAValueMapProducer, - keysForValueMaps = cms.InputTag('reducedEgamma','reducedGedGsfElectrons'), - src = "gedGsfElectronsFrom94XTo106X") + from Configuration.Eras.Modifier_pp_on_AA_2018_cff import pp_on_AA_2018 + pp_on_AA_2018.toModify(task, func=lambda t: t.add(process.gedGsfElectronsFrom94XTo106XTask)) + pp_on_AA_2018.toModify(process.electronMVAValueMapProducer, + keysForValueMaps = cms.InputTag('reducedEgamma','reducedGedGsfElectrons'), + src = "gedGsfElectronsFrom94XTo106X") for idmod in electron_ids: setupAllVIDIdsInModule(process,idmod,setupVIDElectronSelection,None,False,task) @@ -460,8 +461,9 @@ def _add_jetsPuppi(process): process.patJets.tagInfoSources = ["pixelClusterTagInfos"] _run2_miniAOD_ANY.toModify(process.patJets, addTagInfos = False ) - - pp_on_AA.toModify(process.patJets, tagInfoSources = cms.VInputTag(["impactParameterTagInfos","secondaryVertexTagInfos"]) ) + + from Configuration.Eras.Modifier_pp_on_AA_2018_cff import pp_on_AA_2018 + pp_on_AA_2018.toModify(process.patJets, tagInfoSources = cms.VInputTag(["impactParameterTagInfos","secondaryVertexTagInfos"]) ) ## puppi met def _add_metPuppi(process): diff --git a/RecoLocalCalo/HGCalRecAlgos/python/hgcalRecHitToolsPartialWafer_cff.py b/RecoLocalCalo/HGCalRecAlgos/python/hgcalRecHitToolsPartialWafer_cff.py new file mode 100644 index 0000000000000..75074e3c5df79 --- /dev/null +++ b/RecoLocalCalo/HGCalRecAlgos/python/hgcalRecHitToolsPartialWafer_cff.py @@ -0,0 +1,19 @@ +import FWCore.ParameterSet.Config as cms + +from RecoLocalCalo.HGCalRecAlgos.hgcalCheckToolDigiEE_cfi import * + +hgcalCheckToolDigiHE = hgcalCheckToolDigiEE.clone( + source = ('simHGCalUnsuppressedDigis', 'HEfront'), + nameSense = 'HGCalHESiliconSensitive', +) + +hgcalCheckToolRecHitEE = hgcalCheckToolDigiEE.clone( + source = ('HGCalRecHit', 'HGCEERecHits'), + checkDigi = False, +) + +hgcalCheckToolRecHitHE = hgcalCheckToolDigiEE.clone( + source = ('HGCalRecHit', 'HGCHEFRecHits'), + nameSense = 'HGCalHESiliconSensitive', + checkDigi = False, +) diff --git a/RecoLocalCalo/HGCalRecAlgos/test/HGCalRecHitToolsPartialWafer.cc b/RecoLocalCalo/HGCalRecAlgos/test/HGCalRecHitToolsPartialWafer.cc new file mode 100644 index 0000000000000..9557c51712d47 --- /dev/null +++ b/RecoLocalCalo/HGCalRecAlgos/test/HGCalRecHitToolsPartialWafer.cc @@ -0,0 +1,139 @@ +#include "FWCore/Framework/interface/Frameworkfwd.h" +#include "FWCore/Framework/interface/one/EDAnalyzer.h" + +#include "FWCore/Framework/interface/Event.h" +#include "FWCore/Framework/interface/EventSetup.h" +#include "FWCore/Framework/interface/MakerMacros.h" + +#include "FWCore/ParameterSet/interface/ParameterSet.h" +#include "FWCore/ParameterSet/interface/ConfigurationDescriptions.h" +#include "FWCore/Utilities/interface/InputTag.h" +#include "FWCore/MessageLogger/interface/MessageLogger.h" +#include "FWCore/Utilities/interface/Exception.h" + +#include "DataFormats/HGCDigi/interface/HGCDigiCollections.h" +#include "DataFormats/HGCRecHit/interface/HGCRecHitCollections.h" +#include "DataFormats/ForwardDetId/interface/HGCSiliconDetId.h" + +#include "Geometry/CaloGeometry/interface/CaloGeometry.h" +#include "Geometry/CaloTopology/interface/HGCalTopology.h" +#include "Geometry/HGCalGeometry/interface/HGCalGeometry.h" +#include "Geometry/HGCalCommonData/interface/HGCalDDDConstants.h" +#include "Geometry/HGCalCommonData/interface/HGCalParameters.h" +#include "Geometry/Records/interface/CaloGeometryRecord.h" +#include "Geometry/Records/interface/IdealGeometryRecord.h" + +#include "RecoLocalCalo/HGCalRecAlgos/interface/RecHitTools.h" + +#include +#include + +class HGCalRecHitToolsPartialWafer : public edm::one::EDAnalyzer<> { +public: + HGCalRecHitToolsPartialWafer(const edm::ParameterSet& ps); + ~HGCalRecHitToolsPartialWafer() override = default; + + static void fillDescriptions(edm::ConfigurationDescriptions& descriptions); + +protected: + void analyze(edm::Event const&, edm::EventSetup const&) override; + void beginJob() override {} + void endJob() override {} + +private: + template + void analyze(const T& collection, const HGCalGeometry* geom); + + const edm::InputTag source_; + const std::string nameSense_; + const bool checkDigi_; + const edm::EDGetTokenT digiToken_; + const edm::EDGetTokenT recHitToken_; + const edm::ESGetToken geomToken_; + hgcal::RecHitTools tool_; +}; + +HGCalRecHitToolsPartialWafer::HGCalRecHitToolsPartialWafer(const edm::ParameterSet& ps) + : source_(ps.getParameter("source")), + nameSense_(ps.getParameter("nameSense")), + checkDigi_(ps.getParameter("checkDigi")), + digiToken_(consumes(source_)), + recHitToken_(consumes(source_)), + geomToken_(esConsumes()) { + edm::LogVerbatim("HGCalSim") << "Test Hit ID using Digi(1)/RecHit(0): " << checkDigi_ << " for " << nameSense_ + << " with module Label: " << source_; +} + +void HGCalRecHitToolsPartialWafer::fillDescriptions(edm::ConfigurationDescriptions& descriptions) { + edm::ParameterSetDescription desc; + desc.add("source", edm::InputTag("simHGCalUnsuppressedDigis", "EE")); + desc.add("nameSense", "HGCalEESensitive"); + desc.add("checkDigi", true); + descriptions.add("hgcalCheckToolDigiEE", desc); +} + +void HGCalRecHitToolsPartialWafer::analyze(const edm::Event& e, const edm::EventSetup& iS) { + // get HGCal geometry constant + const CaloGeometry geo = iS.getData(geomToken_); + const HGCalGeometry* geom = (nameSense_ == "HGCalEESensitive") + ? static_cast( + geo.getSubdetectorGeometry(DetId::HGCalEE, ForwardSubdetector::ForwardEmpty)) + : static_cast( + geo.getSubdetectorGeometry(DetId::HGCalHSi, ForwardSubdetector::ForwardEmpty)); + //Setup the tool + tool_.setGeometry(geo); + + // get the hit collection + if (checkDigi_) { + const auto& collection = e.getHandle(digiToken_); + if (collection.isValid()) { + edm::LogVerbatim("HGCalSim") << "HGCalRecHitToolsPartialWafer: Finds Digi Collection for " << nameSense_ + << " with " << collection->size() << " hits"; + analyze(*(collection.product()), geom); + } else { + edm::LogVerbatim("HGCalSim") << "HGCalRecHitToolsPartialWafer: Cannot find Digi collection for " << nameSense_; + } + } else { + const auto& collection = e.getHandle(recHitToken_); + if (collection.isValid()) { + edm::LogVerbatim("HGCalSim") << "HGCalRecHitToolsPartialWafer: Finds RecHit Collection for " << nameSense_ + << " with " << collection->size() << " hits"; + analyze(*(collection.product()), geom); + } else { + edm::LogVerbatim("HGCalSim") << "HGCalRecHitToolsPartialWafer: Cannot find RecHit collection for " << nameSense_; + } + } +} + +template +void HGCalRecHitToolsPartialWafer::analyze(const T& collection, const HGCalGeometry* geom) { + const HGCalDDDConstants& hgc = geom->topology().dddConstants(); + uint32_t nhits = collection.size(); + uint32_t good(0), allSi(0), all(0); + + // Loop over all hits + for (const auto& it : collection) { + ++all; + DetId id(it.id()); + if ((id.det() == DetId::HGCalEE) || (id.det() == DetId::HGCalHSi)) { + ++allSi; + HGCSiliconDetId hid(id); + const auto& info = hgc.waferInfo(hid.layer(), hid.waferU(), hid.waferV()); + // Only partial wafers + if (info.part != HGCalTypes::WaferFull) { + ++good; + GlobalPoint pos1 = geom->getPosition(id); + GlobalPoint pos2 = tool_.getPosition(id); + edm::LogVerbatim("HGCalSim") << "Hit[" << all << ":" << allSi << ":" << good << "]" << HGCSiliconDetId(id) + << " Wafer Type:Part:Orient:Cassette " << info.type << ":" << info.part << ":" + << info.orient << ":" << info.cassette << " at (" << pos1.x() << ", " << pos1.y() + << ", " << pos1.z() << ") or (" << pos2.x() << ", " << pos2.y() << ", " << pos2.z() + << ")"; + } + } + } + edm::LogVerbatim("HGCalSim") << "Total hits = " << all << ":" << nhits << " Good DetIds = " << allSi << ":" << good; +} + +//define this as a plug-in +DEFINE_FWK_MODULE(HGCalRecHitToolsPartialWafer); diff --git a/RecoLocalCalo/HGCalRecAlgos/test/testHGCalPartialWaferDigi_cfg.py b/RecoLocalCalo/HGCalRecAlgos/test/testHGCalPartialWaferDigi_cfg.py new file mode 100644 index 0000000000000..ff26448799f92 --- /dev/null +++ b/RecoLocalCalo/HGCalRecAlgos/test/testHGCalPartialWaferDigi_cfg.py @@ -0,0 +1,27 @@ +import FWCore.ParameterSet.Config as cms +from Configuration.Eras.Era_Phase2C11_cff import Phase2C11 + +process = cms.Process("TestPartial",Phase2C11) +process.load("SimGeneral.HepPDTESSource.pythiapdt_cfi") +process.load("Configuration.Geometry.GeometryExtended2026D92Reco_cff") +process.load("Configuration.StandardSequences.MagneticField_cff") +process.load('FWCore.MessageService.MessageLogger_cfi') +process.load('RecoLocalCalo.HGCalRecAlgos.hgcalRecHitToolsPartialWafer_cff') +process.load("Configuration.StandardSequences.FrontierConditions_GlobalTag_cff") +from Configuration.AlCa.GlobalTag import GlobalTag +process.GlobalTag = GlobalTag(process.GlobalTag, 'auto:phase2_realistic_T21', '') + +if hasattr(process,'MessageLogger'): + process.MessageLogger.HGCalSim=dict() + +process.source = cms.Source("PoolSource", + fileNames = cms.untracked.vstring('file:hgcV17Digi.root') ) + +process.maxEvents = cms.untracked.PSet( + input = cms.untracked.int32(-1) +) + +process.analysis_step = cms.Path(process.hgcalCheckToolDigiEE+process.hgcalCheckToolDigiHE) + +# Schedule definition +process.schedule = cms.Schedule(process.analysis_step) diff --git a/RecoLocalCalo/HGCalRecAlgos/test/testHGCalPartialWaferRecHit_cfg.py b/RecoLocalCalo/HGCalRecAlgos/test/testHGCalPartialWaferRecHit_cfg.py new file mode 100644 index 0000000000000..40416aefca350 --- /dev/null +++ b/RecoLocalCalo/HGCalRecAlgos/test/testHGCalPartialWaferRecHit_cfg.py @@ -0,0 +1,27 @@ +import FWCore.ParameterSet.Config as cms +from Configuration.Eras.Era_Phase2C11_cff import Phase2C11 + +process = cms.Process("TestPartial",Phase2C11) +process.load("SimGeneral.HepPDTESSource.pythiapdt_cfi") +process.load("Configuration.Geometry.GeometryExtended2026D92Reco_cff") +process.load("Configuration.StandardSequences.MagneticField_cff") +process.load('FWCore.MessageService.MessageLogger_cfi') +process.load('RecoLocalCalo.HGCalRecAlgos.hgcalRecHitToolsPartialWafer_cff') +process.load("Configuration.StandardSequences.FrontierConditions_GlobalTag_cff") +from Configuration.AlCa.GlobalTag import GlobalTag +process.GlobalTag = GlobalTag(process.GlobalTag, 'auto:phase2_realistic_T21', '') + +if hasattr(process,'MessageLogger'): + process.MessageLogger.HGCalSim=dict() + +process.source = cms.Source("PoolSource", + fileNames = cms.untracked.vstring('file:hgcV17Reco.root') ) + +process.maxEvents = cms.untracked.PSet( + input = cms.untracked.int32(-1) +) + +process.analysis_step = cms.Path(process.hgcalCheckToolRecHitEE+process.hgcalCheckToolRecHitHE) + +# Schedule definition +process.schedule = cms.Schedule(process.analysis_step) diff --git a/RecoLocalCalo/HGCalRecAlgos/test/testHGCalPartialWafer_cfg.py b/RecoLocalCalo/HGCalRecAlgos/test/testHGCalPartialWaferSimHit_cfg.py similarity index 100% rename from RecoLocalCalo/HGCalRecAlgos/test/testHGCalPartialWafer_cfg.py rename to RecoLocalCalo/HGCalRecAlgos/test/testHGCalPartialWaferSimHit_cfg.py diff --git a/RecoVertex/AdaptiveVertexFinder/test/sequenceTest.py b/RecoVertex/AdaptiveVertexFinder/test/sequenceTest.py index b8afbd229195c..173655be68218 100644 --- a/RecoVertex/AdaptiveVertexFinder/test/sequenceTest.py +++ b/RecoVertex/AdaptiveVertexFinder/test/sequenceTest.py @@ -7,11 +7,11 @@ # import of standard configurations -process.load('Configuration/StandardSequences/Geometry_cff') -process.load('Configuration/StandardSequences/MagneticField_38T_cff') -process.load('Configuration/StandardSequences/FrontierConditions_GlobalTag_cff') -process.load('Configuration/StandardSequences/Reconstruction_cff') -process.load('Configuration/EventContent/EventContent_cff') +process.load('Configuration.StandardSequences.GeometryDB_cff') +process.load('Configuration.StandardSequences.MagneticField_38T_cff') +process.load('Configuration.StandardSequences.FrontierConditions_GlobalTag_cff') +process.load('Configuration.StandardSequences.Reconstruction_cff') +process.load('Configuration.EventContent.EventContent_cff') #process.load('RecoVertex/AdaptiveVertexFinder/inclusiveVertexing_cff') @@ -45,8 +45,7 @@ ) # Other statements -process.GlobalTag.globaltag = 'POSTLS172_V4::All' - +process.GlobalTag.globaltag = cms.string( autoCond[ 'phase1_2022_realistic' ] ) process.p = cms.Path(process.inclusiveVertexing*process.inclusiveCandidateVertexing) process.out_step = cms.EndPath(process.FEVT) diff --git a/RecoVertex/BeamSpotProducer/test/alcareco.py b/RecoVertex/BeamSpotProducer/test/alcareco.py deleted file mode 100644 index 4f60ee133bac0..0000000000000 --- a/RecoVertex/BeamSpotProducer/test/alcareco.py +++ /dev/null @@ -1,75 +0,0 @@ -import FWCore.ParameterSet.Config as cms - -process = cms.Process("AlcaRecoBeamSpot") - -# initialize MessageLogger -process.load("FWCore.MessageLogger.MessageLogger_cfi") - -# Beam fitter -process.load("RecoVertex.BeamSpotProducer.d0_phi_analyzer_cff") - -process.source = cms.Source("PoolSource", - fileNames = cms.untracked.vstring('/store/relval/CMSSW_2_1_7/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/IDEAL_V9_v1/0001/02F50799-FB7D-DD11-80FC-000423D98DC4.root', - '/store/relval/CMSSW_2_1_7/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/IDEAL_V9_v1/0001/066D059D-FB7D-DD11-A998-000423D98800.root', - '/store/relval/CMSSW_2_1_7/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/IDEAL_V9_v1/0001/08A9C567-FB7D-DD11-8B00-000423DD2F34.root', - '/store/relval/CMSSW_2_1_7/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/IDEAL_V9_v1/0001/0C4D30C3-FB7D-DD11-94C2-000423D98DD4.root', - '/store/relval/CMSSW_2_1_7/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/IDEAL_V9_v1/0001/1697AF63-FB7D-DD11-A122-000423D98AF0.root', - '/store/relval/CMSSW_2_1_7/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/IDEAL_V9_v1/0001/1A6D5F2A-FB7D-DD11-A860-000423D94C68.root', - '/store/relval/CMSSW_2_1_7/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/IDEAL_V9_v1/0001/1C3D4D97-FB7D-DD11-A5AB-000423D9890C.root', - '/store/relval/CMSSW_2_1_7/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/IDEAL_V9_v1/0001/24BBE96A-FB7D-DD11-914F-000423D98834.root', - '/store/relval/CMSSW_2_1_7/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/IDEAL_V9_v1/0001/2E2850F6-FB7D-DD11-AB6C-000423D6AF24.root', - '/store/relval/CMSSW_2_1_7/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/IDEAL_V9_v1/0001/34BD8472-FB7D-DD11-ADAE-000423D6B48C.root', - '/store/relval/CMSSW_2_1_7/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/IDEAL_V9_v1/0001/36B15966-FB7D-DD11-B785-000423D99896.root', - '/store/relval/CMSSW_2_1_7/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/IDEAL_V9_v1/0001/48BE7490-FB7D-DD11-BD97-000423D99AA2.root', - '/store/relval/CMSSW_2_1_7/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/IDEAL_V9_v1/0001/521EC634-FB7D-DD11-872C-000423D99AAE.root', - '/store/relval/CMSSW_2_1_7/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/IDEAL_V9_v1/0001/744F149D-FB7D-DD11-B095-000423D99658.root', - '/store/relval/CMSSW_2_1_7/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/IDEAL_V9_v1/0001/76C46999-FB7D-DD11-B900-000423D98750.root', - '/store/relval/CMSSW_2_1_7/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/IDEAL_V9_v1/0001/848DDA6F-FB7D-DD11-8874-000423D99A8E.root', - '/store/relval/CMSSW_2_1_7/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/IDEAL_V9_v1/0001/8663FD5F-FC7D-DD11-8AAF-000423D98834.root', - '/store/relval/CMSSW_2_1_7/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/IDEAL_V9_v1/0001/8ABB0C69-FB7D-DD11-9AFA-000423D98B6C.root', - '/store/relval/CMSSW_2_1_7/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/IDEAL_V9_v1/0001/8C4C798C-FB7D-DD11-AA5E-000423D8FA38.root', - '/store/relval/CMSSW_2_1_7/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/IDEAL_V9_v1/0001/8ECDBE32-FB7D-DD11-A4DC-000423D986A8.root', - '/store/relval/CMSSW_2_1_7/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/IDEAL_V9_v1/0001/90C2B3C8-FB7D-DD11-B485-000423D98634.root', - '/store/relval/CMSSW_2_1_7/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/IDEAL_V9_v1/0001/94B8975E-FB7D-DD11-BEAF-000423D94C68.root', - '/store/relval/CMSSW_2_1_7/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/IDEAL_V9_v1/0001/9680F65D-FB7D-DD11-8DFB-001617E30D0A.root', - '/store/relval/CMSSW_2_1_7/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/IDEAL_V9_v1/0001/9EA1BDF9-FB7D-DD11-83A2-000423D98AF0.root', - '/store/relval/CMSSW_2_1_7/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/IDEAL_V9_v1/0001/AE2B6AC2-FB7D-DD11-AA76-000423D99CEE.root', - '/store/relval/CMSSW_2_1_7/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/IDEAL_V9_v1/0001/AEA5A698-FB7D-DD11-9B19-000423D98F98.root', - '/store/relval/CMSSW_2_1_7/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/IDEAL_V9_v1/0001/D0CFA0F2-FB7D-DD11-8AC2-000423D94534.root', - '/store/relval/CMSSW_2_1_7/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/IDEAL_V9_v1/0001/D4D2885D-FC7D-DD11-94CD-000423D952C0.root', - '/store/relval/CMSSW_2_1_7/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/IDEAL_V9_v1/0001/E801C5F7-FB7D-DD11-B414-000423D990CC.root', - '/store/relval/CMSSW_2_1_7/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/IDEAL_V9_v1/0001/FAD35597-FB7D-DD11-8946-000423D99660.root', - '/store/relval/CMSSW_2_1_7/RelValTTbar/GEN-SIM-DIGI-RAW-HLTDEBUG-RECO/IDEAL_V9_v1/0002/98057D1C-437E-DD11-A450-001617C3B654.root') - ) - -process.maxEvents = cms.untracked.PSet( - input = cms.untracked.int32(1500) -) - -## Geometry -## -process.load("Configuration.StandardSequences.Geometry_cff") - -## Magnetic Field -## -process.load("Configuration.StandardSequences.MagneticField_cff") - -#process.p = cms.Path(process.d0_phi_analyzer) - -process.MessageLogger.debugModules = ['BeamSpotAnalyzer'] -process.d0_phi_analyzer.OutputFileName = 'EarlyCollision.root' -process.d0_phi_analyzer.BSAnalyzerParameters.TrackCollection = 'TrackRefitter' -#process.d0_phi_analyzer.InputBeamWidth = - -process.load("Configuration.StandardSequences.FrontierConditions_GlobalTag_cff") -#process.GlobalTag.globaltag = 'IDEAL_V9::All' # take your favourite - -process.GlobalTag.connect = "sqlite_file:/afs/cern.ch/user/f/futyand/public/globaltag/10PB_21X.db" -process.GlobalTag.globaltag = '10PB_V1::All' - -process.load("RecoTracker.TrackProducer.RefitterWithMaterial_cff") -# process.TrackRefitter.src = 'generalTracks' # should be default - -process.p1 = cms.Path(process.TrackRefitter - *process.d0_phi_analyzer - ) diff --git a/RecoVertex/KalmanVertexFit/test/analyzeKVF_cfg.py b/RecoVertex/KalmanVertexFit/test/analyzeKVF_cfg.py index 559919731d7f5..2c29b40f1e314 100644 --- a/RecoVertex/KalmanVertexFit/test/analyzeKVF_cfg.py +++ b/RecoVertex/KalmanVertexFit/test/analyzeKVF_cfg.py @@ -8,7 +8,7 @@ process.load("Configuration.StandardSequences.Services_cff") -process.load("Configuration.StandardSequences.Geometry_cff") +process.load("Configuration.StandardSequences.GeometryDB_cff") process.load("Configuration.StandardSequences.FakeConditions_cff") diff --git a/SimG4CMS/Calo/macros/MakeECPlot.C b/SimG4CMS/Calo/macros/MakeECPlot.C index 282985a3c516b..145eaf163f4a7 100644 --- a/SimG4CMS/Calo/macros/MakeECPlot.C +++ b/SimG4CMS/Calo/macros/MakeECPlot.C @@ -1,3 +1,33 @@ +////////////////////////////////////////////////////////////////////////////// +// +// Usage: +// .L MakeECPlots.C+g +// +// To make plot from a file created using EcalSimHitStudy +// makeECPlots(fname, text, prefix, save); +// +// where +// fname std::string Name of the ROOT file ("runWithGun_Fix.root") +// text std::string Text written in the Canvas +// ("Fixed Depth Calculation") +// prefix std::string Text added to the name of the Canvas ("Fix") +// save bool Flag to save the canvas as a gif file (false) +// +// To compare plots from 2 different runs with EcalSimHitStudy with +// "old" and "new" settings +// comparePlots(dirname, tex, mom, ratio, fname, save=false) +// +// where +// dirname std::string Name of the directory ("EcalSimHitStudy") +// text std::string Postfix to the histogram name ("All") +// mom int Momentum of the single particle used which +// is also a part of the file name (10) +// ratio bool Shows both distributions or plot the ratio (false) +// fname std:string Prefix of the file name ("elec") +// save bool Flag to save the canvas as a gif file (false) +// +////////////////////////////////////////////////////////////////////////////// + #include #include #include @@ -18,207 +48,238 @@ #include #include -void makePlots(std::string fname="runWithGun_Fix.root", - std::string text="Fixed Depth Calculation", - std::string prefix="Fix", bool save=false) { +void makeECPlots(std::string fname = "runWithGun_Fix.root", + std::string text = "Fixed Depth Calculation", + std::string prefix = "Fix", + bool save = false) { std::string name[4] = {"ECLL_EB", "ECLL_EBref", "ECLL_EE", "ECLL_EERef"}; - double xrnglo[4] = {1200.0,1200.0,3100.0,3100.0}; - double xrnghi[4] = {1600.0,1600.0,3600.0,3600.0}; - std::string xtitl[4] = {"R_{Cyl} (mm)","R_{Cyl} (mm)","|z| (mm)", "|z| (mm)"}; - std::string ytitl[4] = {"# X_{0} (*100)", "# X_{0} (*100)", "# X_{0} (*100)", - "# X_{0} (*100)"}; - std::string title[4] = {"EB (Normal)", "EB (Reflected)", "EE (Normal)", - "EE (Reflected)"}; + double xrnglo[4] = {1200.0, 1200.0, 3100.0, 3100.0}; + double xrnghi[4] = {1600.0, 1600.0, 3600.0, 3600.0}; + std::string xtitl[4] = {"R_{Cyl} (mm)", "R_{Cyl} (mm)", "|z| (mm)", "|z| (mm)"}; + std::string ytitl[4] = {"# X_{0} (*100)", "# X_{0} (*100)", "# X_{0} (*100)", "# X_{0} (*100)"}; + std::string title[4] = {"EB (Normal)", "EB (Reflected)", "EE (Normal)", "EE (Reflected)"}; - gStyle->SetCanvasBorderMode(0); gStyle->SetCanvasColor(kWhite); - gStyle->SetPadColor(kWhite); gStyle->SetFillColor(kWhite); + gStyle->SetCanvasBorderMode(0); + gStyle->SetCanvasColor(kWhite); + gStyle->SetPadColor(kWhite); + gStyle->SetFillColor(kWhite); gStyle->SetOptStat(11110); - TFile *file = new TFile(fname.c_str()); + TFile *file = new TFile(fname.c_str()); if (file) { char namep[100]; - for (int k=0; k<4; ++k) { - TH2D* hist(0); - for (int i=0; i<4; ++i) { - if (i == 0) sprintf (namep, "%s", name[k].c_str()); - else sprintf (namep, "%s;%d", name[k].c_str(),i); - hist = (TH2D*)file->FindObjectAny(name[k].c_str()); - std::cout << namep << " read out at " << hist << std::endl; - if (hist != 0) { - std::cout << "Entries " << hist->GetEntries() << std::endl; - if (hist->GetEntries() > 0) break; - } + for (int k = 0; k < 4; ++k) { + TH2D *hist(0); + for (int i = 0; i < 4; ++i) { + if (i == 0) + sprintf(namep, "%s", name[k].c_str()); + else + sprintf(namep, "%s;%d", name[k].c_str(), i); + hist = (TH2D *)file->FindObjectAny(name[k].c_str()); + std::cout << namep << " read out at " << hist << std::endl; + if (hist != 0) { + std::cout << "Entries " << hist->GetEntries() << std::endl; + if (hist->GetEntries() > 0) + break; + } } if (hist != 0) { - sprintf (namep,"%s%s",name[k].c_str(),prefix.c_str()); - TCanvas *pad = new TCanvas(namep,namep,500,500); - pad->SetRightMargin(0.10); pad->SetTopMargin(0.10); - hist->GetYaxis()->SetTitle(ytitl[k].c_str()); - hist->GetXaxis()->SetTitle(xtitl[k].c_str()); - hist->SetTitle(title[k].c_str()); - hist->GetXaxis()->SetRangeUser(xrnglo[k],xrnghi[k]); - hist->GetYaxis()->SetTitleOffset(1.4); - hist->Draw(); - pad->Update(); - TPaveStats* st1 = (TPaveStats*)hist->GetListOfFunctions()->FindObject("stats"); - if (st1 != NULL) { - st1->SetY1NDC(0.70); st1->SetY2NDC(0.90); - st1->SetX1NDC(0.65); st1->SetX2NDC(0.90); - } - TPaveText *txt1 = new TPaveText(0.50,0.60,0.90,0.65,"blNDC"); - txt1->SetFillColor(0); - txt1->AddText(text.c_str()); - pad->Update(); - if (save) { - sprintf (namep, "c_%s%s.gif",name[k].c_str(),prefix.c_str()); - pad->Print(namep); - } + sprintf(namep, "%s%s", name[k].c_str(), prefix.c_str()); + TCanvas *pad = new TCanvas(namep, namep, 500, 500); + pad->SetRightMargin(0.10); + pad->SetTopMargin(0.10); + hist->GetYaxis()->SetTitle(ytitl[k].c_str()); + hist->GetXaxis()->SetTitle(xtitl[k].c_str()); + hist->SetTitle(title[k].c_str()); + hist->GetXaxis()->SetRangeUser(xrnglo[k], xrnghi[k]); + hist->GetYaxis()->SetTitleOffset(1.4); + hist->Draw(); + pad->Update(); + TPaveStats *st1 = (TPaveStats *)hist->GetListOfFunctions()->FindObject("stats"); + if (st1 != NULL) { + st1->SetY1NDC(0.70); + st1->SetY2NDC(0.90); + st1->SetX1NDC(0.65); + st1->SetX2NDC(0.90); + } + TPaveText *txt1 = new TPaveText(0.50, 0.60, 0.90, 0.65, "blNDC"); + txt1->SetFillColor(0); + txt1->AddText(text.c_str()); + pad->Update(); + if (save) { + sprintf(namep, "c_%s%s.gif", name[k].c_str(), prefix.c_str()); + pad->Print(namep); + } } } } } -std::vector comparePlots(std::string dirname="EcalSimHitStudy", - std::string text="All", int mom=10, - bool ratio=false, std::string fname="elec", - bool save=false) { - - std::vector tcvs; - gStyle->SetCanvasBorderMode(0); gStyle->SetCanvasColor(kWhite); - gStyle->SetPadColor(kWhite); gStyle->SetFillColor(kWhite); - gStyle->SetOptTitle(0); gStyle->SetOptFit(0); - if (ratio) gStyle->SetOptStat(0); - else gStyle->SetOptStat(1100); +std::vector comparePlots(std::string dirname = "EcalSimHitStudy", + std::string text = "All", + int mom = 10, + bool ratio = false, + std::string fname = "elec", + bool save = false) { + std::vector tcvs; + gStyle->SetCanvasBorderMode(0); + gStyle->SetCanvasColor(kWhite); + gStyle->SetPadColor(kWhite); + gStyle->SetFillColor(kWhite); + gStyle->SetOptTitle(0); + gStyle->SetOptFit(0); + if (ratio) + gStyle->SetOptStat(0); + else + gStyle->SetOptStat(1100); - std::string tags[2] = {"Old", "New"}; - int color[2] = {2,4}; - int marker[2] = {20,21}; - int style[2] = {1,2}; - int rebin[16] = {50,50,50,50, 2, 2, 2, 2, 2, 2,20,20,20,20,20,20}; - int type[16] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; - int edgex[16] = { 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0}; - std::string name1[16] = {"Etot0", "Etot1", "EtotG0", "EtotG1", - "r1by250", "r1by251", "r1by90", "r1by91", - "r9by250", "r9by251", "sEtaEta0", "sEtaEta1", - "sEtaPhi0", "sEtaPhi1", "sPhiPhi0", "sPhiPhi1"}; - char name[100]; - TFile *file[2]; + std::string tags[2] = {"Old", "New"}; + int color[2] = {2, 4}; + int marker[2] = {20, 21}; + int style[2] = {1, 2}; + int rebin[16] = {50, 50, 50, 50, 2, 2, 2, 2, 2, 2, 20, 20, 20, 20, 20, 20}; + int type[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + int edgex[16] = {0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0}; + std::string name1[16] = {"Etot0", + "Etot1", + "EtotG0", + "EtotG1", + "r1by250", + "r1by251", + "r1by90", + "r1by91", + "r9by250", + "r9by251", + "sEtaEta0", + "sEtaEta1", + "sEtaPhi0", + "sEtaPhi1", + "sPhiPhi0", + "sPhiPhi1"}; + char name[100]; + TFile *file[2]; TDirectory *dir[2]; - for (int i=0; i<2; ++i) { - sprintf (name, "%s%d%s.root", fname.c_str(), mom, tags[i].c_str()); + for (int i = 0; i < 2; ++i) { + sprintf(name, "%s%d%s.root", fname.c_str(), mom, tags[i].c_str()); file[i] = new TFile(name); - dir[i] = (TDirectory*)file[i]->FindObjectAny(dirname.c_str()); + dir[i] = (TDirectory *)file[i]->FindObjectAny(dirname.c_str()); } - for (int k=0; k<16; ++k) { - TH1D* hist[2]; - sprintf (name, "%s", name1[k].c_str()); - for (int i=0; i<2; ++i) { - hist[i] = (TH1D*)dir[i]->FindObjectAny(name); + for (int k = 0; k < 16; ++k) { + TH1D *hist[2]; + sprintf(name, "%s", name1[k].c_str()); + for (int i = 0; i < 2; ++i) { + hist[i] = (TH1D *)dir[i]->FindObjectAny(name); if (hist[i] != 0) { - hist[i]->GetXaxis()->SetLabelOffset(0.005); - hist[i]->GetXaxis()->SetTitleOffset(1.00); - hist[i]->GetYaxis()->SetLabelOffset(0.005); - hist[i]->GetYaxis()->SetTitleOffset(1.20); - hist[i]->SetMarkerStyle(marker[i]); - hist[i]->SetMarkerColor(color[i]); - hist[i]->SetLineColor(color[i]); - hist[i]->SetLineStyle(style[i]); - hist[i]->SetLineWidth(2); + hist[i]->GetXaxis()->SetLabelOffset(0.005); + hist[i]->GetXaxis()->SetTitleOffset(1.00); + hist[i]->GetYaxis()->SetLabelOffset(0.005); + hist[i]->GetYaxis()->SetTitleOffset(1.20); + hist[i]->SetMarkerStyle(marker[i]); + hist[i]->SetMarkerColor(color[i]); + hist[i]->SetLineColor(color[i]); + hist[i]->SetLineStyle(style[i]); + hist[i]->SetLineWidth(2); } } if (hist[0] != 0 && hist[1] != 0) { double ytop(0.90), dy(0.05); double xmin = (edgex[k] == 0) ? 0.65 : 0.11; - double xmin1= (edgex[k] == 0) ? 0.55 : 0.11; - double ymax = ratio ? (ytop - 0.01) : (ytop - 2*dy - 0.01); + double xmin1 = (edgex[k] == 0) ? 0.55 : 0.11; + double ymax = ratio ? (ytop - 0.01) : (ytop - 2 * dy - 0.01); double ymin = ratio ? (ymax - 0.045) : (ymax - 0.09); - TLegend *legend = new TLegend(xmin1, ymin, xmin1+0.35, ymax); + TLegend *legend = new TLegend(xmin1, ymin, xmin1 + 0.35, ymax); legend->SetFillColor(kWhite); if (ratio) { - sprintf (name, "c_R%sE%d%s", name1[k].c_str(), mom, text.c_str()); + sprintf(name, "c_R%sE%d%s", name1[k].c_str(), mom, text.c_str()); } else { - sprintf (name, "c_%sE%d%s", name1[k].c_str(), mom, text.c_str()); + sprintf(name, "c_%sE%d%s", name1[k].c_str(), mom, text.c_str()); } TCanvas *pad = new TCanvas(name, name, 700, 500); pad->SetRightMargin(0.10); pad->SetTopMargin(0.10); - if (type[k] != 0) pad->SetLogy(); + if (type[k] != 0) + pad->SetLogy(); if (ratio) { - int nbin = hist[0]->GetNbinsX(); - int nbinR = nbin/rebin[k]; - double xlow = hist[0]->GetXaxis()->GetBinLowEdge(1); - double xhigh= hist[0]->GetXaxis()->GetBinLowEdge(nbin) + hist[0]->GetXaxis()->GetBinWidth(nbin);; - sprintf (name, "%sRatio", name1[k].c_str()); - TH1D* histr = new TH1D(name, hist[0]->GetTitle(), nbinR, xlow, xhigh); - sprintf (name, "Ratio (%s/%s)", tags[0].c_str(), tags[1].c_str()); - histr->GetXaxis()->SetTitle(hist[0]->GetXaxis()->GetTitle()); - histr->GetYaxis()->SetTitle(name); - histr->GetXaxis()->SetLabelOffset(0.005); - histr->GetXaxis()->SetTitleOffset(1.00); - histr->GetYaxis()->SetLabelOffset(0.005); - histr->GetYaxis()->SetTitleOffset(1.20); - histr->GetYaxis()->SetRangeUser(0.0,2.0); - histr->SetMarkerStyle(marker[0]); - histr->SetMarkerColor(color[0]); - histr->SetLineColor(color[0]); - histr->SetLineStyle(style[0]); - for (int j=0; jGetBinContent(ib); - tden += hist[1]->GetBinContent(ib); - rnum += ((hist[0]->GetBinError(ib))*(hist[0]->GetBinError(ib))); - rden += ((hist[1]->GetBinError(ib))*(hist[1]->GetBinError(ib))); - } - if (tden > 0 && tnum > 0) { - double rat = tnum/tden; - double err = rat*sqrt((rnum/(tnum*tnum))+(rden/(tden*tden))); - histr->SetBinContent(j+1,rat); - histr->SetBinError(j+1,err); - } - } - histr->Draw(); - sprintf (name, "%d GeV Electron (%s)",mom,text.c_str()); - legend->AddEntry(histr,name,"lp"); - pad->Update(); - TLine* line = new TLine(xlow,1.0,xhigh,1.0); - line->SetLineColor(color[1]); - line->SetLineWidth(2); - line->SetLineStyle(2); - line->Draw("same"); - pad->Update(); + int nbin = hist[0]->GetNbinsX(); + int nbinR = nbin / rebin[k]; + double xlow = hist[0]->GetXaxis()->GetBinLowEdge(1); + double xhigh = hist[0]->GetXaxis()->GetBinLowEdge(nbin) + hist[0]->GetXaxis()->GetBinWidth(nbin); + ; + sprintf(name, "%sRatio", name1[k].c_str()); + TH1D *histr = new TH1D(name, hist[0]->GetTitle(), nbinR, xlow, xhigh); + sprintf(name, "Ratio (%s/%s)", tags[0].c_str(), tags[1].c_str()); + histr->GetXaxis()->SetTitle(hist[0]->GetXaxis()->GetTitle()); + histr->GetYaxis()->SetTitle(name); + histr->GetXaxis()->SetLabelOffset(0.005); + histr->GetXaxis()->SetTitleOffset(1.00); + histr->GetYaxis()->SetLabelOffset(0.005); + histr->GetYaxis()->SetTitleOffset(1.20); + histr->GetYaxis()->SetRangeUser(0.0, 2.0); + histr->SetMarkerStyle(marker[0]); + histr->SetMarkerColor(color[0]); + histr->SetLineColor(color[0]); + histr->SetLineStyle(style[0]); + for (int j = 0; j < nbinR; ++j) { + double tnum(0), tden(0), rnum(0), rden(0); + for (int i = 0; i < rebin[k]; ++i) { + int ib = j * rebin[k] + i + 1; + tnum += hist[0]->GetBinContent(ib); + tden += hist[1]->GetBinContent(ib); + rnum += ((hist[0]->GetBinError(ib)) * (hist[0]->GetBinError(ib))); + rden += ((hist[1]->GetBinError(ib)) * (hist[1]->GetBinError(ib))); + } + if (tden > 0 && tnum > 0) { + double rat = tnum / tden; + double err = rat * sqrt((rnum / (tnum * tnum)) + (rden / (tden * tden))); + histr->SetBinContent(j + 1, rat); + histr->SetBinError(j + 1, err); + } + } + histr->Draw(); + sprintf(name, "%d GeV Electron (%s)", mom, text.c_str()); + legend->AddEntry(histr, name, "lp"); + pad->Update(); + TLine *line = new TLine(xlow, 1.0, xhigh, 1.0); + line->SetLineColor(color[1]); + line->SetLineWidth(2); + line->SetLineStyle(2); + line->Draw("same"); + pad->Update(); } else { - double mean[2], error[2]; - for (int i=0; i<2; ++i) { - if (rebin[k] > 1) hist[i]->Rebin(rebin[k]); - if (i == 0) hist[i]->Draw("hist"); - else hist[i]->Draw("sameshist"); - pad->Update(); - sprintf (name, "%d GeV Electron (%s %s)",mom,text.c_str(),tags[i].c_str()); - legend->AddEntry(hist[i],name,"lp"); - TPaveStats* st1 = (TPaveStats*)hist[i]->GetListOfFunctions()->FindObject("stats"); - if (st1 != NULL) { - st1->SetLineColor(color[i]); st1->SetTextColor(color[i]); - st1->SetY1NDC(ytop-dy); st1->SetY2NDC(ytop); - st1->SetX1NDC(xmin); st1->SetX2NDC(xmin+0.25); - ytop -= dy; - } - double entries = hist[i]->GetEntries(); - mean[i] = hist[i]->GetMean(); - error[i] = (hist[i]->GetRMS())/sqrt(entries); - std::cout << text << ":" << hist[i]->GetName() << " V " << tags[i] - << " Mean " << mean[i] << " RMS " << hist[i]->GetRMS() - << " Error " << error[i] << std::endl; - } - double diff = 0.5*(mean[0]-mean[1])/(mean[0]+mean[1]); - double ddiff= (sqrt((mean[0]*error[1])*(mean[0]*error[1])+ - (mean[1]*error[0])*(mean[1]*error[0]))/ - ((mean[0]*mean[0])+(mean[1]*mean[1]))); - double sign = std::abs(diff)/ddiff; - std::cout << "Difference " << diff << " +- " << ddiff - << " Significance " << sign << std::endl; - pad->Modified(); - pad->Update(); + double mean[2], error[2]; + for (int i = 0; i < 2; ++i) { + if (rebin[k] > 1) + hist[i]->Rebin(rebin[k]); + if (i == 0) + hist[i]->Draw("hist"); + else + hist[i]->Draw("sameshist"); + pad->Update(); + sprintf(name, "%d GeV Electron (%s %s)", mom, text.c_str(), tags[i].c_str()); + legend->AddEntry(hist[i], name, "lp"); + TPaveStats *st1 = (TPaveStats *)hist[i]->GetListOfFunctions()->FindObject("stats"); + if (st1 != NULL) { + st1->SetLineColor(color[i]); + st1->SetTextColor(color[i]); + st1->SetY1NDC(ytop - dy); + st1->SetY2NDC(ytop); + st1->SetX1NDC(xmin); + st1->SetX2NDC(xmin + 0.25); + ytop -= dy; + } + double entries = hist[i]->GetEntries(); + mean[i] = hist[i]->GetMean(); + error[i] = (hist[i]->GetRMS()) / sqrt(entries); + std::cout << text << ":" << hist[i]->GetName() << " V " << tags[i] << " Mean " << mean[i] << " RMS " + << hist[i]->GetRMS() << " Error " << error[i] << std::endl; + } + double diff = 0.5 * (mean[0] - mean[1]) / (mean[0] + mean[1]); + double ddiff = + (sqrt((mean[0] * error[1]) * (mean[0] * error[1]) + (mean[1] * error[0]) * (mean[1] * error[0])) / + ((mean[0] * mean[0]) + (mean[1] * mean[1]))); + double sign = std::abs(diff) / ddiff; + std::cout << "Difference " << diff << " +- " << ddiff << " Significance " << sign << std::endl; + pad->Modified(); + pad->Update(); } if (ratio) { } @@ -227,8 +288,8 @@ std::vector comparePlots(std::string dirname="EcalSimHitStudy", pad->Update(); tcvs.push_back(pad); if (save) { - sprintf (name, "%s.pdf", pad->GetName()); - pad->Print(name); + sprintf(name, "%s.pdf", pad->GetName()); + pad->Print(name); } } } diff --git a/SimG4CMS/Calo/macros/MakeGVPlots.C b/SimG4CMS/Calo/macros/MakeGVPlots.C index db79ac614e03c..7598fb45b1828 100644 --- a/SimG4CMS/Calo/macros/MakeGVPlots.C +++ b/SimG4CMS/Calo/macros/MakeGVPlots.C @@ -8,7 +8,7 @@ // // To plot on the same Canvas plots from Geant4 and GeantV done using // CaloSimHitAnalysis -// makeGV2Plots(fnmG4, fnmGV, todomin, todomax, normalize, tag, text, +// makeGV2Plots(fnmG4, fnmGV, todomin, todomax, normalize, tag, text, // save, modet, mode, dirnm) // // To plot from passive hit collection produced using CaloSimHitAnalysis @@ -31,31 +31,31 @@ // digit indicate text message on the plot // (o for header "CMS Simulation"; t input type; // h for input specification; x for B-field/MT etc) -// mode int Flag if one file is G4 and other GV (0), or +// mode int Flag if one file is G4 and other GV (0), or // both files are GV (1) or G4 (2) (defualt 0) // dirnm std::string Name of the directory ("caloSimHitAnalysis") // // The histogram series have different meanings for each function // // GVPlots (17 in total): -// "Energy deposit per Hit", "Hit time", "Total energy deposit", +// "Energy deposit per Hit", "Hit time", "Total energy deposit", // "Energy deposit after 15 ns", "R vs Z", "R vs Z for hits after 15 ns", // "#phi vs #eta", "Energy deposit", "Time of Hit", -// "Energy deposit per Hit after 15 ns", "Total energy deposit in 100 ns", +// "Energy deposit per Hit after 15 ns", "Total energy deposit in 100 ns", // "Energy deposit for EM particles", "Energy deposit for non-EM particles", // "R", "Z", "#eta", "phi" // // GV2Plots (14 in total): -// "Energy deposit per Hit", "Hit time", "Total energy deposit", +// "Energy deposit per Hit", "Hit time", "Total energy deposit", // "Energy deposit after 15 ns", "Energy deposit", "Time of Hit", -// "Energy deposit per Hit after 15 ns", "Total energy deposit in 100 ns", +// "Energy deposit per Hit after 15 ns", "Total energy deposit in 100 ns", // "Energy deposit for EM particles", "Energy deposit for non-EM particles", // "R", "Z", "#eta", "phi" // // GVSPlots (8 in total): -// "Total Hits", "Tracks", "Step Length', +// "Total Hits", "Tracks", "Step Length', // "Energy Deposit in all components", "Time of all hits", -// "Energy Deposit in tracker subdetectors", +// "Energy Deposit in tracker subdetectors", // "Time of hits in tracker subdetectors" // // All plots in GVPlots or GV2Plots happen for EB, EE, HB and HE @@ -87,459 +87,590 @@ void setTDRStyle(); -void makeGVPlots(std::string fname="analG4.root", bool ifG4=true, - int todomin=0, int todomax=3, std::string tag="", - std::string text="", bool save=false, - std::string dirnm="caloSimHitAnalysis") { - - std::string names[17] = {"EdepT", "TimeT", "Etot", "Edep15", "rz", "rz2", - "etaphi", "Edep", "Time", "EdepT15", "EtotG", - "EdepEM", "EdepHad", "rr", "zz", "eta", "phi"}; - std::string namex[17] = {"Edep", "Time", "Etot", "Edep15", "rz", "rz2", - "etaphi", "EdepX", "TimeX", "EdepT15", "EtotG", - "EdepEM", "EdepHad", "rr", "zz", "eta", "phi"}; - int types[17] = {1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; - int dets[4] = {0, 1, 2, 3}; - std::string detName[4]= {"EB", "EE", "HB", "HE"}; +void makeGVPlots(std::string fname = "analG4.root", + bool ifG4 = true, + int todomin = 0, + int todomax = 3, + std::string tag = "", + std::string text = "", + bool save = false, + std::string dirnm = "caloSimHitAnalysis") { + std::string names[17] = {"EdepT", + "TimeT", + "Etot", + "Edep15", + "rz", + "rz2", + "etaphi", + "Edep", + "Time", + "EdepT15", + "EtotG", + "EdepEM", + "EdepHad", + "rr", + "zz", + "eta", + "phi"}; + std::string namex[17] = {"Edep", + "Time", + "Etot", + "Edep15", + "rz", + "rz2", + "etaphi", + "EdepX", + "TimeX", + "EdepT15", + "EtotG", + "EdepEM", + "EdepHad", + "rr", + "zz", + "eta", + "phi"}; + int types[17] = {1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; + int dets[4] = {0, 1, 2, 3}; + std::string detName[4] = {"EB", "EE", "HB", "HE"}; std::string xtitle[17] = {"Energy deposit per Hit (GeV)", - "Hit time (ns)", - "Total energy deposit (GeV)", - "Energy deposit (GeV) after 15 ns", - "z (cm)", "z (cm)", "#eta", - "Energy deposit (GeV)", - "Time of Hit (ns)", - "Energy deposit (GeV) per Hit after 15 ns", - "Total energy deposit (GeV) in 100 ns", - "Energy deposit (GeV) for EM particles", - "Energy deposit (GeV) for non-EM particles", - "R (cm)", "z (cm)", "#eta", "phi"}; - std::string ytitle[17] = {"Hits", "Hits", "Events", "Hits", "R (cm)", - "R (cm)", "#phi", "Hits", "Hits", "Hits", "Events", - "Hits", "Hits", "Hits", "Hits", "Hits", "Hits"}; - - gStyle->SetCanvasBorderMode(0); gStyle->SetCanvasColor(kWhite); - gStyle->SetPadColor(kWhite); gStyle->SetFillColor(kWhite); + "Hit time (ns)", + "Total energy deposit (GeV)", + "Energy deposit (GeV) after 15 ns", + "z (cm)", + "z (cm)", + "#eta", + "Energy deposit (GeV)", + "Time of Hit (ns)", + "Energy deposit (GeV) per Hit after 15 ns", + "Total energy deposit (GeV) in 100 ns", + "Energy deposit (GeV) for EM particles", + "Energy deposit (GeV) for non-EM particles", + "R (cm)", + "z (cm)", + "#eta", + "phi"}; + std::string ytitle[17] = {"Hits", + "Hits", + "Events", + "Hits", + "R (cm)", + "R (cm)", + "#phi", + "Hits", + "Hits", + "Hits", + "Events", + "Hits", + "Hits", + "Hits", + "Hits", + "Hits", + "Hits"}; + + gStyle->SetCanvasBorderMode(0); + gStyle->SetCanvasColor(kWhite); + gStyle->SetPadColor(kWhite); + gStyle->SetFillColor(kWhite); gStyle->SetOptStat(111110); - TFile *file = new TFile(fname.c_str()); + TFile *file = new TFile(fname.c_str()); if (file) { - TDirectory *dir = (TDirectory*)file->FindObjectAny(dirnm.c_str()); + TDirectory *dir = (TDirectory *)file->FindObjectAny(dirnm.c_str()); char cname[100], name[100], name1[100], title[100]; - for (int i1 = 0; i1<4; ++i1) { - for (int i2=todomin; i2<=todomax; ++i2) { - if (types[i2] == 1) { - sprintf (name, "%s%d", names[i2].c_str(), dets[i1]); - sprintf (name1, "%s%d", namex[i2].c_str(), dets[i1]); - if (ifG4) - sprintf (title, "%s %s (Geant4 Simulation)", text.c_str(), detName[i1].c_str()); - else - sprintf (title, "%s %s (GeantV Simulation)", text.c_str(), detName[i1].c_str()); - } else if (i1 == 0) { - sprintf (name, "%s", names[i2].c_str()); - sprintf (name1, "%s", namex[i2].c_str()); - if (ifG4) sprintf (title, "%s (Geant4 Simulation)", text.c_str()); - else sprintf (title, "%s (GeantV Simulation)", text.c_str()); - } else { - continue; - } - TH1D* hist1(nullptr); - TH2D* hist2(nullptr); - if (types[i2] == 1) hist1 = (TH1D*)dir->FindObjectAny(name); - else hist2 = (TH2D*)dir->FindObjectAny(name); -// std::cout << name << " read out at " << hist1 << ":" << hist2 << std::endl; + for (int i1 = 0; i1 < 4; ++i1) { + for (int i2 = todomin; i2 <= todomax; ++i2) { + if (types[i2] == 1) { + sprintf(name, "%s%d", names[i2].c_str(), dets[i1]); + sprintf(name1, "%s%d", namex[i2].c_str(), dets[i1]); + if (ifG4) + sprintf(title, "%s %s (Geant4 Simulation)", text.c_str(), detName[i1].c_str()); + else + sprintf(title, "%s %s (GeantV Simulation)", text.c_str(), detName[i1].c_str()); + } else if (i1 == 0) { + sprintf(name, "%s", names[i2].c_str()); + sprintf(name1, "%s", namex[i2].c_str()); + if (ifG4) + sprintf(title, "%s (Geant4 Simulation)", text.c_str()); + else + sprintf(title, "%s (GeantV Simulation)", text.c_str()); + } else { + continue; + } + TH1D *hist1(nullptr); + TH2D *hist2(nullptr); + if (types[i2] == 1) + hist1 = (TH1D *)dir->FindObjectAny(name); + else + hist2 = (TH2D *)dir->FindObjectAny(name); + // std::cout << name << " read out at " << hist1 << ":" << hist2 << std::endl; if ((hist1 != nullptr) || (hist2 != nullptr)) { - if (ifG4) sprintf (cname, "%sG4%s", name1, tag.c_str()); - else sprintf (cname, "%sGV%s", name1, tag.c_str()); - TCanvas *pad = new TCanvas(cname,cname,500,500); - pad->SetRightMargin(0.10); pad->SetTopMargin(0.10); - if (types[i2] == 1) { - hist1->GetYaxis()->SetTitleOffset(1.2); - hist1->GetYaxis()->SetTitle(ytitle[i2].c_str()); - hist1->GetXaxis()->SetTitle(xtitle[i2].c_str()); - hist1->SetTitle(title); - pad->SetLogy(); - hist1->Draw(); - } else { - hist2->GetYaxis()->SetTitleOffset(1.2); - hist2->GetYaxis()->SetTitle(ytitle[i2].c_str()); - hist2->GetXaxis()->SetTitle(xtitle[i2].c_str()); - hist2->SetTitle(title); - hist2->Draw(); - } - pad->Update(); - TPaveStats* st1 = ((hist1 != nullptr) ? - ((TPaveStats*)hist1->GetListOfFunctions()->FindObject("stats")) : - ((TPaveStats*)hist2->GetListOfFunctions()->FindObject("stats"))); - if (st1 != NULL) { - st1->SetY1NDC(0.70); st1->SetY2NDC(0.90); - st1->SetX1NDC(0.65); st1->SetX2NDC(0.90); - } - pad->Modified(); pad->Update(); - if (save) { - sprintf (name, "c_%s.jpg", pad->GetName()); - pad->Print(name); - } - } + if (ifG4) + sprintf(cname, "%sG4%s", name1, tag.c_str()); + else + sprintf(cname, "%sGV%s", name1, tag.c_str()); + TCanvas *pad = new TCanvas(cname, cname, 500, 500); + pad->SetRightMargin(0.10); + pad->SetTopMargin(0.10); + if (types[i2] == 1) { + hist1->GetYaxis()->SetTitleOffset(1.2); + hist1->GetYaxis()->SetTitle(ytitle[i2].c_str()); + hist1->GetXaxis()->SetTitle(xtitle[i2].c_str()); + hist1->SetTitle(title); + pad->SetLogy(); + hist1->Draw(); + } else { + hist2->GetYaxis()->SetTitleOffset(1.2); + hist2->GetYaxis()->SetTitle(ytitle[i2].c_str()); + hist2->GetXaxis()->SetTitle(xtitle[i2].c_str()); + hist2->SetTitle(title); + hist2->Draw(); + } + pad->Update(); + TPaveStats *st1 = ((hist1 != nullptr) ? ((TPaveStats *)hist1->GetListOfFunctions()->FindObject("stats")) + : ((TPaveStats *)hist2->GetListOfFunctions()->FindObject("stats"))); + if (st1 != NULL) { + st1->SetY1NDC(0.70); + st1->SetY2NDC(0.90); + st1->SetX1NDC(0.65); + st1->SetX2NDC(0.90); + } + pad->Modified(); + pad->Update(); + if (save) { + sprintf(name, "c_%s.jpg", pad->GetName()); + pad->Print(name); + } + } } } } } - -void makeGV2Plots(std::string fnmG4="analG4.root", - std::string fnmGV="analGV.root", int todomin=0, - int todomax=2, bool normalize=true, std::string tag="", - std::string text="", int save=0, int modet=0, int mode=0, - std::string dirnm="caloSimHitAnalysis") { - - std::string names[14] = {"EdepT", "TimeT", "Etot", "Edep15", "Edep", "Time", - "EdepT15", "EtotG", "EdepEM", "EdepHad", "rr", "zz", - "eta", "phi"}; - std::string namex[14] = {"Edep", "Time", "Etot", "Edep15", "EdepX", "TimeX", - "EdepT15", "EtotG", "EdepEM", "EdepHad", "rr", "zz", - "eta", "phi"}; - int dets[4] = {0, 1, 2, 3}; +void makeGV2Plots(std::string fnmG4 = "analG4.root", + std::string fnmGV = "analGV.root", + int todomin = 0, + int todomax = 2, + bool normalize = true, + std::string tag = "", + std::string text = "", + int save = 0, + int modet = 0, + int mode = 0, + std::string dirnm = "caloSimHitAnalysis") { + std::string names[14] = {"EdepT", + "TimeT", + "Etot", + "Edep15", + "Edep", + "Time", + "EdepT15", + "EtotG", + "EdepEM", + "EdepHad", + "rr", + "zz", + "eta", + "phi"}; + std::string namex[14] = {"Edep", + "Time", + "Etot", + "Edep15", + "EdepX", + "TimeX", + "EdepT15", + "EtotG", + "EdepEM", + "EdepHad", + "rr", + "zz", + "eta", + "phi"}; + int dets[4] = {0, 1, 2, 3}; std::string detName[4] = {"EB", "EE", "HB", "HE"}; std::string xtitle[14] = {"Energy deposit per Hit (GeV)", - "Hit time (ns)", - "Total energy deposit (GeV)", - "Energy deposit (GeV) after 15 ns", - "Energy deposit (GeV)", - "Time of Hit (ns)", - "Energy deposit (GeV) per Hit after 15 ns", - "Total energy deposit (GeV) in 100 ns", - "Energy deposit (GeV) for EM particles", - "Energy deposit (GeV) for non-EM particles", - "R (cm)", "z (cm)", "#eta", "phi"}; - std::string ytitle[14] = {"Hits", "Hits", "Events", "Hits", "Hits", "Hits", - "Hits", "Events", "Hits", "Hits", "Hits", "Hits", - "Hits", "Hits"}; + "Hit time (ns)", + "Total energy deposit (GeV)", + "Energy deposit (GeV) after 15 ns", + "Energy deposit (GeV)", + "Time of Hit (ns)", + "Energy deposit (GeV) per Hit after 15 ns", + "Total energy deposit (GeV) in 100 ns", + "Energy deposit (GeV) for EM particles", + "Energy deposit (GeV) for non-EM particles", + "R (cm)", + "z (cm)", + "#eta", + "phi"}; + std::string ytitle[14] = {"Hits", + "Hits", + "Events", + "Hits", + "Hits", + "Hits", + "Hits", + "Events", + "Hits", + "Hits", + "Hits", + "Hits", + "Hits", + "Hits"}; std::string title1[4] = {"2 GeV", "10 GeV", "50 GeV", "100 GeV"}; - std::string title2[2] = {"#eta = 1.0; #phi = 1.0", - "|#eta| < 3.0; 0.0 < #phi < 2#pi"}; - std::string title3[4] = {"B = 0.0 Tesla", "B = 3.8 Tesla", - "Multithreaded (B = 0.0 Tesla)", - "Multithreaded (B = 3.8 Tesla)"}; + std::string title2[2] = {"#eta = 1.0; #phi = 1.0", "|#eta| < 3.0; 0.0 < #phi < 2#pi"}; + std::string title3[4] = { + "B = 0.0 Tesla", "B = 3.8 Tesla", "Multithreaded (B = 0.0 Tesla)", "Multithreaded (B = 3.8 Tesla)"}; if (modet >= 10) { setTDRStyle(); } else { - gStyle->SetCanvasBorderMode(0); gStyle->SetCanvasColor(kWhite); - gStyle->SetPadColor(kWhite); gStyle->SetFillColor(kWhite); + gStyle->SetCanvasBorderMode(0); + gStyle->SetCanvasColor(kWhite); + gStyle->SetPadColor(kWhite); + gStyle->SetFillColor(kWhite); } - if (normalize) gStyle->SetOptStat(0); - else gStyle->SetOptStat(111110); - TFile *file1 = new TFile(fnmG4.c_str()); - TFile *file2 = new TFile(fnmGV.c_str()); + if (normalize) + gStyle->SetOptStat(0); + else + gStyle->SetOptStat(111110); + TFile *file1 = new TFile(fnmG4.c_str()); + TFile *file2 = new TFile(fnmGV.c_str()); if (file1 && file2) { - TDirectory *dir1 = (TDirectory*)file1->FindObjectAny(dirnm.c_str()); - TDirectory *dir2 = (TDirectory*)file2->FindObjectAny(dirnm.c_str()); + TDirectory *dir1 = (TDirectory *)file1->FindObjectAny(dirnm.c_str()); + TDirectory *dir2 = (TDirectory *)file2->FindObjectAny(dirnm.c_str()); char name[100], cname[100], title[100]; - for (int i1 = 0; i1<4; ++i1) { - for (int i2=todomin; i2<=todomax; ++i2) { - sprintf (name, "%s%d", names[i2].c_str(), dets[i1]); - sprintf (cname, "%s%s%s", namex[i2].c_str(), detName[i1].c_str(), - tag.c_str()); - if (modet >= 10) - sprintf (title, ""); - else if (mode == 1) - sprintf (title, "%s %s (2 runs of GeantV)", text.c_str(), detName[i1].c_str()); - else if (mode == 2) - sprintf (title, "%s %s (2 runs of Geant4)", text.c_str(), detName[i1].c_str()); - else - sprintf (title, "%s %s (Geant4 vs GeantV)", text.c_str(), detName[i1].c_str()); - TH1D *hist[2]; - hist[0] = (TH1D*)dir1->FindObjectAny(name); - hist[1] = (TH1D*)dir2->FindObjectAny(name); + for (int i1 = 0; i1 < 4; ++i1) { + for (int i2 = todomin; i2 <= todomax; ++i2) { + sprintf(name, "%s%d", names[i2].c_str(), dets[i1]); + sprintf(cname, "%s%s%s", namex[i2].c_str(), detName[i1].c_str(), tag.c_str()); + if (modet >= 10) + sprintf(title, ""); + else if (mode == 1) + sprintf(title, "%s %s (2 runs of GeantV)", text.c_str(), detName[i1].c_str()); + else if (mode == 2) + sprintf(title, "%s %s (2 runs of Geant4)", text.c_str(), detName[i1].c_str()); + else + sprintf(title, "%s %s (Geant4 vs GeantV)", text.c_str(), detName[i1].c_str()); + TH1D *hist[2]; + hist[0] = (TH1D *)dir1->FindObjectAny(name); + hist[1] = (TH1D *)dir2->FindObjectAny(name); if ((hist[0] != nullptr) && (hist[1] != nullptr)) { - // Plot superimposed histograms - double ymx(0.78); - TCanvas *pad = new TCanvas(cname,cname,500,500); - TLegend *legend = new TLegend(0.44, ymx, 0.64, 0.89); - pad->SetRightMargin(0.10); pad->SetTopMargin(0.10); pad->SetLogy(); - pad->SetFillColor(kWhite); legend->SetFillColor(kWhite); - int icol[2] = {1,2}; - int isty[2] = {1,2}; - int imty[2] = {20,24}; - std::string type[2] = {"Geant4", "GeantV"}; - double ymax(0.90); - double total[2] = {0,0}; - for (int i=0; i<2; ++i) { - hist[i]->GetYaxis()->SetTitleOffset(1.2); - hist[i]->GetYaxis()->SetTitle(ytitle[i2].c_str()); - hist[i]->GetXaxis()->SetTitle(xtitle[i2].c_str()); - hist[i]->SetTitle(title); - hist[i]->SetMarkerStyle(imty[i]); - hist[i]->SetMarkerColor(icol[i]); - hist[i]->SetLineColor(icol[i]); - hist[i]->SetLineStyle(isty[i]); - hist[i]->SetNdivisions(505,"X"); - total[i] = hist[i]->GetEntries(); - if (mode == 1) - sprintf (name, "%s (run %d)", type[1].c_str(), i); - else if (mode == 2) - sprintf (name, "%s (run %d)", type[0].c_str(), i); - else - sprintf (name, "%s", type[i].c_str()); - legend->AddEntry(hist[i], name, "lp"); - if (i == 0) { - if (normalize) hist[i]->DrawNormalized("hist"); - else hist[i]->Draw(); - } else { - if (normalize) hist[i]->DrawNormalized("sames hist"); - else hist[i]->Draw("sames"); - } - pad->Update(); - } - legend->Draw("same"); - pad->Modified(); pad->Update(); - for (int i=0; i<2; ++i) { - TPaveStats* st = (TPaveStats*)hist[i]->GetListOfFunctions()->FindObject("stats"); - if (st != NULL) { - st->SetLineColor(icol[i]); st->SetTextColor(icol[i]); - st->SetY1NDC(ymax-0.15); st->SetY2NDC(ymax); - st->SetX1NDC(0.65); st->SetX2NDC(0.90); - ymax -= 0.15; - } - } - pad->Modified(); pad->Update(); - if (ymx > ymax) ymx = ymax; - ymx -= 0.005; - int indx = (modet/10)%10; - double ymi = ymx - 0.05; - if (indx > 0 && indx <= 4) { - sprintf (title, "%s Electrons", title1[indx-1].c_str()); - TPaveText *txt0 = new TPaveText(0.70,ymi,0.895,ymx,"blNDC"); - txt0->SetFillColor(0); - txt0->AddText(title); - txt0->Draw("same"); - ymx -= 0.05; - } - indx = (modet/100)%10; - ymi = ymx - 0.05; - if (indx > 0 && indx <= 2) { - sprintf (title, "%s", title2[indx-1].c_str()); - TPaveText *txt0 = new TPaveText(0.65,ymi,0.895,ymx,"blNDC"); - txt0->SetFillColor(0); - txt0->AddText(title); - txt0->Draw("same"); - ymx -= 0.05; - } - indx = (modet/1000)%10; - ymi = ymx - 0.05; - if (indx > 0 && indx <= 4) { - sprintf (title, "%s", title3[indx-1].c_str()); - TPaveText *txt0 = new TPaveText(0.55,ymi,0.895,ymx,"blNDC"); - txt0->SetFillColor(0); - txt0->AddText(title); - txt0->Draw("same"); - ymx -= 0.05; - } - indx = modet%10; - if (indx > 0) { - sprintf (title, "CMS Simulation"); - TPaveText *txt0 = new TPaveText(0.10,0.91,0.35,0.96,"blNDC"); - txt0->SetFillColor(0); - txt0->AddText(title); - txt0->Draw("same"); - } - if (save != 0) { - if (save > 0) sprintf (name, "c_%s.pdf", pad->GetName()); - else sprintf (name, "c_%s.jpg", pad->GetName()); - pad->Print(name); - } - - // Ratio plot - if (normalize) { - int nbin = hist[0]->GetNbinsX(); - double xmin = hist[0]->GetBinLowEdge(1); - double dx = hist[0]->GetBinWidth(1); - double xmax = xmin + nbin*dx; - double fac = total[1]/total[0]; - int npt = 0; - double sumNum(0), sumDen(0), xpt[200], dxp[200], ypt[200], dyp[200]; - for (int i=0; iGetBinContent(i+1) > 0 && - hist[1]->GetBinContent(i+1) > 0) { - ypt[npt] = (fac*hist[0]->GetBinContent(i+1)/ - hist[1]->GetBinContent(i+1)); - double er1 = hist[0]->GetBinError(i+1)/hist[0]->GetBinContent(i+1); - double er2 = hist[1]->GetBinError(i+1)/hist[1]->GetBinContent(i+1); - dyp[npt] = ypt[npt] * sqrt (er1*er1 + er2*er2); - xpt[npt] = xmin + (i-0.5)*dx; - dxp[npt] = 0; - double temp1 = (ypt[npt]>1.0) ? 1.0/ypt[npt] : ypt[npt]; - double temp2 = (ypt[npt]>1.0) ? dyp[npt]/(ypt[npt]*ypt[npt]) : dyp[npt]; - sumNum += (fabs(1-temp1)/(temp2*temp2)); - sumDen += (1.0/(temp2*temp2)); - ++npt; - } - } - sumNum = (sumDen>0) ? (sumNum/sumDen) : 0; - sumDen = (sumDen>0) ? 1.0/sqrt(sumDen) : 0; - TGraphAsymmErrors *graph = new TGraphAsymmErrors(npt, xpt, ypt, dxp, - dxp, dyp, dyp); - graph->SetMarkerStyle(24); - graph->SetMarkerColor(1); - graph->SetMarkerSize(0.8); - graph->SetLineColor(1); - graph->SetLineWidth(2); - sprintf (name, "%sRatio", pad->GetName()); - TCanvas *canvas = new TCanvas(name, name, 500, 400); - gStyle->SetOptStat(0); gPad->SetTopMargin(0.05); - gPad->SetLeftMargin(0.15); gPad->SetRightMargin(0.025); - gPad->SetBottomMargin(0.20); - TH1F *vFrame = canvas->DrawFrame(xmin, 0.01, xmax, 0.5); - vFrame->GetYaxis()->SetRangeUser(0.4,1.5); - vFrame->GetXaxis()->SetLabelSize(0.035); - vFrame->GetYaxis()->SetLabelSize(0.04); - vFrame->GetXaxis()->SetTitleSize(0.045); - vFrame->GetYaxis()->SetTitleSize(0.045); - vFrame->GetYaxis()->SetTitleOffset(1.2); - vFrame->GetXaxis()->SetRangeUser(xmin, xmax); - vFrame->GetYaxis()->SetTitle("Geant4/GeantV"); - sprintf (name, "%s in %s", xtitle[i2].c_str(), detName[i1].c_str()); - vFrame->GetXaxis()->SetTitle(name); - graph->Draw("P"); - TLine *line = new TLine(xmin, 1.0, xmax, 1.0); - line->SetLineStyle(2); line->SetLineWidth(2); line->SetLineColor(kRed); - line->Draw(); - sprintf (title, "Mean Deviation = %5.3f #pm %5.3f", sumNum, sumDen); - TPaveText* text = new TPaveText(0.16, 0.85, 0.60, 0.90, "brNDC"); - text->AddText(title); text->Draw("same"); - canvas->Modified(); canvas->Update(); - if (save != 0) { - if (save > 0) sprintf (name, "c_%s.pdf", canvas->GetName()); - else sprintf (name, "c_%s.jpg", canvas->GetName()); - canvas->Print(name); - } - } - } + // Plot superimposed histograms + double ymx(0.78); + TCanvas *pad = new TCanvas(cname, cname, 500, 500); + TLegend *legend = new TLegend(0.44, ymx, 0.64, 0.89); + pad->SetRightMargin(0.10); + pad->SetTopMargin(0.10); + pad->SetLogy(); + pad->SetFillColor(kWhite); + legend->SetFillColor(kWhite); + int icol[2] = {1, 2}; + int isty[2] = {1, 2}; + int imty[2] = {20, 24}; + std::string type[2] = {"Geant4", "GeantV"}; + double ymax(0.90); + double total[2] = {0, 0}; + for (int i = 0; i < 2; ++i) { + hist[i]->GetYaxis()->SetTitleOffset(1.2); + hist[i]->GetYaxis()->SetTitle(ytitle[i2].c_str()); + hist[i]->GetXaxis()->SetTitle(xtitle[i2].c_str()); + hist[i]->SetTitle(title); + hist[i]->SetMarkerStyle(imty[i]); + hist[i]->SetMarkerColor(icol[i]); + hist[i]->SetLineColor(icol[i]); + hist[i]->SetLineStyle(isty[i]); + hist[i]->SetNdivisions(505, "X"); + total[i] = hist[i]->GetEntries(); + if (mode == 1) + sprintf(name, "%s (run %d)", type[1].c_str(), i); + else if (mode == 2) + sprintf(name, "%s (run %d)", type[0].c_str(), i); + else + sprintf(name, "%s", type[i].c_str()); + legend->AddEntry(hist[i], name, "lp"); + if (i == 0) { + if (normalize) + hist[i]->DrawNormalized("hist"); + else + hist[i]->Draw(); + } else { + if (normalize) + hist[i]->DrawNormalized("sames hist"); + else + hist[i]->Draw("sames"); + } + pad->Update(); + } + legend->Draw("same"); + pad->Modified(); + pad->Update(); + for (int i = 0; i < 2; ++i) { + TPaveStats *st = (TPaveStats *)hist[i]->GetListOfFunctions()->FindObject("stats"); + if (st != NULL) { + st->SetLineColor(icol[i]); + st->SetTextColor(icol[i]); + st->SetY1NDC(ymax - 0.15); + st->SetY2NDC(ymax); + st->SetX1NDC(0.65); + st->SetX2NDC(0.90); + ymax -= 0.15; + } + } + pad->Modified(); + pad->Update(); + if (ymx > ymax) + ymx = ymax; + ymx -= 0.005; + int indx = (modet / 10) % 10; + double ymi = ymx - 0.05; + if (indx > 0 && indx <= 4) { + sprintf(title, "%s Electrons", title1[indx - 1].c_str()); + TPaveText *txt0 = new TPaveText(0.70, ymi, 0.895, ymx, "blNDC"); + txt0->SetFillColor(0); + txt0->AddText(title); + txt0->Draw("same"); + ymx -= 0.05; + } + indx = (modet / 100) % 10; + ymi = ymx - 0.05; + if (indx > 0 && indx <= 2) { + sprintf(title, "%s", title2[indx - 1].c_str()); + TPaveText *txt0 = new TPaveText(0.65, ymi, 0.895, ymx, "blNDC"); + txt0->SetFillColor(0); + txt0->AddText(title); + txt0->Draw("same"); + ymx -= 0.05; + } + indx = (modet / 1000) % 10; + ymi = ymx - 0.05; + if (indx > 0 && indx <= 4) { + sprintf(title, "%s", title3[indx - 1].c_str()); + TPaveText *txt0 = new TPaveText(0.55, ymi, 0.895, ymx, "blNDC"); + txt0->SetFillColor(0); + txt0->AddText(title); + txt0->Draw("same"); + ymx -= 0.05; + } + indx = modet % 10; + if (indx > 0) { + sprintf(title, "CMS Simulation"); + TPaveText *txt0 = new TPaveText(0.10, 0.91, 0.35, 0.96, "blNDC"); + txt0->SetFillColor(0); + txt0->AddText(title); + txt0->Draw("same"); + } + if (save != 0) { + if (save > 0) + sprintf(name, "c_%s.pdf", pad->GetName()); + else + sprintf(name, "c_%s.jpg", pad->GetName()); + pad->Print(name); + } + + // Ratio plot + if (normalize) { + int nbin = hist[0]->GetNbinsX(); + double xmin = hist[0]->GetBinLowEdge(1); + double dx = hist[0]->GetBinWidth(1); + double xmax = xmin + nbin * dx; + double fac = total[1] / total[0]; + int npt = 0; + double sumNum(0), sumDen(0), xpt[200], dxp[200], ypt[200], dyp[200]; + for (int i = 0; i < nbin; ++i) { + if (hist[0]->GetBinContent(i + 1) > 0 && hist[1]->GetBinContent(i + 1) > 0) { + ypt[npt] = (fac * hist[0]->GetBinContent(i + 1) / hist[1]->GetBinContent(i + 1)); + double er1 = hist[0]->GetBinError(i + 1) / hist[0]->GetBinContent(i + 1); + double er2 = hist[1]->GetBinError(i + 1) / hist[1]->GetBinContent(i + 1); + dyp[npt] = ypt[npt] * sqrt(er1 * er1 + er2 * er2); + xpt[npt] = xmin + (i - 0.5) * dx; + dxp[npt] = 0; + double temp1 = (ypt[npt] > 1.0) ? 1.0 / ypt[npt] : ypt[npt]; + double temp2 = (ypt[npt] > 1.0) ? dyp[npt] / (ypt[npt] * ypt[npt]) : dyp[npt]; + sumNum += (fabs(1 - temp1) / (temp2 * temp2)); + sumDen += (1.0 / (temp2 * temp2)); + ++npt; + } + } + sumNum = (sumDen > 0) ? (sumNum / sumDen) : 0; + sumDen = (sumDen > 0) ? 1.0 / sqrt(sumDen) : 0; + TGraphAsymmErrors *graph = new TGraphAsymmErrors(npt, xpt, ypt, dxp, dxp, dyp, dyp); + graph->SetMarkerStyle(24); + graph->SetMarkerColor(1); + graph->SetMarkerSize(0.8); + graph->SetLineColor(1); + graph->SetLineWidth(2); + sprintf(name, "%sRatio", pad->GetName()); + TCanvas *canvas = new TCanvas(name, name, 500, 400); + gStyle->SetOptStat(0); + gPad->SetTopMargin(0.05); + gPad->SetLeftMargin(0.15); + gPad->SetRightMargin(0.025); + gPad->SetBottomMargin(0.20); + TH1F *vFrame = canvas->DrawFrame(xmin, 0.01, xmax, 0.5); + vFrame->GetYaxis()->SetRangeUser(0.4, 1.5); + vFrame->GetXaxis()->SetLabelSize(0.035); + vFrame->GetYaxis()->SetLabelSize(0.04); + vFrame->GetXaxis()->SetTitleSize(0.045); + vFrame->GetYaxis()->SetTitleSize(0.045); + vFrame->GetYaxis()->SetTitleOffset(1.2); + vFrame->GetXaxis()->SetRangeUser(xmin, xmax); + vFrame->GetYaxis()->SetTitle("Geant4/GeantV"); + sprintf(name, "%s in %s", xtitle[i2].c_str(), detName[i1].c_str()); + vFrame->GetXaxis()->SetTitle(name); + graph->Draw("P"); + TLine *line = new TLine(xmin, 1.0, xmax, 1.0); + line->SetLineStyle(2); + line->SetLineWidth(2); + line->SetLineColor(kRed); + line->Draw(); + sprintf(title, "Mean Deviation = %5.3f #pm %5.3f", sumNum, sumDen); + TPaveText *text = new TPaveText(0.16, 0.85, 0.60, 0.90, "brNDC"); + text->AddText(title); + text->Draw("same"); + canvas->Modified(); + canvas->Update(); + if (save != 0) { + if (save > 0) + sprintf(name, "c_%s.pdf", canvas->GetName()); + else + sprintf(name, "c_%s.jpg", canvas->GetName()); + canvas->Print(name); + } + } + } } } } } - -void makeGVSPlots(std::string fnmG4="analG4.root", - std::string fnmGV="analGV.root", - int todomin=0, int todomax=7, - std::string tag="", std::string text="", bool save=false, - std::string dirnm="caloSimHitAnalysis") { - - std::string names[8] = {"hitp", "trackp", "stepp", "edepp", "timep", "volp", - "edept", "timet"}; - std::string xtitle[8] = {"Hits", "Tracks", "Step Length (cm)", - "Energy Deposit (MeV)", "Time (ns)", - "Volume elements", "Energy Deposit (MeV)", - "Time (ns)"}; - std::string ytitle[8] = {"Events", "Events", "Hits", "Hits", "Hits", - "Events", "Hits", "Hits"}; - std::string detName[6] = {"Barrel Pixel", "Forward Pixel", "TIB", "TID", - "TOB", "TEC"}; +void makeGVSPlots(std::string fnmG4 = "analG4.root", + std::string fnmGV = "analGV.root", + int todomin = 0, + int todomax = 7, + std::string tag = "", + std::string text = "", + bool save = false, + std::string dirnm = "caloSimHitAnalysis") { + std::string names[8] = {"hitp", "trackp", "stepp", "edepp", "timep", "volp", "edept", "timet"}; + std::string xtitle[8] = {"Hits", + "Tracks", + "Step Length (cm)", + "Energy Deposit (MeV)", + "Time (ns)", + "Volume elements", + "Energy Deposit (MeV)", + "Time (ns)"}; + std::string ytitle[8] = {"Events", "Events", "Hits", "Hits", "Hits", "Events", "Hits", "Hits"}; + std::string detName[6] = {"Barrel Pixel", "Forward Pixel", "TIB", "TID", "TOB", "TEC"}; std::string particles[3] = {"Electrons", "Positrons", "Photons"}; int boxp[8] = {0, 1, 0, 0, 0, 0, 0, 0}; int nhis[8] = {-4, -4, -4, 1, 1, 1, 6, 6}; - gStyle->SetCanvasBorderMode(0); gStyle->SetCanvasColor(kWhite); - gStyle->SetPadColor(kWhite); gStyle->SetFillColor(kWhite); + gStyle->SetCanvasBorderMode(0); + gStyle->SetCanvasColor(kWhite); + gStyle->SetPadColor(kWhite); + gStyle->SetFillColor(kWhite); gStyle->SetOptStat(111110); - TFile *file1 = new TFile(fnmG4.c_str()); - TFile *file2 = new TFile(fnmGV.c_str()); + TFile *file1 = new TFile(fnmG4.c_str()); + TFile *file2 = new TFile(fnmGV.c_str()); if (file1 && file2) { - TDirectory *dir1 = (TDirectory*)file1->FindObjectAny(dirnm.c_str()); - TDirectory *dir2 = (TDirectory*)file2->FindObjectAny(dirnm.c_str()); + TDirectory *dir1 = (TDirectory *)file1->FindObjectAny(dirnm.c_str()); + TDirectory *dir2 = (TDirectory *)file2->FindObjectAny(dirnm.c_str()); char name[100], cname[100], title[100]; - for (int i2=todomin; i2<=todomax; ++i2) { + for (int i2 = todomin; i2 <= todomax; ++i2) { int nhism = (nhis[i2] >= 0) ? nhis[i2] : -nhis[i2]; - for (int i1=0; i1FindObjectAny(name); - hist[1] = (TH1D*)dir2->FindObjectAny(name); - if ((hist[0] != nullptr) && (hist[1] != nullptr)) { - // Plot superimposed histograms - TCanvas *pad = new TCanvas(cname,cname,500,500); - TLegend *legend = new TLegend(0.44, 0.78, 0.64, 0.89); - pad->SetRightMargin(0.10); pad->SetTopMargin(0.10); pad->SetLogy(); - pad->SetFillColor(kWhite); legend->SetFillColor(kWhite); - int icol[2] = {1,2}; - int isty[2] = {1,2}; - int imty[2] = {20,24}; - std::string type[2] = {"Geant4", "GeantV"}; - double ymax(0.90); - double total[2] = {0,0}; - double ymaxv[2] = {0,0}; - for (int i=0; i<2; ++i) { - hist[i]->GetYaxis()->SetTitleOffset(1.2); - hist[i]->GetYaxis()->SetTitle(ytitle[i2].c_str()); - hist[i]->GetXaxis()->SetTitle(xtitle[i2].c_str()); - hist[i]->SetTitle(title); - hist[i]->SetMarkerStyle(imty[i]); - hist[i]->SetMarkerColor(icol[i]); - hist[i]->SetLineColor(icol[i]); - hist[i]->SetLineStyle(isty[i]); - hist[i]->SetNdivisions(505,"X"); - total[i] = hist[i]->GetEntries(); - legend->AddEntry(hist[i],type[i].c_str(),"lp"); - ymaxv[i] = hist[i]->GetMaximum(); - } - int first = (ymaxv[0] > ymaxv[1]) ? 0 : 1; - int next = 1 - first; - hist[first]->Draw(); - hist[next]->Draw("sames"); - pad->Update(); - legend->Draw("same"); - pad->Modified(); pad->Update(); - for (int i=0; i<2; ++i) { - TPaveStats* st = (TPaveStats*)hist[i]->GetListOfFunctions()->FindObject("stats"); - if (st != NULL) { - double xl = (boxp[i2] == 0) ? 0.65 : 0.10; - st->SetLineColor(icol[i]); st->SetTextColor(icol[i]); - st->SetY1NDC(ymax-0.15); st->SetY2NDC(ymax); - st->SetX1NDC(xl); st->SetX2NDC(xl+0.25); - ymax -= 0.15; - } - } - pad->Modified(); pad->Update(); - if (save) { - sprintf (name, "c_%s.jpg", pad->GetName()); - pad->Print(name); - } - } + for (int i1 = 0; i1 < nhism; ++i1) { + if (nhis[i2] <= 1 && i1 == 0) { + sprintf(name, "%s", names[i2].c_str()); + sprintf(cname, "%s%s", names[i2].c_str(), tag.c_str()); + sprintf(title, "%s (Geant4 vs GeantV)", text.c_str()); + } else if (nhis[i2] < 0) { + sprintf(name, "%s%d", names[i2].c_str(), i1 - 1); + sprintf(cname, "%s%d%s", names[i2].c_str(), i1 - 1, tag.c_str()); + sprintf(title, "%s in %s (Geant4 vs GeantV)", particles[i1 - 1].c_str(), text.c_str()); + } else { + sprintf(name, "%s%d", names[i2].c_str(), i1); + sprintf(cname, "%s%d%s", names[i2].c_str(), i1, tag.c_str()); + sprintf(title, "%s in %s (Geant4 vs GeantV)", text.c_str(), detName[i1].c_str()); + } + TH1D *hist[2]; + hist[0] = (TH1D *)dir1->FindObjectAny(name); + hist[1] = (TH1D *)dir2->FindObjectAny(name); + if ((hist[0] != nullptr) && (hist[1] != nullptr)) { + // Plot superimposed histograms + TCanvas *pad = new TCanvas(cname, cname, 500, 500); + TLegend *legend = new TLegend(0.44, 0.78, 0.64, 0.89); + pad->SetRightMargin(0.10); + pad->SetTopMargin(0.10); + pad->SetLogy(); + pad->SetFillColor(kWhite); + legend->SetFillColor(kWhite); + int icol[2] = {1, 2}; + int isty[2] = {1, 2}; + int imty[2] = {20, 24}; + std::string type[2] = {"Geant4", "GeantV"}; + double ymax(0.90); + double total[2] = {0, 0}; + double ymaxv[2] = {0, 0}; + for (int i = 0; i < 2; ++i) { + hist[i]->GetYaxis()->SetTitleOffset(1.2); + hist[i]->GetYaxis()->SetTitle(ytitle[i2].c_str()); + hist[i]->GetXaxis()->SetTitle(xtitle[i2].c_str()); + hist[i]->SetTitle(title); + hist[i]->SetMarkerStyle(imty[i]); + hist[i]->SetMarkerColor(icol[i]); + hist[i]->SetLineColor(icol[i]); + hist[i]->SetLineStyle(isty[i]); + hist[i]->SetNdivisions(505, "X"); + total[i] = hist[i]->GetEntries(); + legend->AddEntry(hist[i], type[i].c_str(), "lp"); + ymaxv[i] = hist[i]->GetMaximum(); + } + int first = (ymaxv[0] > ymaxv[1]) ? 0 : 1; + int next = 1 - first; + hist[first]->Draw(); + hist[next]->Draw("sames"); + pad->Update(); + legend->Draw("same"); + pad->Modified(); + pad->Update(); + for (int i = 0; i < 2; ++i) { + TPaveStats *st = (TPaveStats *)hist[i]->GetListOfFunctions()->FindObject("stats"); + if (st != NULL) { + double xl = (boxp[i2] == 0) ? 0.65 : 0.10; + st->SetLineColor(icol[i]); + st->SetTextColor(icol[i]); + st->SetY1NDC(ymax - 0.15); + st->SetY2NDC(ymax); + st->SetX1NDC(xl); + st->SetX2NDC(xl + 0.25); + ymax -= 0.15; + } + } + pad->Modified(); + pad->Update(); + if (save) { + sprintf(name, "c_%s.jpg", pad->GetName()); + pad->Print(name); + } + } } } } } void setTDRStyle() { - TStyle *tdrStyle = new TStyle("tdrStyle","Style for P-TDR"); + TStyle *tdrStyle = new TStyle("tdrStyle", "Style for P-TDR"); // For the canvas: tdrStyle->SetCanvasBorderMode(0); tdrStyle->SetCanvasColor(kWhite); - tdrStyle->SetCanvasDefH(600); //Height of canvas - tdrStyle->SetCanvasDefW(600); //Width of canvas - tdrStyle->SetCanvasDefX(0); //POsition on screen + tdrStyle->SetCanvasDefH(600); //Height of canvas + tdrStyle->SetCanvasDefW(600); //Width of canvas + tdrStyle->SetCanvasDefX(0); //POsition on screen tdrStyle->SetCanvasDefY(0); // For the Pad: tdrStyle->SetPadBorderMode(0); - // tdrStyle->SetPadBorderSize(Width_t size = 1); tdrStyle->SetPadColor(kWhite); tdrStyle->SetPadGridX(false); tdrStyle->SetPadGridY(false); @@ -555,36 +686,28 @@ void setTDRStyle() { tdrStyle->SetFrameLineColor(1); tdrStyle->SetFrameLineStyle(1); tdrStyle->SetFrameLineWidth(1); - + // For the histo: - // tdrStyle->SetHistFillColor(1); - // tdrStyle->SetHistFillStyle(0); tdrStyle->SetHistLineColor(1); tdrStyle->SetHistLineStyle(0); tdrStyle->SetHistLineWidth(1); - // tdrStyle->SetLegoInnerR(Float_t rad = 0.5); - // tdrStyle->SetNumberContours(Int_t number = 20); - tdrStyle->SetEndErrorSize(2); - // tdrStyle->SetErrorMarker(20); - //tdrStyle->SetErrorX(0.); - + tdrStyle->SetMarkerStyle(20); - + //For the fit/function: tdrStyle->SetOptFit(1); tdrStyle->SetFitFormat("5.4g"); tdrStyle->SetFuncColor(2); tdrStyle->SetFuncStyle(1); tdrStyle->SetFuncWidth(1); + //For the date: tdrStyle->SetOptDate(0); - // tdrStyle->SetDateX(Float_t x = 0.01); - // tdrStyle->SetDateY(Float_t y = 0.01); // For the statistics box: tdrStyle->SetOptFile(0); - tdrStyle->SetOptStat(0); // To display the mean and RMS: SetOptStat("mr"); + tdrStyle->SetOptStat(0); // To display the mean and RMS: SetOptStat("mr"); tdrStyle->SetStatColor(kWhite); tdrStyle->SetStatFont(42); tdrStyle->SetStatFontSize(0.025); @@ -593,9 +716,6 @@ void setTDRStyle() { tdrStyle->SetStatBorderSize(1); tdrStyle->SetStatH(0.1); tdrStyle->SetStatW(0.15); - // tdrStyle->SetStatStyle(Style_t style = 1001); - // tdrStyle->SetStatX(Float_t x = 0); - // tdrStyle->SetStatY(Float_t y = 0); // Margins: tdrStyle->SetPadTopMargin(0.05); @@ -611,23 +731,14 @@ void setTDRStyle() { tdrStyle->SetTitleTextColor(1); tdrStyle->SetTitleFillColor(10); tdrStyle->SetTitleFontSize(0.05); - // tdrStyle->SetTitleH(0); // Set the height of the title box - // tdrStyle->SetTitleW(0); // Set the width of the title box - // tdrStyle->SetTitleX(0); // Set the position of the title box - // tdrStyle->SetTitleY(0.985); // Set the position of the title box - // tdrStyle->SetTitleStyle(Style_t style = 1001); - // tdrStyle->SetTitleBorderSize(2); // For the axis titles: tdrStyle->SetTitleColor(1, "XYZ"); tdrStyle->SetTitleFont(42, "XYZ"); tdrStyle->SetTitleSize(0.06, "XYZ"); - // tdrStyle->SetTitleXSize(Float_t size = 0.02); // Another way to set the size? - // tdrStyle->SetTitleYSize(Float_t size = 0.02); tdrStyle->SetTitleXOffset(0.9); tdrStyle->SetTitleYOffset(1.25); - // tdrStyle->SetTitleOffset(1.1, "Y"); // Another way to set the Offset // For the axis labels: @@ -651,37 +762,15 @@ void setTDRStyle() { tdrStyle->SetOptLogz(0); // Postscript options: - tdrStyle->SetPaperSize(20.,20.); - // tdrStyle->SetLineScalePS(Float_t scale = 3); - // tdrStyle->SetLineStyleString(Int_t i, const char* text); - // tdrStyle->SetHeaderPS(const char* header); - // tdrStyle->SetTitlePS(const char* pstitle); - - // tdrStyle->SetBarOffset(Float_t baroff = 0.5); - // tdrStyle->SetBarWidth(Float_t barwidth = 0.5); - // tdrStyle->SetPaintTextFormat(const char* format = "g"); - // tdrStyle->SetPalette(Int_t ncolors = 0, Int_t* colors = 0); - // tdrStyle->SetTimeOffset(Double_t toffset); + tdrStyle->SetPaperSize(20., 20.); tdrStyle->SetOptLogy(0); tdrStyle->SetOptLogz(0); -// Postscript options: - tdrStyle->SetPaperSize(20.,20.); - // tdrStyle->SetLineScalePS(Float_t scale = 3); - // tdrStyle->SetLineStyleString(Int_t i, const char* text); - // tdrStyle->SetHeaderPS(const char* header); - // tdrStyle->SetTitlePS(const char* pstitle); - - // tdrStyle->SetBarOffset(Float_t baroff = 0.5); - // tdrStyle->SetBarWidth(Float_t barwidth = 0.5); - // tdrStyle->SetPaintTextFormat(const char* format = "g"); - // tdrStyle->SetPalette(Int_t ncolors = 0, Int_t* colors = 0); - // tdrStyle->SetTimeOffset(Double_t toffset); - // tdrStyle->SetHistMinimumZero(kTRUE); + // Postscript options: + tdrStyle->SetPaperSize(20., 20.); tdrStyle->SetHatchesLineWidth(5); tdrStyle->SetHatchesSpacing(0.05); tdrStyle->cd(); - } diff --git a/SimG4CMS/Calo/macros/MakeHFNPlots.C b/SimG4CMS/Calo/macros/MakeHFNPlots.C index e90ddddbabdcd..48ce73d1d4120 100644 --- a/SimG4CMS/Calo/macros/MakeHFNPlots.C +++ b/SimG4CMS/Calo/macros/MakeHFNPlots.C @@ -3,19 +3,23 @@ // Usage: // .L MakeHFNPlots.C+g // -// To make plot of layers from a file created using .SimHit/Digi/RecHitStudy +// To make plot of layers from a file created using SimHit/Digi/RecHit +// using the scripts runHFNoseSimHitStudy_cfg.py, runHFNoseDigiStudy_cfg.py, +// runHFNoseRecHitStudy_cfg.py in Validation/HGCalValidation +// // makeLayerPlots(fname, type, todomin, todomax, tag, text, save) // // where -// fname std::string Name of the ROOT file (hfnSimHitD44tt.root) -// type int File type (0:SimHit; 2:Digi; 3:RecHit) -// todomin int Range of plots to make (minimum: -1 -// todomax int maximum: 8) -// tag std::string To be added to the name of the canvas ("") -// text std::string To be added to the title of the histogram ("") -// save bool If the canvas is to be saved as jpg file (false) +// fname std::string Name of the ROOT file [hfnSimHitD94tt.root] +// type int File type (0:SimHit; 2:Digi; 3:RecHit) [0] +// todomin int Range of plots to make [0] +// todomax int (minimum: -1; maximum: 8) [7] +// tag std::string To be added to the name of the canvas [""] +// text std::string To be added to the title of the histogram [""] +// save bool If the canvas is to be saved as jpg file [false] // ////////////////////////////////////////////////////////////////////////////// + #include #include #include @@ -37,51 +41,59 @@ #include #include -void makeLayerPlots(std::string fname="hfnSimHitD44tt.root", int type=0, - int todomin=0, int todomax=7, std::string tag="", - std::string text="", bool save=false) { - +void makeLayerPlots(std::string fname = "hfnSimHitD94tt.root", + int type = 0, + int todomin = 0, + int todomax = 7, + std::string tag = "", + std::string text = "", + bool save = false) { std::string dirnm[3] = {"hgcalSimHitStudy", "hfnoseDigiStudy", "hfnoseRecHitStudy"}; std::string units[3] = {" (mm)", " (cm)", " (cm)"}; std::string titlx[3] = {"SimHit", "Digi", "RecHit"}; - gStyle->SetCanvasBorderMode(0); gStyle->SetCanvasColor(kWhite); - gStyle->SetPadColor(kWhite); + gStyle->SetCanvasBorderMode(0); + gStyle->SetCanvasColor(kWhite); + gStyle->SetPadColor(kWhite); gStyle->SetOptStat(0); - if (type < 0 || type > 2) type = 0; + if (type < 0 || type > 2) + type = 0; TFile *file = new TFile(fname.c_str()); if (file) { - TDirectory *dir = (TDirectory*)file->FindObjectAny(dirnm[type].c_str()); + TDirectory *dir = (TDirectory *)file->FindObjectAny(dirnm[type].c_str()); char cname[100], name[100], title[100], xtitl[100], ytitl[100]; - for (int i=todomin; i<=todomax; ++i) { + for (int i = todomin; i <= todomax; ++i) { if (i < 0) { - sprintf (name, "RZ_HGCalHFNoseSensitive"); - sprintf (title, "%s (%s)", text.c_str(), titlx[type].c_str()); - sprintf (xtitl, "z %s", units[type].c_str()); - sprintf (ytitl, "R %s", units[type].c_str()); + sprintf(name, "RZ_HGCalHFNoseSensitive"); + sprintf(title, "%s (%s)", text.c_str(), titlx[type].c_str()); + sprintf(xtitl, "z %s", units[type].c_str()); + sprintf(ytitl, "R %s", units[type].c_str()); } else { - sprintf (name, "XY_L%d", i+1); - sprintf (title, "%s (Layer %d %s)", text.c_str(), i+1, titlx[type].c_str()); - sprintf (xtitl, "x %s", units[type].c_str()); - sprintf (ytitl, "y %s", units[type].c_str()); + sprintf(name, "XY_L%d", i + 1); + sprintf(title, "%s (Layer %d %s)", text.c_str(), i + 1, titlx[type].c_str()); + sprintf(xtitl, "x %s", units[type].c_str()); + sprintf(ytitl, "y %s", units[type].c_str()); } - TH2D* hist = (TH2D*)dir->FindObjectAny(name); + TH2D *hist = (TH2D *)dir->FindObjectAny(name); std::cout << name << " read out at " << hist << std::endl; if (hist != nullptr) { - sprintf (cname, "%s%s", name, tag.c_str()); - TCanvas *pad = new TCanvas(cname,cname,500,500); - pad->SetRightMargin(0.10); pad->SetTopMargin(0.10); - hist->GetYaxis()->SetTitleOffset(1.2); - hist->GetYaxis()->SetTitle(ytitl); - hist->GetXaxis()->SetTitle(xtitl); - hist->SetTitle(title); - if (i < 0 && type == 0) hist->GetXaxis()->SetNdivisions(5); - hist->Draw("colz"); - pad->Modified(); pad->Update(); - if (save) { - sprintf (name, "c_%s.jpg", pad->GetName()); - pad->Print(name); - } + sprintf(cname, "%s%s", name, tag.c_str()); + TCanvas *pad = new TCanvas(cname, cname, 500, 500); + pad->SetRightMargin(0.10); + pad->SetTopMargin(0.10); + hist->GetYaxis()->SetTitleOffset(1.2); + hist->GetYaxis()->SetTitle(ytitl); + hist->GetXaxis()->SetTitle(xtitl); + hist->SetTitle(title); + if (i < 0 && type == 0) + hist->GetXaxis()->SetNdivisions(5); + hist->Draw("colz"); + pad->Modified(); + pad->Update(); + if (save) { + sprintf(name, "c_%s.jpg", pad->GetName()); + pad->Print(name); + } } } } diff --git a/SimG4CMS/Calo/macros/MakeHitStudyPlots.C b/SimG4CMS/Calo/macros/MakeHitStudyPlots.C index 7e1dd2546a3cd..211d55015e3ca 100644 --- a/SimG4CMS/Calo/macros/MakeHitStudyPlots.C +++ b/SimG4CMS/Calo/macros/MakeHitStudyPlots.C @@ -1,3 +1,28 @@ +////////////////////////////////////////////////////////////////////////////// +// +// Usage: +// .L MakeHitStudyPlots.C+g +// +// To make plot of various quantities which are created by CaloSimHitStudy +// from one or two different settings +// +// makeHitStudyPlots(file1, tag1, file2, tag2, toDo, ratio, save, dirnm) +// +// where +// file1 std::string Name of the first ROOT file [analRun3Old.root] +// tag1 std::string Tag for the first file [Old] +// file2 std::string Name of the second ROOT file [analRun3New.root] +// tag2 std::string Tag for the second file [New] +// todo int The plot type to be made [0] +// if -1, 6 different types are plotted +// (3, 5, 8, 9, 10, 11) +// ratio bool if the ratio to be plotted [true] +// (works when both files are active) +// save bool If the canvas is to be saved as jpg file [false] +// dirnm std::string Name of the directory [CaloSimHitStudy] +// +////////////////////////////////////////////////////////////////////////////// + #include #include #include @@ -21,9 +46,10 @@ void makeHitStudyPlots(std::string file1 = "analRun3Old.root", std::string tag1 = "Old", std::string file2 = "analRun3New.root", std::string tag2 = "New", - int todo = 0, - std::string dirnm = "CaloSimHitStudy", - bool save = false) { + int toDo = 0, + bool ratio = true, + bool save = false, + std::string dirnm = "CaloSimHitStudy") { std::string names[18] = {"Edep", "EdepEM", "EdepHad", @@ -44,12 +70,17 @@ void makeHitStudyPlots(std::string file1 = "analRun3Old.root", "PtInc"}; int numb[18] = {9, 9, 9, 16, 9, 9, 9, 1, 1, 1, 16, 9, 9, 16, 1, 1, 1, 1}; int rebin[18] = {10, 10, 10, 1, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 1, 1, 1, 1}; + int todos[6] = {3, 5, 8, 9, 10, 11}; + bool debug(false); gStyle->SetCanvasBorderMode(0); gStyle->SetCanvasColor(kWhite); gStyle->SetPadColor(kWhite); gStyle->SetFillColor(kWhite); - gStyle->SetOptStat(1110); + if (ratio) + gStyle->SetOptStat(0); + else + gStyle->SetOptStat(1110); TFile* file[2]; int nfile(0); std::string tag(""), tags[2]; @@ -69,62 +100,141 @@ void makeHitStudyPlots(std::string file1 = "analRun3Old.root", tag += tag2; } } - std::cout << "Use " << nfile << " files from " << file1 << " and " << file2 << std::endl; - for (int i1 = 0; i1 < numb[todo]; ++i1) { - int first(0); - double y1(0.90), dy(0.12); - double y2 = y1 - dy * nfile - 0.01; - TLegend* leg = new TLegend(0.74, y2 - nfile * 0.04, 0.89, y2); - leg->SetBorderSize(1); - leg->SetFillColor(10); - TCanvas* pad; - for (int ifile = 0; ifile < nfile; ++ifile) { - TDirectory* dir = (TDirectory*)file[ifile]->FindObjectAny(dirnm.c_str()); + int todoMin = (toDo >= 0) ? 0 : 0; + int todoMax = (toDo >= 0) ? 0 : 5; + std::cout << "Use " << nfile << " files from " << file1 << " and " << file2 << " and look for " << todoMin << ":" + << todoMax << std::endl; + for (int i0 = todoMin; i0 <= todoMax; ++i0) { + int todo = (todoMax == 0) ? toDo : todos[i0]; + for (int i1 = 0; i1 < numb[todo]; ++i1) { + double y1(0.90), dy(0.12); + double y2 = y1 - dy * nfile - 0.01; + TLegend* leg = (ratio) ? (new TLegend(0.10, 0.86, 0.90, 0.90)) : (new TLegend(0.65, y2 - nfile * 0.04, 0.90, y2)); + leg->SetBorderSize(1); + leg->SetFillColor(10); + TCanvas* pad; + TH1D* hist0[nfile]; char name[100], namec[100]; - if (numb[todo] == 1) { - sprintf(name, "%s", names[todo].c_str()); - sprintf(namec, "%s%s", names[todo].c_str(), tag.c_str()); - } else { - sprintf(name, "%s%d", names[todo].c_str(), i1); - sprintf(namec, "%s%d%s", names[todo].c_str(), i1, tag.c_str()); - } - TH1D* hist = static_cast(dir->FindObjectAny(name)); - std::cout << name << " read out at " << hist << " for " << tags[ifile] << std::endl; - if (hist != nullptr) { - hist->SetLineColor(first + 1); - hist->SetLineStyle(first + 1); - hist->GetYaxis()->SetTitleOffset(1.4); - if (rebin[todo] > 1) - hist->Rebin(rebin[todo]); - if (first == 0) { - pad = new TCanvas(namec, namec, 500, 500); - pad->SetRightMargin(0.10); - pad->SetTopMargin(0.10); - pad->SetLogy(); - hist->Draw(); + for (int ifile = 0; ifile < nfile; ++ifile) { + TDirectory* dir = (TDirectory*)file[ifile]->FindObjectAny(dirnm.c_str()); + if (numb[todo] == 1) { + sprintf(name, "%s", names[todo].c_str()); + sprintf(namec, "%s%s", names[todo].c_str(), tag.c_str()); } else { - hist->Draw("sames"); + sprintf(name, "%s%d", names[todo].c_str(), i1); + sprintf(namec, "%s%d%s", names[todo].c_str(), i1, tag.c_str()); } - leg->AddEntry(hist, tags[ifile].c_str(), "lp"); - pad->Update(); - ++first; - TPaveStats* st = ((TPaveStats*)hist->GetListOfFunctions()->FindObject("stats")); - if (st != NULL) { - st->SetLineColor(first); - st->SetTextColor(first); - st->SetY1NDC(y1 - dy); - st->SetY2NDC(y1); - st->SetX1NDC(0.65); - st->SetX2NDC(0.90); - y1 -= dy; + hist0[ifile] = static_cast(dir->FindObjectAny(name)); + if (debug) + std::cout << name << " read out at " << hist0[ifile] << " for " << tags[ifile] << std::endl; + } + if (!ratio) { + int first(0); + for (int ifile = 0; ifile < nfile; ++ifile) { + TH1D* hist(hist0[ifile]); + if (hist != nullptr) { + hist->SetLineColor(first + 1); + hist->SetLineStyle(first + 1); + hist->GetYaxis()->SetTitleOffset(1.4); + if (rebin[todo] > 1) + hist->Rebin(rebin[todo]); + if (first == 0) { + pad = new TCanvas(namec, namec, 500, 500); + pad->SetRightMargin(0.10); + pad->SetTopMargin(0.10); + pad->SetLogy(); + hist->Draw(); + } else { + hist->Draw("sames"); + } + leg->AddEntry(hist, tags[ifile].c_str(), "lp"); + pad->Update(); + ++first; + TPaveStats* st = ((TPaveStats*)hist->GetListOfFunctions()->FindObject("stats")); + if (st != NULL) { + st->SetLineColor(first); + st->SetTextColor(first); + st->SetY1NDC(y1 - dy); + st->SetY2NDC(y1); + st->SetX1NDC(0.65); + st->SetX2NDC(0.90); + y1 -= dy; + } + pad->Modified(); + pad->Update(); + leg->Draw("same"); + pad->Update(); + if (save) { + sprintf(name, "c_%s.pdf", pad->GetName()); + pad->Print(name); + } + } } - pad->Modified(); - pad->Update(); - leg->Draw("same"); - pad->Update(); - if (save) { - sprintf(name, "c_%s.pdf", pad->GetName()); - pad->Print(name); + } else { + if (nfile == 2) { + int nbin = hist0[0]->GetNbinsX(); + int nbinR = nbin / rebin[todo]; + double xlow = hist0[0]->GetXaxis()->GetBinLowEdge(1); + double xhigh = hist0[0]->GetXaxis()->GetBinLowEdge(nbin) + hist0[0]->GetXaxis()->GetBinWidth(nbin); + ; + if (numb[todo] == 1) { + sprintf(name, "%sRatio", names[todo].c_str()); + sprintf(namec, "%sRatio%s", names[todo].c_str(), tag.c_str()); + } else { + sprintf(name, "%s%dRatio", names[todo].c_str(), i1); + sprintf(namec, "%s%dRatio%s", names[todo].c_str(), i1, tag.c_str()); + } + pad = new TCanvas(namec, namec, 500, 500); + TH1D* histr = new TH1D(name, hist0[0]->GetTitle(), nbinR, xlow, xhigh); + sprintf(name, "Ratio (%s/%s)", tags[0].c_str(), tags[1].c_str()); + histr->GetXaxis()->SetTitle(hist0[0]->GetXaxis()->GetTitle()); + histr->GetYaxis()->SetTitle(name); + histr->GetXaxis()->SetLabelOffset(0.005); + histr->GetXaxis()->SetTitleOffset(1.00); + histr->GetYaxis()->SetLabelOffset(0.005); + histr->GetYaxis()->SetTitleOffset(1.20); + histr->GetYaxis()->SetRangeUser(0.0, 2.0); + double sumNum(0), sumDen(0), maxDev(0); + for (int j = 0; j < nbinR; ++j) { + double tnum(0), tden(0), rnum(0), rden(0); + for (int i = 0; i < rebin[todo]; ++i) { + int ib = j * rebin[todo] + i + 1; + tnum += hist0[0]->GetBinContent(ib); + tden += hist0[1]->GetBinContent(ib); + rnum += ((hist0[0]->GetBinError(ib)) * (hist0[0]->GetBinError(ib))); + rden += ((hist0[1]->GetBinError(ib)) * (hist0[1]->GetBinError(ib))); + } + if (tden > 0 && tnum > 0) { + double rat = tnum / tden; + double err = rat * sqrt((rnum / (tnum * tnum)) + (rden / (tden * tden))); + histr->SetBinContent(j + 1, rat); + histr->SetBinError(j + 1, err); + double temp1 = (rat > 1.0) ? 1.0 / rat : rat; + double temp2 = (rat > 1.0) ? err / (rat * rat) : err; + sumNum += (fabs(1 - temp1) / (temp2 * temp2)); + sumDen += (1.0 / (temp2 * temp2)); + if (fabs(1 - temp1) > maxDev) + maxDev = fabs(1 - temp1); + } + } + histr->Draw(); + sprintf(name, "%s vs %s", tag1.c_str(), tag2.c_str()); + leg->AddEntry(histr, name, "lp"); + leg->Draw("same"); + pad->Update(); + TLine* line = new TLine(xlow, 1.0, xhigh, 1.0); + line->SetLineColor(2); + line->SetLineWidth(2); + line->SetLineStyle(2); + line->Draw("same"); + pad->Modified(); + pad->Update(); + sumNum = (sumDen > 0) ? (sumNum / sumDen) : 0; + sumDen = (sumDen > 0) ? 1.0 / sqrt(sumDen) : 0; + if (sumNum == 0) + sumDen = 0; + std::cout << tag1 << " vs " << tag2 << " " << hist0[0]->GetXaxis()->GetTitle() << " Mean deviation " << sumNum + << " +- " << sumDen << " maximum " << maxDev << std::endl; } } } diff --git a/SimG4Core/CustomPhysics/BuildFile.xml b/SimG4Core/CustomPhysics/BuildFile.xml index df15a9aeea4ce..f805ec2132a3f 100644 --- a/SimG4Core/CustomPhysics/BuildFile.xml +++ b/SimG4Core/CustomPhysics/BuildFile.xml @@ -1,11 +1,16 @@ + + + + + diff --git a/SimG4Core/CustomPhysics/interface/APrimePhysics.h b/SimG4Core/CustomPhysics/interface/APrimePhysics.h new file mode 100644 index 0000000000000..698d091dc3006 --- /dev/null +++ b/SimG4Core/CustomPhysics/interface/APrimePhysics.h @@ -0,0 +1,40 @@ +#ifndef SIMG4CORE_CUSTOMPHYSICS_APRIMEPHYSICS_H +#define SIMG4CORE_CUSTOMPHYSICS_APRIMEPHYSICS_H + +// Geant4 +#include "G4VPhysicsConstructor.hh" + +class APrimePhysics : public G4VPhysicsConstructor { +public: + /** + * Class constructor. + * @param name The name of the physics. + */ + APrimePhysics(double APMass, const G4String& scalefile, const G4double cxBias, const G4String& name = "APrime"); + + /** + * Class destructor. + */ + ~APrimePhysics() override; + + /** + * Construct particles. + */ + void ConstructParticle() override; + + /** + * Construct the process. + */ + void ConstructProcess() override; + +private: + /** + * Definition of the APrime particle. + */ + G4ParticleDefinition* aprimeDef_; + double apmass; + G4String mgfile; + G4double biasFactor; +}; + +#endif diff --git a/SimG4Core/CustomPhysics/interface/DBremWatcher.h b/SimG4Core/CustomPhysics/interface/DBremWatcher.h new file mode 100644 index 0000000000000..3428e872dc85f --- /dev/null +++ b/SimG4Core/CustomPhysics/interface/DBremWatcher.h @@ -0,0 +1,45 @@ +#ifndef SimG4Core_DBremWatcher_H +#define SimG4Core_DBremWatcher_H + +#include "SimG4Core/Notification/interface/Observer.h" +#include "SimG4Core/Notification/interface/BeginOfTrack.h" +#include "SimG4Core/Notification/interface/EndOfTrack.h" +#include "SimG4Core/Notification/interface/BeginOfEvent.h" +#include "SimG4Core/Notification/interface/BeginOfRun.h" +#include "SimG4Core/Notification/interface/EndOfEvent.h" +#include "SimG4Core/Watcher/interface/SimProducer.h" +#include "FWCore/ParameterSet/interface/ParameterSet.h" +#include "G4ThreeVector.hh" + +#include +#include + +class DBremWatcher : public SimProducer, + public Observer, + public Observer, + public Observer, + public Observer, + public Observer { +public: + DBremWatcher(edm::ParameterSet const &p); + ~DBremWatcher() override; + void update(const BeginOfTrack *trk) override; + void update(const BeginOfEvent *event) override; + void update(const EndOfEvent *event) override; + void update(const BeginOfRun *run) override; + void update(const EndOfTrack *trk) override; + void produce(edm::Event &, const edm::EventSetup &) override; + +private: + std::vector pdgs_; + int MotherId; + float m_weight; + double biasFactor; + bool foundbrem; + G4ThreeVector aPrimeTraj; + G4ThreeVector finaltraj; + G4ThreeVector VertexPos; + float f_energy; +}; + +#endif diff --git a/SimG4Core/CustomPhysics/interface/G4APrime.h b/SimG4Core/CustomPhysics/interface/G4APrime.h new file mode 100644 index 0000000000000..13f9feb65ab07 --- /dev/null +++ b/SimG4Core/CustomPhysics/interface/G4APrime.h @@ -0,0 +1,41 @@ +/** + * @file G4APrime.h + * @brief Class creating the A' particle in Geant. + * @author Michael Revering, University of Minnesota + */ + +#ifndef G4APrime_h +#define G4APrime_h + +// Geant +#include "G4ParticleDefinition.hh" + +class G4APrime : public G4ParticleDefinition { +private: + static G4APrime* theAPrime; + + G4APrime(const G4String& Name, + G4double mass, + G4double width, + G4double charge, + G4int iSpin, + G4int iParity, + G4int iConjugation, + G4int iIsospin, + G4int iIsospin3, + G4int gParity, + const G4String& pType, + G4int lepton, + G4int baryon, + G4int encoding, + G4bool stable, + G4double lifetime, + G4DecayTable* decaytable); + + ~G4APrime() override; + +public: + static G4APrime* APrime(double apmass = 1000); +}; + +#endif diff --git a/SimG4Core/CustomPhysics/interface/G4muDarkBremsstrahlung.h b/SimG4Core/CustomPhysics/interface/G4muDarkBremsstrahlung.h new file mode 100644 index 0000000000000..39f41b4faa817 --- /dev/null +++ b/SimG4Core/CustomPhysics/interface/G4muDarkBremsstrahlung.h @@ -0,0 +1,40 @@ +/** + * @file G4muDarkBremsstrahlung.h + * @brief Class providing the Dark Bremsstrahlung process class. + * @author Michael Revering, University of Minnesota + */ + +#ifndef G4muDarkBremsstrahlung_h +#define G4muDarkBremsstrahlung_h + +// Geant +#include "G4VEmProcess.hh" + +class G4Material; + +class G4muDarkBremsstrahlung : public G4VEmProcess { +public: + G4muDarkBremsstrahlung(const G4String& scalefile, const G4double biasFactor, const G4String& name = "muDBrem"); + + ~G4muDarkBremsstrahlung() override; + + G4bool IsApplicable(const G4ParticleDefinition& p) override; + + void PrintInfo() override; + + void SetMethod(std::string method_in); + + G4bool IsEnabled(); + void SetEnable(bool active); + G4muDarkBremsstrahlung& operator=(const G4muDarkBremsstrahlung& right) = delete; + G4muDarkBremsstrahlung(const G4muDarkBremsstrahlung&) = delete; + +protected: + void InitialiseProcess(const G4ParticleDefinition*) override; + G4bool isInitialised; + const G4String& mgfile; + const G4double cxBias; + G4bool isEnabled; +}; + +#endif diff --git a/SimG4Core/CustomPhysics/interface/G4muDarkBremsstrahlungModel.h b/SimG4Core/CustomPhysics/interface/G4muDarkBremsstrahlungModel.h new file mode 100644 index 0000000000000..27ecbca0fa152 --- /dev/null +++ b/SimG4Core/CustomPhysics/interface/G4muDarkBremsstrahlungModel.h @@ -0,0 +1,98 @@ +/** + * @file G4muDarkBremsstrahlungModel.h + * @brief Class provided to simulate the dark brem cross section and interaction. + * @author Michael Revering, University of Minnesota + */ + +#ifndef G4muDarkBremsstrahlungModel_h +#define G4muDarkBremsstrahlungModel_h + +// Geant +#include "G4VEmModel.hh" +#include "G4Material.hh" +#include "G4Element.hh" +#include "G4DataVector.hh" +#include "G4ParticleChangeForLoss.hh" + +// ROOT +#include "TLorentzVector.h" + +struct ParamsForChi { + double AA; + double ZZ; + double MMA; + double EE0; +}; +struct frame { + TLorentzVector* fEl; + TLorentzVector* cm; + G4double E; +}; + +class G4Element; +class G4ParticleChangeForLoss; + +class G4muDarkBremsstrahlungModel : public G4VEmModel { +public: + G4muDarkBremsstrahlungModel(const G4String& scalefile, + const G4double biasFactor, + const G4ParticleDefinition* p = nullptr, + const G4String& nam = "eDBrem"); + + ~G4muDarkBremsstrahlungModel() override; + + void Initialise(const G4ParticleDefinition*, const G4DataVector&) override; + + G4double ComputeCrossSectionPerAtom( + const G4ParticleDefinition*, G4double tkin, G4double Z, G4double, G4double cut, G4double maxE = DBL_MAX) override; + + G4DataVector* ComputePartialSumSigma(const G4Material* material, G4double tkin, G4double cut); + + void SampleSecondaries(std::vector*, + const G4MaterialCutsCouple*, + const G4DynamicParticle*, + G4double tmin, + G4double maxEnergy) override; + + void LoadMG(); + + void MakePlaceholders(); + + void SetMethod(std::string); + + frame GetMadgraphData(double E0); + G4muDarkBremsstrahlungModel& operator=(const G4muDarkBremsstrahlungModel& right) = delete; + G4muDarkBremsstrahlungModel(const G4muDarkBremsstrahlungModel&) = delete; + +protected: + const G4Element* SelectRandomAtom(const G4MaterialCutsCouple* couple); + +private: + void SetParticle(const G4ParticleDefinition* p); + + static G4double chi(double t, void* pp); + + static G4double DsigmaDx(double x, void* pp); + +protected: + const G4String& mgfile; + const G4double cxBias; + const G4ParticleDefinition* particle; + G4ParticleDefinition* theAPrime; + G4ParticleChangeForLoss* fParticleChange; + G4double MA; + G4bool isMuon; + +private: + G4double highKinEnergy; + G4double lowKinEnergy; + G4double probsup; + G4bool isInitialised; + std::string method; + G4bool mg_loaded; + std::map > mgdata; + std::vector > energies; + std::vector partialSumSigma; +}; + +#endif diff --git a/SimG4Core/CustomPhysics/python/DarkBrem_SIM_cfi.py b/SimG4Core/CustomPhysics/python/DarkBrem_SIM_cfi.py new file mode 100644 index 0000000000000..ca37d54184918 --- /dev/null +++ b/SimG4Core/CustomPhysics/python/DarkBrem_SIM_cfi.py @@ -0,0 +1,23 @@ +#To use, add the following to the python configuration: +#process.load('SimG4Core.CustomPhysics.DarkBrem_SIM_cfi') +#process.g4SimHits.Physics.type = 'SimG4Core/Physics/CustomPhysics' +#process.g4SimHits.Physics = cms.PSet( +#process.g4SimHits.Physics, +#process.customPhysicsSetup +#) +#process.g4SimHits.Watchers = cms.VPSet(cms.PSet( +# DBremWatcher = cms.PSet( +# PDGCodes = cms.untracked.vint32([9994]), +# DBremBiasFactor = process.customPhysicsSetup.DBremBiasFactor +# ), +# type = cms.string('DBremWatcher') +#) ) + +import FWCore.ParameterSet.Config as cms + +customPhysicsSetup = cms.PSet( + DBrem = cms.untracked.bool(True), + DBremMass = cms.untracked.double(1000.0), #Mass in MeV + DBremScaleFile = cms.untracked.string("root://cmseos.fnal.gov//store/user/revering/MuDBrem_Cu_mA1p0.root"), + DBremBiasFactor = cms.untracked.double(100) +) diff --git a/SimG4Core/CustomPhysics/src/APrimePhysics.cc b/SimG4Core/CustomPhysics/src/APrimePhysics.cc new file mode 100644 index 0000000000000..575b4aa596b72 --- /dev/null +++ b/SimG4Core/CustomPhysics/src/APrimePhysics.cc @@ -0,0 +1,36 @@ +#include "SimG4Core/CustomPhysics/interface/APrimePhysics.h" +#include "SimG4Core/CustomPhysics/interface/G4APrime.h" +#include "SimG4Core/CustomPhysics/interface/G4muDarkBremsstrahlung.h" +// Geant 4 +#include "G4Electron.hh" +#include "G4MuonMinus.hh" +#include "G4MuonPlus.hh" +#include "G4ProcessManager.hh" +#include "G4SystemOfUnits.hh" + +APrimePhysics::APrimePhysics(double APMass, const G4String& scalefile, const G4double cxBias, const G4String& name) + : G4VPhysicsConstructor(name), aprimeDef_(nullptr) { + apmass = APMass; + mgfile = scalefile; + biasFactor = cxBias; +} + +APrimePhysics::~APrimePhysics() {} + +void APrimePhysics::ConstructParticle() { + /** + * Insert A-prime into the Geant4 particle table. + * For now we flag it as stable. + */ + aprimeDef_ = G4APrime::APrime(apmass); + //aprimeDef->SetProcessManager(new G4ProcessManager(aprimeDef)); +} + +void APrimePhysics::ConstructProcess() { + G4ParticleDefinition* muonminus = G4MuonMinus::MuonMinusDefinition(); + G4ParticleDefinition* muonplus = G4MuonPlus::MuonPlusDefinition(); + G4ProcessManager* pmplus = muonplus->GetProcessManager(); + G4ProcessManager* pmminus = muonminus->GetProcessManager(); + pmplus->AddDiscreteProcess(new G4muDarkBremsstrahlung(mgfile, biasFactor), 6); + pmminus->AddDiscreteProcess(new G4muDarkBremsstrahlung(mgfile, biasFactor), 6); +} diff --git a/SimG4Core/CustomPhysics/src/CustomPhysics.cc b/SimG4Core/CustomPhysics/src/CustomPhysics.cc index ac502c89fe49a..51dbfbda36b1a 100644 --- a/SimG4Core/CustomPhysics/src/CustomPhysics.cc +++ b/SimG4Core/CustomPhysics/src/CustomPhysics.cc @@ -4,6 +4,7 @@ #include "SimG4Core/PhysicsLists/interface/CMSEmStandardPhysics.h" #include "SimG4Core/PhysicsLists/interface/CMSHadronPhysicsFTFP_BERT.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" +#include "SimG4Core/CustomPhysics/interface/APrimePhysics.h" #include "G4DecayPhysics.hh" #include "G4EmExtraPhysics.hh" @@ -18,6 +19,7 @@ CustomPhysics::CustomPhysics(const edm::ParameterSet& p) : PhysicsList(p) { int ver = p.getUntrackedParameter("Verbosity", 0); bool tracking = p.getParameter("TrackingCut"); bool ssPhys = p.getUntrackedParameter("ExoticaPhysicsSS", false); + bool dbrem = p.getUntrackedParameter("DBrem", false); double timeLimit = p.getParameter("MaxTrackTime") * ns; edm::LogInfo("PhysicsList") << "You are using the simulation engine: " << "FTFP_BERT_EMM for regular particles \n" @@ -52,7 +54,11 @@ CustomPhysics::CustomPhysics(const edm::ParameterSet& p) : PhysicsList(p) { } // Custom Physics - if (ssPhys) { + if (dbrem) { + RegisterPhysics(new APrimePhysics(p.getUntrackedParameter("DBremMass"), + p.getUntrackedParameter("DBremScaleFile"), + p.getUntrackedParameter("DBremBiasFactor"))); + } else if (ssPhys) { RegisterPhysics(new CustomPhysicsListSS("custom", p)); } else { RegisterPhysics(new CustomPhysicsList("custom", p)); diff --git a/SimG4Core/CustomPhysics/src/DBremWatcher.cc b/SimG4Core/CustomPhysics/src/DBremWatcher.cc new file mode 100644 index 0000000000000..2d3b14576b6c7 --- /dev/null +++ b/SimG4Core/CustomPhysics/src/DBremWatcher.cc @@ -0,0 +1,148 @@ +#include "SimG4Core/CustomPhysics/interface/DBremWatcher.h" + +#include "SimG4Core/Notification/interface/BeginOfTrack.h" +#include "SimG4Core/Notification/interface/BeginOfEvent.h" +#include "SimG4Core/Notification/interface/BeginOfRun.h" +#include "SimG4Core/Notification/interface/EndOfEvent.h" +#include "SimG4Core/Notification/interface/TrackInformation.h" +#include "SimG4Core/Watcher/interface/SimWatcher.h" +#include "SimG4Core/Notification/interface/Observer.h" +#include "FWCore/MessageLogger/interface/MessageLogger.h" +#include "FWCore/Framework/interface/Event.h" +#include "G4Region.hh" +#include "G4RegionStore.hh" +#include "G4LogicalVolumeStore.hh" +#include "G4ProductionCuts.hh" +#include "G4ProcessTable.hh" +#include "G4ProcessManager.hh" +#include "G4MuonMinus.hh" +#include "SimG4Core/CustomPhysics/interface/G4muDarkBremsstrahlung.h" +#include "G4Track.hh" +#include "G4PhysicalConstants.hh" +#include "G4SystemOfUnits.hh" +#include "G4VProcess.hh" +#include "G4VParticleChange.hh" +#include "DataFormats/GeometryVector/interface/GlobalPoint.h" +#include + +DBremWatcher::DBremWatcher(edm::ParameterSet const& p) { + edm::ParameterSet ps = p.getParameter("DBremWatcher"); + biasFactor = ps.getUntrackedParameter("DBremBiasFactor", 1); + m_weight = 0; + foundbrem = false; + finaltraj = G4ThreeVector(0, 0, 0); + aPrimeTraj = G4ThreeVector(0, 0, 0); + VertexPos = G4ThreeVector(0, 0, 0); + f_energy = 0; + produces("DBremEventWeight"); + produces("DBremLocationX"); + produces("DBremLocationY"); + produces("DBremLocationZ"); + //produces("DBremMaterial"); + produces("DBremAngle"); + produces("DBremInitialEnergy"); + produces("DBremFinalEnergy"); + produces("BiasFactor"); + pdgs_ = ps.getUntrackedParameter>("PDGCodes"); + edm::LogInfo("DBremWatcher") << "DBremWatcher:: Save Sim Track if PDG code " + << "is one from the list of " << pdgs_.size() << " items"; + for (unsigned int k = 0; k < pdgs_.size(); ++k) + edm::LogInfo("DBremWatcher") << "[" << k << "] " << pdgs_[k]; +} + +DBremWatcher::~DBremWatcher() {} + +void DBremWatcher::update(const BeginOfTrack* trk) { + G4Track* theTrack = (G4Track*)((*trk)()); + TrackInformation* trkInfo = (TrackInformation*)(theTrack->GetUserInformation()); + if (trkInfo) { + int pdg = theTrack->GetDefinition()->GetPDGEncoding(); + G4ThreeVector Vpos = theTrack->GetVertexPosition(); + const G4VProcess* TrPro = theTrack->GetCreatorProcess(); + if (TrPro != nullptr) { + if ((theTrack->GetCreatorProcess()->GetProcessName()) == "muDBrem") { + if (std::find(pdgs_.begin(), pdgs_.end(), pdg) == pdgs_.end()) { + //Found the deflected muon track + trkInfo->storeTrack(true); + if (!theTrack->IsGoodForTracking()) { + theTrack->SetGoodForTrackingFlag(true); + } + f_energy = theTrack->GetTotalEnergy(); + foundbrem = true; + finaltraj = theTrack->GetMomentum(); + } else { + m_weight = theTrack->GetWeight(); + } + } + } + if (std::find(pdgs_.begin(), pdgs_.end(), pdg) != pdgs_.end()) { + //Found an A' + trkInfo->storeTrack(true); + VertexPos = Vpos; + aPrimeTraj = theTrack->GetMomentum(); + LogDebug("DBremWatcher") << "Save SimTrack the Track " << theTrack->GetTrackID() << " Type " + << theTrack->GetDefinition()->GetParticleName() << " Momentum " + << theTrack->GetMomentum() / MeV << " MeV/c"; + } + } +} + +void DBremWatcher::update(const BeginOfRun* run) {} + +void DBremWatcher::update(const BeginOfEvent* event) { + G4String pname = "muDBrem"; + G4ProcessTable* ptable = G4ProcessTable::GetProcessTable(); + G4bool state = true; + ptable->SetProcessActivation(pname, state); + foundbrem = false; +} + +void DBremWatcher::update(const EndOfEvent* event) {} + +void DBremWatcher::update(const EndOfTrack* trk) { + G4Track* theTrack = (G4Track*)((*trk)()); + TrackInformation* trkInfo = (TrackInformation*)(theTrack->GetUserInformation()); + const G4VProcess* TrPro = theTrack->GetCreatorProcess(); + if (trkInfo && TrPro != nullptr) { + int pdg = theTrack->GetDefinition()->GetPDGEncoding(); + + if (std::find(pdgs_.begin(), pdgs_.end(), pdg) == pdgs_.end() && + (theTrack->GetCreatorProcess()->GetProcessName()) == "muDBrem") { + trkInfo->storeTrack(true); + } + } +} + +void DBremWatcher::produce(edm::Event& fEvent, const edm::EventSetup&) { + if (foundbrem) { + std::unique_ptr weight = std::make_unique(m_weight); + fEvent.put(std::move(weight), "DBremEventWeight"); + std::unique_ptr vtxposx = std::make_unique(VertexPos.x()); + std::unique_ptr vtxposy = std::make_unique(VertexPos.y()); + std::unique_ptr vtxposz = std::make_unique(VertexPos.z()); + fEvent.put(std::move(vtxposx), "DBremLocationX"); + fEvent.put(std::move(vtxposy), "DBremLocationY"); + fEvent.put(std::move(vtxposz), "DBremLocationZ"); + std::unique_ptr finalE = std::make_unique(f_energy / GeV); + fEvent.put(std::move(finalE), "DBremFinalEnergy"); + float deflectionAngle = -1; + float initialEnergy = sqrt(pow(finaltraj.x() + aPrimeTraj.x(), 2) + pow(finaltraj.y() + aPrimeTraj.y(), 2) + + pow(finaltraj.z() + aPrimeTraj.z(), 2) + pow(0.1056 * GeV, 2)); + G4ThreeVector mother( + finaltraj.x() + aPrimeTraj.x(), finaltraj.y() + aPrimeTraj.y(), finaltraj.z() + aPrimeTraj.z()); + deflectionAngle = mother.angle(finaltraj); + std::unique_ptr dAngle = std::make_unique(deflectionAngle); + std::unique_ptr initialE = std::make_unique(initialEnergy / GeV); + fEvent.put(std::move(dAngle), "DBremAngle"); + fEvent.put(std::move(initialE), "DBremInitialEnergy"); + std::unique_ptr bias = std::make_unique(biasFactor); + fEvent.put(std::move(bias), "BiasFactor"); + } else { + std::unique_ptr weight = std::make_unique(0.); + fEvent.put(std::move(weight), "DBremEventWeight"); + } +} + +#include "SimG4Core/Watcher/interface/SimWatcherFactory.h" + +DEFINE_SIMWATCHER(DBremWatcher); diff --git a/SimG4Core/CustomPhysics/src/G4APrime.cc b/SimG4Core/CustomPhysics/src/G4APrime.cc new file mode 100644 index 0000000000000..34064773e5fe3 --- /dev/null +++ b/SimG4Core/CustomPhysics/src/G4APrime.cc @@ -0,0 +1,82 @@ +#include "SimG4Core/CustomPhysics/interface/G4APrime.h" +#include "G4SystemOfUnits.hh" + +G4APrime* G4APrime::theAPrime = nullptr; + +G4APrime::G4APrime(const G4String& aName, + G4double mass, + G4double width, + G4double charge, + G4int iSpin, + G4int iParity, + G4int iConjugation, + G4int iIsospin, + G4int iIsospin3, + G4int gParity, + const G4String& pType, + G4int lepton, + G4int baryon, + G4int encoding, + G4bool stable, + G4double lifetime, + G4DecayTable* decaytable) + : G4ParticleDefinition(aName, + mass, + width, + charge, + iSpin, + iParity, + iConjugation, + iIsospin, + iIsospin3, + gParity, + pType, + lepton, + baryon, + encoding, + stable, + lifetime, + decaytable) {} + +G4APrime::~G4APrime() {} + +G4APrime* G4APrime::APrime(double apmass) { + if (!theAPrime) { + const G4String& name = "A^1"; + G4double mass = apmass * MeV; + G4double width = 0.; + G4double charge = 0; + G4int iSpin = 0; + G4int iParity = 0; + G4int iConjugation = 0; + G4int iIsospin = 0; + G4int iIsospin3 = 0; + G4int gParity = 0; + const G4String& pType = "APrime"; + G4int lepton = 0; + G4int baryon = 0; + G4int encoding = 9994; + G4bool stable = true; + G4double lifetime = -1; + G4DecayTable* decaytable = nullptr; + + theAPrime = new G4APrime(name, + mass, + width, + charge, + iSpin, + iParity, + iConjugation, + iIsospin, + iIsospin3, + gParity, + pType, + lepton, + baryon, + encoding, + stable, + lifetime, + decaytable); + } + return theAPrime; +} diff --git a/SimG4Core/CustomPhysics/src/G4muDarkBremsstrahlung.cc b/SimG4Core/CustomPhysics/src/G4muDarkBremsstrahlung.cc new file mode 100644 index 0000000000000..5d35d9e0e1b5f --- /dev/null +++ b/SimG4Core/CustomPhysics/src/G4muDarkBremsstrahlung.cc @@ -0,0 +1,48 @@ +#include "SimG4Core/CustomPhysics/interface/G4muDarkBremsstrahlung.h" +#include "SimG4Core/CustomPhysics/interface/G4muDarkBremsstrahlungModel.h" +#include "SimG4Core/CustomPhysics/interface/G4APrime.h" + +//Geant 4 +#include "G4MuonMinus.hh" +#include "G4MuonPlus.hh" +#include "G4LossTableManager.hh" + +using namespace std; + +G4muDarkBremsstrahlung::G4muDarkBremsstrahlung(const G4String& scalefile, + const G4double biasFactor, + const G4String& name) + : G4VEmProcess(name), isInitialised(false), mgfile(scalefile), cxBias(biasFactor) { + G4int subtype = 40; + SetProcessSubType(subtype); + SetSecondaryParticle(G4APrime::APrime()); +} + +G4muDarkBremsstrahlung::~G4muDarkBremsstrahlung() {} + +G4bool G4muDarkBremsstrahlung::IsApplicable(const G4ParticleDefinition& p) { + return (&p == G4MuonPlus::MuonPlus() || &p == G4MuonMinus::MuonMinus()); +} + +void G4muDarkBremsstrahlung::InitialiseProcess(const G4ParticleDefinition*) { + if (!isInitialised) { + AddEmModel(0, new G4muDarkBremsstrahlungModel(mgfile, cxBias)); + + isInitialised = true; + isEnabled = true; + } +} + +void G4muDarkBremsstrahlung::PrintInfo() {} + +void G4muDarkBremsstrahlung::SetMethod(std::string method_in) { + ((G4muDarkBremsstrahlungModel*)EmModel(1))->SetMethod(method_in); + return; +} + +G4bool G4muDarkBremsstrahlung::IsEnabled() { return isEnabled; } + +void G4muDarkBremsstrahlung::SetEnable(bool state) { + isEnabled = state; + return; +} diff --git a/SimG4Core/CustomPhysics/src/G4muDarkBremsstrahlungModel.cc b/SimG4Core/CustomPhysics/src/G4muDarkBremsstrahlungModel.cc new file mode 100644 index 0000000000000..a1b6a53945020 --- /dev/null +++ b/SimG4Core/CustomPhysics/src/G4muDarkBremsstrahlungModel.cc @@ -0,0 +1,454 @@ +#include "SimG4Core/CustomPhysics/interface/G4muDarkBremsstrahlungModel.h" +#include "SimG4Core/CustomPhysics/interface/G4muDarkBremsstrahlung.h" +#include "SimG4Core/CustomPhysics/interface/G4APrime.h" + +//Geant 4 +#include "G4ProcessTable.hh" +#include "G4ProcTblElement.hh" +#include "G4MuonMinus.hh" +#include "G4MuonPlus.hh" +#include "G4ProductionCutsTable.hh" +#include "G4SystemOfUnits.hh" +//Root +#include "TFile.h" +#include "TTree.h" +//gsl +#include +#include + +using namespace std; + +G4muDarkBremsstrahlungModel::G4muDarkBremsstrahlungModel(const G4String& scalefile, + const G4double biasFactor, + const G4ParticleDefinition* p, + const G4String& nam) + : G4VEmModel(nam), + mgfile(scalefile), + cxBias(biasFactor), + particle(nullptr), + isMuon(true), + probsup(1.0), + isInitialised(false), + method("forward_only"), + mg_loaded(false) { + if (p) { + SetParticle(p); + } //Verify that the particle is a muon. + theAPrime = G4APrime::APrime(); + MA = G4APrime::APrime()->GetPDGMass() / CLHEP::GeV; //Get the A' mass. + + highKinEnergy = HighEnergyLimit(); + lowKinEnergy = LowEnergyLimit(); + fParticleChange = nullptr; +} + +G4muDarkBremsstrahlungModel::~G4muDarkBremsstrahlungModel() { + size_t n = partialSumSigma.size(); + if (n > 0) { + for (size_t i = 0; i < n; i++) { + delete partialSumSigma[i]; + } + } +} + +void G4muDarkBremsstrahlungModel::SetParticle(const G4ParticleDefinition* p) { + particle = p; + + if ((p == G4MuonPlus::MuonPlus()) || (p == G4MuonMinus::MuonMinus())) { + isMuon = true; + } else { + isMuon = false; + } +} + +void G4muDarkBremsstrahlungModel::Initialise(const G4ParticleDefinition* p, const G4DataVector& cuts) { + if (p) { + SetParticle(p); + } + + highKinEnergy = HighEnergyLimit(); + lowKinEnergy = LowEnergyLimit(); + const G4ProductionCutsTable* theCoupleTable = G4ProductionCutsTable::GetProductionCutsTable(); + + if (theCoupleTable) { + G4int numOfCouples = theCoupleTable->GetTableSize(); + G4int nn = partialSumSigma.size(); + G4int nc = cuts.size(); + if (nn > 0) { + for (G4int ii = 0; ii < nn; ii++) { + G4DataVector* a = partialSumSigma[ii]; + if (a) + delete a; + } + partialSumSigma.clear(); + } + if (numOfCouples > 0) { + for (G4int i = 0; i < numOfCouples; i++) { + G4double cute = DBL_MAX; + if (i < nc) + cute = cuts[i]; + const G4MaterialCutsCouple* couple = theCoupleTable->GetMaterialCutsCouple(i); + const G4Material* material = couple->GetMaterial(); + G4DataVector* dv = ComputePartialSumSigma(material, 0.5 * highKinEnergy, std::min(cute, 0.25 * highKinEnergy)); + partialSumSigma.push_back(dv); + } + } + } + + if (isInitialised) + return; + fParticleChange = GetParticleChangeForLoss(); + isInitialised = true; +} + +void G4muDarkBremsstrahlungModel::LoadMG() +//Parses a Madgraph root file to extract the kinetic energy fraction and pt of the outgoing electron in each event. Loads the two numbers from every event into a map of vectors of pairs (mgdata). Map is keyed by energy, vector pairs are energy fraction + pt. Also creates an list of energies and placeholders (energies), so that different energies can be looped separately. +{ + TFile* f = TFile::Open(mgfile.c_str()); + TTree* tree = (TTree*)f->Get("Events"); + TLorentzVector* mvec = new TLorentzVector(); + TLorentzVector* avec = new TLorentzVector(); + TLorentzVector* nvec = new TLorentzVector(); + tree->SetBranchAddress("IncidentParticle", &mvec); + tree->SetBranchAddress("APrime", &avec); + tree->SetBranchAddress("Nucleus", &nvec); + int entries = tree->GetEntries(); + int start = int(G4UniformRand() * entries); + for (int i = start; i < int(start + entries / 10.); i++) { + if (i < entries) { + tree->GetEntry(i); + } else { + tree->GetEntry(i - entries); + } + frame evnt; + evnt.fEl = (TLorentzVector*)mvec->Clone(); + evnt.cm = (TLorentzVector*)avec->Clone(); + *evnt.cm = *evnt.cm + *evnt.fEl; + TLorentzVector* ebeam = (TLorentzVector*)nvec->Clone(); + *ebeam = *ebeam + *evnt.cm; + evnt.E = round(ebeam->Z() * 10.) / 10.; + if (mgdata.count(evnt.E) == 0) { + mgdata[evnt.E]; + } + mgdata[evnt.E].push_back(evnt); + } + f->Close(); +} + +void G4muDarkBremsstrahlungModel::MakePlaceholders() { + //Need to do this to set up random sampling of mg distributions + for (const auto& iter : mgdata) { + energies.push_back(std::make_pair(iter.first, iter.second.size())); + } + + for (uint64_t i = 0; i < energies.size(); i++) { + energies[i].second = int(G4UniformRand() * mgdata[energies[i].first].size()); + } +} + +frame G4muDarkBremsstrahlungModel::GetMadgraphData(double E0) +//Gets the energy fraction and Pt from the imported LHE data. E0 should be in GeV, returns the total energy and Pt in GeV. Scales from the closest imported beam energy above the given value (scales down to avoid biasing issues). +{ + double samplingE = energies[0].first; + frame cmdata; + uint64_t i = 0; + bool pass = false; + //G4double Mel = 5.1E-04; + //Cycle through imported beam energies until the closest one above is found, or the max is reached. + while (!pass) { + i++; + samplingE = energies[i].first; + if ((E0 <= samplingE) || (i >= energies.size())) { + pass = true; + } + } + + if (i == energies.size()) { + i--; + } //Decrement if the loop hit the maximum, to prevent a segfault. + //energies is a vector of pairs. energies[i].first holds the imported beam energy, + //energies[i].second holds the place as we loop through different energy sampling files. + //Need to loop around if we hit the end, when the size of mgdata is smaller than our index + //on energies[i].second. + if (energies[i].second >= double(mgdata[energies[i].first].size())) { + energies[i].second = 0; + } + + //Get the lorentz vectors from the index given by the placeholder. + cmdata = mgdata[energies[i].first].at(energies[i].second); + + //Increment the placeholder. + energies[i].second = energies[i].second + 1; + + return cmdata; +} + +G4double G4muDarkBremsstrahlungModel::DsigmaDx(double x, void* pp) { + ParamsForChi* params = (ParamsForChi*)pp; + + //G4double Mel = 5.1E-04; + G4double Mmu = 0.106; + + G4double beta = sqrt(1 - (params->MMA) * (params->MMA) / (params->EE0) / (params->EE0)); + G4double num = 1. - x + x * x / 3.; + G4double denom = (params->MMA) * (params->MMA) * (1. - x) / x + Mmu * Mmu * x; + G4double DsDx = beta * num / denom; + + return DsDx; +} + +G4double G4muDarkBremsstrahlungModel::chi(double t, void* pp) { + ParamsForChi* params = (ParamsForChi*)pp; + /* Reminder II: + * params->AA; + * params->ZZ; + * params->MMA; + * params->EE0; + */ + G4double Mel = 5.1E-04; + G4double MUp = 2.79; + G4double Mpr = 0.938; + + G4double d = 0.164 / pow((params->AA), 2. / 3.); + G4double ap = 773.0 / Mel / pow((params->ZZ), 2. / 3.); + G4double a = 111.0 / Mel / pow((params->ZZ), 1. / 3.); + G4double G2el = (params->ZZ) * (params->ZZ) * a * a * a * a * t * t / (1.0 + a * a * t) / (1.0 + a * a * t) / + (1.0 + t / d) / (1.0 + t / d); + G4double G2in = (params->ZZ) * ap * ap * ap * ap * t * t / (1.0 + ap * ap * t) / (1.0 + ap * ap * t) / + (1.0 + t / 0.71) / (1.0 + t / 0.71) / (1.0 + t / 0.71) / (1.0 + t / 0.71) / (1.0 + t / 0.71) / + (1.0 + t / 0.71) / (1.0 + t / 0.71) / (1.0 + t / 0.71) * + (1.0 + t * (MUp * MUp - 1.0) / 4.0 / Mpr / Mpr) * (1.0 + t * (MUp * MUp - 1.0) / 4.0 / Mpr / Mpr); + G4double G2 = G2el + G2in; + G4double ttmin = (params->MMA) * (params->MMA) * (params->MMA) * (params->MMA) / 4.0 / (params->EE0) / (params->EE0); + // G4double ttmin = lowerLimit(x,theta,p); + G4double Under = G2 * (t - ttmin) / t / t; + + return Under; +} + +G4double G4muDarkBremsstrahlungModel::ComputeCrossSectionPerAtom( + const G4ParticleDefinition*, G4double E0, G4double Z, G4double A, G4double cut, G4double) +// Calculates the cross section per atom in GEANT4 internal units. Uses WW approximation to find the total cross section, performing numerical integrals over x and theta. +{ + G4double cross = 0.0; + if (E0 < keV || E0 < cut) { + return cross; + } + + E0 = E0 / CLHEP::GeV; //Change energy to GeV. + //G4double Mel = 5.1E-04; + G4double Mmu = 0.106; + if (E0 < 2. * MA) + return 0.; + + //begin: chi-formfactor calculation + gsl_integration_workspace* w = gsl_integration_workspace_alloc(1000); + + G4double result, error; + G4double tmin = MA * MA * MA * MA / (4. * E0 * E0); + G4double tmax = MA * MA; + + gsl_function F; + ParamsForChi alpha = {1.0, 1.0, 1.0, 1.0}; + F.function = &G4muDarkBremsstrahlungModel::chi; + F.params = α + alpha.AA = A; + alpha.ZZ = Z; + alpha.MMA = MA; + alpha.EE0 = E0; + + //Integrate over chi. + gsl_integration_qags(&F, tmin, tmax, 0, 1e-7, 1000, w, &result, &error); + + G4double ChiRes = result; + gsl_integration_workspace_free(w); + + //Integrate over x. Can use log approximation instead, which falls off at high A' mass. + gsl_integration_workspace* dxspace = gsl_integration_workspace_alloc(1000); + gsl_function G; + G.function = &DsigmaDx; + G.params = α + G4double xmin = 0; + G4double xmax = 1; + if ((Mmu / E0) > (MA / E0)) + xmax = 1 - Mmu / E0; + else + xmax = 1 - MA / E0; + G4double res, err; + + gsl_integration_qags(&G, xmin, xmax, 0, 1e-7, 1000, dxspace, &res, &err); + + G4double DsDx = res; + gsl_integration_workspace_free(dxspace); + + G4double GeVtoPb = 3.894E08; + G4double alphaEW = 1.0 / 137.0; + G4double epsilBench = 1; + + cross = GeVtoPb * 4. * alphaEW * alphaEW * alphaEW * epsilBench * epsilBench * ChiRes * DsDx * CLHEP::picobarn; + if (cross < 0.) { + cross = 0.; + } + E0 = E0 * CLHEP::GeV; + + cross = cross * cxBias; + return cross; +} + +G4DataVector* G4muDarkBremsstrahlungModel::ComputePartialSumSigma(const G4Material* material, + G4double kineticEnergy, + G4double cut) + +// Build the table of cross section per element. +//The table is built for MATERIALS. +// This table is used by DoIt to select randomly an element in the material. +{ + G4int nElements = material->GetNumberOfElements(); + const G4ElementVector* theElementVector = material->GetElementVector(); + const G4double* theAtomNumDensityVector = material->GetAtomicNumDensityVector(); + G4DataVector* dv = new G4DataVector(); + G4double cross = 0.0; + + for (G4int i = 0; i < nElements; i++) { + cross += theAtomNumDensityVector[i] * + ComputeCrossSectionPerAtom( + particle, kineticEnergy, (*theElementVector)[i]->GetZ(), (*theElementVector)[i]->GetA(), cut); + dv->push_back(cross); + } + return dv; +} + +void G4muDarkBremsstrahlungModel::SampleSecondaries(std::vector* vdp, + const G4MaterialCutsCouple* couple, + const G4DynamicParticle* dp, + G4double tmin, + G4double maxEnergy) +//Simulates the emission of a dark photon + electron. Gets an energy fraction and Pt from madgraph files. Scales the energy so that the fraction of kinectic energy is constant, keeps the Pt constant. If the Pt is larger than the new energy, that event is skipped, and a new one is taken from the file. +{ + //Deactivate the process after one dark brem. Needs to be reactivated in the end of event action. If this is in the stepping action instead, more than one brem can occur within each step. + G4bool state = false; + G4String pname = "muDBrem"; + G4ProcessTable* ptable = G4ProcessTable::GetProcessTable(); + ptable->SetProcessActivation(pname, state); + if (mg_loaded == false) { + LoadMG(); + MakePlaceholders(); //Setup the placeholder offsets for getting data. + mg_loaded = true; + } + G4double E0 = dp->GetTotalEnergy(); + G4double tmax = min(maxEnergy, E0); + if (tmin >= tmax) { + return; + } // limits of the energy sampling + G4double Mmu = 0.106; + E0 = E0 / CLHEP::GeV; //Convert the energy to GeV, the units used in the sampling files. + + frame data = GetMadgraphData(E0); + double EAcc, Pt, P, PhiAcc; + if (method == "forward_only") { + EAcc = (data.fEl->E() - Mmu) / (data.E - Mmu - MA) * (E0 - Mmu - MA); + EAcc = Mmu + EAcc; + Pt = data.fEl->Pt(); + P = sqrt(EAcc * EAcc - Mmu * Mmu); + PhiAcc = data.fEl->Phi(); + int i = 0; + while (Pt * Pt + Mmu * Mmu > EAcc * EAcc) //Skip events until the Pt is less than the energy. + { + i++; + data = GetMadgraphData(E0); + EAcc = (data.fEl->E() - Mmu) / (data.E - Mmu - MA) * (E0 - Mmu - MA); + EAcc = Mmu + EAcc; + Pt = data.fEl->Pt(); + P = sqrt(EAcc * EAcc - Mmu * Mmu); + PhiAcc = data.fEl->Phi(); + + if (i > 10000) { + break; + } + } + } else if (method == "cm_scaling") { + TLorentzVector* el = new TLorentzVector(data.fEl->X(), data.fEl->Y(), data.fEl->Z(), data.fEl->E()); + double ediff = data.E - E0; + TLorentzVector* newcm = new TLorentzVector(data.cm->X(), data.cm->Y(), data.cm->Z() - ediff, data.cm->E() - ediff); + el->Boost(-1. * data.cm->BoostVector()); + el->Boost(newcm->BoostVector()); + double newE = (data.fEl->E() - Mmu) / (data.E - Mmu - MA) * (E0 - Mmu - MA); + el->SetE(newE); + EAcc = el->E(); + Pt = el->Pt(); + P = el->P(); + PhiAcc = el->Phi(); + } else { + EAcc = E0; + P = dp->GetTotalMomentum(); + Pt = sqrt(dp->Get4Momentum().px() * dp->Get4Momentum().px() + dp->Get4Momentum().py() * dp->Get4Momentum().py()); + PhiAcc = dp->Get4Momentum().phi(); + } + + EAcc = EAcc * CLHEP::GeV; //Change the energy back to MeV, the internal GEANT unit. + + G4double muon_mass_mev = 105.6; + G4double momentum = sqrt(EAcc * EAcc - muon_mass_mev * muon_mass_mev); //Muon momentum in MeV. + G4ThreeVector newDirection; + double ThetaAcc = std::asin(Pt / P); + newDirection.set(std::sin(ThetaAcc) * std::cos(PhiAcc), std::sin(ThetaAcc) * std::sin(PhiAcc), std::cos(ThetaAcc)); + newDirection.rotateUz(dp->GetMomentumDirection()); + newDirection.setMag(momentum); + // create g4dynamicparticle object for the dark photon. + G4ThreeVector direction = (dp->GetMomentum() - newDirection); + G4DynamicParticle* dphoton = new G4DynamicParticle(theAPrime, direction); + vdp->push_back(dphoton); + + // energy of primary + G4double finalKE = EAcc - muon_mass_mev; + + // stop tracking and create new secondary instead of primary + bool makeSecondary = true; + if (makeSecondary) { + fParticleChange->ProposeTrackStatus(fStopAndKill); + fParticleChange->SetProposedKineticEnergy(0.0); + G4DynamicParticle* mu = + new G4DynamicParticle(const_cast(particle), newDirection.unit(), finalKE); + vdp->push_back(mu); + // continue tracking + } else { + fParticleChange->SetProposedMomentumDirection(newDirection.unit()); + fParticleChange->SetProposedKineticEnergy(finalKE); + } +} + +//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo.... + +const G4Element* G4muDarkBremsstrahlungModel::SelectRandomAtom(const G4MaterialCutsCouple* couple) { + // select randomly 1 element within the material + + const G4Material* material = couple->GetMaterial(); + G4int nElements = material->GetNumberOfElements(); + const G4ElementVector* theElementVector = material->GetElementVector(); + + const G4Element* elm = nullptr; + + if (1 < nElements) { + --nElements; + G4DataVector* dv = partialSumSigma[couple->GetIndex()]; + G4double rval = G4UniformRand() * ((*dv)[nElements]); + + elm = (*theElementVector)[nElements]; + for (G4int i = 0; i < nElements; ++i) { + if (rval <= (*dv)[i]) { + elm = (*theElementVector)[i]; + break; + } + } + } else { + elm = (*theElementVector)[0]; + } + + SetCurrentElement(elm); + return elm; +} + +void G4muDarkBremsstrahlungModel::SetMethod(std::string method_in) { + method = method_in; + return; +} diff --git a/SimG4Core/GeometryProducer/interface/GeometryProducer.h b/SimG4Core/GeometryProducer/interface/GeometryProducer.h index 860653a69174c..f1f24c8f1b7da 100644 --- a/SimG4Core/GeometryProducer/interface/GeometryProducer.h +++ b/SimG4Core/GeometryProducer/interface/GeometryProducer.h @@ -59,6 +59,8 @@ class GeometryProducer : public edm::one::EDProducer("UseMagneticField")), m_pUseSensitiveDetectors(p.getParameter("UseSensitiveDetectors")), - m_pGeoFromDD4hep(false) { + m_pGeoFromDD4hep(p.getParameter("GeoFromDD4hep")) { // Look for an outside SimActivityRegistry // this is used by the visualization code + edm::Service otherRegistry; if (otherRegistry) m_registry.connect(*otherRegistry); createWatchers(m_p, m_registry, m_watchers, m_producers); - m_sdMakers = sim::sensitiveDetectorMakers(m_p, consumesCollector(), std::vector()); + if (m_pUseSensitiveDetectors) + m_sdMakers = sim::sensitiveDetectorMakers(m_p, consumesCollector(), std::vector()); + tokMF_ = esConsumes(); if (m_pGeoFromDD4hep) { tokDD4hep_ = esConsumes(); @@ -103,6 +106,7 @@ void GeometryProducer::beginLuminosityBlock(edm::LuminosityBlock &, edm::EventSe } void GeometryProducer::beginRun(const edm::Run &run, const edm::EventSetup &es) { + makeGeom(es); updateMagneticField(es); for (auto &maker : m_sdMakers) { maker.second->beginRun(es); @@ -115,6 +119,13 @@ void GeometryProducer::produce(edm::Event &e, const edm::EventSetup &es) { if (!m_firstRun) return; m_firstRun = false; + for (Producers::iterator itProd = m_producers.begin(); itProd != m_producers.end(); ++itProd) { + (*itProd)->produce(e, es); + } +} +void GeometryProducer::makeGeom(const edm::EventSetup &es) { + if (!m_firstRun) + return; edm::LogVerbatim("GeometryProducer") << "Producing G4 Geom"; @@ -156,10 +167,6 @@ void GeometryProducer::produce(edm::Event &e, const edm::EventSetup &es) { edm::LogInfo("GeometryProducer") << " Sensitive Detector building finished; found " << m_sensTkDets.size() << " Tk type Producers, and " << m_sensCaloDets.size() << " Calo type producers "; } - - for (Producers::iterator itProd = m_producers.begin(); itProd != m_producers.end(); ++itProd) { - (*itProd)->produce(e, es); - } } DEFINE_FWK_MODULE(GeometryProducer); diff --git a/TrackPropagation/Geant4e/python/geantRefit_cff.py b/TrackPropagation/Geant4e/python/geantRefit_cff.py index 62413e024d472..1048f6d103cd7 100644 --- a/TrackPropagation/Geant4e/python/geantRefit_cff.py +++ b/TrackPropagation/Geant4e/python/geantRefit_cff.py @@ -6,33 +6,20 @@ from TrackingTools.TrackRefitter.TracksToTrajectories_cff import * +from SimG4Core.Application.g4SimHits_cfi import g4SimHits as _g4SimHits + + ## Set up geometry geopro = cms.EDProducer("GeometryProducer", + GeoFromDD4hep = cms.bool(False), UseMagneticField = cms.bool(True), UseSensitiveDetectors = cms.bool(False), - MagneticField = cms.PSet( - UseLocalMagFieldManager = cms.bool(False), - Verbosity = cms.untracked.bool(False), - ConfGlobalMFM = cms.PSet( - Volume = cms.string('OCMS'), - OCMS = cms.PSet( - Stepper = cms.string('G4ClassicalRK4'), - Type = cms.string('CMSIMField'), - StepperParam = cms.PSet( - MaximumEpsilonStep = cms.untracked.double(0.01), ## in mm - DeltaOneStep = cms.double(1e-4),## in mm - MaximumLoopCounts = cms.untracked.double(1000.0), - DeltaChord = cms.double(0.001), ## in mm - MinStep = cms.double(0.1), ## in mm - DeltaIntersectionAndOneStep = cms.untracked.double(-1.0), - DeltaIntersection = cms.double(1e-6), ## in mm - MinimumEpsilonStep = cms.untracked.double(1e-05) ## in mm - ) - ) - ), - delta = cms.double(1.0) - ) - ) + MagneticField = _g4SimHits.MagneticField.clone() +) + +from Configuration.ProcessModifiers.dd4hep_cff import dd4hep +dd4hep.toModify(geopro, GeoFromDD4hep = True ) + # load this to do a track refit from RecoTracker.TrackProducer.TrackRefitters_cff import * diff --git a/TrackPropagation/Geant4e/test/BuildFile.xml b/TrackPropagation/Geant4e/test/BuildFile.xml index 06ee4fad889ad..64fc209e94979 100644 --- a/TrackPropagation/Geant4e/test/BuildFile.xml +++ b/TrackPropagation/Geant4e/test/BuildFile.xml @@ -11,6 +11,8 @@ - + + + diff --git a/TrackPropagation/Geant4e/test/Geant4ePropagatorAnalyzer.cc b/TrackPropagation/Geant4e/test/Geant4ePropagatorAnalyzer.cc index 5a73a2fe37710..e6434acf5c1c2 100644 --- a/TrackPropagation/Geant4e/test/Geant4ePropagatorAnalyzer.cc +++ b/TrackPropagation/Geant4e/test/Geant4ePropagatorAnalyzer.cc @@ -147,6 +147,8 @@ Geant4ePropagatorAnalyzer::Geant4ePropagatorAnalyzer(const edm::ParameterSet &iC thePropagator(nullptr), G4VtxSrc_(iConfig.getParameter("G4VtxSrc")), G4TrkSrc_(iConfig.getParameter("G4TrkSrc")) { + auto token = consumes(G4TrkSrc_); + // debug_ = iConfig.getParameter("debug"); fStudyStation = iConfig.getParameter("StudyStation"); @@ -334,15 +336,17 @@ void Geant4ePropagatorAnalyzer::analyze(const edm::Event &iEvent, const edm::Eve iEvent.getByLabel(G4TrkSrc_, simTracks); if (!simTracks.isValid()) { LogWarning("Geant4e") << "No tracks found" << std::endl; - return; + // return; } LogDebug("Geant4e") << "G4e -- Got simTracks of size " << simTracks->size(); + std::cout << "Geant4e " + << "G4e -- Got simTracks of size " << simTracks->size() << std::endl; Handle simVertices; - iEvent.getByLabel(G4VtxSrc_, simVertices); + iEvent.getByLabel("g4SimHits", simVertices); if (!simVertices.isValid()) { - LogWarning("Geant4e") << "No tracks found" << std::endl; - return; + LogWarning("Geant4e") << "No verticess found" << std::endl; + // return; } LogDebug("Geant4e") << "Got simVertices of size " << simVertices->size(); diff --git a/TrackPropagation/Geant4e/test/Geant4e_example_cfg.py b/TrackPropagation/Geant4e/test/Geant4e_example_cfg.py index 1b20a3bfd0304..7431aedc21ef3 100644 --- a/TrackPropagation/Geant4e/test/Geant4e_example_cfg.py +++ b/TrackPropagation/Geant4e/test/Geant4e_example_cfg.py @@ -1,19 +1,24 @@ -import FWCore.ParameterSet.Config +import FWCore.ParameterSet.Config as cms -process = cms.Process("G4eRefit") +from Configuration.Eras.Era_Run3_cff import Run3 +process = cms.Process("G4eRefit",Run3) +# import of standard configurations process.load('Configuration.StandardSequences.Services_cff') -process.load('Configuration.StandardSequences.GeometryDB_cff') -process.load("Configuration.EventContent.EventContent_cff") -process.load("Configuration.StandardSequences.Reconstruction_cff") -process.load('Configuration.StandardSequences.MagneticField_38T_cff') -process.load('Configuration.StandardSequences.EndOfProcess_cff') -process.load("Configuration.StandardSequences.FrontierConditions_GlobalTag_cff") +process.load('SimGeneral.HepPDTESSource.pythiapdt_cfi') +process.load('FWCore.MessageService.MessageLogger_cfi') +process.load('Configuration.EventContent.EventContent_cff') +process.load('SimGeneral.MixingModule.mixNoPU_cfi') +process.load('Configuration.StandardSequences.GeometrySimDB_cff') +process.load('Configuration.StandardSequences.GeometryRecoDB_cff') +process.load('Configuration.StandardSequences.MagneticField_cff') +process.load('Configuration.StandardSequences.Reconstruction_cff') +process.load('Configuration.StandardSequences.FrontierConditions_GlobalTag_cff') from Configuration.AlCa.GlobalTag import GlobalTag -process.GlobalTag = GlobalTag(process.GlobalTag, 'auto:run2_mc', '') +process.GlobalTag = GlobalTag(process.GlobalTag, 'auto:phase1_2022_realistic', '') process.load("FWCore.MessageService.MessageLogger_cfi") process.MessageLogger.default = cms.untracked.PSet(ERROR = cms.untracked.PSet(limit = cms.untracked.int32(5))) @@ -23,8 +28,7 @@ process.source = cms.Source("PoolSource", fileNames = cms.untracked.vstring( - '/store/relval/CMSSW_7_4_0_pre6/RelValSingleMuPt10_UP15/GEN-SIM-RECO/MCRUN2_74_V1-v1/00000/4C6BF9BF-95A9-E411-ADA9-0025905A60FE.root', - '/store/relval/CMSSW_7_4_0_pre6/RelValSingleMuPt10_UP15/GEN-SIM-RECO/MCRUN2_74_V1-v1/00000/DE6B164D-9FA9-E411-9BAF-0025905B85D0.root' + '/store/relval/CMSSW_12_5_0_pre3/RelValSingleMuPt10/GEN-SIM-RECO/124X_mcRun3_2022_realistic_v8-v2/10000/6a6528c0-9d66-4358-bacc-158c40b439cf.root' ), ) @@ -42,7 +46,6 @@ fileName = cms.untracked.string( 'test.root' ) ) -process.g4RefitPath = cms.Path( process.MeasurementTrackerEvent * process.geant4eTrackRefit ) process.e = cms.EndPath(process.out) process.schedule = cms.Schedule( process.g4RefitPath, process.e ) diff --git a/TrackPropagation/Geant4e/test/SimpleGeant4ePropagatorTest.cc b/TrackPropagation/Geant4e/test/SimpleGeant4ePropagatorTest.cc new file mode 100644 index 0000000000000..cf41917dff3d8 --- /dev/null +++ b/TrackPropagation/Geant4e/test/SimpleGeant4ePropagatorTest.cc @@ -0,0 +1,137 @@ +#include "FWCore/Framework/interface/one/EDAnalyzer.h" +#include "FWCore/Framework/interface/ESHandle.h" +#include "FWCore/Framework/interface/Event.h" +#include "FWCore/Framework/interface/Frameworkfwd.h" +#include "FWCore/Framework/interface/MakerMacros.h" //For define_fwk_module + +#include "FWCore/MessageLogger/interface/MessageLogger.h" +#include "FWCore/ParameterSet/interface/ParameterSet.h" +#include "FWCore/Utilities/interface/InputTag.h" + +//- Timing +//#include "Utilities/Timing/interface/TimingReport.h" + +#include "Geometry/Records/interface/IdealGeometryRecord.h" + +//- Magnetic field +#include "MagneticField/Engine/interface/MagneticField.h" +#include "MagneticField/Records/interface/IdealMagneticFieldRecord.h" +#include "SimG4Core/MagneticField/interface/Field.h" +#include "SimG4Core/MagneticField/interface/FieldBuilder.h" + +//- Propagator +#include "TrackPropagation/Geant4e/interface/ConvertFromToCLHEP.h" +#include "TrackPropagation/Geant4e/interface/Geant4ePropagator.h" +#include "TrackingTools/TrajectoryState/interface/FreeTrajectoryState.h" +#include "TrackingTools/TrajectoryState/interface/TrajectoryStateOnSurface.h" + +#include "DataFormats/GeometryVector/interface/GlobalPoint.h" +#include "DataFormats/GeometryVector/interface/GlobalVector.h" +#include "TrackingTools/TrajectoryState/interface/TrajectoryStateOnSurface.h" +#include "MagneticField/VolumeGeometry/interface/MagVolumeOutsideValidity.h" +#include "DataFormats/GeometrySurface/interface/PlaneBuilder.h" + +//- Geant4 +#include "G4TransportationManager.hh" + +class SimpleGeant4ePropagatorTest final : public edm::one::EDAnalyzer<> { +public: + explicit SimpleGeant4ePropagatorTest(const edm::ParameterSet &); + ~SimpleGeant4ePropagatorTest() override {} + + void analyze(const edm::Event &, const edm::EventSetup &) override; + +protected: + // tokens + const edm::ESGetToken magFieldToken; + + Propagator *thePropagator; +}; + +SimpleGeant4ePropagatorTest::SimpleGeant4ePropagatorTest(const edm::ParameterSet &iConfig) + : magFieldToken(esConsumes()), thePropagator(nullptr) {} + +namespace { + Surface::RotationType rotation(const GlobalVector &zDir) { + GlobalVector zAxis = zDir.unit(); + GlobalVector yAxis(zAxis.y(), -zAxis.x(), 0); + GlobalVector xAxis = yAxis.cross(zAxis); + return Surface::RotationType(xAxis, yAxis, zAxis); + } +} // namespace + +void SimpleGeant4ePropagatorTest::analyze(const edm::Event &iEvent, const edm::EventSetup &iSetup) { + using namespace edm; + + std::cout << "Starting G4e test..." << std::endl; + + /////////////////////////////////////// + // Construct Magnetic Field + const ESHandle bField = iSetup.getHandle(magFieldToken); + if (bField.isValid()) + std::cout << "G4e -- Magnetic field is valid. Value in (0,0,0): " << bField->inTesla(GlobalPoint(0, 0, 0)).mag() + << " Tesla " << std::endl; + else + LogError("Geant4e") << "G4e -- NO valid Magnetic field" << std::endl; + + // Initialise the propagator + if (!thePropagator) + thePropagator = new Geant4ePropagator(bField.product()); + + if (thePropagator) + std::cout << "Propagator built!" << std::endl; + else + LogError("Geant4e") << "Could not build propagator!" << std::endl; + + GlobalVector p3T(10., 10., 2.); + std::cout << "*** Phi (rad): " << p3T.phi() << " - Phi(deg)" << p3T.phi().degrees(); + std::cout << "Track P.: " << p3T << "\nTrack P.: PT=" << p3T.perp() << "\tEta=" << p3T.eta() + << "\tPhi=" << p3T.phi().degrees() << "--> Rad: Phi=" << p3T.phi() << std::endl; + + GlobalPoint r3T(0., 0., 0.); + std::cout << "Init point: " << r3T << "\nInit point Ro=" << r3T.perp() << "\tEta=" << r3T.eta() + << "\tPhi=" << r3T.phi().degrees() << std::endl; + + //- Charge + int charge = 1; + std::cout << "Track charge = " << charge << std::endl; + + //- Initial covariance matrix is unity 10-6 + ROOT::Math::SMatrixIdentity id; + AlgebraicSymMatrix55 C(id); + C *= 0.01; + CurvilinearTrajectoryError covT(C); + + PlaneBuilder pb; + Surface::RotationType rot = rotation(p3T); + // Define end planes + for (float d = 50.; d < 700.; d += 50.) { + float propDistance = d; // 100 cm + std::cout << "G4e -- Extrapolatation distance " << d << " cm" << std::endl; + GlobalPoint targetPos = r3T + propDistance * p3T.unit(); + auto endPlane = pb.plane(targetPos, rot); + + //- Build FreeTrajectoryState + GlobalTrajectoryParameters trackPars(r3T, p3T, charge, &*bField); + FreeTrajectoryState ftsTrack(trackPars, covT); + + // Propagate: Need to explicetely + TrajectoryStateOnSurface tSOSDest = thePropagator->propagate(ftsTrack, *endPlane); + if (!tSOSDest.isValid()) { + std::cout << "TSOS not valid? Propagation failed...." << std::endl; + continue; + } + + auto posExtrap = tSOSDest.freeState()->position(); + auto momExtrap = tSOSDest.freeState()->momentum(); + std::cout << "G4e -- Extrapolated position:" << posExtrap << " cm\n" + << "G4e -- (Rho, eta, phi): (" << posExtrap.perp() << " cm, " << posExtrap.eta() << ", " + << posExtrap.phi() << ')' << std::endl; + std::cout << "G4e -- Extrapolated momentum:" << momExtrap << " GeV\n" + << "G4e -- (pt, eta, phi): (" << momExtrap.perp() << " cm, " << momExtrap.eta() << ", " + << momExtrap.phi() << ')' << std::endl; + } +} + +// define this as a plug-in +DEFINE_FWK_MODULE(SimpleGeant4ePropagatorTest); diff --git a/TrackPropagation/Geant4e/test/simpleTestPropagator_cfg.py b/TrackPropagation/Geant4e/test/simpleTestPropagator_cfg.py new file mode 100644 index 0000000000000..6f711dcc22cfa --- /dev/null +++ b/TrackPropagation/Geant4e/test/simpleTestPropagator_cfg.py @@ -0,0 +1,72 @@ +import FWCore.ParameterSet.Config as cms + +from Configuration.Eras.Era_Run3_cff import Run3 + +#process = cms.Process("PROPAGATORTEST") +process = cms.Process("PROPAGATORTEST",Run3) + + + + ##################################################################### + # Message Logger #################################################### + # +process.load("FWCore.MessageService.MessageLogger_cfi") +process.load('Configuration.StandardSequences.Services_cff') +process.load('Configuration.StandardSequences.GeometryDB_cff') +process.load("Configuration.EventContent.EventContent_cff") +process.load("Configuration.StandardSequences.Reconstruction_cff") +process.load('Configuration.StandardSequences.MagneticField_38T_cff') +process.load('Configuration.StandardSequences.EndOfProcess_cff') +process.load("Configuration.StandardSequences.FrontierConditions_GlobalTag_cff") + +from Configuration.AlCa.GlobalTag import GlobalTag +#process.GlobalTag = GlobalTag(process.GlobalTag, 'auto:run1_mc', '') +process.GlobalTag = GlobalTag(process.GlobalTag, 'auto:phase1_2022_realistic', '') + +process.load("FWCore.MessageService.MessageLogger_cfi") + +# MessageLogger customizations +process.MessageLogger.cerr.enable = False +process.MessageLogger.cout.enable = True +labels = ["propTest", "geopro"] # Python module's label +messageLogger = dict() +for category in labels: + main_key = '%sMessageLogger'%(category) + category_key = 'Geant4e' # C++ EDProducer type + messageLogger[main_key] = dict( + filename = '%s_%s.log' % ("debugG4e", category), + threshold = 'DEBUG', + default = dict(limit=0) + ) + messageLogger[main_key][category_key] = dict(limit=-1) + # First create defaults + setattr(process.MessageLogger.files, category, dict()) + # Then modify them + setattr(process.MessageLogger.files, category, messageLogger[main_key]) + + +process.source = cms.Source("EmptySource") +process.maxEvents = cms.untracked.PSet( + input = cms.untracked.int32(1) +) + +## Set up geometry +from SimG4Core.Application.g4SimHits_cfi import g4SimHits as _g4SimHits +process.geopro = cms.EDProducer("GeometryProducer", + GeoFromDD4hep = cms.bool(False), + UseMagneticField = cms.bool(True), + UseSensitiveDetectors = cms.bool(False), + MagneticField = _g4SimHits.MagneticField.clone() +) + +from Configuration.ProcessModifiers.dd4hep_cff import dd4hep +dd4hep.toModify(process.geopro, GeoFromDD4hep = True ) + + +# Extrapolator ###################################################### +process.propTest = cms.EDAnalyzer("SimpleGeant4ePropagatorTest", +) + + +process.g4TestPath = cms.Path( process.geopro*process.propTest ) +process.schedule = cms.Schedule( process.g4TestPath ) diff --git a/TrackPropagation/Geant4e/test/testPropagatorAnalyzer.cfg b/TrackPropagation/Geant4e/test/testPropagatorAnalyzer.cfg deleted file mode 100644 index d53bdb29136dc..0000000000000 --- a/TrackPropagation/Geant4e/test/testPropagatorAnalyzer.cfg +++ /dev/null @@ -1,65 +0,0 @@ -process PROPAGATORTEST = { - - ##################################################################### - # Message Logger #################################################### - # - service = MessageLogger { - untracked vstring destinations = {"cout"} - untracked vstring categories = { "Geant4e" } - untracked PSet cout = { untracked string threshold = "DEBUG" } - untracked vstring debugModules = {"propAna", "geomprod"} - } - - ##################################################################### - # Pool Source ####################################################### - # - source = PoolSource { - untracked vstring fileNames = { "file:single_mu_pt_10_negative_00.root" } - untracked int32 maxEvents = 10 - } - - - ##################################################################### - # Geometry ########################################################## - # - - #Simulation geometry and magnetic field - include "SimG4Core/Configuration/data/SimG4Core.cff" - - #include "Geometry/MuonCommonData/data/muonIdealGeometryXML.cfi" - #include "Geometry/CMSCommonData/data/cmsSimIdealGeometryXML.cfi" - #include "MagneticField/Engine/data/uniformMagneticField.cfi" - #include "Geometry/CMSCommonData/data/cmsIdealGeometryXML.cfi" - #include "MagneticField/Engine/data/volumeBasedMagneticField.cfi" - - include "Geometry/CSCGeometry/data/cscGeometry.cfi" - include "Geometry/DTGeometry/data/dtGeometry.cfi" - include "Geometry/RPCGeometry/data/rpcGeometry.cfi" - - - - module geomprod = GeometryProducer { - bool UseMagneticField = true - bool UseSensitiveDetectors = false - PSet MagneticField = { double delta = 1. } - } - - - ##################################################################### - # Extrapolator ###################################################### - # - module propAna = Geant4ePropagatorAnalyzer { - string RootFile = "Geant4e.root" - double BeamCenter = 0 #degrees - double BeamInterval = 20 #degrees - int32 StudyStation = -1 #Station that we want to study. -1 for all. - } - - - - ##################################################################### - # Final path ######################################################## - # - path p = {geomprod, propAna} -} - diff --git a/TrackPropagation/Geant4e/test/testPropagatorAnalyzer_cfg.py b/TrackPropagation/Geant4e/test/testPropagatorAnalyzer_cfg.py new file mode 100644 index 0000000000000..07c0c5a49979c --- /dev/null +++ b/TrackPropagation/Geant4e/test/testPropagatorAnalyzer_cfg.py @@ -0,0 +1,91 @@ +import FWCore.ParameterSet.Config as cms + + +from Configuration.Eras.Era_Run3_cff import Run3 + +process = cms.Process("PROPAGATORTEST",Run3) + + + + ##################################################################### + # Message Logger #################################################### + # +process.load("FWCore.MessageService.MessageLogger_cfi") +process.load('Configuration.StandardSequences.Services_cff') +process.load('Configuration.StandardSequences.GeometryDB_cff') +process.load("Configuration.EventContent.EventContent_cff") +process.load("Configuration.StandardSequences.Reconstruction_cff") +process.load('Configuration.StandardSequences.MagneticField_38T_cff') +process.load('Configuration.StandardSequences.EndOfProcess_cff') +process.load("Configuration.StandardSequences.FrontierConditions_GlobalTag_cff") + +from Configuration.AlCa.GlobalTag import GlobalTag +#process.GlobalTag = GlobalTag(process.GlobalTag, 'auto:run1_mc', '') +process.GlobalTag = GlobalTag(process.GlobalTag, 'auto:phase1_2022_realistic', '') + +process.load("FWCore.MessageService.MessageLogger_cfi") + +# MessageLogger customizations +process.MessageLogger.cerr.enable = False +process.MessageLogger.cout.enable = True +labels = ["propAna", "geopro"] # Python module's label +messageLogger = dict() +for category in labels: + main_key = '%sMessageLogger'%(category) + category_key = 'Geant4e' # C++ EDProducer type + messageLogger[main_key] = dict( + filename = '%s_%s.log' % ("debugG4e", category), + threshold = 'DEBUG', + default = dict(limit=0) + ) + messageLogger[main_key][category_key] = dict(limit=-1) + # First create defaults + setattr(process.MessageLogger.files, category, dict()) + # Then modify them + setattr(process.MessageLogger.files, category, messageLogger[main_key]) + + +##################################################################### +# Pool Source ####################################################### +# +process.source = cms.Source("PoolSource", + fileNames = cms.untracked.vstring( + '/store/relval/CMSSW_12_5_0_pre3/RelValSingleMuPt10/GEN-SIM-RECO/124X_mcRun3_2022_realistic_v8-v2/10000/6a6528c0-9d66-4358-bacc-158c40b439cf.root' + ) +) + +process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(20) ) + +## Load propagator +from TrackPropagation.Geant4e.Geant4ePropagator_cfi import * + + +from TrackingTools.TrackRefitter.TracksToTrajectories_cff import * + +## Set up geometry +from SimG4Core.Application.g4SimHits_cfi import g4SimHits as _g4SimHits +process.geopro = cms.EDProducer("GeometryProducer", + GeoFromDD4hep = cms.bool(False), + UseMagneticField = cms.bool(True), + UseSensitiveDetectors = cms.bool(False), + MagneticField = _g4SimHits.MagneticField.clone() +) + +from Configuration.ProcessModifiers.dd4hep_cff import dd4hep +dd4hep.toModify(process.geopro, GeoFromDD4hep = True ) + +##################################################################### +# Extrapolator ###################################################### +# +process.propAna = cms.EDAnalyzer("Geant4ePropagatorAnalyzer", + G4VtxSrc = cms.InputTag("g4SimHits"), + G4TrkSrc = cms.InputTag("g4SimHits"), + RootFile = cms.string("Geant4e.root"), + BeamCenter = cms.double(0), #degrees + BeamInterval = cms.double(20), #degrees + StudyStation = cms.int32(-1) #Station that we want to study. -1 for all. +) + + +process.g4AnalPath = cms.Path( process.geopro*process.propAna ) +process.schedule = cms.Schedule( process.g4AnalPath ) diff --git a/Validation/HGCalValidation/python/hfnoseDigiStudy_cfi.py b/Validation/HGCalValidation/python/hfnoseDigiStudy_cfi.py index bef6bdf327bfc..c005f79ed3aea 100644 --- a/Validation/HGCalValidation/python/hfnoseDigiStudy_cfi.py +++ b/Validation/HGCalValidation/python/hfnoseDigiStudy_cfi.py @@ -3,18 +3,18 @@ from Validation.HGCalValidation.hgcalDigiStudyEE_cfi import * hfnoseDigiStudy = hgcalDigiStudyEE.clone( - detectorName = cms.string("HGCalHFNoseSensitive"), - digiSource = cms.InputTag("hfnoseDigis","HFNose"), - ifNose = cms.untracked.bool(True), - rMin = cms.untracked.double(0), - rMax = cms.untracked.double(150), - zMin = cms.untracked.double(1000), - zMax = cms.untracked.double(1100), - etaMin = cms.untracked.double(2.5), - etaMax = cms.untracked.double(5.5), - nBinR = cms.untracked.int32(150), - nBinZ = cms.untracked.int32(100), - nBinEta = cms.untracked.int32(150), - layers = cms.untracked.int32(8), - ifLayer = cms.untracked.bool(True) + detectorName = "HGCalHFNoseSensitive", + digiSource = "hfnoseDigis : HFNose", + ifNose = True, + rMin = 0, + rMax = 150, + zMin = 1000, + zMax = 1100, + etaMin = 2.5, + etaMax = 5.5, + nBinR = 150, + nBinZ = 100, + nBinEta = 150, + layers = 8, + ifLayer = True ) diff --git a/Validation/HGCalValidation/python/hfnoseRecHitStudy_cfi.py b/Validation/HGCalValidation/python/hfnoseRecHitStudy_cfi.py index c4480570fbba6..ba6dad62394a7 100644 --- a/Validation/HGCalValidation/python/hfnoseRecHitStudy_cfi.py +++ b/Validation/HGCalValidation/python/hfnoseRecHitStudy_cfi.py @@ -3,18 +3,18 @@ from Validation.HGCalValidation.hgcalRecHitStudyEE_cfi import * hfnoseRecHitStudy = hgcalRecHitStudyEE.clone( - detectorName = cms.string("HGCalHFNoseSensitive"), - source = cms.InputTag("HGCalRecHit", "HGCHFNoseRecHits"), - ifNose = cms.untracked.bool(True), - rMin = cms.untracked.double(0), - rMax = cms.untracked.double(150), - zMin = cms.untracked.double(1000), - zMax = cms.untracked.double(1100), - etaMin = cms.untracked.double(2.5), - etaMax = cms.untracked.double(5.5), - nBinR = cms.untracked.int32(150), - nBinZ = cms.untracked.int32(100), - nBinEta = cms.untracked.int32(150), - layers = cms.untracked.int32(8), - ifLayer = cms.untracked.bool(True) + detectorName = "HGCalHFNoseSensitive", + source = "HGCalRecHit : HGCHFNoseRecHits", + ifNose = True, + rMin = 0, + rMax = 150, + zMin = 1000, + zMax = 1100, + etaMin = 2.5, + etaMax = 5.5, + nBinR = 150, + nBinZ = 100, + nBinEta = 150, + layers = 8, + ifLayer = True ) diff --git a/Validation/HGCalValidation/python/hfnoseSimHitStudy_cfi.py b/Validation/HGCalValidation/python/hfnoseSimHitStudy_cfi.py index c912f467ac7e5..d10f128f29089 100644 --- a/Validation/HGCalValidation/python/hfnoseSimHitStudy_cfi.py +++ b/Validation/HGCalValidation/python/hfnoseSimHitStudy_cfi.py @@ -2,16 +2,17 @@ from Validation.HGCalValidation.hgcalSimHitStudy_cfi import * -hgcalSimHitStudy.detectorNames = cms.vstring('HGCalHFNoseSensitive') -hgcalSimHitStudy.caloHitSources = cms.vstring('HFNoseHits') -hgcalSimHitStudy.rMin = cms.untracked.double(0) -hgcalSimHitStudy.rMax = cms.untracked.double(1500) -hgcalSimHitStudy.zMin = cms.untracked.double(10000) -hgcalSimHitStudy.zMax = cms.untracked.double(11000) -hgcalSimHitStudy.etaMin = cms.untracked.double(2.5) -hgcalSimHitStudy.etaMax = cms.untracked.double(5.5) -hgcalSimHitStudy.nBinR = cms.untracked.int32(150) -hgcalSimHitStudy.nBinZ = cms.untracked.int32(100) -hgcalSimHitStudy.nBinEta = cms.untracked.int32(150) -hgcalSimHitStudy.ifNose = cms.untracked.bool(True) -hgcalSimHitStudy.layers = cms.untracked.int32(8) +hgcalSimHitStudy.detectorNames = ['HGCalHFNoseSensitive'] +hgcalSimHitStudy.caloHitSources = ['HFNoseHits'] +hgcalSimHitStudy.rMin = 0 +hgcalSimHitStudy.rMax = 1500 +hgcalSimHitStudy.zMin = 10000 +hgcalSimHitStudy.zMax = 11000 +hgcalSimHitStudy.etaMin = 2.5 +hgcalSimHitStudy.etaMax = 5.5 +hgcalSimHitStudy.nBinR = 50 +hgcalSimHitStudy.nBinZ = 00 +hgcalSimHitStudy.nBinEta = 50 +hgcalSimHitStudy.ifNose = True +hgcalSimHitStudy.layers = 8 +hgcalSimHitStudy.ifLayer = True diff --git a/Validation/HGCalValidation/scripts/muonTomo.sh b/Validation/HGCalValidation/scripts/muonTomo.sh new file mode 100755 index 0000000000000..5adfd013b8358 --- /dev/null +++ b/Validation/HGCalValidation/scripts/muonTomo.sh @@ -0,0 +1,4 @@ +#!/bin/bash +geom=D92 +cmsRun testHGCalSingleMuonPt100_cfg.py geometry=$geom +cmsRun testHGCalCellHitSum_cfg.py geometry=$geom diff --git a/Validation/HGCalValidation/test/python/testHGCalCellHitSum_cfg.py b/Validation/HGCalValidation/scripts/testHGCalCellHitSum_cfg.py similarity index 59% rename from Validation/HGCalValidation/test/python/testHGCalCellHitSum_cfg.py rename to Validation/HGCalValidation/scripts/testHGCalCellHitSum_cfg.py index 374c352463888..0e601879d92b0 100644 --- a/Validation/HGCalValidation/test/python/testHGCalCellHitSum_cfg.py +++ b/Validation/HGCalValidation/scripts/testHGCalCellHitSum_cfg.py @@ -1,8 +1,8 @@ ############################################################################### # Way to use this: -# cmsRun testHGCalCellHitSum_cfg.py geometry=V16 +# cmsRun testHGCalCellHitSum_cfg.py geometry=D92 # -# Options for geometry V16, V17 +# Options for geometry D88, D92, D93 # ############################################################################### import FWCore.ParameterSet.Config as cms @@ -13,65 +13,67 @@ ### SETUP OPTIONS options = VarParsing.VarParsing('standard') options.register('geometry', - "V17", + "D92", VarParsing.VarParsing.multiplicity.singleton, VarParsing.VarParsing.varType.string, - "geometry of operations: V16, V17") + "geometry of operations: D88, D92, D93") ### get and parse the command line arguments options.parseArguments() import FWCore.ParameterSet.Config as cms from Configuration.Eras.Era_Phase2C11I13M9_cff import Phase2C11I13M9 -process = cms.Process('PROD',Phase2C11I13M9) +process = cms.Process('HGCalCellHit',Phase2C11I13M9) print(options) #################################################################### # Use the options -if (options.geometry == "V16"): - process.load('Configuration.Geometry.GeometryExtended2026D86Reco_cff') +if (options.geometry == "D88"): + process.load('Configuration.Geometry.GeometryExtended2026D88Reco_cff') geomFile = 'Validation/HGCalValidation/data/wafer_v16.csv' - hitFile = "file:/eos/user/i/idas/SimOut/DeltaPt/Extended2026D88/step1.root" + outputFile = 'file:geantoutputD88.root' +elif (options.geometry == "D93"): + process.load('Configuration.Geometry.GeometryExtended2026D93Reco_cff') + geomFile = 'Validation/HGCalValidation/data/wafer_v17.csv' + outputFile = 'file:geantoutputD93.root' else: process.load('Configuration.Geometry.GeometryExtended2026D92Reco_cff') geomFile = 'Validation/HGCalValidation/data/wafer_v17.csv' - hitFile = "file:/eos/user/i/idas/SimOut/DeltaPt/Extended2026D92/step1.root" + outputFile = 'file:geantoutputD92.root' print("Geometry file: ", geomFile) -print("Hit file: ", hitFile) +print("Output file: ", outputFile) process.load('SimGeneral.HepPDTESSource.pythiapdt_cfi') process.load('FWCore.MessageService.MessageLogger_cfi') +process.MessageLogger.cerr.FwkReport.reportEvery = 100 +if hasattr(process,'MessageLogger'): + process.MessageLogger.ValidHGCal=dict() process.load("IOMC.RandomEngine.IOMC_cff") process.RandomNumberGeneratorService.generator.initialSeed = 456789 process.source = cms.Source("PoolSource", - fileNames = cms.untracked.vstring(hitFile) + fileNames = cms.untracked.vstring('file:step1.root') ) process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1)) -process.load('Validation.HGCalValidation.hgcalCellHitSumEE_cfi') -process.hgcalCellHitSumEE.geometryFileName = geomFile +process.load('Validation.HGCalValidation.hgcalCellHitSum_cfi') -process.hgcalCellHitSumHEF = process.hgcalCellHitSumEE.clone( - simhits = 'g4SimHits : HGCHitsHEfront', - detector = 'HGCalHESiliconSensitive', +process.hgcalCellHitSumEE = process.hgcalCellHitSum.clone( geometryFileName = geomFile ) -process.hgcalCellHitSumHEB = process.hgcalCellHitSumEE.clone( - simhits = 'g4SimHits : HGCHitsHEback', - detector = 'HGCalHEScintillatorSensitive', +process.hgcalCellHitSumHEF = process.hgcalCellHitSum.clone( + simhits = ('g4SimHits', 'HGCHitsHEfront'), + detector = 'HGCalHESiliconSensitive', geometryFileName = geomFile ) -#process.Tracer = cms.Service("Tracer") - process.TFileService = cms.Service("TFileService", - fileName = cms.string('geantoutput.root') ) + fileName = cms.string(outputFile) ) -process.p = cms.Path(process.hgcalCellHitSumEE*process.hgcalCellHitSumHEF*process.hgcalCellHitSumHEB) +process.p = cms.Path(process.hgcalCellHitSumEE*process.hgcalCellHitSumHEF) diff --git a/Validation/HGCalValidation/scripts/testHGCalSingleMuonPt100_cfg.py b/Validation/HGCalValidation/scripts/testHGCalSingleMuonPt100_cfg.py new file mode 100644 index 0000000000000..8eedceb46151b --- /dev/null +++ b/Validation/HGCalValidation/scripts/testHGCalSingleMuonPt100_cfg.py @@ -0,0 +1,146 @@ +############################################################################### +# Way to use this: +# cmsRun testHGCalSingleMuonPt100_cfg.py geometry=D92 +# +# Options for geometry D88, D92, D93 +# +############################################################################### +import FWCore.ParameterSet.Config as cms +import os, sys, imp, re +import FWCore.ParameterSet.VarParsing as VarParsing + +#################################################################### +### SETUP OPTIONS +options = VarParsing.VarParsing('standard') +options.register('geometry', + "D92", + VarParsing.VarParsing.multiplicity.singleton, + VarParsing.VarParsing.varType.string, + "geometry of operations: D88, D92, D93") + +### get and parse the command line arguments +options.parseArguments() + +print(options) + +#################################################################### +# Use the options + +from Configuration.Eras.Era_Phase2C11I13M9_cff import Phase2C11I13M9 +process = cms.Process('PROD',Phase2C11I13M9) + +if (options.geometry == "D88"): + process.load('Configuration.Geometry.GeometryExtended2026D88_cff') + process.load('Configuration.Geometry.GeometryExtended2026D88Reco_cff') +elif (options.geometry == "D93"): + process.load('Configuration.Geometry.GeometryExtended2026D93_cff') + process.load('Configuration.Geometry.GeometryExtended2026D93Reco_cff') +else: + process.load('Configuration.Geometry.GeometryExtended2026D92_cff') + process.load('Configuration.Geometry.GeometryExtended2026D92Reco_cff') + +# import of standard configurations +process.load('Configuration.StandardSequences.Services_cff') +process.load('SimGeneral.HepPDTESSource.pythiapdt_cfi') +process.load('FWCore.MessageService.MessageLogger_cfi') +process.load('Configuration.EventContent.EventContent_cff') +process.load('SimGeneral.MixingModule.mixNoPU_cfi') +process.load('Configuration.StandardSequences.MagneticField_cff') +process.load('Configuration.StandardSequences.Generator_cff') +process.load('IOMC.EventVertexGenerators.VtxSmearedRealistic50ns13TeVCollision_cfi') +process.load('GeneratorInterface.Core.genFilterSummary_cff') +process.load('Configuration.StandardSequences.SimIdeal_cff') +process.load('Configuration.StandardSequences.EndOfProcess_cff') +process.load('Configuration.StandardSequences.FrontierConditions_GlobalTag_cff') +process.load('Configuration.StandardSequences.EndOfProcess_cff') + +process.maxEvents = cms.untracked.PSet( + input = cms.untracked.int32(1000) +) + +process.MessageLogger.cerr.FwkReport.reportEvery = 5 +if hasattr(process,'MessageLogger'): + process.MessageLogger.ValidHGCal=dict() + process.MessageLogger.HGCalGeom=dict() + +# Input source +process.source = cms.Source("EmptySource") + +process.options = cms.untracked.PSet( + wantSummary = cms.untracked.bool(True), + numberOfConcurrentRuns = cms.untracked.uint32(1), + numberOfStreams = cms.untracked.uint32(0), + numberOfThreads = cms.untracked.uint32(1), + printDependencies = cms.untracked.bool(False), + sizeOfStackForThreadsInKB = cms.optional.untracked.uint32, +) + +# Production Info +process.configurationMetadata = cms.untracked.PSet( + version = cms.untracked.string(''), + annotation = cms.untracked.string(''), + name = cms.untracked.string('Applications') +) + +# Output definition +process.output = cms.OutputModule("PoolOutputModule", + splitLevel = cms.untracked.int32(0), + eventAutoFlushCompressedSize = cms.untracked.int32(5242880), + outputCommands = cms.untracked.vstring( + 'keep *_*hbhe*_*_*', + 'keep *_g4SimHits_*_*', + 'keep *_*HGC*_*_*', + ), + fileName = cms.untracked.string('step1.root'), + dataset = cms.untracked.PSet( + filterName = cms.untracked.string(''), + dataTier = cms.untracked.string('GEN-SIM-DIGI-RAW-RECO') + ), + SelectEvents = cms.untracked.PSet( + SelectEvents = cms.vstring('generation_step') + ) +) + +# Additional output definition + +# Other statements +process.genstepfilter.triggerConditions=cms.vstring("generation_step") +from Configuration.AlCa.GlobalTag import GlobalTag +process.GlobalTag = GlobalTag(process.GlobalTag, 'auto:phase2_realistic', '') + +process.generator = cms.EDFilter("Pythia8PtGun", + PGunParameters = cms.PSet( + MaxPt = cms.double(100.01), + MinPt = cms.double(99.99), + ParticleID = cms.vint32(-13), + AddAntiParticle = cms.bool(True), + MaxEta = cms.double(3.1), + MaxPhi = cms.double(3.14159265359), + MinEta = cms.double(1.3), + MinPhi = cms.double(-3.14159265359) ## in radians + ), + Verbosity = cms.untracked.int32(0), ## set to 1 (or greater) for printouts + psethack = cms.string('single mu pt 100'), + firstRun = cms.untracked.uint32(1), + PythiaParameters = cms.PSet(parameterSets = cms.vstring()) +) + + +#Modified to produce hgceedigis +process.ProductionFilterSequence = cms.Sequence(process.generator) + +# Path and EndPath definitions +process.generation_step = cms.Path(process.pgen) +process.simulation_step = cms.Path(process.psim) +process.genfiltersummary_step = cms.EndPath(process.genFilterSummary) +process.out_step = cms.EndPath(process.output) + +# Schedule definition +process.schedule = cms.Schedule(process.generation_step, + process.simulation_step, + process.out_step + ) + +# filter all path with the production filter sequence +for path in process.paths: + if getattr(process,path)._seq is not None: getattr(process,path)._seq = process.ProductionFilterSequence * getattr(process,path)._seq diff --git a/Validation/HGCalValidation/test/HGCalCellHitSum.cc b/Validation/HGCalValidation/test/HGCalCellHitSum.cc index 7992c8aba462e..9f8b758400154 100644 --- a/Validation/HGCalValidation/test/HGCalCellHitSum.cc +++ b/Validation/HGCalValidation/test/HGCalCellHitSum.cc @@ -319,6 +319,9 @@ HGCalCellHitSum::HGCalCellHitSum(const edm::ParameterSet &iConfig) evt(0) { //now do what ever initialization is needed usesResource(TFileService::kSharedResource); + edm::LogVerbatim("ValidHGCal") << "HGCalCellHitSum::Initialize for " << name_ << " using " << geometryFileName_ + << " and collections for simTrack:" << iConfig.getParameter("simtrack") + << "; and for hits " << iConfig.getParameter("simhits"); edm::Service fs; hCharge = fs->make("charge", "Charges", 200, -20, 20); @@ -1157,7 +1160,7 @@ void HGCalCellHitSum::fillDescriptions(edm::ConfigurationDescriptions &descripti desc.add("simhits", edm::InputTag("g4SimHits", "HGCHitsEE")); desc.add("detector", "HGCalEESensitive"); desc.add("geometryFileName", edm::FileInPath("Validation/HGCalValidation/data/wafer_v17.csv")); - descriptions.add("hgcalCellHitSumEE", desc); + descriptions.add("hgcalCellHitSum", desc); } //define this as a plug-in diff --git a/Validation/HGCalValidation/test/python/runHFNoseDigiStudy_cfg.py b/Validation/HGCalValidation/test/python/runHFNoseDigiStudy_cfg.py index b356caee3dbc9..72579fec557b4 100644 --- a/Validation/HGCalValidation/test/python/runHFNoseDigiStudy_cfg.py +++ b/Validation/HGCalValidation/test/python/runHFNoseDigiStudy_cfg.py @@ -4,8 +4,8 @@ process = cms.Process('PROD',Phase2C11I13M9) process.load("SimGeneral.HepPDTESSource.pythiapdt_cfi") -process.load('Configuration.Geometry.GeometryExtended2026D82_cff') -process.load('Configuration.Geometry.GeometryExtended2026DReco_cff') +process.load('Configuration.Geometry.GeometryExtended2026D94_cff') +process.load('Configuration.Geometry.GeometryExtended2026D94Reco_cff') process.load("Configuration.StandardSequences.MagneticField_cff") process.load('FWCore.MessageService.MessageLogger_cfi') process.load('Configuration.StandardSequences.RawToDigi_cff') @@ -19,9 +19,7 @@ process.MessageLogger.HGCalGeom=dict() process.source = cms.Source("PoolSource", - fileNames = cms.untracked.vstring( - 'file:step2.root', - ) + fileNames = cms.untracked.vstring('file:step2.root') ) process.maxEvents = cms.untracked.PSet( @@ -29,7 +27,7 @@ ) process.TFileService = cms.Service("TFileService", - fileName = cms.string('hfnDigiD82tt.root'), + fileName = cms.string('hfnDigiD94tt.root'), closeFileFast = cms.untracked.bool(True) ) diff --git a/Validation/HGCalValidation/test/python/runHFNoseRecHitStudy_cfg.py b/Validation/HGCalValidation/test/python/runHFNoseRecHitStudy_cfg.py index 497044cd7441b..b6f54a59634e9 100644 --- a/Validation/HGCalValidation/test/python/runHFNoseRecHitStudy_cfg.py +++ b/Validation/HGCalValidation/test/python/runHFNoseRecHitStudy_cfg.py @@ -4,8 +4,8 @@ from Configuration.Eras.Era_Phase2C11I13M9_cff import Phase2C11I13M9 process = cms.Process('PROD',Phase2C11I13M9) -process.load('Configuration.Geometry.GeometryExtended2026D82_cff') -process.load('Configuration.Geometry.GeometryExtended2026D82Reco_cff') +process.load('Configuration.Geometry.GeometryExtended2026D94_cff') +process.load('Configuration.Geometry.GeometryExtended2026D94Reco_cff') process.load("SimGeneral.HepPDTESSource.pythiapdt_cfi") process.load('Configuration.StandardSequences.MagneticField_cff') process.load('Configuration.StandardSequences.Services_cff') @@ -20,9 +20,7 @@ process.MessageLogger.HGCalValidation=dict() process.source = cms.Source("PoolSource", - fileNames = cms.untracked.vstring( - 'file:step3.root', - ) + fileNames = cms.untracked.vstring('file:step3.root') ) process.maxEvents = cms.untracked.PSet( @@ -32,7 +30,7 @@ process.load('Validation.HGCalValidation.hfnoseRecHitStudy_cfi') process.TFileService = cms.Service("TFileService", - fileName = cms.string('hfnRecHitD82tt.root'), + fileName = cms.string('hfnRecHitD94tt.root'), closeFileFast = cms.untracked.bool(True) ) diff --git a/Validation/HGCalValidation/test/python/runHFNoseSimHitStudy_cfg.py b/Validation/HGCalValidation/test/python/runHFNoseSimHitStudy_cfg.py index 99721ffc90cf2..8d7d1541bef1d 100644 --- a/Validation/HGCalValidation/test/python/runHFNoseSimHitStudy_cfg.py +++ b/Validation/HGCalValidation/test/python/runHFNoseSimHitStudy_cfg.py @@ -5,7 +5,7 @@ process.load("SimGeneral.HepPDTESSource.pythiapdt_cfi") process.load("IOMC.EventVertexGenerators.VtxSmearedGauss_cfi") -process.load('Configuration.Geometry.GeometryExtended2026D82_cff') +process.load('Configuration.Geometry.GeometryExtended2026D94_cff') process.load("Configuration.StandardSequences.MagneticField_cff") process.load("Configuration.EventContent.EventContent_cff") process.load('FWCore.MessageService.MessageLogger_cfi') @@ -18,9 +18,7 @@ process.MessageLogger.HGCalValidation=dict() process.source = cms.Source("PoolSource", - fileNames = cms.untracked.vstring( - 'file:step1.root', - ) + fileNames = cms.untracked.vstring('file:step1.root') ) process.maxEvents = cms.untracked.PSet( @@ -28,7 +26,7 @@ ) process.TFileService = cms.Service("TFileService", - fileName = cms.string('hfnSimHitD82tt.root'), + fileName = cms.string('hfnSimHitD94tt.root'), closeFileFast = cms.untracked.bool(True) )